2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
24 * - Penny Leach <penny@catalyst.net.nz>
26 * @package core_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
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:
62 * $button = new portfolio_add_button();
63 * $button->set_callback_options('name_of_caller_class', array('id' => 6), '/your/mod/lib.php');
64 * $button->render(PORTFOLIO_ADD_FULL_FORM, get_string('addeverythingtoportfolio', 'yourmodule'));
68 * $button = new portfolio_add_button(array('callbackclass' => 'name_of_caller_class', 'callbackargs' => array('id' => 6), 'callbackfile' => '/your/mod/lib.php'));
69 * $somehtml .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
71 *{@link http://docs.moodle.org/dev/Adding_a_Portfolio_Button_to_a_page} for more information
73 * @package core_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 $callbackfile;
89 /** @var array array of more specific formats (eg based on mime detection) */
92 /** @var array array of portfolio instances */
95 /** @var stored_file for single-file exports */
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 'callbackfile': 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)) {
124 $constructoroptions = array('callbackclass', 'callbackargs', 'callbackfile', 'formats');
125 foreach ((array)$options as $key => $value) {
126 if (!in_array($key, $constructoroptions)) {
127 throw new portfolio_button_exception('invalidbuttonproperty', 'portfolio', $key);
129 $this->{$key} = $value;
134 * Function to set the callback options
136 * @param string $class Name of the class containing the callback functions
137 * activity modules should ALWAYS use their name_portfolio_caller
138 * other locations must use something unique
139 * @param array $argarray This can be an array or hash of arguments to pass
140 * back to the callback functions (passed by reference)
141 * these MUST be primatives to be added as hidden form fields.
142 * and the values get cleaned to PARAM_ALPHAEXT or PARAM_NUMBER or PARAM_PATH
143 * @param string $file This can be autodetected if it's in the same file as your caller,
144 * but often, the caller is a script.php and the class in a lib.php
145 * so you can pass it here if necessary.
146 * This path should be relative (ie, not include) dirroot, eg '/mod/forum/lib.php'
148 public function set_callback_options($class, array $argarray, $file=null) {
151 $backtrace = debug_backtrace();
152 if (!array_key_exists(0, $backtrace) ||
!array_key_exists('file', $backtrace[0]) ||
!is_readable($backtrace[0]['file'])) {
153 throw new portfolio_button_exception('nocallbackfile', 'portfolio');
156 $file = substr($backtrace[0]['file'], strlen($CFG->dirroot
));
157 } else if (!is_readable($CFG->dirroot
. $file)) {
158 throw new portfolio_button_exception('nocallbackfile', 'portfolio', '', $file);
160 $this->callbackfile
= $file;
161 require_once($CFG->libdir
. '/portfolio/caller.php'); // require the base class first
162 require_once($CFG->dirroot
. $file);
163 if (!class_exists($class)) {
164 throw new portfolio_button_exception('nocallbackclass', 'portfolio', '', $class);
167 // this will throw exceptions
168 // but should not actually do anything other than verify callbackargs
169 $test = new $class($argarray);
172 $this->callbackclass
= $class;
173 $this->callbackargs
= $argarray;
177 * Sets the available export formats for this content.
178 * This function will also poll the static function in the caller class
179 * and make sure we're not overriding a format that has nothing to do with mimetypes.
180 * Eg: if you pass IMAGE here but the caller can export LEAP2A it will keep LEAP2A as well.
181 * @see portfolio_most_specific_formats for more information
182 * @see portfolio_format_from_mimetype
184 * @param array $formats if the calling code knows better than the static method on the calling class (base_supported_formats).
185 * Eg: if it's going to be a single file, or if you know it's HTML, you can pass it here instead.
186 * This is almost always the case so it should be use all the times
187 * portfolio_format_from_mimetype for how to get the appropriate formats to pass here for uploaded files.
188 * or just call set_format_by_file instead
190 public function set_formats($formats=null) {
191 if (is_string($formats)) {
192 $formats = array($formats);
194 if (empty($formats)) {
197 if (empty($this->callbackclass
)) {
198 throw new portfolio_button_exception('noclassbeforeformats', 'portfolio');
200 $callerformats = call_user_func(array($this->callbackclass
, 'base_supported_formats'));
201 $this->formats
= portfolio_most_specific_formats($formats, $callerformats);
205 * Reset formats to the default,
206 * which is usually what base_supported_formats returns
208 public function reset_formats() {
209 $this->set_formats();
214 * If we already know we have exactly one file,
215 * bypass set_formats and just pass the file
216 * so we can detect the formats by mimetype.
218 * @param stored_file $file file to set the format from
219 * @param array $extraformats any additional formats other than by mimetype
222 public function set_format_by_file(stored_file
$file, $extraformats=null) {
224 $fileformat = portfolio_format_from_mimetype($file->get_mimetype());
225 if (is_string($extraformats)) {
226 $extraformats = array($extraformats);
227 } else if (!is_array($extraformats)) {
228 $extraformats = array();
230 $this->set_formats(array_merge(array($fileformat), $extraformats));
234 * Correllary this is use to set_format_by_file, but it is also used when there is no stored_file and
235 * when we're writing out a new type of file (like csv or pdf)
237 * @param string $extn the file extension we intend to generate
238 * @param array $extraformats any additional formats other than by mimetype
241 public function set_format_by_intended_file($extn, $extraformats=null) {
242 $mimetype = mimeinfo('type', 'something. ' . $extn);
243 $fileformat = portfolio_format_from_mimetype($mimetype);
244 $this->intendedmimetype
= $fileformat;
245 if (is_string($extraformats)) {
246 $extraformats = array($extraformats);
247 } else if (!is_array($extraformats)) {
248 $extraformats = array();
250 $this->set_formats(array_merge(array($fileformat), $extraformats));
254 * Echo the form/button/icon/text link to the page
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 string $addstr string to use for the button or icon alt text or link text.
260 * this is whole string, not key. optional, defaults to 'Export to portfolio';
262 public function render($format=null, $addstr=null) {
263 echo $this->to_html($format, $addstr);
267 * Returns the form/button/icon/text link as html
269 * @param int $format format to display the button or form or icon or link.
270 * See constants PORTFOLIO_ADD_XXX for more info.
271 * Optional, defaults to PORTFOLIO_ADD_FULL_FORM
272 * @param string $addstr string to use for the button or icon alt text or link text.
273 * This is whole string, not key. optional, defaults to 'Add to portfolio';
274 * @return void|string
276 public function to_html($format=null, $addstr=null) {
277 global $CFG, $COURSE, $OUTPUT, $USER;
278 if (!$this->is_renderable()) {
281 if (empty($this->callbackclass
) ||
empty($this->callbackfile
)) {
282 throw new portfolio_button_exception('mustsetcallbackoptions', 'portfolio');
284 if (empty($this->formats
)) {
285 // use the caller defaults
286 $this->set_formats();
288 $url = new moodle_url('/portfolio/add.php');
289 foreach ($this->callbackargs
as $key => $value) {
290 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
293 $a->value
= print_r($value, true);
294 debugging(get_string('nonprimative', 'portfolio', $a));
297 $url->param('ca_' . $key, $value);
299 $url->param('sesskey', sesskey());
300 $url->param('callbackfile', $this->callbackfile
);
301 $url->param('callbackclass', $this->callbackclass
);
302 $url->param('course', (!empty($COURSE)) ?
$COURSE->id
: 0);
303 $url->param('callerformats', implode(',', $this->formats
));
305 if ($this->file
instanceof stored_file
) {
306 $mimetype = $this->file
->get_mimetype();
307 } else if ($this->intendedmimetype
) {
308 $mimetype = $this->intendedmimetype
;
311 if (count($this->instances
) == 1) {
312 $tmp = array_values($this->instances
);
315 $formats = portfolio_supported_formats_intersect($this->formats
, $instance->supported_formats());
316 if (count($formats) == 0) {
317 // bail. no common formats.
318 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $this->callbackclass, 'formats' => implode(',', $this->formats))));
321 if ($error = portfolio_instance_sanity_check($instance)) {
322 // bail, plugin is misconfigured
323 //debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
326 if (!$instance->allows_multiple_exports() && $already = portfolio_existing_exports($USER->id
, $instance->get('plugin'))) {
327 //debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
330 if ($mimetype&& !$instance->file_mime_check($mimetype)) {
331 // bail, we have a specific file or mimetype and this plugin doesn't support it
332 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype)));
335 $url->param('instance', $instance->get('id'));
338 if (!$selectoutput = portfolio_instance_select($this->instances
, $this->formats
, $this->callbackclass
, $mimetype, 'instance', true)) {
342 // if we just want a url to redirect to, do it now
343 if ($format == PORTFOLIO_ADD_FAKE_URL
) {
344 return $url->out(false);
347 if (empty($addstr)) {
348 $addstr = get_string('addtoportfolio', 'portfolio');
350 if (empty($format)) {
351 $format = PORTFOLIO_ADD_FULL_FORM
;
354 $formoutput = '<form method="post" action="' . $CFG->wwwroot
. '/portfolio/add.php" id="portfolio-add-button">' . "\n";
355 $formoutput .= html_writer
::input_hidden_params($url);
356 $linkoutput = '<a class="portfolio-add-link" title="'.$addstr.'" href="' . $url->out();
359 case PORTFOLIO_ADD_FULL_FORM
:
360 $formoutput .= $selectoutput;
361 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
362 $formoutput .= "\n" . '</form>';
364 case PORTFOLIO_ADD_ICON_FORM
:
365 $formoutput .= $selectoutput;
366 $formoutput .= "\n" . '<input class="portfolio-add-icon" type="image" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt=' . $addstr .'" />';
367 $formoutput .= "\n" . '</form>';
369 case PORTFOLIO_ADD_ICON_LINK
:
370 $linkoutput .= '"><img class="portfolio-add-icon iconsmall" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt="' . $addstr .'" /></a>';
372 case PORTFOLIO_ADD_TEXT_LINK
:
373 $linkoutput .= '">' . $addstr .'</a>';
376 debugging(get_string('invalidaddformat', 'portfolio', $format));
378 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM
, PORTFOLIO_ADD_ICON_FORM
)) ?
$formoutput : $linkoutput);
383 * Perform some internal checks.
384 * These are not errors, just situations
385 * where it's not appropriate to add the button
389 private function is_renderable() {
391 if (empty($CFG->enableportfolios
)) {
394 if (defined('PORTFOLIO_INTERNAL')) {
395 // something somewhere has detected a risk of this being called during inside the preparation
396 // eg forum_print_attachments
399 if (empty($this->instances
) ||
count($this->instances
) == 0) {
406 * Getter for $format property
410 public function get_formats() {
411 return $this->formats
;
415 * Getter for $callbackargs property
419 public function get_callbackargs() {
420 return $this->callbackargs
;
424 * Getter for $callbackfile property
428 public function get_callbackfile() {
429 return $this->callbackfile
;
433 * Getter for $callbackclass property
437 public function get_callbackclass() {
438 return $this->callbackclass
;
443 * Returns a drop menu with a list of available instances.
445 * @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
446 * @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
447 * @param string $callbackclass the callback class name - used for debugging only for when there are no common formats
448 * @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.
449 * @param string $selectname the name of the select element. Optional, defaults to instance.
450 * @param bool $return whether to print or return the output. Optional, defaults to print.
451 * @param bool $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
452 * @return void|array|string the html, from <select> to </select> inclusive.
454 function portfolio_instance_select($instances, $callerformats, $callbackclass, $mimetype=null, $selectname='instance', $return=false, $returnarray=false) {
457 if (empty($CFG->enableportfolios
)) {
461 $insane = portfolio_instance_sanity_check();
462 $pinsane = portfolio_plugin_sanity_check();
465 $selectoutput = "\n" . '<select name="' . $selectname . '">' . "\n";
466 $existingexports = portfolio_existing_exports_by_plugin($USER->id
);
467 foreach ($instances as $instance) {
468 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
469 if (count($formats) == 0) {
470 // bail. no common formats.
473 if (array_key_exists($instance->get('id'), $insane)) {
474 // bail, plugin is misconfigured
475 //debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
477 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
478 // bail, plugin is misconfigured
479 //debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
482 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
483 // bail, already exporting something with this plugin and it doesn't support multiple exports
486 if ($mimetype && !$instance->file_mime_check($mimetype)) {
487 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype())));
488 // bail, we have a specific file and this plugin doesn't support it
492 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
493 $options[$instance->get('id')] = $instance->get('name');
496 // bail. no common formats.
497 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
500 $selectoutput .= "\n" . "</select>\n";
501 if (!empty($returnarray)) {
504 if (!empty($return)) {
505 return $selectoutput;
511 * Return all portfolio instances
513 * @todo MDL-15768 - check capabilities here
514 * @param bool $visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
515 * @param bool $useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
516 * @return array of portfolio instances (full objects, not just database records)
518 function portfolio_instances($visibleonly=true, $useronly=true) {
523 $sql = 'SELECT * FROM {portfolio_instance}';
525 if ($visibleonly ||
$useronly) {
527 $sql .= ' WHERE visible = ?';
530 $sql .= ' AND id NOT IN (
531 SELECT instance FROM {portfolio_instance_user}
532 WHERE userid = ? AND name = ? AND ' . $DB->sql_compare_text('value') . ' = ?
534 $values = array_merge($values, array($USER->id
, 'visible', 0));
536 $sql .= ' ORDER BY name';
538 $instances = array();
539 foreach ($DB->get_records_sql($sql, $values) as $instance) {
540 $instances[$instance->id
] = portfolio_instance($instance->id
, $instance);
546 * Supported formats currently in use.
547 * Canonical place for a list of all formats
548 * that portfolio plugins and callers
549 * can use for exporting content
551 * @return array keyed array of all the available export formats (constant => classname)
553 function portfolio_supported_formats() {
555 PORTFOLIO_FORMAT_FILE
=> 'portfolio_format_file',
556 PORTFOLIO_FORMAT_IMAGE
=> 'portfolio_format_image',
557 PORTFOLIO_FORMAT_RICHHTML
=> 'portfolio_format_richhtml',
558 PORTFOLIO_FORMAT_PLAINHTML
=> 'portfolio_format_plainhtml',
559 PORTFOLIO_FORMAT_TEXT
=> 'portfolio_format_text',
560 PORTFOLIO_FORMAT_VIDEO
=> 'portfolio_format_video',
561 PORTFOLIO_FORMAT_PDF
=> 'portfolio_format_pdf',
562 PORTFOLIO_FORMAT_DOCUMENT
=> 'portfolio_format_document',
563 PORTFOLIO_FORMAT_SPREADSHEET
=> 'portfolio_format_spreadsheet',
564 PORTFOLIO_FORMAT_PRESENTATION
=> 'portfolio_format_presentation',
565 /*PORTFOLIO_FORMAT_MBKP, */ // later
566 PORTFOLIO_FORMAT_LEAP2A
=> 'portfolio_format_leap2a',
567 PORTFOLIO_FORMAT_RICH
=> 'portfolio_format_rich',
572 * Deduce export format from file mimetype
573 * This function returns the revelant portfolio export format
574 * which is used to determine which portfolio plugins can be used
575 * for exporting this content
576 * according to the given mime type
577 * this only works when exporting exactly <b>one</b> file, or generating a new one
578 * (like a pdf or csv export)
580 * @param string $mimetype (usually $file->get_mimetype())
581 * @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
583 function portfolio_format_from_mimetype($mimetype) {
585 static $alreadymatched;
586 if (empty($alreadymatched)) {
587 $alreadymatched = array();
589 if (array_key_exists($mimetype, $alreadymatched)) {
590 return $alreadymatched[$mimetype];
592 $allformats = portfolio_supported_formats();
593 require_once($CFG->libdir
. '/portfolio/formats.php');
594 foreach ($allformats as $format => $classname) {
595 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
596 if (!is_array($supportedmimetypes)) {
597 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
598 debugging(print_r($supportedmimetypes, true));
601 if (in_array($mimetype, $supportedmimetypes)) {
602 $alreadymatched[$mimetype] = $format;
606 return PORTFOLIO_FORMAT_FILE
; // base case for files...
610 * Intersection of plugin formats and caller formats.
611 * Walks both the caller formats and portfolio plugin formats
612 * and looks for matches (walking the hierarchy as well)
613 * and returns the intersection
615 * @param array $callerformats formats the caller supports
616 * @param array $pluginformats formats the portfolio plugin supports
619 function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
621 $allformats = portfolio_supported_formats();
622 $intersection = array();
623 foreach ($callerformats as $cf) {
624 if (!array_key_exists($cf, $allformats)) {
625 if (!portfolio_format_is_abstract($cf)) {
626 debugging(get_string('invalidformat', 'portfolio', $cf));
630 require_once($CFG->libdir
. '/portfolio/formats.php');
631 $cfobj = new $allformats[$cf]();
632 foreach ($pluginformats as $p => $pf) {
633 if (!array_key_exists($pf, $allformats)) {
634 if (!portfolio_format_is_abstract($pf)) {
635 debugging(get_string('invalidformat', 'portfolio', $pf));
637 unset($pluginformats[$p]); // to avoid the same warning over and over
640 if ($cfobj instanceof $allformats[$pf]) {
641 $intersection[] = $cf;
645 return $intersection;
649 * Tiny helper to figure out whether a portfolio format is abstract
651 * @param string $format the format to test
654 function portfolio_format_is_abstract($format) {
655 if (class_exists($format)) {
657 } else if (class_exists('portfolio_format_' . $format)) {
658 $class = 'portfolio_format_' . $format;
660 $allformats = portfolio_supported_formats();
661 if (array_key_exists($format, $allformats)) {
662 $class = $allformats[$format];
666 return true; // it may as well be, we can't instantiate it :)
668 $rc = new ReflectionClass($class);
669 return $rc->isAbstract();
673 * Return the combination of the two arrays of formats with duplicates in terms of specificity removed
674 * and also removes conflicting formats.
675 * Use case: a module is exporting a single file, so the general formats would be FILE and MBKP
676 * while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
677 * and this function would return IMAGE and MBKP
679 * @param array $specificformats array of more specific formats (eg based on mime detection)
680 * @param array $generalformats array of more general formats (usually more supported)
681 * @return array merged formats with dups removed
683 function portfolio_most_specific_formats($specificformats, $generalformats) {
685 $allformats = portfolio_supported_formats();
686 if (empty($specificformats)) {
687 return $generalformats;
688 } else if (empty($generalformats)) {
689 return $specificformats;
691 $removedformats = array();
692 foreach ($specificformats as $k => $f) {
693 // look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
694 if (!array_key_exists($f, $allformats)) {
695 if (!portfolio_format_is_abstract($f)) {
696 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
699 if (in_array($f, $removedformats)) {
700 // already been removed from the general list
701 //debugging("skipping $f because it was already removed");
702 unset($specificformats[$k]);
704 require_once($CFG->libdir
. '/portfolio/formats.php');
705 $fobj = new $allformats[$f];
706 foreach ($generalformats as $key => $cf) {
707 if (in_array($cf, $removedformats)) {
708 //debugging("skipping $cf because it was already removed");
711 $cfclass = $allformats[$cf];
712 $cfobj = new $allformats[$cf];
713 if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
714 //debugging("unsetting $key $cf because it's not specific enough ($f is better)");
715 unset($generalformats[$key]);
716 $removedformats[] = $cf;
719 // check for conflicts
720 if ($fobj->conflicts($cf)) {
721 //debugging("unsetting $key $cf because it conflicts with $f");
722 unset($generalformats[$key]);
723 $removedformats[] = $cf;
726 if ($cfobj->conflicts($f)) {
727 //debugging("unsetting $key $cf because it reverse-conflicts with $f");
728 $removedformats[] = $cf;
729 unset($generalformats[$key]);
733 //debugging('inside loop');
734 //print_object($generalformats);
737 //debugging('final formats');
738 $finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
739 //print_object($finalformats);
740 return $finalformats;
744 * Helper function to return a format object from the constant
746 * @param string $name the constant PORTFOLIO_FORMAT_XXX
747 * @return portfolio_format
749 function portfolio_format_object($name) {
751 require_once($CFG->libdir
. '/portfolio/formats.php');
752 $formats = portfolio_supported_formats();
753 return new $formats[$name];
757 * Helper function to return an instance of a plugin (with config loaded)
759 * @param int $instanceid id of instance
760 * @param object $record database row that corresponds to this instance
761 * this is passed to avoid unnecessary lookups
762 * Optional, and the record will be retrieved if null.
763 * @return object of portfolio_plugin_XXX
765 function portfolio_instance($instanceid, $record=null) {
771 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
772 throw new portfolio_exception('invalidinstance', 'portfolio');
775 require_once($CFG->libdir
. '/portfolio/plugin.php');
776 require_once($CFG->dirroot
. '/portfolio/'. $instance->plugin
. '/lib.php');
777 $classname = 'portfolio_plugin_' . $instance->plugin
;
778 return new $classname($instanceid, $instance);
782 * Helper function to call a static function on a portfolio plugin class.
783 * This will figure out the classname and require the right file and call the function.
784 * You can send a variable number of arguments to this function after the first two
785 * and they will be passed on to the function you wish to call.
787 * @param string $plugin name of plugin
788 * @param string $function function to call
791 function portfolio_static_function($plugin, $function) {
795 if (is_object($plugin) ||
is_array($plugin)) {
796 $plugin = (object)$plugin;
797 $pname = $plugin->name
;
802 $args = func_get_args();
803 if (count($args) <= 2) {
811 require_once($CFG->libdir
. '/portfolio/plugin.php');
812 require_once($CFG->dirroot
. '/portfolio/' . $plugin . '/lib.php');
813 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
817 * Helper function to check all the plugins for sanity and set any insane ones to invisible.
819 * @param array $plugins array of supported plugin types
820 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
822 function portfolio_plugin_sanity_check($plugins=null) {
824 if (is_string($plugins)) {
825 $plugins = array($plugins);
826 } else if (empty($plugins)) {
827 $plugins = get_plugin_list('portfolio');
828 $plugins = array_keys($plugins);
832 foreach ($plugins as $plugin) {
833 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
834 $insane[$plugin] = $result;
837 if (empty($insane)) {
840 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
841 $where = ' plugin ' . $where;
842 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
847 * Helper function to check all the instances for sanity and set any insane ones to invisible.
849 * @param array $instances array of plugin instances
850 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
852 function portfolio_instance_sanity_check($instances=null) {
854 if (empty($instances)) {
855 $instances = portfolio_instances(false);
856 } else if (!is_array($instances)) {
857 $instances = array($instances);
861 foreach ($instances as $instance) {
862 if (is_object($instance) && !($instance instanceof portfolio_plugin_base
)) {
863 $instance = portfolio_instance($instance->id
, $instance);
864 } else if (is_numeric($instance)) {
865 $instance = portfolio_instance($instance);
867 if (!($instance instanceof portfolio_plugin_base
)) {
868 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
871 if ($result = $instance->instance_sanity_check()) {
872 $insane[$instance->get('id')] = $result;
875 if (empty($insane)) {
878 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
879 $where = ' id ' . $where;
880 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
881 portfolio_insane_notify_admins($insane, true);
886 * Helper function to display a table of plugins (or instances) and reasons for disabling
888 * @param array $insane array of portfolio plugin
889 * @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
890 * @param bool $return option to deliver the report in html format or print it out directly to the page.
891 * @return void|string of portfolio report in html table format
893 function portfolio_report_insane($insane, $instances=false, $return=false) {
895 if (empty($insane)) {
900 if (empty($pluginstr)) {
901 $pluginstr = get_string('plugin', 'portfolio');
904 $headerstr = get_string('someinstancesdisabled', 'portfolio');
906 $headerstr = get_string('somepluginsdisabled', 'portfolio');
909 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
910 $table = new html_table();
911 $table->head
= array($pluginstr, '');
912 $table->data
= array();
913 foreach ($insane as $plugin => $reason) {
915 $instance = $instances[$plugin];
916 $plugin = $instance->get('plugin');
917 $name = $instance->get('name');
921 $table->data
[] = array($name, get_string($reason, 'portfolio_' . $plugin));
923 $output .= html_writer
::table($table);
924 $output .= '<br /><br /><br />';
934 * Event handler for the portfolio_send event
936 * @param int $eventdata event id
939 function portfolio_handle_event($eventdata) {
942 require_once($CFG->libdir
. '/portfolio/exporter.php');
943 $exporter = portfolio_exporter
::rewaken_object($eventdata);
944 $exporter->process_stage_package();
945 $exporter->process_stage_send();
947 $exporter->process_stage_cleanup();
952 * Main portfolio cronjob.
953 * Currently just cleans up expired transfer records.
955 * @todo - MDL-15997 - Add hooks in the plugins - either per instance or per plugin
957 function portfolio_cron() {
960 require_once($CFG->libdir
. '/portfolio/exporter.php');
961 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()), '', 'id')) {
962 foreach ($expired as $d) {
964 $e = portfolio_exporter
::rewaken_object($d->id
);
965 $e->process_stage_cleanup(true);
966 } catch (Exception
$e) {
967 mtrace('Exception thrown in portfolio cron while cleaning up ' . $d->id
. ': ' . $e->getMessage());
974 * Helper function to rethrow a caught portfolio_exception as an export exception.
975 * Used because when a portfolio_export exception is thrown the export is cancelled
976 * throws portfolio_export_exceptiog
978 * @param portfolio_exporter $exporter current exporter object
979 * @param object $exception exception to rethrow
981 function portfolio_export_rethrow_exception($exporter, $exception) {
982 throw new portfolio_export_exception($exporter, $exception->errorcode
, $exception->module
, $exception->link
, $exception->a
);
986 * Try and determine expected_time for purely file based exports
987 * or exports that might include large file attachments.
989 * @param stored_file|array $totest - either an array of stored_file objects or a single stored_file object
990 * @return string PORTFOLIO_TIME_XXX
992 function portfolio_expected_time_file($totest) {
994 if ($totest instanceof stored_file
) {
995 $totest = array($totest);
998 foreach ($totest as $file) {
999 if (!($file instanceof stored_file
)) {
1000 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
1001 debugging(print_r($file, true));
1004 $size +
= $file->get_filesize();
1007 $fileinfo = portfolio_filesize_info();
1009 $moderate = $high = 0; // avoid warnings
1011 foreach (array('moderate', 'high') as $setting) {
1012 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
1013 if (empty($CFG->{$settingname}) ||
!array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
1014 debugging("weird or unset admin value for $settingname, using default instead");
1015 $
$setting = $fileinfo[$setting];
1017 $
$setting = $CFG->{$settingname};
1021 if ($size < $moderate) {
1022 return PORTFOLIO_TIME_LOW
;
1023 } else if ($size < $high) {
1024 return PORTFOLIO_TIME_MODERATE
;
1026 return PORTFOLIO_TIME_HIGH
;
1031 * The default filesizes and threshold information for file based transfers.
1032 * This shouldn't need to be used outside the admin pages and the portfolio code
1036 function portfolio_filesize_info() {
1037 $filesizes = array();
1038 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
1039 foreach ($sizelist as $size) {
1040 $filesizes[$size] = display_size($size);
1043 'options' => $filesizes,
1044 'moderate' => 1048576,
1050 * Try and determine expected_time for purely database based exports
1051 * or exports that might include large parts of a database.
1053 * @param int $recordcount number of records trying to export
1054 * @return string PORTFOLIO_TIME_XXX
1056 function portfolio_expected_time_db($recordcount) {
1059 if (empty($CFG->portfolio_moderate_dbsize_threshold
)) {
1060 set_config('portfolio_moderate_dbsize_threshold', 10);
1062 if (empty($CFG->portfolio_high_dbsize_threshold
)) {
1063 set_config('portfolio_high_dbsize_threshold', 50);
1065 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold
) {
1066 return PORTFOLIO_TIME_LOW
;
1067 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold
) {
1068 return PORTFOLIO_TIME_MODERATE
;
1070 return PORTFOLIO_TIME_HIGH
;
1074 * Function to send portfolio report to admins
1076 * @param array $insane array of insane plugins
1077 * @param array $instances (optional) if reporting instances rather than whole plugins
1079 function portfolio_insane_notify_admins($insane, $instances=false) {
1083 if (defined('ADMIN_EDITING_PORTFOLIO')) {
1087 $admins = get_admins();
1089 if (empty($admins)) {
1093 $instances = portfolio_instances(false, false);
1099 $a->sitename
= format_string($site->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, SITEID
)));
1100 $a->fixurl
= "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
1101 $a->htmllist
= portfolio_report_insane($insane, $instances, true);
1104 foreach ($insane as $k => $reason) {
1106 $a->textlist
= $instances[$k]->get('name') . ': ' . $reason . "\n";
1108 $a->textlist
= $k . ': ' . $reason . "\n";
1112 $subject = get_string('insanesubject', 'portfolio');
1113 $plainbody = get_string('insanebody', 'portfolio', $a);
1114 $htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
1115 $smallbody = get_string('insanebodysmall', 'portfolio', $a);
1117 foreach ($admins as $admin) {
1118 $eventdata = new stdClass();
1119 $eventdata->modulename
= 'portfolio';
1120 $eventdata->component
= 'portfolio';
1121 $eventdata->name
= 'notices';
1122 $eventdata->userfrom
= $admin;
1123 $eventdata->userto
= $admin;
1124 $eventdata->subject
= $subject;
1125 $eventdata->fullmessage
= $plainbody;
1126 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1127 $eventdata->fullmessagehtml
= $htmlbody;
1128 $eventdata->smallmessage
= $smallbody;
1129 message_send($eventdata);
1136 * @param moodle_page $PAGE global variable from page object
1137 * @param portfolio_caller_base $caller plugin type caller
1139 function portfolio_export_pagesetup($PAGE, $caller) {
1140 // set up the context so that build_navigation works nice
1141 $caller->set_context($PAGE);
1143 list($extranav, $cm) = $caller->get_navigation();
1145 // and now we know the course for sure and maybe the cm, call require_login with it
1146 require_login($PAGE->course
, false, $cm);
1148 foreach ($extranav as $navitem) {
1149 $PAGE->navbar
->add($navitem['name']);
1151 $PAGE->navbar
->add(get_string('exporting', 'portfolio'));
1155 * Get export type id
1157 * @param string $type plugin type
1158 * @param int $userid the user to check for
1159 * @return mixed|bool
1161 function portfolio_export_type_to_id($type, $userid) {
1163 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1164 return $DB->get_field_sql($sql, array($userid, $type));
1168 * Return a list of current exports for the given user.
1169 * This will not go through and call rewaken_object, because it's heavy.
1170 * It's really just used to figure out what exports are currently happening.
1171 * This is useful for plugins that don't support multiple exports per session
1173 * @param int $userid the user to check for
1174 * @param string $type (optional) the portfolio plugin to filter by
1177 function portfolio_existing_exports($userid, $type=null) {
1179 $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 = ? ';
1180 $values = array($userid);
1182 $sql .= ' AND i.plugin = ?';
1185 return $DB->get_records_sql($sql, $values);
1189 * Return an array of existing exports by type for a given user.
1190 * This is much more lightweight than existing_exports because it only returns the types, rather than the whole serialised data
1191 * so can be used for checking availability of multiple plugins at the same time.
1192 * @see existing_exports
1194 * @param int $userid the user to check for
1197 function portfolio_existing_exports_by_plugin($userid) {
1199 $sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1200 $values = array($userid);
1201 return $DB->get_records_sql_menu($sql, $values);
1205 * Return default common options for {@link format_text()} when preparing a content to be exported.
1206 * It is important not to apply filters and not to clean the HTML in format_text()
1210 function portfolio_format_text_options() {
1212 $options = new stdClass();
1213 $options->para
= false;
1214 $options->newlines
= true;
1215 $options->filter
= false;
1216 $options->noclean
= true;
1217 $options->overflowdiv
= false;
1223 * callback function from {@link portfolio_rewrite_pluginfile_urls}
1224 * looks through preg_replace matches and replaces content with whatever the active portfolio export format says
1226 * @param int $contextid module context id
1227 * @param string $component module name (eg:mod_assignment)
1228 * @param string $filearea normal file_area arguments
1229 * @param int $itemid component item id
1230 * @param portfolio_format $format exporter format type
1231 * @param array $options extra options to pass through to the file_output function in the format (optional)
1232 * @param array $matches internal matching
1233 * @return object|array|string
1235 function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
1236 $matches = $matches[0]; // no internal matching
1237 $dom = new DomDocument();
1238 if (!$dom->loadXML($matches)) {
1241 $attributes = array();
1242 foreach ($dom->documentElement
->attributes
as $attr => $node) {
1243 $attributes[$attr] = $node->value
;
1245 // now figure out the file
1246 $fs = get_file_storage();
1248 if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
1251 if (!array_key_exists($key, $attributes)) {
1252 debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
1255 $filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') +
strlen('@@PLUGINFILE@@'));
1257 if (strpos($filename, '/') !== 0) {
1258 $bits = explode('/', $filename);
1259 $filename = array_pop($bits);
1260 $filepath = implode('/', $bits);
1262 if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
1263 debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
1266 if (empty($options)) {
1269 $options['attributes'] = $attributes;
1270 return $format->file_output($file, $options);
1275 * Go through all the @@PLUGINFILE@@ matches in some text,
1276 * extract the file information and pass it back to the portfolio export format
1277 * to regenerate the html to output
1279 * @param string $text the text to search through
1280 * @param int $contextid normal file_area arguments
1281 * @param string $component module name
1282 * @param string $filearea normal file_area arguments
1283 * @param int $itemid normal file_area arguments
1284 * @param portfolio_format $format the portfolio export format
1285 * @param array $options additional options to be included in the plugin file url (optional)
1288 function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
1289 $pattern = '/(<[^<]*?="@@PLUGINFILE@@\/[^>]*?(?:\/>|>.*?<\/[^>]*?>))/';
1290 $callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
1291 return preg_replace_callback($pattern, $callback, $text);
1293 // this function has to go last, because the regexp screws up syntax highlighting in some editors