MDL-32102 Course completion - bump to 2011070105.08 (07 was already in use)
[moodle.git] / lib / portfoliolib.php
blob22f4544c4f4efccdb9aaa0a322024909a002c2c5
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * 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
27 * @subpackage 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)
61 * This class can be used like this:
62 * <code>
63 * $button = new portfolio_add_button();
64 * $button->set_callback_options('name_of_caller_class', array('id' => 6), '/your/mod/lib.php');
65 * $button->render(PORTFOLIO_ADD_FULL_FORM, get_string('addeverythingtoportfolio', 'yourmodule'));
66 * </code>
68 * or like this:
69 * <code>
70 * $button = new portfolio_add_button(array('callbackclass' => 'name_of_caller_class', 'callbackargs' => array('id' => 6), 'callbackfile' => '/your/mod/lib.php'));
71 * $somehtml .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
72 * </code>
74 * See {@link http://docs.moodle.org/dev/Adding_a_Portfolio_Button_to_a_page} for more information
76 * @package moodlecore
77 * @subpackage portfolio
78 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
79 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
81 class portfolio_add_button {
83 private $callbackclass;
84 private $callbackargs;
85 private $callbackfile;
86 private $formats;
87 private $instances;
88 private $file; // for single-file exports
89 private $intendedmimetype; // for writing specific types of files
91 /**
92 * constructor. either pass the options here or set them using the helper methods.
93 * generally the code will be clearer if you use the helper methods.
95 * @param array $options keyed array of options:
96 * key 'callbackclass': name of the caller class (eg forum_portfolio_caller')
97 * key 'callbackargs': the array of callback arguments your caller class wants passed to it in the constructor
98 * key 'callbackfile': the file containing the class definition of your caller class.
99 * See set_callback_options for more information on these three.
100 * key 'formats': an array of PORTFOLIO_FORMATS this caller will support
101 * See set_formats or set_format_by_file for more information on this.
103 public function __construct($options=null) {
104 global $SESSION, $CFG;
106 if (empty($CFG->enableportfolios)) {
107 debugging('Building portfolio add button while portfolios is disabled. This code can be optimised.', DEBUG_DEVELOPER);
110 $this->instances = portfolio_instances();
111 if (empty($options)) {
112 return true;
114 $constructoroptions = array('callbackclass', 'callbackargs', 'callbackfile', 'formats');
115 foreach ((array)$options as $key => $value) {
116 if (!in_array($key, $constructoroptions)) {
117 throw new portfolio_button_exception('invalidbuttonproperty', 'portfolio', $key);
119 $this->{$key} = $value;
124 * @param string $class name of the class containing the callback functions
125 * activity modules should ALWAYS use their name_portfolio_caller
126 * other locations must use something unique
127 * @param mixed $argarray this can be an array or hash of arguments to pass
128 * back to the callback functions (passed by reference)
129 * these MUST be primatives to be added as hidden form fields.
130 * and the values get cleaned to PARAM_ALPHAEXT or PARAM_NUMBER or PARAM_PATH
131 * @param string $file this can be autodetected if it's in the same file as your caller,
132 * but often, the caller is a script.php and the class in a lib.php
133 * so you can pass it here if necessary.
134 * this path should be relative (ie, not include) dirroot, eg '/mod/forum/lib.php'
136 public function set_callback_options($class, array $argarray, $file=null) {
137 global $CFG;
138 if (empty($file)) {
139 $backtrace = debug_backtrace();
140 if (!array_key_exists(0, $backtrace) || !array_key_exists('file', $backtrace[0]) || !is_readable($backtrace[0]['file'])) {
141 throw new portfolio_button_exception('nocallbackfile', 'portfolio');
144 $file = substr($backtrace[0]['file'], strlen($CFG->dirroot));
145 } else if (!is_readable($CFG->dirroot . $file)) {
146 throw new portfolio_button_exception('nocallbackfile', 'portfolio', '', $file);
148 $this->callbackfile = $file;
149 require_once($CFG->libdir . '/portfolio/caller.php'); // require the base class first
150 require_once($CFG->dirroot . $file);
151 if (!class_exists($class)) {
152 throw new portfolio_button_exception('nocallbackclass', 'portfolio', '', $class);
155 // this will throw exceptions
156 // but should not actually do anything other than verify callbackargs
157 $test = new $class($argarray);
158 unset($test);
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
171 * @param array $formats if the calling code knows better than the static method on the calling class (base_supported_formats)
172 * eg, if it's going to be a single file, or if you know it's HTML, you can pass it here instead
173 * this is almost always the case so you should always use this.
174 * {@see portfolio_format_from_mimetype} for how to get the appropriate formats to pass here for uploaded files.
175 * or just call set_format_by_file instead
177 public function set_formats($formats=null) {
178 if (is_string($formats)) {
179 $formats = array($formats);
181 if (empty($formats)) {
182 $formats = array();
184 if (empty($this->callbackclass)) {
185 throw new portfolio_button_exception('noclassbeforeformats', 'portfolio');
187 $callerformats = call_user_func(array($this->callbackclass, 'base_supported_formats'));
188 $this->formats = portfolio_most_specific_formats($formats, $callerformats);
192 * reset formats to the default
193 * which is usually what base_supported_formats returns
195 public function reset_formats() {
196 $this->set_formats();
201 * if we already know we have exactly one file,
202 * bypass set_formats and just pass the file
203 * so we can detect the formats by mimetype.
205 * @param stored_file $file file to set the format from
206 * @param mixed $extraformats any additional formats other than by mimetype
207 * eg leap2a etc
209 public function set_format_by_file(stored_file $file, $extraformats=null) {
210 $this->file = $file;
211 $fileformat = portfolio_format_from_mimetype($file->get_mimetype());
212 if (is_string($extraformats)) {
213 $extraformats = array($extraformats);
214 } else if (!is_array($extraformats)) {
215 $extraformats = array();
217 $this->set_formats(array_merge(array($fileformat), $extraformats));
221 * correllary to set_format_by_file, but this is used when we don't yet have a stored_file
222 * when we're writing out a new type of file (like csv or pdf)
224 * @param string $extn the file extension we intend to generate
225 * @param mixed $extraformats any additional formats other than by mimetype
226 * eg leap2a etc
228 public function set_format_by_intended_file($extn, $extraformats=null) {
229 $mimetype = mimeinfo('type', 'something. ' . $extn);
230 $fileformat = portfolio_format_from_mimetype($mimetype);
231 $this->intendedmimetype = $fileformat;
232 if (is_string($extraformats)) {
233 $extraformats = array($extraformats);
234 } else if (!is_array($extraformats)) {
235 $extraformats = array();
237 $this->set_formats(array_merge(array($fileformat), $extraformats));
241 * echo the form/button/icon/text link to the page
243 * @param int $format format to display the button or form or icon or link.
244 * See constants PORTFOLIO_ADD_XXX for more info.
245 * optional, defaults to PORTFOLIO_ADD_FULL_FORM
246 * @param str $addstr string to use for the button or icon alt text or link text.
247 * this is whole string, not key. optional, defaults to 'Export to portfolio';
249 public function render($format=null, $addstr=null) {
250 echo $this->to_html($format, $addstr);
254 * returns the form/button/icon/text link as html
256 * @param int $format format to display the button or form or icon or link.
257 * See constants PORTFOLIO_ADD_XXX for more info.
258 * optional, defaults to PORTFOLIO_ADD_FULL_FORM
259 * @param str $addstr string to use for the button or icon alt text or link text.
260 * this is whole string, not key. optional, defaults to 'Add to portfolio';
262 public function to_html($format=null, $addstr=null) {
263 global $CFG, $COURSE, $OUTPUT, $USER;
264 if (!$this->is_renderable()) {
265 return;
267 if (empty($this->callbackclass) || empty($this->callbackfile)) {
268 throw new portfolio_button_exception('mustsetcallbackoptions', 'portfolio');
270 if (empty($this->formats)) {
271 // use the caller defaults
272 $this->set_formats();
274 $url = new moodle_url('/portfolio/add.php');
275 foreach ($this->callbackargs as $key => $value) {
276 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
277 $a = new stdClass();
278 $a->key = $key;
279 $a->value = print_r($value, true);
280 debugging(get_string('nonprimative', 'portfolio', $a));
281 return;
283 $url->param('ca_' . $key, $value);
285 $url->param('sesskey', sesskey());
286 $url->param('callbackfile', $this->callbackfile);
287 $url->param('callbackclass', $this->callbackclass);
288 $url->param('course', (!empty($COURSE)) ? $COURSE->id : 0);
289 $url->param('callerformats', implode(',', $this->formats));
290 $mimetype = null;
291 if ($this->file instanceof stored_file) {
292 $mimetype = $this->file->get_mimetype();
293 } else if ($this->intendedmimetype) {
294 $mimetype = $this->intendedmimetype;
296 $selectoutput = '';
297 if (count($this->instances) == 1) {
298 $tmp = array_values($this->instances);
299 $instance = $tmp[0];
301 $formats = portfolio_supported_formats_intersect($this->formats, $instance->supported_formats());
302 if (count($formats) == 0) {
303 // bail. no common formats.
304 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $this->callbackclass, 'formats' => implode(',', $this->formats))));
305 return;
307 if ($error = portfolio_instance_sanity_check($instance)) {
308 // bail, plugin is misconfigured
309 //debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
310 return;
312 if (!$instance->allows_multiple_exports() && $already = portfolio_existing_exports($USER->id, $instance->get('plugin'))) {
313 //debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
314 return;
316 if ($mimetype&& !$instance->file_mime_check($mimetype)) {
317 // bail, we have a specific file or mimetype and this plugin doesn't support it
318 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype)));
319 return;
321 $url->param('instance', $instance->get('id'));
323 else {
324 if (!$selectoutput = portfolio_instance_select($this->instances, $this->formats, $this->callbackclass, $mimetype, 'instance', true)) {
325 return;
328 // if we just want a url to redirect to, do it now
329 if ($format == PORTFOLIO_ADD_FAKE_URL) {
330 return $url->out(false);
333 if (empty($addstr)) {
334 $addstr = get_string('addtoportfolio', 'portfolio');
336 if (empty($format)) {
337 $format = PORTFOLIO_ADD_FULL_FORM;
340 $formoutput = '<form method="post" action="' . $CFG->wwwroot . '/portfolio/add.php" id="portfolio-add-button">' . "\n";
341 $formoutput .= html_writer::input_hidden_params($url);
342 $linkoutput = '<a class="portfolio-add-link" title="'.$addstr.'" href="' . $url->out();
344 switch ($format) {
345 case PORTFOLIO_ADD_FULL_FORM:
346 $formoutput .= $selectoutput;
347 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
348 $formoutput .= "\n" . '</form>';
349 break;
350 case PORTFOLIO_ADD_ICON_FORM:
351 $formoutput .= $selectoutput;
352 $formoutput .= "\n" . '<input class="portfolio-add-icon" type="image" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt=' . $addstr .'" />';
353 $formoutput .= "\n" . '</form>';
354 break;
355 case PORTFOLIO_ADD_ICON_LINK:
356 $linkoutput .= '"><img class="portfolio-add-icon iconsmall" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt="' . $addstr .'" /></a>';
357 break;
358 case PORTFOLIO_ADD_TEXT_LINK:
359 $linkoutput .= '">' . $addstr .'</a>';
360 break;
361 default:
362 debugging(get_string('invalidaddformat', 'portfolio', $format));
364 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
365 return $output;
369 * does some internal checks
370 * these are not errors, just situations
371 * where it's not appropriate to add the button
373 private function is_renderable() {
374 global $CFG;
375 if (empty($CFG->enableportfolios)) {
376 return false;
378 if (defined('PORTFOLIO_INTERNAL')) {
379 // something somewhere has detected a risk of this being called during inside the preparation
380 // eg forum_print_attachments
381 return false;
383 if (empty($this->instances) || count($this->instances) == 0) {
384 return false;
386 return true;
390 * Getter for $format property
391 * @return array
393 public function get_formats() {
394 return $this->formats;
398 * Getter for $callbackargs property
399 * @return array
401 public function get_callbackargs() {
402 return $this->callbackargs;
406 * Getter for $callbackfile property
407 * @return array
409 public function get_callbackfile() {
410 return $this->callbackfile;
414 * Getter for $callbackclass property
415 * @return array
417 public function get_callbackclass() {
418 return $this->callbackclass;
423 * returns a drop menu with a list of available instances.
425 * @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
426 * @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
427 * @param array $callbackclass the callback class name - used for debugging only for when there are no common formats
428 * @param mimetype $mimetype if we already know we have exactly one file, or are going to write one, pass it here to do mime filtering.
429 * @param string $selectname the name of the select element. Optional, defaults to instance.
430 * @param boolean $return whether to print or return the output. Optional, defaults to print.
431 * @param booealn $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
433 * @return string the html, from <select> to </select> inclusive.
435 function portfolio_instance_select($instances, $callerformats, $callbackclass, $mimetype=null, $selectname='instance', $return=false, $returnarray=false) {
436 global $CFG, $USER;
438 if (empty($CFG->enableportfolios)) {
439 return;
442 $insane = portfolio_instance_sanity_check();
443 $pinsane = portfolio_plugin_sanity_check();
445 $count = 0;
446 $selectoutput = "\n" . '<select name="' . $selectname . '">' . "\n";
447 $existingexports = portfolio_existing_exports_by_plugin($USER->id);
448 foreach ($instances as $instance) {
449 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
450 if (count($formats) == 0) {
451 // bail. no common formats.
452 continue;
454 if (array_key_exists($instance->get('id'), $insane)) {
455 // bail, plugin is misconfigured
456 //debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
457 continue;
458 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
459 // bail, plugin is misconfigured
460 //debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
461 continue;
463 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
464 // bail, already exporting something with this plugin and it doesn't support multiple exports
465 continue;
467 if ($mimetype && !$instance->file_mime_check($mimetype)) {
468 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype())));
469 // bail, we have a specific file and this plugin doesn't support it
470 continue;
472 $count++;
473 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
474 $options[$instance->get('id')] = $instance->get('name');
476 if (empty($count)) {
477 // bail. no common formats.
478 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
479 return;
481 $selectoutput .= "\n" . "</select>\n";
482 if (!empty($returnarray)) {
483 return $options;
485 if (!empty($return)) {
486 return $selectoutput;
488 echo $selectoutput;
492 * return all portfolio instances
494 * @todo check capabilities here - see MDL-15768
496 * @param boolean visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
497 * @param boolean useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
499 * @return array of portfolio instances (full objects, not just database records)
501 function portfolio_instances($visibleonly=true, $useronly=true) {
503 global $DB, $USER;
505 $values = array();
506 $sql = 'SELECT * FROM {portfolio_instance}';
508 if ($visibleonly || $useronly) {
509 $values[] = 1;
510 $sql .= ' WHERE visible = ?';
512 if ($useronly) {
513 $sql .= ' AND id NOT IN (
514 SELECT instance FROM {portfolio_instance_user}
515 WHERE userid = ? AND name = ? AND ' . $DB->sql_compare_text('value') . ' = ?
517 $values = array_merge($values, array($USER->id, 'visible', 0));
519 $sql .= ' ORDER BY name';
521 $instances = array();
522 foreach ($DB->get_records_sql($sql, $values) as $instance) {
523 $instances[$instance->id] = portfolio_instance($instance->id, $instance);
525 return $instances;
529 * Supported formats currently in use.
531 * Canonical place for a list of all formats
532 * that portfolio plugins and callers
533 * can use for exporting content
535 * @return keyed array of all the available export formats (constant => classname)
537 function portfolio_supported_formats() {
538 return array(
539 PORTFOLIO_FORMAT_FILE => 'portfolio_format_file',
540 PORTFOLIO_FORMAT_IMAGE => 'portfolio_format_image',
541 PORTFOLIO_FORMAT_RICHHTML => 'portfolio_format_richhtml',
542 PORTFOLIO_FORMAT_PLAINHTML => 'portfolio_format_plainhtml',
543 PORTFOLIO_FORMAT_TEXT => 'portfolio_format_text',
544 PORTFOLIO_FORMAT_VIDEO => 'portfolio_format_video',
545 PORTFOLIO_FORMAT_PDF => 'portfolio_format_pdf',
546 PORTFOLIO_FORMAT_DOCUMENT => 'portfolio_format_document',
547 PORTFOLIO_FORMAT_SPREADSHEET => 'portfolio_format_spreadsheet',
548 PORTFOLIO_FORMAT_PRESENTATION => 'portfolio_format_presentation',
549 /*PORTFOLIO_FORMAT_MBKP, */ // later
550 PORTFOLIO_FORMAT_LEAP2A => 'portfolio_format_leap2a',
551 PORTFOLIO_FORMAT_RICH => 'portfolio_format_rich',
556 * Deduce export format from file mimetype
558 * This function returns the revelant portfolio export format
559 * which is used to determine which portfolio plugins can be used
560 * for exporting this content
561 * according to the given mime type
562 * this only works when exporting exactly <b>one</b> file, or generating a new one
563 * (like a pdf or csv export)
565 * @param string $mimetype (usually $file->get_mimetype())
567 * @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
569 function portfolio_format_from_mimetype($mimetype) {
570 global $CFG;
571 static $alreadymatched;
572 if (empty($alreadymatched)) {
573 $alreadymatched = array();
575 if (array_key_exists($mimetype, $alreadymatched)) {
576 return $alreadymatched[$mimetype];
578 $allformats = portfolio_supported_formats();
579 require_once($CFG->libdir . '/portfolio/formats.php');
580 foreach ($allformats as $format => $classname) {
581 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
582 if (!is_array($supportedmimetypes)) {
583 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
584 debugging(print_r($supportedmimetypes, true));
585 continue;
587 if (in_array($mimetype, $supportedmimetypes)) {
588 $alreadymatched[$mimetype] = $format;
589 return $format;
592 return PORTFOLIO_FORMAT_FILE; // base case for files...
596 * Intersection of plugin formats and caller formats
598 * Walks both the caller formats and portfolio plugin formats
599 * and looks for matches (walking the hierarchy as well)
600 * and returns the intersection
602 * @param array $callerformats formats the caller supports
603 * @param array $pluginformats formats the portfolio plugin supports
605 function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
606 global $CFG;
607 $allformats = portfolio_supported_formats();
608 $intersection = array();
609 foreach ($callerformats as $cf) {
610 if (!array_key_exists($cf, $allformats)) {
611 if (!portfolio_format_is_abstract($cf)) {
612 debugging(get_string('invalidformat', 'portfolio', $cf));
614 continue;
616 require_once($CFG->libdir . '/portfolio/formats.php');
617 $cfobj = new $allformats[$cf]();
618 foreach ($pluginformats as $p => $pf) {
619 if (!array_key_exists($pf, $allformats)) {
620 if (!portfolio_format_is_abstract($pf)) {
621 debugging(get_string('invalidformat', 'portfolio', $pf));
623 unset($pluginformats[$p]); // to avoid the same warning over and over
624 continue;
626 if ($cfobj instanceof $allformats[$pf]) {
627 $intersection[] = $cf;
631 return $intersection;
635 * tiny helper to figure out whether a portfolio format is abstract
637 * @param string $format the format to test
639 * @retun bool
641 function portfolio_format_is_abstract($format) {
642 if (class_exists($format)) {
643 $class = $format;
644 } else if (class_exists('portfolio_format_' . $format)) {
645 $class = 'portfolio_format_' . $format;
646 } else {
647 $allformats = portfolio_supported_formats();
648 if (array_key_exists($format, $allformats)) {
649 $class = $allformats[$format];
652 if (empty($class)) {
653 return true; // it may as well be, we can't instantiate it :)
655 $rc = new ReflectionClass($class);
656 return $rc->isAbstract();
660 * return the combination of the two arrays of formats with duplicates in terms of specificity removed
661 * and also removes conflicting formats
662 * use case: a module is exporting a single file, so the general formats would be FILE and MBKP
663 * while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
664 * and this function would return IMAGE and MBKP
666 * @param array $specificformats array of more specific formats (eg based on mime detection)
667 * @param array $generalformats array of more general formats (usually more supported)
669 * @return array merged formats with dups removed
671 function portfolio_most_specific_formats($specificformats, $generalformats) {
672 global $CFG;
673 $allformats = portfolio_supported_formats();
674 if (empty($specificformats)) {
675 return $generalformats;
676 } else if (empty($generalformats)) {
677 return $specificformats;
679 $removedformats = array();
680 foreach ($specificformats as $k => $f) {
681 // look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
682 if (!array_key_exists($f, $allformats)) {
683 if (!portfolio_format_is_abstract($f)) {
684 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
687 if (in_array($f, $removedformats)) {
688 // already been removed from the general list
689 //debugging("skipping $f because it was already removed");
690 unset($specificformats[$k]);
692 require_once($CFG->libdir . '/portfolio/formats.php');
693 $fobj = new $allformats[$f];
694 foreach ($generalformats as $key => $cf) {
695 if (in_array($cf, $removedformats)) {
696 //debugging("skipping $cf because it was already removed");
697 continue;
699 $cfclass = $allformats[$cf];
700 $cfobj = new $allformats[$cf];
701 if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
702 //debugging("unsetting $key $cf because it's not specific enough ($f is better)");
703 unset($generalformats[$key]);
704 $removedformats[] = $cf;
705 continue;
707 // check for conflicts
708 if ($fobj->conflicts($cf)) {
709 //debugging("unsetting $key $cf because it conflicts with $f");
710 unset($generalformats[$key]);
711 $removedformats[] = $cf;
712 continue;
714 if ($cfobj->conflicts($f)) {
715 //debugging("unsetting $key $cf because it reverse-conflicts with $f");
716 $removedformats[] = $cf;
717 unset($generalformats[$key]);
718 continue;
721 //debugging('inside loop');
722 //print_object($generalformats);
725 //debugging('final formats');
726 $finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
727 //print_object($finalformats);
728 return $finalformats;
732 * helper function to return a format object from the constant
734 * @param string $name the constant PORTFOLIO_FORMAT_XXX
736 * @return portfolio_format object
738 function portfolio_format_object($name) {
739 global $CFG;
740 require_once($CFG->libdir . '/portfolio/formats.php');
741 $formats = portfolio_supported_formats();
742 return new $formats[$name];
746 * helper function to return an instance of a plugin (with config loaded)
748 * @param int $instance id of instance
749 * @param array $record database row that corresponds to this instance
750 * this is passed to avoid unnecessary lookups
751 * Optional, and the record will be retrieved if null.
753 * @return subclass of portfolio_plugin_base
755 function portfolio_instance($instanceid, $record=null) {
756 global $DB, $CFG;
758 if ($record) {
759 $instance = $record;
760 } else {
761 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
762 throw new portfolio_exception('invalidinstance', 'portfolio');
765 require_once($CFG->libdir . '/portfolio/plugin.php');
766 require_once($CFG->dirroot . '/portfolio/'. $instance->plugin . '/lib.php');
767 $classname = 'portfolio_plugin_' . $instance->plugin;
768 return new $classname($instanceid, $instance);
772 * 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
781 function portfolio_static_function($plugin, $function) {
782 global $CFG;
784 $pname = null;
785 if (is_object($plugin) || is_array($plugin)) {
786 $plugin = (object)$plugin;
787 $pname = $plugin->name;
788 } else {
789 $pname = $plugin;
792 $args = func_get_args();
793 if (count($args) <= 2) {
794 $args = array();
796 else {
797 array_shift($args);
798 array_shift($args);
801 require_once($CFG->libdir . '/portfolio/plugin.php');
802 require_once($CFG->dirroot . '/portfolio/' . $plugin . '/lib.php');
803 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
807 * helper function to check all the plugins for sanity and set any insane ones to invisible.
809 * @param array $plugins to check (if null, defaults to all)
810 * one string will work too for a single plugin.
812 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
814 function portfolio_plugin_sanity_check($plugins=null) {
815 global $DB;
816 if (is_string($plugins)) {
817 $plugins = array($plugins);
818 } else if (empty($plugins)) {
819 $plugins = get_plugin_list('portfolio');
820 $plugins = array_keys($plugins);
823 $insane = array();
824 foreach ($plugins as $plugin) {
825 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
826 $insane[$plugin] = $result;
829 if (empty($insane)) {
830 return array();
832 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
833 $where = ' plugin ' . $where;
834 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
835 return $insane;
839 * helper function to check all the instances for sanity and set any insane ones to invisible.
841 * @param array $instances to check (if null, defaults to all)
842 * one instance or id will work too
844 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
846 function portfolio_instance_sanity_check($instances=null) {
847 global $DB;
848 if (empty($instances)) {
849 $instances = portfolio_instances(false);
850 } else if (!is_array($instances)) {
851 $instances = array($instances);
854 $insane = array();
855 foreach ($instances as $instance) {
856 if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) {
857 $instance = portfolio_instance($instance->id, $instance);
858 } else if (is_numeric($instance)) {
859 $instance = portfolio_instance($instance);
861 if (!($instance instanceof portfolio_plugin_base)) {
862 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
863 continue;
865 if ($result = $instance->instance_sanity_check()) {
866 $insane[$instance->get('id')] = $result;
869 if (empty($insane)) {
870 return array();
872 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
873 $where = ' id ' . $where;
874 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
875 portfolio_insane_notify_admins($insane, true);
876 return $insane;
880 * helper function to display a table of plugins (or instances) and reasons for disabling
882 * @param array $insane array of insane plugins (key = plugin (or instance id), value = reason)
883 * @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
886 function portfolio_report_insane($insane, $instances=false, $return=false) {
887 global $OUTPUT;
888 if (empty($insane)) {
889 return;
892 static $pluginstr;
893 if (empty($pluginstr)) {
894 $pluginstr = get_string('plugin', 'portfolio');
896 if ($instances) {
897 $headerstr = get_string('someinstancesdisabled', 'portfolio');
898 } else {
899 $headerstr = get_string('somepluginsdisabled', 'portfolio');
902 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
903 $table = new html_table();
904 $table->head = array($pluginstr, '');
905 $table->data = array();
906 foreach ($insane as $plugin => $reason) {
907 if ($instances) {
908 $instance = $instances[$plugin];
909 $plugin = $instance->get('plugin');
910 $name = $instance->get('name');
911 } else {
912 $name = $plugin;
914 $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
916 $output .= html_writer::table($table);
917 $output .= '<br /><br /><br />';
919 if ($return) {
920 return $output;
922 echo $output;
927 * event handler for the portfolio_send event
929 function portfolio_handle_event($eventdata) {
930 global $CFG;
932 require_once($CFG->libdir . '/portfolio/exporter.php');
933 $exporter = portfolio_exporter::rewaken_object($eventdata);
934 $exporter->process_stage_package();
935 $exporter->process_stage_send();
936 $exporter->save();
937 $exporter->process_stage_cleanup();
938 return true;
942 * main portfolio cronjob
943 * currently just cleans up expired transfer records.
945 * @todo add hooks in the plugins - either per instance or per plugin
947 function portfolio_cron() {
948 global $DB, $CFG;
950 require_once($CFG->libdir . '/portfolio/exporter.php');
951 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()), '', 'id')) {
952 foreach ($expired as $d) {
953 try {
954 $e = portfolio_exporter::rewaken_object($d->id);
955 $e->process_stage_cleanup(true);
956 } catch (Exception $e) {
957 mtrace('Exception thrown in portfolio cron while cleaning up ' . $d->id . ': ' . $e->getMessage());
964 * 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
968 * throws portfolio_export_exceptiog
970 * @param portfolio_exporter $exporter current exporter object
971 * @param exception $exception exception to rethrow
973 * @return void
975 function portfolio_export_rethrow_exception($exporter, $exception) {
976 throw new portfolio_export_exception($exporter, $exception->errorcode, $exception->module, $exception->link, $exception->a);
980 * try and determine expected_time for purely file based exports
981 * or exports that might include large file attachments.
983 * @global object
984 * @param mixed $totest - either an array of stored_file objects or a single stored_file object
985 * @return constant PORTFOLIO_TIME_XXX
987 function portfolio_expected_time_file($totest) {
988 global $CFG;
989 if ($totest instanceof stored_file) {
990 $totest = array($totest);
992 $size = 0;
993 foreach ($totest as $file) {
994 if (!($file instanceof stored_file)) {
995 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
996 debugging(print_r($file, true));
997 continue;
999 $size += $file->get_filesize();
1002 $fileinfo = portfolio_filesize_info();
1004 $moderate = $high = 0; // avoid warnings
1006 foreach (array('moderate', 'high') as $setting) {
1007 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
1008 if (empty($CFG->{$settingname}) || !array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
1009 debugging("weird or unset admin value for $settingname, using default instead");
1010 $$setting = $fileinfo[$setting];
1011 } else {
1012 $$setting = $CFG->{$settingname};
1016 if ($size < $moderate) {
1017 return PORTFOLIO_TIME_LOW;
1018 } else if ($size < $high) {
1019 return PORTFOLIO_TIME_MODERATE;
1021 return PORTFOLIO_TIME_HIGH;
1026 * the default filesizes and threshold information for file based transfers
1027 * this shouldn't need to be used outside the admin pages and the portfolio code
1029 function portfolio_filesize_info() {
1030 $filesizes = array();
1031 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
1032 foreach ($sizelist as $size) {
1033 $filesizes[$size] = display_size($size);
1035 return array(
1036 'options' => $filesizes,
1037 'moderate' => 1048576,
1038 'high' => 5242880,
1043 * try and determine expected_time for purely database based exports
1044 * or exports that might include large parts of a database
1046 * @global object
1047 * @param integer $recordcount - number of records trying to export
1048 * @return constant PORTFOLIO_TIME_XXX
1050 function portfolio_expected_time_db($recordcount) {
1051 global $CFG;
1053 if (empty($CFG->portfolio_moderate_dbsize_threshold)) {
1054 set_config('portfolio_moderate_dbsize_threshold', 10);
1056 if (empty($CFG->portfolio_high_dbsize_threshold)) {
1057 set_config('portfolio_high_dbsize_threshold', 50);
1059 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold) {
1060 return PORTFOLIO_TIME_LOW;
1061 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold) {
1062 return PORTFOLIO_TIME_MODERATE;
1064 return PORTFOLIO_TIME_HIGH;
1068 * @global object
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' => get_context_instance(CONTEXT_COURSE, 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 = $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);
1124 function portfolio_export_pagesetup($PAGE, $caller) {
1125 // set up the context so that build_navigation works nice
1126 $caller->set_context($PAGE);
1128 list($extranav, $cm) = $caller->get_navigation();
1130 // and now we know the course for sure and maybe the cm, call require_login with it
1131 require_login($PAGE->course, false, $cm);
1133 foreach ($extranav as $navitem) {
1134 $PAGE->navbar->add($navitem['name']);
1136 $PAGE->navbar->add(get_string('exporting', 'portfolio'));
1139 function portfolio_export_type_to_id($type, $userid) {
1140 global $DB;
1141 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1142 return $DB->get_field_sql($sql, array($userid, $type));
1146 * return a list of current exports for the given user
1147 * this will not go through and call rewaken_object, because it's heavy
1148 * it's really just used to figure out what exports are currently happening.
1149 * this is useful for plugins that don't support multiple exports per session
1151 * @param int $userid the user to check for
1152 * @param string $type (optional) the portfolio plugin to filter by
1154 * @return array
1156 function portfolio_existing_exports($userid, $type=null) {
1157 global $DB;
1158 $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 = ? ';
1159 $values = array($userid);
1160 if ($type) {
1161 $sql .= ' AND i.plugin = ?';
1162 $values[] = $type;
1164 return $DB->get_records_sql($sql, $values);
1168 * Return an array of existing exports by type for a given user.
1169 * This is much more lightweight than {@see existing_exports} because it only returns the types, rather than the whole serialised data
1170 * so can be used for checking availability of multiple plugins at the same time.
1172 function portfolio_existing_exports_by_plugin($userid) {
1173 global $DB;
1174 $sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1175 $values = array($userid);
1176 return $DB->get_records_sql_menu($sql, $values);
1180 * Return default common options for {@link format_text()} when preparing a content to be exported
1182 * It is important not to apply filters and not to clean the HTML in format_text()
1184 * @return stdClass
1186 function portfolio_format_text_options() {
1188 $options = new stdClass();
1189 $options->para = false;
1190 $options->newlines = true;
1191 $options->filter = false;
1192 $options->noclean = true;
1193 $options->overflowdiv = false;
1195 return $options;
1199 * callback function from {@link portfolio_rewrite_pluginfile_urls}
1200 * looks through preg_replace matches and replaces content with whatever the active portfolio export format says
1202 function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
1203 $matches = $matches[0]; // no internal matching
1204 $dom = new DomDocument();
1205 if (!$dom->loadXML($matches)) {
1206 return $matches;
1208 $attributes = array();
1209 foreach ($dom->documentElement->attributes as $attr => $node) {
1210 $attributes[$attr] = $node->value;
1212 // now figure out the file
1213 $fs = get_file_storage();
1214 $key = 'href';
1215 if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
1216 $key = 'src';
1218 if (!array_key_exists($key, $attributes)) {
1219 debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
1220 return $matches;
1222 $filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') + strlen('@@PLUGINFILE@@'));
1223 $filepath = '/';
1224 if (strpos($filename, '/') !== 0) {
1225 $bits = explode('/', $filename);
1226 $filename = array_pop($bits);
1227 $filepath = implode('/', $bits);
1229 if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
1230 debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
1231 return $matches;
1233 if (empty($options)) {
1234 $options = array();
1236 $options['attributes'] = $attributes;
1237 return $format->file_output($file, $options);
1242 * go through all the @@PLUGINFILE@@ matches in some text,
1243 * extract the file information and pass it back to the portfolio export format
1244 * to regenerate the html to output
1246 * @param string $text the text to search through
1247 * @param int $contextid normal file_area arguments
1248 * @param string $component
1249 * @param string $filearea normal file_area arguments
1250 * @param int $itemid normal file_area arguments
1251 * @param portfolio_format $format the portfolio export format
1252 * @param array $options extra options to pass through to the file_output function in the format (optional)
1254 * @return string
1256 function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
1257 $pattern = '/(<[^<]*?="@@PLUGINFILE@@\/[^>]*?(?:\/>|>.*?<\/[^>]*?>))/';
1258 $callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
1259 return preg_replace_callback($pattern, $callback, $text);
1261 // this function has to go last, because the regexp screws up syntax highlighting in some editors