3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
24 * - Penny Leach <penny@catalyst.net.nz>
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
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:
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'));
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);
74 * See {@link http://docs.moodle.org/dev/Adding_a_Portfolio_Button_to_a_page} for more information
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;
88 private $file; // for single-file exports
89 private $intendedmimetype; // for writing specific types of files
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)) {
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) {
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);
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)) {
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
209 public function set_format_by_file(stored_file
$file, $extraformats=null) {
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
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()) {
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)) {
279 $a->value
= print_r($value, true);
280 debugging(get_string('nonprimative', 'portfolio', $a));
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
));
291 if ($this->file
instanceof stored_file
) {
292 $mimetype = $this->file
->get_mimetype();
293 } else if ($this->intendedmimetype
) {
294 $mimetype = $this->intendedmimetype
;
297 if (count($this->instances
) == 1) {
298 $tmp = array_values($this->instances
);
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))));
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'))));
312 if (!$instance->allows_multiple_exports() && $already = portfolio_existing_exports($USER->id
, $instance->get('plugin'))) {
313 //debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
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)));
321 $url->param('instance', $instance->get('id'));
324 if (!$selectoutput = portfolio_instance_select($this->instances
, $this->formats
, $this->callbackclass
, $mimetype, 'instance', true)) {
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();
345 case PORTFOLIO_ADD_FULL_FORM
:
346 $formoutput .= $selectoutput;
347 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
348 $formoutput .= "\n" . '</form>';
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>';
355 case PORTFOLIO_ADD_ICON_LINK
:
356 $linkoutput .= '"><img class="portfolio-add-icon iconsmall" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt="' . $addstr .'" /></a>';
358 case PORTFOLIO_ADD_TEXT_LINK
:
359 $linkoutput .= '">' . $addstr .'</a>';
362 debugging(get_string('invalidaddformat', 'portfolio', $format));
364 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM
, PORTFOLIO_ADD_ICON_FORM
)) ?
$formoutput : $linkoutput);
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() {
375 if (empty($CFG->enableportfolios
)) {
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
383 if (empty($this->instances
) ||
count($this->instances
) == 0) {
390 * Getter for $format property
393 public function get_formats() {
394 return $this->formats
;
398 * Getter for $callbackargs property
401 public function get_callbackargs() {
402 return $this->callbackargs
;
406 * Getter for $callbackfile property
409 public function get_callbackfile() {
410 return $this->callbackfile
;
414 * Getter for $callbackclass property
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) {
438 if (empty($CFG->enableportfolios
)) {
442 $insane = portfolio_instance_sanity_check();
443 $pinsane = portfolio_plugin_sanity_check();
446 $selectoutput = "\n" . '<label class="accesshide" for="instanceid">' . get_string('plugin', 'portfolio') . '</label>';
447 $selectoutput .= "\n" . '<select id="instanceid" name="' . $selectname . '">' . "\n";
448 $existingexports = portfolio_existing_exports_by_plugin($USER->id
);
449 foreach ($instances as $instance) {
450 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
451 if (count($formats) == 0) {
452 // bail. no common formats.
455 if (array_key_exists($instance->get('id'), $insane)) {
456 // bail, plugin is misconfigured
457 //debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
459 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
460 // bail, plugin is misconfigured
461 //debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
464 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
465 // bail, already exporting something with this plugin and it doesn't support multiple exports
468 if ($mimetype && !$instance->file_mime_check($mimetype)) {
469 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype())));
470 // bail, we have a specific file and this plugin doesn't support it
474 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
475 $options[$instance->get('id')] = $instance->get('name');
478 // bail. no common formats.
479 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
482 $selectoutput .= "\n" . "</select>\n";
483 if (!empty($returnarray)) {
486 if (!empty($return)) {
487 return $selectoutput;
493 * return all portfolio instances
495 * @todo check capabilities here - see MDL-15768
497 * @param boolean visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
498 * @param boolean useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
500 * @return array of portfolio instances (full objects, not just database records)
502 function portfolio_instances($visibleonly=true, $useronly=true) {
507 $sql = 'SELECT * FROM {portfolio_instance}';
509 if ($visibleonly ||
$useronly) {
511 $sql .= ' WHERE visible = ?';
514 $sql .= ' AND id NOT IN (
515 SELECT instance FROM {portfolio_instance_user}
516 WHERE userid = ? AND name = ? AND ' . $DB->sql_compare_text('value') . ' = ?
518 $values = array_merge($values, array($USER->id
, 'visible', 0));
520 $sql .= ' ORDER BY name';
522 $instances = array();
523 foreach ($DB->get_records_sql($sql, $values) as $instance) {
524 $instances[$instance->id
] = portfolio_instance($instance->id
, $instance);
530 * Supported formats currently in use.
532 * Canonical place for a list of all formats
533 * that portfolio plugins and callers
534 * can use for exporting content
536 * @return keyed array of all the available export formats (constant => classname)
538 function portfolio_supported_formats() {
540 PORTFOLIO_FORMAT_FILE
=> 'portfolio_format_file',
541 PORTFOLIO_FORMAT_IMAGE
=> 'portfolio_format_image',
542 PORTFOLIO_FORMAT_RICHHTML
=> 'portfolio_format_richhtml',
543 PORTFOLIO_FORMAT_PLAINHTML
=> 'portfolio_format_plainhtml',
544 PORTFOLIO_FORMAT_TEXT
=> 'portfolio_format_text',
545 PORTFOLIO_FORMAT_VIDEO
=> 'portfolio_format_video',
546 PORTFOLIO_FORMAT_PDF
=> 'portfolio_format_pdf',
547 PORTFOLIO_FORMAT_DOCUMENT
=> 'portfolio_format_document',
548 PORTFOLIO_FORMAT_SPREADSHEET
=> 'portfolio_format_spreadsheet',
549 PORTFOLIO_FORMAT_PRESENTATION
=> 'portfolio_format_presentation',
550 /*PORTFOLIO_FORMAT_MBKP, */ // later
551 PORTFOLIO_FORMAT_LEAP2A
=> 'portfolio_format_leap2a',
552 PORTFOLIO_FORMAT_RICH
=> 'portfolio_format_rich',
557 * Deduce export format from file mimetype
559 * This function returns the revelant portfolio export format
560 * which is used to determine which portfolio plugins can be used
561 * for exporting this content
562 * according to the given mime type
563 * this only works when exporting exactly <b>one</b> file, or generating a new one
564 * (like a pdf or csv export)
566 * @param string $mimetype (usually $file->get_mimetype())
568 * @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
570 function portfolio_format_from_mimetype($mimetype) {
572 static $alreadymatched;
573 if (empty($alreadymatched)) {
574 $alreadymatched = array();
576 if (array_key_exists($mimetype, $alreadymatched)) {
577 return $alreadymatched[$mimetype];
579 $allformats = portfolio_supported_formats();
580 require_once($CFG->libdir
. '/portfolio/formats.php');
581 foreach ($allformats as $format => $classname) {
582 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
583 if (!is_array($supportedmimetypes)) {
584 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
585 debugging(print_r($supportedmimetypes, true));
588 if (in_array($mimetype, $supportedmimetypes)) {
589 $alreadymatched[$mimetype] = $format;
593 return PORTFOLIO_FORMAT_FILE
; // base case for files...
597 * Intersection of plugin formats and caller formats
599 * Walks both the caller formats and portfolio plugin formats
600 * and looks for matches (walking the hierarchy as well)
601 * and returns the intersection
603 * @param array $callerformats formats the caller supports
604 * @param array $pluginformats formats the portfolio plugin supports
606 function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
608 $allformats = portfolio_supported_formats();
609 $intersection = array();
610 foreach ($callerformats as $cf) {
611 if (!array_key_exists($cf, $allformats)) {
612 if (!portfolio_format_is_abstract($cf)) {
613 debugging(get_string('invalidformat', 'portfolio', $cf));
617 require_once($CFG->libdir
. '/portfolio/formats.php');
618 $cfobj = new $allformats[$cf]();
619 foreach ($pluginformats as $p => $pf) {
620 if (!array_key_exists($pf, $allformats)) {
621 if (!portfolio_format_is_abstract($pf)) {
622 debugging(get_string('invalidformat', 'portfolio', $pf));
624 unset($pluginformats[$p]); // to avoid the same warning over and over
627 if ($cfobj instanceof $allformats[$pf]) {
628 $intersection[] = $cf;
632 return $intersection;
636 * tiny helper to figure out whether a portfolio format is abstract
638 * @param string $format the format to test
642 function portfolio_format_is_abstract($format) {
643 if (class_exists($format)) {
645 } else if (class_exists('portfolio_format_' . $format)) {
646 $class = 'portfolio_format_' . $format;
648 $allformats = portfolio_supported_formats();
649 if (array_key_exists($format, $allformats)) {
650 $class = $allformats[$format];
654 return true; // it may as well be, we can't instantiate it :)
656 $rc = new ReflectionClass($class);
657 return $rc->isAbstract();
661 * return the combination of the two arrays of formats with duplicates in terms of specificity removed
662 * and also removes conflicting formats
663 * use case: a module is exporting a single file, so the general formats would be FILE and MBKP
664 * while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
665 * and this function would return IMAGE and MBKP
667 * @param array $specificformats array of more specific formats (eg based on mime detection)
668 * @param array $generalformats array of more general formats (usually more supported)
670 * @return array merged formats with dups removed
672 function portfolio_most_specific_formats($specificformats, $generalformats) {
674 $allformats = portfolio_supported_formats();
675 if (empty($specificformats)) {
676 return $generalformats;
677 } else if (empty($generalformats)) {
678 return $specificformats;
680 $removedformats = array();
681 foreach ($specificformats as $k => $f) {
682 // look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
683 if (!array_key_exists($f, $allformats)) {
684 if (!portfolio_format_is_abstract($f)) {
685 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
688 if (in_array($f, $removedformats)) {
689 // already been removed from the general list
690 //debugging("skipping $f because it was already removed");
691 unset($specificformats[$k]);
693 require_once($CFG->libdir
. '/portfolio/formats.php');
694 $fobj = new $allformats[$f];
695 foreach ($generalformats as $key => $cf) {
696 if (in_array($cf, $removedformats)) {
697 //debugging("skipping $cf because it was already removed");
700 $cfclass = $allformats[$cf];
701 $cfobj = new $allformats[$cf];
702 if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
703 //debugging("unsetting $key $cf because it's not specific enough ($f is better)");
704 unset($generalformats[$key]);
705 $removedformats[] = $cf;
708 // check for conflicts
709 if ($fobj->conflicts($cf)) {
710 //debugging("unsetting $key $cf because it conflicts with $f");
711 unset($generalformats[$key]);
712 $removedformats[] = $cf;
715 if ($cfobj->conflicts($f)) {
716 //debugging("unsetting $key $cf because it reverse-conflicts with $f");
717 $removedformats[] = $cf;
718 unset($generalformats[$key]);
722 //debugging('inside loop');
723 //print_object($generalformats);
726 //debugging('final formats');
727 $finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
728 //print_object($finalformats);
729 return $finalformats;
733 * helper function to return a format object from the constant
735 * @param string $name the constant PORTFOLIO_FORMAT_XXX
737 * @return portfolio_format object
739 function portfolio_format_object($name) {
741 require_once($CFG->libdir
. '/portfolio/formats.php');
742 $formats = portfolio_supported_formats();
743 return new $formats[$name];
747 * helper function to return an instance of a plugin (with config loaded)
749 * @param int $instance id of instance
750 * @param array $record database row that corresponds to this instance
751 * this is passed to avoid unnecessary lookups
752 * Optional, and the record will be retrieved if null.
754 * @return subclass of portfolio_plugin_base
756 function portfolio_instance($instanceid, $record=null) {
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
775 * This will figure out the classname and require the right file and call the function.
776 * you can send a variable number of arguments to this function after the first two
777 * and they will be passed on to the function you wish to call.
779 * @param string $plugin name of plugin
780 * @param string $function function to call
782 function portfolio_static_function($plugin, $function) {
786 if (is_object($plugin) ||
is_array($plugin)) {
787 $plugin = (object)$plugin;
788 $pname = $plugin->name
;
793 $args = func_get_args();
794 if (count($args) <= 2) {
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 to check (if null, defaults to all)
811 * one string will work too for a single plugin.
813 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
815 function portfolio_plugin_sanity_check($plugins=null) {
817 if (is_string($plugins)) {
818 $plugins = array($plugins);
819 } else if (empty($plugins)) {
820 $plugins = get_plugin_list('portfolio');
821 $plugins = array_keys($plugins);
825 foreach ($plugins as $plugin) {
826 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
827 $insane[$plugin] = $result;
830 if (empty($insane)) {
833 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
834 $where = ' plugin ' . $where;
835 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
840 * helper function to check all the instances for sanity and set any insane ones to invisible.
842 * @param array $instances to check (if null, defaults to all)
843 * one instance or id will work too
845 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
847 function portfolio_instance_sanity_check($instances=null) {
849 if (empty($instances)) {
850 $instances = portfolio_instances(false);
851 } else if (!is_array($instances)) {
852 $instances = array($instances);
856 foreach ($instances as $instance) {
857 if (is_object($instance) && !($instance instanceof portfolio_plugin_base
)) {
858 $instance = portfolio_instance($instance->id
, $instance);
859 } else if (is_numeric($instance)) {
860 $instance = portfolio_instance($instance);
862 if (!($instance instanceof portfolio_plugin_base
)) {
863 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
866 if ($result = $instance->instance_sanity_check()) {
867 $insane[$instance->get('id')] = $result;
870 if (empty($insane)) {
873 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
874 $where = ' id ' . $where;
875 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
876 portfolio_insane_notify_admins($insane, true);
881 * helper function to display a table of plugins (or instances) and reasons for disabling
883 * @param array $insane array of insane plugins (key = plugin (or instance id), value = reason)
884 * @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
887 function portfolio_report_insane($insane, $instances=false, $return=false) {
889 if (empty($insane)) {
894 if (empty($pluginstr)) {
895 $pluginstr = get_string('plugin', 'portfolio');
898 $headerstr = get_string('someinstancesdisabled', 'portfolio');
900 $headerstr = get_string('somepluginsdisabled', 'portfolio');
903 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
904 $table = new html_table();
905 $table->head
= array($pluginstr, '');
906 $table->data
= array();
907 foreach ($insane as $plugin => $reason) {
909 $instance = $instances[$plugin];
910 $plugin = $instance->get('plugin');
911 $name = $instance->get('name');
915 $table->data
[] = array($name, get_string($reason, 'portfolio_' . $plugin));
917 $output .= html_writer
::table($table);
918 $output .= '<br /><br /><br />';
928 * event handler for the portfolio_send event
930 function portfolio_handle_event($eventdata) {
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();
938 $exporter->process_stage_cleanup();
943 * main portfolio cronjob
944 * currently just cleans up expired transfer records.
946 * @todo add hooks in the plugins - either per instance or per plugin
948 function portfolio_cron() {
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) {
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
967 * used because when a portfolio_export exception is thrown the export is cancelled
969 * throws portfolio_export_exceptiog
971 * @param portfolio_exporter $exporter current exporter object
972 * @param exception $exception exception to rethrow
976 function portfolio_export_rethrow_exception($exporter, $exception) {
977 throw new portfolio_export_exception($exporter, $exception->errorcode
, $exception->module
, $exception->link
, $exception->a
);
981 * try and determine expected_time for purely file based exports
982 * or exports that might include large file attachments.
985 * @param mixed $totest - either an array of stored_file objects or a single stored_file object
986 * @return constant PORTFOLIO_TIME_XXX
988 function portfolio_expected_time_file($totest) {
990 if ($totest instanceof stored_file
) {
991 $totest = array($totest);
994 foreach ($totest as $file) {
995 if (!($file instanceof stored_file
)) {
996 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
997 debugging(print_r($file, true));
1000 $size +
= $file->get_filesize();
1003 $fileinfo = portfolio_filesize_info();
1005 $moderate = $high = 0; // avoid warnings
1007 foreach (array('moderate', 'high') as $setting) {
1008 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
1009 if (empty($CFG->{$settingname}) ||
!array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
1010 debugging("weird or unset admin value for $settingname, using default instead");
1011 $
$setting = $fileinfo[$setting];
1013 $
$setting = $CFG->{$settingname};
1017 if ($size < $moderate) {
1018 return PORTFOLIO_TIME_LOW
;
1019 } else if ($size < $high) {
1020 return PORTFOLIO_TIME_MODERATE
;
1022 return PORTFOLIO_TIME_HIGH
;
1027 * the default filesizes and threshold information for file based transfers
1028 * this shouldn't need to be used outside the admin pages and the portfolio code
1030 function portfolio_filesize_info() {
1031 $filesizes = array();
1032 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
1033 foreach ($sizelist as $size) {
1034 $filesizes[$size] = display_size($size);
1037 'options' => $filesizes,
1038 'moderate' => 1048576,
1044 * try and determine expected_time for purely database based exports
1045 * or exports that might include large parts of a database
1048 * @param integer $recordcount - number of records trying to export
1049 * @return constant PORTFOLIO_TIME_XXX
1051 function portfolio_expected_time_db($recordcount) {
1054 if (empty($CFG->portfolio_moderate_dbsize_threshold
)) {
1055 set_config('portfolio_moderate_dbsize_threshold', 10);
1057 if (empty($CFG->portfolio_high_dbsize_threshold
)) {
1058 set_config('portfolio_high_dbsize_threshold', 50);
1060 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold
) {
1061 return PORTFOLIO_TIME_LOW
;
1062 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold
) {
1063 return PORTFOLIO_TIME_MODERATE
;
1065 return PORTFOLIO_TIME_HIGH
;
1071 function portfolio_insane_notify_admins($insane, $instances=false) {
1075 if (defined('ADMIN_EDITING_PORTFOLIO')) {
1079 $admins = get_admins();
1081 if (empty($admins)) {
1085 $instances = portfolio_instances(false, false);
1091 $a->sitename
= format_string($site->fullname
, true, array('context' => get_context_instance(CONTEXT_COURSE
, SITEID
)));
1092 $a->fixurl
= "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
1093 $a->htmllist
= portfolio_report_insane($insane, $instances, true);
1096 foreach ($insane as $k => $reason) {
1098 $a->textlist
= $instances[$k]->get('name') . ': ' . $reason . "\n";
1100 $a->textlist
= $k . ': ' . $reason . "\n";
1104 $subject = get_string('insanesubject', 'portfolio');
1105 $plainbody = get_string('insanebody', 'portfolio', $a);
1106 $htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
1107 $smallbody = get_string('insanebodysmall', 'portfolio', $a);
1109 foreach ($admins as $admin) {
1110 $eventdata = new stdClass();
1111 $eventdata->modulename
= 'portfolio';
1112 $eventdata->component
= 'portfolio';
1113 $eventdata->name
= 'notices';
1114 $eventdata->userfrom
= $admin;
1115 $eventdata->userto
= $admin;
1116 $eventdata->subject
= $subject;
1117 $eventdata->fullmessage
= $plainbody;
1118 $eventdata->fullmessageformat
= FORMAT_PLAIN
;
1119 $eventdata->fullmessagehtml
= $htmlbody;
1120 $eventdata->smallmessage
= $smallbody;
1121 message_send($eventdata);
1125 function portfolio_export_pagesetup($PAGE, $caller) {
1126 // set up the context so that build_navigation works nice
1127 $caller->set_context($PAGE);
1129 list($extranav, $cm) = $caller->get_navigation();
1131 // and now we know the course for sure and maybe the cm, call require_login with it
1132 require_login($PAGE->course
, false, $cm);
1134 foreach ($extranav as $navitem) {
1135 $PAGE->navbar
->add($navitem['name']);
1137 $PAGE->navbar
->add(get_string('exporting', 'portfolio'));
1140 function portfolio_export_type_to_id($type, $userid) {
1142 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1143 return $DB->get_field_sql($sql, array($userid, $type));
1147 * return a list of current exports for the given user
1148 * this will not go through and call rewaken_object, because it's heavy
1149 * it's really just used to figure out what exports are currently happening.
1150 * this is useful for plugins that don't support multiple exports per session
1152 * @param int $userid the user to check for
1153 * @param string $type (optional) the portfolio plugin to filter by
1157 function portfolio_existing_exports($userid, $type=null) {
1159 $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 = ? ';
1160 $values = array($userid);
1162 $sql .= ' AND i.plugin = ?';
1165 return $DB->get_records_sql($sql, $values);
1169 * Return an array of existing exports by type for a given user.
1170 * This is much more lightweight than {@see existing_exports} because it only returns the types, rather than the whole serialised data
1171 * so can be used for checking availability of multiple plugins at the same time.
1173 function portfolio_existing_exports_by_plugin($userid) {
1175 $sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1176 $values = array($userid);
1177 return $DB->get_records_sql_menu($sql, $values);
1181 * Return default common options for {@link format_text()} when preparing a content to be exported
1183 * It is important not to apply filters and not to clean the HTML in format_text()
1187 function portfolio_format_text_options() {
1189 $options = new stdClass();
1190 $options->para
= false;
1191 $options->newlines
= true;
1192 $options->filter
= false;
1193 $options->noclean
= true;
1194 $options->overflowdiv
= false;
1200 * callback function from {@link portfolio_rewrite_pluginfile_urls}
1201 * looks through preg_replace matches and replaces content with whatever the active portfolio export format says
1203 function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
1204 $matches = $matches[0]; // no internal matching
1205 $dom = new DomDocument();
1206 if (!$dom->loadXML($matches)) {
1209 $attributes = array();
1210 foreach ($dom->documentElement
->attributes
as $attr => $node) {
1211 $attributes[$attr] = $node->value
;
1213 // now figure out the file
1214 $fs = get_file_storage();
1216 if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
1219 if (!array_key_exists($key, $attributes)) {
1220 debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
1223 $filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') +
strlen('@@PLUGINFILE@@'));
1225 if (strpos($filename, '/') !== 0) {
1226 $bits = explode('/', $filename);
1227 $filename = array_pop($bits);
1228 $filepath = implode('/', $bits);
1230 if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
1231 debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
1234 if (empty($options)) {
1237 $options['attributes'] = $attributes;
1238 return $format->file_output($file, $options);
1243 * go through all the @@PLUGINFILE@@ matches in some text,
1244 * extract the file information and pass it back to the portfolio export format
1245 * to regenerate the html to output
1247 * @param string $text the text to search through
1248 * @param int $contextid normal file_area arguments
1249 * @param string $component
1250 * @param string $filearea normal file_area arguments
1251 * @param int $itemid normal file_area arguments
1252 * @param portfolio_format $format the portfolio export format
1253 * @param array $options extra options to pass through to the file_output function in the format (optional)
1257 function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
1258 $pattern = '/(<[^<]*?="@@PLUGINFILE@@\/[^>]*?(?:\/>|>.*?<\/[^>]*?>))/';
1259 $callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
1260 return preg_replace_callback($pattern, $callback, $text);
1262 // this function has to go last, because the regexp screws up syntax highlighting in some editors