MDL-69269 contentbank: add support to download content
[moodle.git] / contentbank / classes / contenttype.php
blob614dd4ed95834a7076d0b2811e5e4c3ac1df4aca
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Content type manager class
20 * @package core_contentbank
21 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace core_contentbank;
27 use core\event\contentbank_content_created;
28 use core\event\contentbank_content_deleted;
29 use core\event\contentbank_content_viewed;
30 use stored_file;
31 use Exception;
32 use moodle_url;
34 /**
35 * Content type manager class
37 * @package core_contentbank
38 * @copyright 2020 Amaia Anabitarte <amaia@moodle.com>
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 abstract class contenttype {
43 /** Plugin implements uploading feature */
44 const CAN_UPLOAD = 'upload';
46 /** Plugin implements edition feature */
47 const CAN_EDIT = 'edit';
49 /** Plugin implements download feature
50 * @since Moodle 3.10
52 const CAN_DOWNLOAD = 'download';
54 /** @var \context This contenttype's context. **/
55 protected $context = null;
57 /**
58 * Content type constructor
60 * @param \context $context Optional context to check (default null)
62 public function __construct(\context $context = null) {
63 if (empty($context)) {
64 $context = \context_system::instance();
66 $this->context = $context;
69 /**
70 * Fills content_bank table with appropiate information.
72 * @throws dml_exception A DML specific exception is thrown for any creation error.
73 * @param \stdClass $record An optional content record compatible object (default null)
74 * @return content Object with content bank information.
76 public function create_content(\stdClass $record = null): content {
77 global $USER, $DB;
79 $entry = new \stdClass();
80 $entry->contenttype = $this->get_contenttype_name();
81 $entry->contextid = $this->context->id;
82 $entry->name = $record->name ?? '';
83 $entry->usercreated = $record->usercreated ?? $USER->id;
84 $entry->timecreated = time();
85 $entry->usermodified = $entry->usercreated;
86 $entry->timemodified = $entry->timecreated;
87 $entry->configdata = $record->configdata ?? '';
88 $entry->instanceid = $record->instanceid ?? 0;
89 $entry->id = $DB->insert_record('contentbank_content', $entry);
90 $classname = '\\'.$entry->contenttype.'\\content';
91 $content = new $classname($entry);
92 // Trigger an event for creating the content.
93 $event = contentbank_content_created::create_from_record($content->get_content());
94 $event->trigger();
95 return $content;
98 /**
99 * Create a new content from an uploaded file.
101 * @throws file_exception If file operations fail
102 * @throws dml_exception if the content creation fails
103 * @param stored_file $file the uploaded file
104 * @param \stdClass|null $record an optional content record
105 * @return content Object with content bank information.
107 public function upload_content(stored_file $file, \stdClass $record = null): content {
108 if (empty($record)) {
109 $record = new \stdClass();
110 $record->name = $file->get_filename();
112 $content = $this->create_content($record);
113 try {
114 $content->import_file($file);
115 } catch (Exception $e) {
116 $this->delete_content($content);
117 throw $e;
120 return $content;
124 * Delete this content from the content_bank.
125 * This method can be overwritten by the plugins if they need to delete specific information.
127 * @param content $content The content to delete.
128 * @return boolean true if the content has been deleted; false otherwise.
130 public function delete_content(content $content): bool {
131 global $DB;
133 // Delete the file if it exists.
134 if ($file = $content->get_file()) {
135 $file->delete();
138 // Delete the contentbank DB entry.
139 $result = $DB->delete_records('contentbank_content', ['id' => $content->get_id()]);
140 if ($result) {
141 // Trigger an event for deleting this content.
142 $record = $content->get_content();
143 $event = contentbank_content_deleted::create([
144 'objectid' => $content->get_id(),
145 'relateduserid' => $record->usercreated,
146 'context' => \context::instance_by_id($record->contextid),
147 'other' => [
148 'contenttype' => $content->get_content_type(),
149 'name' => $content->get_name()
152 $event->add_record_snapshot('contentbank_content', $record);
153 $event->trigger();
155 return $result;
159 * Rename this content from the content_bank.
160 * This method can be overwritten by the plugins if they need to change some other specific information.
162 * @param content $content The content to rename.
163 * @param string $name The name of the content.
164 * @return boolean true if the content has been renamed; false otherwise.
166 public function rename_content(content $content, string $name): bool {
167 return $content->set_name($name);
171 * Move content to another context.
172 * This method can be overwritten by the plugins if they need to change some other specific information.
174 * @param content $content The content to rename.
175 * @param \context $context The new context.
176 * @return boolean true if the content has been renamed; false otherwise.
178 public function move_content(content $content, \context $context): bool {
179 return $content->set_contextid($context->id);
183 * Returns the contenttype name of this content.
185 * @return string Content type of the current instance
187 public function get_contenttype_name(): string {
188 $classname = get_class($this);
189 $contenttype = explode('\\', $classname);
190 return array_shift($contenttype);
194 * Returns the plugin name of the current instance.
196 * @return string Plugin name of the current instance
198 public function get_plugin_name(): string {
199 $contenttype = $this->get_contenttype_name();
200 $plugin = explode('_', $contenttype);
201 return array_pop($plugin);
205 * Returns the URL where the content will be visualized.
207 * @param content $content The content to be displayed.
208 * @return string URL where to visualize the given content.
210 public function get_view_url(content $content): string {
211 return new moodle_url('/contentbank/view.php', ['id' => $content->get_id()]);
215 * Returns the HTML content to add to view.php visualizer.
217 * @param content $content The content to be displayed.
218 * @return string HTML code to include in view.php.
220 public function get_view_content(content $content): string {
221 // Trigger an event for viewing this content.
222 $event = contentbank_content_viewed::create_from_record($content->get_content());
223 $event->trigger();
225 return '';
229 * Returns the URL to download the content.
231 * @since Moodle 3.10
232 * @param content $content The content to be downloaded.
233 * @return string URL with the content to download.
235 public function get_download_url(content $content): string {
236 $downloadurl = '';
237 $file = $content->get_file();
238 if (!empty($file)) {
239 $url = \moodle_url::make_pluginfile_url(
240 $file->get_contextid(),
241 $file->get_component(),
242 $file->get_filearea(),
243 $file->get_itemid(),
244 $file->get_filepath(),
245 $file->get_filename()
247 $downloadurl = $url->out(false);
250 return $downloadurl;
254 * Returns the HTML code to render the icon for content bank contents.
256 * @param content $content The content to be displayed.
257 * @return string HTML code to render the icon
259 public function get_icon(content $content): string {
260 global $OUTPUT;
261 return $OUTPUT->image_url('f/unknown-64', 'moodle')->out(false);
265 * Returns user has access capability for the main content bank and the content itself (base on is_access_allowed from plugin).
267 * @return bool True if content could be accessed. False otherwise.
269 final public function can_access(): bool {
270 $classname = 'contenttype/'.$this->get_plugin_name();
271 $capability = $classname.":access";
272 $hascapabilities = has_capability('moodle/contentbank:access', $this->context)
273 && has_capability($capability, $this->context);
274 return $hascapabilities && $this->is_access_allowed();
278 * Returns user has access capability for the content itself.
280 * @return bool True if content could be accessed. False otherwise.
282 protected function is_access_allowed(): bool {
283 // Plugins can overwrite this function to add any check they need.
284 return true;
288 * Returns the user has permission to upload new content.
290 * @return bool True if content could be uploaded. False otherwise.
292 final public function can_upload(): bool {
293 if (!$this->is_feature_supported(self::CAN_UPLOAD)) {
294 return false;
296 if (!$this->can_access()) {
297 return false;
300 $classname = 'contenttype/'.$this->get_plugin_name();
301 $uploadcap = $classname.':upload';
302 $hascapabilities = has_capability('moodle/contentbank:upload', $this->context)
303 && has_capability($uploadcap, $this->context);
304 return $hascapabilities && $this->is_upload_allowed();
308 * Returns plugin allows uploading.
310 * @return bool True if plugin allows uploading. False otherwise.
312 protected function is_upload_allowed(): bool {
313 // Plugins can overwrite this function to add any check they need.
314 return true;
318 * Check if the user can delete this content.
320 * @param content $content The content to be deleted.
321 * @return bool True if content could be uploaded. False otherwise.
323 final public function can_delete(content $content): bool {
324 global $USER;
326 if ($this->context->id != $content->get_content()->contextid) {
327 // The content has to have exactly the same context as this contenttype.
328 return false;
331 $hascapability = has_capability('moodle/contentbank:deleteanycontent', $this->context);
332 if ($content->get_content()->usercreated == $USER->id) {
333 // This content has been created by the current user; check if she can delete her content.
334 $hascapability = $hascapability || has_capability('moodle/contentbank:deleteowncontent', $this->context);
337 return $hascapability && $this->is_delete_allowed($content);
341 * Returns if content allows deleting.
343 * @param content $content The content to be deleted.
344 * @return bool True if content allows uploading. False otherwise.
346 protected function is_delete_allowed(content $content): bool {
347 // Plugins can overwrite this function to add any check they need.
348 return true;
352 * Check if the user can managed this content.
354 * @param content $content The content to be managed.
355 * @return bool True if content could be managed. False otherwise.
357 public final function can_manage(content $content): bool {
358 global $USER;
360 if ($this->context->id != $content->get_content()->contextid) {
361 // The content has to have exactly the same context as this contenttype.
362 return false;
365 // Check main contentbank management permission.
366 $hascapability = has_capability('moodle/contentbank:manageanycontent', $this->context);
367 if ($content->get_content()->usercreated == $USER->id) {
368 // This content has been created by the current user; check if they can manage their content.
369 $hascapability = $hascapability || has_capability('moodle/contentbank:manageowncontent', $this->context);
372 return $hascapability && $this->is_manage_allowed($content);
376 * Returns if content allows managing.
378 * @param content $content The content to be managed.
379 * @return bool True if content allows uploading. False otherwise.
381 protected function is_manage_allowed(content $content): bool {
382 // Plugins can overwrite this function to add any check they need.
383 return true;
387 * Returns whether or not the user has permission to use the editor.
388 * This function will be called with the content to be edited as parameter,
389 * or null when is checking permission to create a new content using the editor.
391 * @param content $content The content to be edited or null when creating a new content.
392 * @return bool True if the user can edit content. False otherwise.
394 final public function can_edit(?content $content = null): bool {
395 if (!$this->is_feature_supported(self::CAN_EDIT)) {
396 return false;
399 if (!$this->can_access()) {
400 return false;
403 if (!is_null($content) && !$this->can_manage($content)) {
404 return false;
407 $classname = 'contenttype/'.$this->get_plugin_name();
409 $editioncap = $classname.':useeditor';
410 $hascapabilities = has_all_capabilities(['moodle/contentbank:useeditor', $editioncap], $this->context);
411 return $hascapabilities && $this->is_edit_allowed($content);
415 * Returns plugin allows edition.
417 * @param content $content The content to be edited.
418 * @return bool True if plugin allows edition. False otherwise.
420 protected function is_edit_allowed(?content $content): bool {
421 // Plugins can overwrite this function to add any check they need.
422 return true;
426 * Returns whether or not the user has permission to download the content.
428 * @since Moodle 3.10
429 * @param content $content The content to be downloaded.
430 * @return bool True if the user can download the content. False otherwise.
432 final public function can_download(content $content): bool {
433 if (!$this->is_feature_supported(self::CAN_DOWNLOAD)) {
434 return false;
437 if (!$this->can_access()) {
438 return false;
441 $hascapability = has_capability('moodle/contentbank:downloadcontent', $this->context);
442 return $hascapability && $this->is_download_allowed($content);
446 * Returns plugin allows downloading.
448 * @since Moodle 3.10
449 * @param content $content The content to be downloaed.
450 * @return bool True if plugin allows downloading. False otherwise.
452 protected function is_download_allowed(content $content): bool {
453 // Plugins can overwrite this function to add any check they need.
454 return true;
458 * Returns the plugin supports the feature.
460 * @param string $feature Feature code e.g CAN_UPLOAD
461 * @return bool True if content could be uploaded. False otherwise.
463 final public function is_feature_supported(string $feature): bool {
464 return in_array($feature, $this->get_implemented_features());
468 * Return an array of implemented features by the plugins.
470 * @return array
472 abstract protected function get_implemented_features(): array;
475 * Return an array of extensions the plugins could manage.
477 * @return array
479 abstract public function get_manageable_extensions(): array;
482 * Returns the list of different types of the given content type.
484 * A content type can have one or more options for creating content. This method will report all of them or only the content
485 * type itself if it has no other options.
487 * @return array An object for each type:
488 * - string typename: descriptive name of the type.
489 * - string typeeditorparams: params required by this content type editor.
490 * - url typeicon: this type icon.
492 abstract public function get_contenttype_types(): array;