Merge branch 'm25_MDL-40200_Notices_When_Viewing_Profile_Invalid_UserId' of https...
[moodle.git] / lib / portfoliolib.php
blob1b42e436a6405e95913724b5f4aa969495515391
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 * This file contains all global functions to do with manipulating portfolios.
20 * Everything else that is logically namespaced by class is in its own file
21 * in lib/portfolio/ directory.
23 * Major Contributors
24 * - Penny Leach <penny@catalyst.net.nz>
26 * @package core_portfolio
27 * @category portfolio
28 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
32 defined('MOODLE_INTERNAL') || die();
34 // require some of the sublibraries first.
35 // this is not an exhaustive list, the others are pulled in as they're needed
36 // so we don't have to always include everything unnecessarily for performance
38 // very lightweight list of constants. always needed and no further dependencies
39 require_once($CFG->libdir . '/portfolio/constants.php');
40 // a couple of exception deinitions. always needed and no further dependencies
41 require_once($CFG->libdir . '/portfolio/exceptions.php'); // exception classes used by portfolio code
42 // The base class for the caller classes. We always need this because we're either drawing a button,
43 // in which case the button needs to know the calling class definition, which requires the base class,
44 // or we're exporting, in which case we need the caller class anyway.
45 require_once($CFG->libdir . '/portfolio/caller.php');
47 // the other dependencies are included on demand:
48 // libdir/portfolio/formats.php - the classes for the export formats
49 // libdir/portfolio/forms.php - all portfolio form classes (requires formslib)
50 // libdir/portfolio/plugin.php - the base class for the export plugins
51 // libdir/portfolio/exporter.php - the exporter class
54 /**
55 * Use this to add a portfolio button or icon or form to a page.
57 * These class methods do not check permissions. the caller must check permissions first.
58 * Later, during the export process, the caller class is instantiated and the check_permissions method is called
59 * If you are exporting a single file, you should always call set_format_by_file($file)
60 * This class can be used like this:
61 * <code>
62 * $button = new portfolio_add_button();
63 * $button->set_callback_options('name_of_caller_class', array('id' => 6), 'yourcomponent'); eg. mod_forum
64 * $button->render(PORTFOLIO_ADD_FULL_FORM, get_string('addeverythingtoportfolio', 'yourcomponent'));
65 * </code>
66 * or like this:
67 * <code>
68 * $button = new portfolio_add_button(array('callbackclass' => 'name_of_caller_class', 'callbackargs' => array('id' => 6), 'callbackcomponent' => 'yourcomponent')); eg. mod_forum
69 * $somehtml .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
70 * </code>
71 *{@link http://docs.moodle.org/dev/Adding_a_Portfolio_Button_to_a_page} for more information
73 * @package core_portfolio
74 * @category portfolio
75 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
78 class portfolio_add_button {
80 /** @var string the name of the callback functions */
81 private $callbackclass;
83 /** @var array can be an array of arguments to pass back to the callback functions (passed by reference)*/
84 private $callbackargs;
86 /** @var string caller file */
87 private $callbackcomponent;
89 /** @var array array of more specific formats (eg based on mime detection) */
90 private $formats;
92 /** @var array array of portfolio instances */
93 private $instances;
95 /** @var stored_file for single-file exports */
96 private $file;
98 /** @var string for writing specific types of files*/
99 private $intendedmimetype;
102 * Constructor. Either pass the options here or set them using the helper methods.
103 * Generally the code will be clearer if you use the helper methods.
105 * @param array $options keyed array of options:
106 * key 'callbackclass': name of the caller class (eg forum_portfolio_caller')
107 * key 'callbackargs': the array of callback arguments your caller class wants passed to it in the constructor
108 * key 'callbackcomponent': the file containing the class definition of your caller class.
109 * See set_callback_options for more information on these three.
110 * key 'formats': an array of PORTFOLIO_FORMATS this caller will support
111 * See set_formats or set_format_by_file for more information on this.
113 public function __construct($options=null) {
114 global $SESSION, $CFG;
116 if (empty($CFG->enableportfolios)) {
117 debugging('Building portfolio add button while portfolios is disabled. This code can be optimised.', DEBUG_DEVELOPER);
120 $this->instances = portfolio_instances();
121 if (empty($options)) {
122 return true;
124 $constructoroptions = array('callbackclass', 'callbackargs', 'callbackcomponent');
125 foreach ((array)$options as $key => $value) {
126 if (!in_array($key, $constructoroptions)) {
127 throw new portfolio_button_exception('invalidbuttonproperty', 'portfolio', $key);
131 $this->set_callback_options($options['callbackclass'], $options['callbackargs'], $options['callbackcomponent']);
135 * Function to set the callback options
137 * @param string $class Name of the class containing the callback functions
138 * activity components should ALWAYS use their name_portfolio_caller
139 * other locations must use something unique
140 * @param array $argarray This can be an array or hash of arguments to pass
141 * back to the callback functions (passed by reference)
142 * these MUST be primatives to be added as hidden form fields.
143 * and the values get cleaned to PARAM_ALPHAEXT or PARAM_FLOAT or PARAM_PATH
144 * @param string $component This is the name of the component in Moodle, eg 'mod_forum'
146 public function set_callback_options($class, array $argarray, $component) {
147 global $CFG;
149 // Require the base class first before any other files.
150 require_once($CFG->libdir . '/portfolio/caller.php');
152 // Include any potential callback files and check for errors.
153 portfolio_include_callback_file($component, $class);
155 // This will throw exceptions but should not actually do anything other than verify callbackargs.
156 $test = new $class($argarray);
157 unset($test);
159 $this->callbackcomponent = $component;
160 $this->callbackclass = $class;
161 $this->callbackargs = $argarray;
165 * Sets the available export formats for this content.
166 * This function will also poll the static function in the caller class
167 * and make sure we're not overriding a format that has nothing to do with mimetypes.
168 * Eg: if you pass IMAGE here but the caller can export LEAP2A it will keep LEAP2A as well.
169 * @see portfolio_most_specific_formats for more information
170 * @see portfolio_format_from_mimetype
172 * @param array $formats if the calling code knows better than the static method on the calling class (base_supported_formats).
173 * Eg: if it's going to be a single file, or if you know it's HTML, you can pass it here instead.
174 * This is almost always the case so it should be use all the times
175 * portfolio_format_from_mimetype for how to get the appropriate formats to pass here for uploaded files.
176 * or just call set_format_by_file instead
178 public function set_formats($formats=null) {
179 if (is_string($formats)) {
180 $formats = array($formats);
182 if (empty($formats)) {
183 $formats = array();
185 if (empty($this->callbackclass)) {
186 throw new portfolio_button_exception('noclassbeforeformats', 'portfolio');
188 $callerformats = call_user_func(array($this->callbackclass, 'base_supported_formats'));
189 $this->formats = portfolio_most_specific_formats($formats, $callerformats);
193 * Reset formats to the default,
194 * which is usually what base_supported_formats returns
196 public function reset_formats() {
197 $this->set_formats();
202 * If we already know we have exactly one file,
203 * bypass set_formats and just pass the file
204 * so we can detect the formats by mimetype.
206 * @param stored_file $file file to set the format from
207 * @param array $extraformats any additional formats other than by mimetype
208 * eg leap2a etc
210 public function set_format_by_file(stored_file $file, $extraformats=null) {
211 $this->file = $file;
212 $fileformat = portfolio_format_from_mimetype($file->get_mimetype());
213 if (is_string($extraformats)) {
214 $extraformats = array($extraformats);
215 } else if (!is_array($extraformats)) {
216 $extraformats = array();
218 $this->set_formats(array_merge(array($fileformat), $extraformats));
222 * Correllary this is use to set_format_by_file, but it is also used when there is no stored_file and
223 * when we're writing out a new type of file (like csv or pdf)
225 * @param string $extn the file extension we intend to generate
226 * @param array $extraformats any additional formats other than by mimetype
227 * eg leap2a etc
229 public function set_format_by_intended_file($extn, $extraformats=null) {
230 $mimetype = mimeinfo('type', 'something. ' . $extn);
231 $fileformat = portfolio_format_from_mimetype($mimetype);
232 $this->intendedmimetype = $fileformat;
233 if (is_string($extraformats)) {
234 $extraformats = array($extraformats);
235 } else if (!is_array($extraformats)) {
236 $extraformats = array();
238 $this->set_formats(array_merge(array($fileformat), $extraformats));
242 * Echo the form/button/icon/text link to the page
244 * @param int $format format to display the button or form or icon or link.
245 * See constants PORTFOLIO_ADD_XXX for more info.
246 * optional, defaults to PORTFOLIO_ADD_FULL_FORM
247 * @param string $addstr string to use for the button or icon alt text or link text.
248 * this is whole string, not key. optional, defaults to 'Export to portfolio';
250 public function render($format=null, $addstr=null) {
251 echo $this->to_html($format, $addstr);
255 * Returns the form/button/icon/text link as html
257 * @param int $format format to display the button or form or icon or link.
258 * See constants PORTFOLIO_ADD_XXX for more info.
259 * Optional, defaults to PORTFOLIO_ADD_FULL_FORM
260 * @param string $addstr string to use for the button or icon alt text or link text.
261 * This is whole string, not key. optional, defaults to 'Add to portfolio';
262 * @return void|string
264 public function to_html($format=null, $addstr=null) {
265 global $CFG, $COURSE, $OUTPUT, $USER;
266 if (!$this->is_renderable()) {
267 return;
269 if (empty($this->callbackclass) || empty($this->callbackcomponent)) {
270 throw new portfolio_button_exception('mustsetcallbackoptions', 'portfolio');
272 if (empty($this->formats)) {
273 // use the caller defaults
274 $this->set_formats();
276 $url = new moodle_url('/portfolio/add.php');
277 foreach ($this->callbackargs as $key => $value) {
278 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
279 $a = new stdClass();
280 $a->key = $key;
281 $a->value = print_r($value, true);
282 debugging(get_string('nonprimative', 'portfolio', $a));
283 return;
285 $url->param('ca_' . $key, $value);
287 $url->param('sesskey', sesskey());
288 $url->param('callbackcomponent', $this->callbackcomponent);
289 $url->param('callbackclass', $this->callbackclass);
290 $url->param('course', (!empty($COURSE)) ? $COURSE->id : 0);
291 $url->param('callerformats', implode(',', $this->formats));
292 $mimetype = null;
293 if ($this->file instanceof stored_file) {
294 $mimetype = $this->file->get_mimetype();
295 } else if ($this->intendedmimetype) {
296 $mimetype = $this->intendedmimetype;
298 $selectoutput = '';
299 if (count($this->instances) == 1) {
300 $tmp = array_values($this->instances);
301 $instance = $tmp[0];
303 $formats = portfolio_supported_formats_intersect($this->formats, $instance->supported_formats());
304 if (count($formats) == 0) {
305 // bail. no common formats.
306 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $this->callbackclass, 'formats' => implode(',', $this->formats))));
307 return;
309 if ($error = portfolio_instance_sanity_check($instance)) {
310 // bail, plugin is misconfigured
311 //debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
312 return;
314 if (!$instance->allows_multiple_exports() && $already = portfolio_existing_exports($USER->id, $instance->get('plugin'))) {
315 //debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
316 return;
318 if ($mimetype&& !$instance->file_mime_check($mimetype)) {
319 // bail, we have a specific file or mimetype and this plugin doesn't support it
320 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype)));
321 return;
323 $url->param('instance', $instance->get('id'));
325 else {
326 if (!$selectoutput = portfolio_instance_select($this->instances, $this->formats, $this->callbackclass, $mimetype, 'instance', true)) {
327 return;
330 // if we just want a url to redirect to, do it now
331 if ($format == PORTFOLIO_ADD_FAKE_URL) {
332 return $url->out(false);
335 if (empty($addstr)) {
336 $addstr = get_string('addtoportfolio', 'portfolio');
338 if (empty($format)) {
339 $format = PORTFOLIO_ADD_FULL_FORM;
342 $formoutput = '<form method="post" action="' . $CFG->wwwroot . '/portfolio/add.php" id="portfolio-add-button">' . "\n";
343 $formoutput .= html_writer::input_hidden_params($url);
344 $linkoutput = '';
346 switch ($format) {
347 case PORTFOLIO_ADD_FULL_FORM:
348 $formoutput .= $selectoutput;
349 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
350 $formoutput .= "\n" . '</form>';
351 break;
352 case PORTFOLIO_ADD_ICON_FORM:
353 $formoutput .= $selectoutput;
354 $formoutput .= "\n" . '<input class="portfolio-add-icon" type="image" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt=' . $addstr .'" />';
355 $formoutput .= "\n" . '</form>';
356 break;
357 case PORTFOLIO_ADD_ICON_LINK:
358 $linkoutput = $OUTPUT->action_icon($url, new pix_icon('t/portfolioadd', $addstr, '',
359 array('class' => 'portfolio-add-icon smallicon')));
360 break;
361 case PORTFOLIO_ADD_TEXT_LINK:
362 $linkoutput = html_writer::link($url, $addstr, array('class' => 'portfolio-add-link',
363 'title' => $addstr));
364 break;
365 default:
366 debugging(get_string('invalidaddformat', 'portfolio', $format));
368 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
369 return $output;
373 * Perform some internal checks.
374 * These are not errors, just situations
375 * where it's not appropriate to add the button
377 * @return bool
379 private function is_renderable() {
380 global $CFG;
381 if (empty($CFG->enableportfolios)) {
382 return false;
384 if (defined('PORTFOLIO_INTERNAL')) {
385 // something somewhere has detected a risk of this being called during inside the preparation
386 // eg forum_print_attachments
387 return false;
389 if (empty($this->instances) || count($this->instances) == 0) {
390 return false;
392 return true;
396 * Getter for $format property
398 * @return array
400 public function get_formats() {
401 return $this->formats;
405 * Getter for $callbackargs property
407 * @return array
409 public function get_callbackargs() {
410 return $this->callbackargs;
414 * Getter for $callbackcomponent property
416 * @return string
418 public function get_callbackcomponent() {
419 return $this->callbackcomponent;
423 * Getter for $callbackclass property
425 * @return string
427 public function get_callbackclass() {
428 return $this->callbackclass;
433 * Returns a drop menu with a list of available instances.
435 * @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
436 * @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
437 * @param string $callbackclass the callback class name - used for debugging only for when there are no common formats
438 * @param string $mimetype if we already know we have exactly one file, or are going to write one, pass it here to do mime filtering.
439 * @param string $selectname the name of the select element. Optional, defaults to instance.
440 * @param bool $return whether to print or return the output. Optional, defaults to print.
441 * @param bool $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
442 * @return void|array|string the html, from <select> to </select> inclusive.
444 function portfolio_instance_select($instances, $callerformats, $callbackclass, $mimetype=null, $selectname='instance', $return=false, $returnarray=false) {
445 global $CFG, $USER;
447 if (empty($CFG->enableportfolios)) {
448 return;
451 $insane = portfolio_instance_sanity_check();
452 $pinsane = portfolio_plugin_sanity_check();
454 $count = 0;
455 $selectoutput = "\n" . '<label class="accesshide" for="instanceid">' . get_string('plugin', 'portfolio') . '</label>';
456 $selectoutput .= "\n" . '<select id="instanceid" name="' . $selectname . '">' . "\n";
457 $existingexports = portfolio_existing_exports_by_plugin($USER->id);
458 foreach ($instances as $instance) {
459 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
460 if (count($formats) == 0) {
461 // bail. no common formats.
462 continue;
464 if (array_key_exists($instance->get('id'), $insane)) {
465 // bail, plugin is misconfigured
466 //debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
467 continue;
468 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
469 // bail, plugin is misconfigured
470 //debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
471 continue;
473 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
474 // bail, already exporting something with this plugin and it doesn't support multiple exports
475 continue;
477 if ($mimetype && !$instance->file_mime_check($mimetype)) {
478 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype())));
479 // bail, we have a specific file and this plugin doesn't support it
480 continue;
482 $count++;
483 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
484 $options[$instance->get('id')] = $instance->get('name');
486 if (empty($count)) {
487 // bail. no common formats.
488 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
489 return;
491 $selectoutput .= "\n" . "</select>\n";
492 if (!empty($returnarray)) {
493 return $options;
495 if (!empty($return)) {
496 return $selectoutput;
498 echo $selectoutput;
502 * Return all portfolio instances
504 * @todo MDL-15768 - check capabilities here
505 * @param bool $visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
506 * @param bool $useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
507 * @return array of portfolio instances (full objects, not just database records)
509 function portfolio_instances($visibleonly=true, $useronly=true) {
511 global $DB, $USER;
513 $values = array();
514 $sql = 'SELECT * FROM {portfolio_instance}';
516 if ($visibleonly || $useronly) {
517 $values[] = 1;
518 $sql .= ' WHERE visible = ?';
520 if ($useronly) {
521 $sql .= ' AND id NOT IN (
522 SELECT instance FROM {portfolio_instance_user}
523 WHERE userid = ? AND name = ? AND ' . $DB->sql_compare_text('value') . ' = ?
525 $values = array_merge($values, array($USER->id, 'visible', 0));
527 $sql .= ' ORDER BY name';
529 $instances = array();
530 foreach ($DB->get_records_sql($sql, $values) as $instance) {
531 $instances[$instance->id] = portfolio_instance($instance->id, $instance);
533 return $instances;
537 * Supported formats currently in use.
538 * Canonical place for a list of all formats
539 * that portfolio plugins and callers
540 * can use for exporting content
542 * @return array keyed array of all the available export formats (constant => classname)
544 function portfolio_supported_formats() {
545 return array(
546 PORTFOLIO_FORMAT_FILE => 'portfolio_format_file',
547 PORTFOLIO_FORMAT_IMAGE => 'portfolio_format_image',
548 PORTFOLIO_FORMAT_RICHHTML => 'portfolio_format_richhtml',
549 PORTFOLIO_FORMAT_PLAINHTML => 'portfolio_format_plainhtml',
550 PORTFOLIO_FORMAT_TEXT => 'portfolio_format_text',
551 PORTFOLIO_FORMAT_VIDEO => 'portfolio_format_video',
552 PORTFOLIO_FORMAT_PDF => 'portfolio_format_pdf',
553 PORTFOLIO_FORMAT_DOCUMENT => 'portfolio_format_document',
554 PORTFOLIO_FORMAT_SPREADSHEET => 'portfolio_format_spreadsheet',
555 PORTFOLIO_FORMAT_PRESENTATION => 'portfolio_format_presentation',
556 /*PORTFOLIO_FORMAT_MBKP, */ // later
557 PORTFOLIO_FORMAT_LEAP2A => 'portfolio_format_leap2a',
558 PORTFOLIO_FORMAT_RICH => 'portfolio_format_rich',
563 * Deduce export format from file mimetype
564 * This function returns the revelant portfolio export format
565 * which is used to determine which portfolio plugins can be used
566 * for exporting this content
567 * according to the given mime type
568 * this only works when exporting exactly <b>one</b> file, or generating a new one
569 * (like a pdf or csv export)
571 * @param string $mimetype (usually $file->get_mimetype())
572 * @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
574 function portfolio_format_from_mimetype($mimetype) {
575 global $CFG;
576 static $alreadymatched;
577 if (empty($alreadymatched)) {
578 $alreadymatched = array();
580 if (array_key_exists($mimetype, $alreadymatched)) {
581 return $alreadymatched[$mimetype];
583 $allformats = portfolio_supported_formats();
584 require_once($CFG->libdir . '/portfolio/formats.php');
585 foreach ($allformats as $format => $classname) {
586 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
587 if (!is_array($supportedmimetypes)) {
588 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
589 debugging(print_r($supportedmimetypes, true));
590 continue;
592 if (in_array($mimetype, $supportedmimetypes)) {
593 $alreadymatched[$mimetype] = $format;
594 return $format;
597 return PORTFOLIO_FORMAT_FILE; // base case for files...
601 * Intersection of plugin formats and caller formats.
602 * Walks both the caller formats and portfolio plugin formats
603 * and looks for matches (walking the hierarchy as well)
604 * and returns the intersection
606 * @param array $callerformats formats the caller supports
607 * @param array $pluginformats formats the portfolio plugin supports
608 * @return array
610 function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
611 global $CFG;
612 $allformats = portfolio_supported_formats();
613 $intersection = array();
614 foreach ($callerformats as $cf) {
615 if (!array_key_exists($cf, $allformats)) {
616 if (!portfolio_format_is_abstract($cf)) {
617 debugging(get_string('invalidformat', 'portfolio', $cf));
619 continue;
621 require_once($CFG->libdir . '/portfolio/formats.php');
622 $cfobj = new $allformats[$cf]();
623 foreach ($pluginformats as $p => $pf) {
624 if (!array_key_exists($pf, $allformats)) {
625 if (!portfolio_format_is_abstract($pf)) {
626 debugging(get_string('invalidformat', 'portfolio', $pf));
628 unset($pluginformats[$p]); // to avoid the same warning over and over
629 continue;
631 if ($cfobj instanceof $allformats[$pf]) {
632 $intersection[] = $cf;
636 return $intersection;
640 * Tiny helper to figure out whether a portfolio format is abstract
642 * @param string $format the format to test
643 * @return bool
645 function portfolio_format_is_abstract($format) {
646 if (class_exists($format)) {
647 $class = $format;
648 } else if (class_exists('portfolio_format_' . $format)) {
649 $class = 'portfolio_format_' . $format;
650 } else {
651 $allformats = portfolio_supported_formats();
652 if (array_key_exists($format, $allformats)) {
653 $class = $allformats[$format];
656 if (empty($class)) {
657 return true; // it may as well be, we can't instantiate it :)
659 $rc = new ReflectionClass($class);
660 return $rc->isAbstract();
664 * Return the combination of the two arrays of formats with duplicates in terms of specificity removed
665 * and also removes conflicting formats.
666 * Use case: a module is exporting a single file, so the general formats would be FILE and MBKP
667 * while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
668 * and this function would return IMAGE and MBKP
670 * @param array $specificformats array of more specific formats (eg based on mime detection)
671 * @param array $generalformats array of more general formats (usually more supported)
672 * @return array merged formats with dups removed
674 function portfolio_most_specific_formats($specificformats, $generalformats) {
675 global $CFG;
676 $allformats = portfolio_supported_formats();
677 if (empty($specificformats)) {
678 return $generalformats;
679 } else if (empty($generalformats)) {
680 return $specificformats;
682 $removedformats = array();
683 foreach ($specificformats as $k => $f) {
684 // look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
685 if (!array_key_exists($f, $allformats)) {
686 if (!portfolio_format_is_abstract($f)) {
687 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
690 if (in_array($f, $removedformats)) {
691 // already been removed from the general list
692 //debugging("skipping $f because it was already removed");
693 unset($specificformats[$k]);
695 require_once($CFG->libdir . '/portfolio/formats.php');
696 $fobj = new $allformats[$f];
697 foreach ($generalformats as $key => $cf) {
698 if (in_array($cf, $removedformats)) {
699 //debugging("skipping $cf because it was already removed");
700 continue;
702 $cfclass = $allformats[$cf];
703 $cfobj = new $allformats[$cf];
704 if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
705 //debugging("unsetting $key $cf because it's not specific enough ($f is better)");
706 unset($generalformats[$key]);
707 $removedformats[] = $cf;
708 continue;
710 // check for conflicts
711 if ($fobj->conflicts($cf)) {
712 //debugging("unsetting $key $cf because it conflicts with $f");
713 unset($generalformats[$key]);
714 $removedformats[] = $cf;
715 continue;
717 if ($cfobj->conflicts($f)) {
718 //debugging("unsetting $key $cf because it reverse-conflicts with $f");
719 $removedformats[] = $cf;
720 unset($generalformats[$key]);
721 continue;
724 //debugging('inside loop');
725 //print_object($generalformats);
728 //debugging('final formats');
729 $finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
730 //print_object($finalformats);
731 return $finalformats;
735 * Helper function to return a format object from the constant
737 * @param string $name the constant PORTFOLIO_FORMAT_XXX
738 * @return portfolio_format
740 function portfolio_format_object($name) {
741 global $CFG;
742 require_once($CFG->libdir . '/portfolio/formats.php');
743 $formats = portfolio_supported_formats();
744 return new $formats[$name];
748 * Helper function to return an instance of a plugin (with config loaded)
750 * @param int $instanceid id of instance
751 * @param object $record database row that corresponds to this instance
752 * this is passed to avoid unnecessary lookups
753 * Optional, and the record will be retrieved if null.
754 * @return object of portfolio_plugin_XXX
756 function portfolio_instance($instanceid, $record=null) {
757 global $DB, $CFG;
759 if ($record) {
760 $instance = $record;
761 } else {
762 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
763 throw new portfolio_exception('invalidinstance', 'portfolio');
766 require_once($CFG->libdir . '/portfolio/plugin.php');
767 require_once($CFG->dirroot . '/portfolio/'. $instance->plugin . '/lib.php');
768 $classname = 'portfolio_plugin_' . $instance->plugin;
769 return new $classname($instanceid, $instance);
773 * Helper function to call a static function on a portfolio plugin class.
774 * This will figure out the classname and require the right file and call the function.
775 * You can send a variable number of arguments to this function after the first two
776 * and they will be passed on to the function you wish to call.
778 * @param string $plugin name of plugin
779 * @param string $function function to call
780 * @return mixed
782 function portfolio_static_function($plugin, $function) {
783 global $CFG;
785 $pname = null;
786 if (is_object($plugin) || is_array($plugin)) {
787 $plugin = (object)$plugin;
788 $pname = $plugin->name;
789 } else {
790 $pname = $plugin;
793 $args = func_get_args();
794 if (count($args) <= 2) {
795 $args = array();
797 else {
798 array_shift($args);
799 array_shift($args);
802 require_once($CFG->libdir . '/portfolio/plugin.php');
803 require_once($CFG->dirroot . '/portfolio/' . $plugin . '/lib.php');
804 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
808 * Helper function to check all the plugins for sanity and set any insane ones to invisible.
810 * @param array $plugins array of supported plugin types
811 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
813 function portfolio_plugin_sanity_check($plugins=null) {
814 global $DB;
815 if (is_string($plugins)) {
816 $plugins = array($plugins);
817 } else if (empty($plugins)) {
818 $plugins = get_plugin_list('portfolio');
819 $plugins = array_keys($plugins);
822 $insane = array();
823 foreach ($plugins as $plugin) {
824 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
825 $insane[$plugin] = $result;
828 if (empty($insane)) {
829 return array();
831 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
832 $where = ' plugin ' . $where;
833 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
834 return $insane;
838 * Helper function to check all the instances for sanity and set any insane ones to invisible.
840 * @param array $instances array of plugin instances
841 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
843 function portfolio_instance_sanity_check($instances=null) {
844 global $DB;
845 if (empty($instances)) {
846 $instances = portfolio_instances(false);
847 } else if (!is_array($instances)) {
848 $instances = array($instances);
851 $insane = array();
852 foreach ($instances as $instance) {
853 if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) {
854 $instance = portfolio_instance($instance->id, $instance);
855 } else if (is_numeric($instance)) {
856 $instance = portfolio_instance($instance);
858 if (!($instance instanceof portfolio_plugin_base)) {
859 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
860 continue;
862 if ($result = $instance->instance_sanity_check()) {
863 $insane[$instance->get('id')] = $result;
866 if (empty($insane)) {
867 return array();
869 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
870 $where = ' id ' . $where;
871 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
872 portfolio_insane_notify_admins($insane, true);
873 return $insane;
877 * Helper function to display a table of plugins (or instances) and reasons for disabling
879 * @param array $insane array of portfolio plugin
880 * @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
881 * @param bool $return option to deliver the report in html format or print it out directly to the page.
882 * @return void|string of portfolio report in html table format
884 function portfolio_report_insane($insane, $instances=false, $return=false) {
885 global $OUTPUT;
886 if (empty($insane)) {
887 return;
890 static $pluginstr;
891 if (empty($pluginstr)) {
892 $pluginstr = get_string('plugin', 'portfolio');
894 if ($instances) {
895 $headerstr = get_string('someinstancesdisabled', 'portfolio');
896 } else {
897 $headerstr = get_string('somepluginsdisabled', 'portfolio');
900 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
901 $table = new html_table();
902 $table->head = array($pluginstr, '');
903 $table->data = array();
904 foreach ($insane as $plugin => $reason) {
905 if ($instances) {
906 $instance = $instances[$plugin];
907 $plugin = $instance->get('plugin');
908 $name = $instance->get('name');
909 } else {
910 $name = $plugin;
912 $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
914 $output .= html_writer::table($table);
915 $output .= '<br /><br /><br />';
917 if ($return) {
918 return $output;
920 echo $output;
925 * Event handler for the portfolio_send event
927 * @param int $eventdata event id
928 * @return bool
930 function portfolio_handle_event($eventdata) {
931 global $CFG;
933 require_once($CFG->libdir . '/portfolio/exporter.php');
934 $exporter = portfolio_exporter::rewaken_object($eventdata);
935 $exporter->process_stage_package();
936 $exporter->process_stage_send();
937 $exporter->save();
938 $exporter->process_stage_cleanup();
939 return true;
943 * Main portfolio cronjob.
944 * Currently just cleans up expired transfer records.
946 * @todo - MDL-15997 - Add hooks in the plugins - either per instance or per plugin
948 function portfolio_cron() {
949 global $DB, $CFG;
951 require_once($CFG->libdir . '/portfolio/exporter.php');
952 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()), '', 'id')) {
953 foreach ($expired as $d) {
954 try {
955 $e = portfolio_exporter::rewaken_object($d->id);
956 $e->process_stage_cleanup(true);
957 } catch (Exception $e) {
958 mtrace('Exception thrown in portfolio cron while cleaning up ' . $d->id . ': ' . $e->getMessage());
965 * Helper function to rethrow a caught portfolio_exception as an export exception.
966 * Used because when a portfolio_export exception is thrown the export is cancelled
967 * throws portfolio_export_exceptiog
969 * @param portfolio_exporter $exporter current exporter object
970 * @param object $exception exception to rethrow
972 function portfolio_export_rethrow_exception($exporter, $exception) {
973 throw new portfolio_export_exception($exporter, $exception->errorcode, $exception->module, $exception->link, $exception->a);
977 * Try and determine expected_time for purely file based exports
978 * or exports that might include large file attachments.
980 * @param stored_file|array $totest - either an array of stored_file objects or a single stored_file object
981 * @return string PORTFOLIO_TIME_XXX
983 function portfolio_expected_time_file($totest) {
984 global $CFG;
985 if ($totest instanceof stored_file) {
986 $totest = array($totest);
988 $size = 0;
989 foreach ($totest as $file) {
990 if (!($file instanceof stored_file)) {
991 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
992 debugging(print_r($file, true));
993 continue;
995 $size += $file->get_filesize();
998 $fileinfo = portfolio_filesize_info();
1000 $moderate = $high = 0; // avoid warnings
1002 foreach (array('moderate', 'high') as $setting) {
1003 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
1004 if (empty($CFG->{$settingname}) || !array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
1005 debugging("weird or unset admin value for $settingname, using default instead");
1006 $$setting = $fileinfo[$setting];
1007 } else {
1008 $$setting = $CFG->{$settingname};
1012 if ($size < $moderate) {
1013 return PORTFOLIO_TIME_LOW;
1014 } else if ($size < $high) {
1015 return PORTFOLIO_TIME_MODERATE;
1017 return PORTFOLIO_TIME_HIGH;
1022 * The default filesizes and threshold information for file based transfers.
1023 * This shouldn't need to be used outside the admin pages and the portfolio code
1025 * @return array
1027 function portfolio_filesize_info() {
1028 $filesizes = array();
1029 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
1030 foreach ($sizelist as $size) {
1031 $filesizes[$size] = display_size($size);
1033 return array(
1034 'options' => $filesizes,
1035 'moderate' => 1048576,
1036 'high' => 5242880,
1041 * Try and determine expected_time for purely database based exports
1042 * or exports that might include large parts of a database.
1044 * @param int $recordcount number of records trying to export
1045 * @return string PORTFOLIO_TIME_XXX
1047 function portfolio_expected_time_db($recordcount) {
1048 global $CFG;
1050 if (empty($CFG->portfolio_moderate_dbsize_threshold)) {
1051 set_config('portfolio_moderate_dbsize_threshold', 10);
1053 if (empty($CFG->portfolio_high_dbsize_threshold)) {
1054 set_config('portfolio_high_dbsize_threshold', 50);
1056 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold) {
1057 return PORTFOLIO_TIME_LOW;
1058 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold) {
1059 return PORTFOLIO_TIME_MODERATE;
1061 return PORTFOLIO_TIME_HIGH;
1065 * Function to send portfolio report to admins
1067 * @param array $insane array of insane plugins
1068 * @param array $instances (optional) if reporting instances rather than whole plugins
1070 function portfolio_insane_notify_admins($insane, $instances=false) {
1072 global $CFG;
1074 if (defined('ADMIN_EDITING_PORTFOLIO')) {
1075 return true;
1078 $admins = get_admins();
1080 if (empty($admins)) {
1081 return;
1083 if ($instances) {
1084 $instances = portfolio_instances(false, false);
1087 $site = get_site();
1089 $a = new StdClass;
1090 $a->sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID)));
1091 $a->fixurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
1092 $a->htmllist = portfolio_report_insane($insane, $instances, true);
1093 $a->textlist = '';
1095 foreach ($insane as $k => $reason) {
1096 if ($instances) {
1097 $a->textlist = $instances[$k]->get('name') . ': ' . $reason . "\n";
1098 } else {
1099 $a->textlist = $k . ': ' . $reason . "\n";
1103 $subject = get_string('insanesubject', 'portfolio');
1104 $plainbody = get_string('insanebody', 'portfolio', $a);
1105 $htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
1106 $smallbody = get_string('insanebodysmall', 'portfolio', $a);
1108 foreach ($admins as $admin) {
1109 $eventdata = new stdClass();
1110 $eventdata->modulename = 'portfolio';
1111 $eventdata->component = 'portfolio';
1112 $eventdata->name = 'notices';
1113 $eventdata->userfrom = get_admin();
1114 $eventdata->userto = $admin;
1115 $eventdata->subject = $subject;
1116 $eventdata->fullmessage = $plainbody;
1117 $eventdata->fullmessageformat = FORMAT_PLAIN;
1118 $eventdata->fullmessagehtml = $htmlbody;
1119 $eventdata->smallmessage = $smallbody;
1120 message_send($eventdata);
1125 * Setup page export
1127 * @param moodle_page $PAGE global variable from page object
1128 * @param portfolio_caller_base $caller plugin type caller
1130 function portfolio_export_pagesetup($PAGE, $caller) {
1131 // set up the context so that build_navigation works nice
1132 $caller->set_context($PAGE);
1134 list($extranav, $cm) = $caller->get_navigation();
1136 // and now we know the course for sure and maybe the cm, call require_login with it
1137 require_login($PAGE->course, false, $cm);
1139 foreach ($extranav as $navitem) {
1140 $PAGE->navbar->add($navitem['name']);
1142 $PAGE->navbar->add(get_string('exporting', 'portfolio'));
1146 * Get export type id
1148 * @param string $type plugin type
1149 * @param int $userid the user to check for
1150 * @return mixed|bool
1152 function portfolio_export_type_to_id($type, $userid) {
1153 global $DB;
1154 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1155 return $DB->get_field_sql($sql, array($userid, $type));
1159 * Return a list of current exports for the given user.
1160 * This will not go through and call rewaken_object, because it's heavy.
1161 * It's really just used to figure out what exports are currently happening.
1162 * This is useful for plugins that don't support multiple exports per session
1164 * @param int $userid the user to check for
1165 * @param string $type (optional) the portfolio plugin to filter by
1166 * @return array
1168 function portfolio_existing_exports($userid, $type=null) {
1169 global $DB;
1170 $sql = 'SELECT t.*,t.instance,i.plugin,i.name FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1171 $values = array($userid);
1172 if ($type) {
1173 $sql .= ' AND i.plugin = ?';
1174 $values[] = $type;
1176 return $DB->get_records_sql($sql, $values);
1180 * Return an array of existing exports by type for a given user.
1181 * This is much more lightweight than existing_exports because it only returns the types, rather than the whole serialised data
1182 * so can be used for checking availability of multiple plugins at the same time.
1183 * @see existing_exports
1185 * @param int $userid the user to check for
1186 * @return array
1188 function portfolio_existing_exports_by_plugin($userid) {
1189 global $DB;
1190 $sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1191 $values = array($userid);
1192 return $DB->get_records_sql_menu($sql, $values);
1196 * Return default common options for {@link format_text()} when preparing a content to be exported.
1197 * It is important not to apply filters and not to clean the HTML in format_text()
1199 * @return stdClass
1201 function portfolio_format_text_options() {
1203 $options = new stdClass();
1204 $options->para = false;
1205 $options->newlines = true;
1206 $options->filter = false;
1207 $options->noclean = true;
1208 $options->overflowdiv = false;
1210 return $options;
1214 * callback function from {@link portfolio_rewrite_pluginfile_urls}
1215 * looks through preg_replace matches and replaces content with whatever the active portfolio export format says
1217 * @param int $contextid module context id
1218 * @param string $component module name (eg:mod_assignment)
1219 * @param string $filearea normal file_area arguments
1220 * @param int $itemid component item id
1221 * @param portfolio_format $format exporter format type
1222 * @param array $options extra options to pass through to the file_output function in the format (optional)
1223 * @param array $matches internal matching
1224 * @return object|array|string
1226 function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
1227 $matches = $matches[0]; // no internal matching
1228 $dom = new DomDocument();
1229 if (!$dom->loadXML($matches)) {
1230 return $matches;
1232 $attributes = array();
1233 foreach ($dom->documentElement->attributes as $attr => $node) {
1234 $attributes[$attr] = $node->value;
1236 // now figure out the file
1237 $fs = get_file_storage();
1238 $key = 'href';
1239 if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
1240 $key = 'src';
1242 if (!array_key_exists($key, $attributes)) {
1243 debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
1244 return $matches;
1246 $filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') + strlen('@@PLUGINFILE@@'));
1247 $filepath = '/';
1248 if (strpos($filename, '/') !== 0) {
1249 $bits = explode('/', $filename);
1250 $filename = array_pop($bits);
1251 $filepath = implode('/', $bits);
1253 if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, urldecode($filename))) {
1254 debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
1255 return $matches;
1257 if (empty($options)) {
1258 $options = array();
1260 $options['attributes'] = $attributes;
1261 return $format->file_output($file, $options);
1265 * Function to require any potential callback files, throwing exceptions
1266 * if an issue occurs.
1268 * @param string $component This is the name of the component in Moodle, eg 'mod_forum'
1269 * @param string $class Name of the class containing the callback functions
1270 * activity components should ALWAYS use their name_portfolio_caller
1271 * other locations must use something unique
1273 function portfolio_include_callback_file($component, $class = null) {
1274 global $CFG;
1275 require_once($CFG->libdir . '/adminlib.php');
1277 // It's possible that they are passing a file path rather than passing a component.
1278 // We want to try and convert this to a component name, eg. mod_forum.
1279 $pos = strrpos($component, '/');
1280 if ($pos !== false) {
1281 // Get rid of the first slash (if it exists).
1282 $component = ltrim($component, '/');
1283 // Get a list of valid plugin types.
1284 $plugintypes = get_plugin_types(false);
1285 // Assume it is not valid for now.
1286 $isvalid = false;
1287 // Go through the plugin types.
1288 foreach ($plugintypes as $type => $path) {
1289 if (strrpos($component, $path) === 0) {
1290 // Found the plugin type.
1291 $isvalid = true;
1292 $plugintype = $type;
1293 $pluginpath = $path;
1296 // Throw exception if not a valid component.
1297 if (!$isvalid) {
1298 throw new coding_exception('Somehow a non-valid plugin path was passed, could be a hackz0r attempt, exiting.');
1300 // Remove the file name.
1301 $component = trim(substr($component, 0, $pos), '/');
1302 // Replace the path with the type.
1303 $component = str_replace($pluginpath, $plugintype, $component);
1304 // Ok, replace '/' with '_'.
1305 $component = str_replace('/', '_', $component);
1306 // Place a debug message saying the third parameter should be changed.
1307 debugging('The third parameter sent to the function set_callback_options should be the component name, not a file path, please update this.', DEBUG_DEVELOPER);
1310 // Check that it is a valid component.
1311 if (!get_component_version($component)) {
1312 throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
1315 // Obtain the component's location.
1316 if (!$componentloc = get_component_directory($component)) {
1317 throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
1320 // Check if the component contains the necessary file for the portfolio plugin.
1321 // These are locallib.php, portfoliolib.php and portfolio_callback.php.
1322 $filefound = false;
1323 if (file_exists($componentloc . '/locallib.php')) {
1324 $filefound = true;
1325 require_once($componentloc . '/locallib.php');
1327 if (file_exists($componentloc . '/portfoliolib.php')) {
1328 $filefound = true;
1329 debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
1330 require_once($componentloc . '/portfoliolib.php');
1332 if (file_exists($componentloc . '/portfolio_callback.php')) {
1333 $filefound = true;
1334 debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
1335 require_once($componentloc . '/portfolio_callback.php');
1338 // Ensure that we found a file we can use, if not throw an exception.
1339 if (!$filefound) {
1340 throw new portfolio_button_exception('nocallbackfile', 'portfolio', '', $component);
1343 if (!is_null($class) && !class_exists($class)) {
1344 throw new portfolio_button_exception('nocallbackclass', 'portfolio', '', $class);
1349 * Go through all the @@PLUGINFILE@@ matches in some text,
1350 * extract the file information and pass it back to the portfolio export format
1351 * to regenerate the html to output
1353 * @param string $text the text to search through
1354 * @param int $contextid normal file_area arguments
1355 * @param string $component module name
1356 * @param string $filearea normal file_area arguments
1357 * @param int $itemid normal file_area arguments
1358 * @param portfolio_format $format the portfolio export format
1359 * @param array $options additional options to be included in the plugin file url (optional)
1360 * @return mixed
1362 function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
1363 $pattern = '/(<[^<]*?="@@PLUGINFILE@@\/[^>]*?(?:\/>|>.*?<\/[^>]*?>))/';
1364 $callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
1365 return preg_replace_callback($pattern, $callback, $text);
1367 // this function has to go last, because the regexp screws up syntax highlighting in some editors