"MDL-16596, fixed upload in non-js filepicker"
[moodle.git] / lib / portfoliolib.php
CommitLineData
67a87e7d 1<?php
50fcb1d8 2
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.
14//
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/>.
17
67a87e7d 18/**
87fcac8d 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.
50fcb1d8 22 *
23 * Major Contributors
24 * - Penny Leach <penny@catalyst.net.nz>
25 *
26 * @package moodlecore
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
87fcac8d 30 */
31
50fcb1d8 32/** require all the sublibraries first. */
87fcac8d 33require_once($CFG->libdir . '/portfolio/constants.php'); // all the constants for time, export format etc.
34require_once($CFG->libdir . '/portfolio/exceptions.php'); // exception classes used by portfolio code
35require_once($CFG->libdir . '/portfolio/formats.php'); // the export format hierarchy
36require_once($CFG->libdir . '/portfolio/forms.php'); // the form classes that subclass moodleform
37require_once($CFG->libdir . '/portfolio/exporter.php'); // the exporter class
38require_once($CFG->libdir . '/portfolio/plugin.php'); // the base classes for plugins
39require_once($CFG->libdir . '/portfolio/caller.php'); // the base classes for calling code
40
41/**
50fcb1d8 42 * use this to add a portfolio button or icon or form to a page
43 *
44 * These class methods do not check permissions. the caller must check permissions first.
45 * Later, during the export process, the caller class is instantiated and the check_permissions method is called
887160c7 46 * If you are exporting a single file, you should always call set_format_by_file($file)
50fcb1d8 47 *
48 * This class can be used like this:
49 * <code>
50 * $button = new portfolio_add_button();
51 * $button->set_callback_options('name_of_caller_class', array('id' => 6), '/your/mod/lib.php');
52 * $button->render(PORTFOLIO_ADD_FULL_FORM, get_string('addeverythingtoportfolio', 'yourmodule'));
53 * </code>
54 *
55 * or like this:
56 * <code>
57 * $button = new portfolio_add_button(array('callbackclass' => 'name_of_caller_class', 'callbackargs' => array('id' => 6), 'callbackfile' => '/your/mod/lib.php'));
58 * $somehtml .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
59 * </code>
60 *
61 * See {@link http://docs.moodle.org/en/Development:Adding_a_Portfolio_Button_to_a_page} for more information
62 *
63 * @package moodlecore
64 * @subpackage portfolio
65 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
66 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
67a87e7d 67*/
ce09fecc 68class portfolio_add_button {
67a87e7d 69
ce09fecc 70 private $callbackclass;
71 private $callbackargs;
72 private $callbackfile;
73 private $formats;
74 private $instances;
887160c7 75 private $file; // for single-file exports
67a87e7d 76
ce09fecc 77 /**
78 * constructor. either pass the options here or set them using the helper methods.
79 * generally the code will be clearer if you use the helper methods.
80 *
81 * @param array $options keyed array of options:
82 * key 'callbackclass': name of the caller class (eg forum_portfolio_caller')
83 * key 'callbackargs': the array of callback arguments your caller class wants passed to it in the constructor
84 * key 'callbackfile': the file containing the class definition of your caller class.
85 * See set_callback_options for more information on these three.
86 * key 'formats': an array of PORTFOLIO_FORMATS this caller will support
887160c7 87 * See set_formats or set_format_by_file for more information on this.
ce09fecc 88 */
89 public function __construct($options=null) {
11ae365c 90 global $SESSION, $CFG;
380a251f 91 $this->instances = portfolio_instances();
ce09fecc 92 if (empty($options)) {
93 return true;
94 }
c95a6095 95 $constructoroptions = array('callbackclass', 'callbackargs', 'callbackfile', 'formats');
ce09fecc 96 foreach ((array)$options as $key => $value) {
97 if (!in_array($key, $constructoroptions)) {
98 throw new portfolio_button_exception('invalidbuttonproperty', 'portfolio', $key);
99 }
100 $this->{$key} = $value;
101 }
a239f01e 102 }
103
ce09fecc 104 /*
105 * @param string $class name of the class containing the callback functions
106 * activity modules should ALWAYS use their name_portfolio_caller
107 * other locations must use something unique
108 * @param mixed $argarray this can be an array or hash of arguments to pass
109 * back to the callback functions (passed by reference)
110 * these MUST be primatives to be added as hidden form fields.
111 * and the values get cleaned to PARAM_ALPHAEXT or PARAM_NUMBER or PARAM_PATH
112 * @param string $file this can be autodetected if it's in the same file as your caller,
113 * but often, the caller is a script.php and the class in a lib.php
114 * so you can pass it here if necessary.
115 * this path should be relative (ie, not include) dirroot, eg '/mod/forum/lib.php'
116 */
117 public function set_callback_options($class, array $argarray, $file=null) {
118 global $CFG;
119 if (empty($file)) {
120 $backtrace = debug_backtrace();
121 if (!array_key_exists(0, $backtrace) || !array_key_exists('file', $backtrace[0]) || !is_readable($backtrace[0]['file'])) {
122 throw new portfolio_button_exception('nocallbackfile', 'portfolio');
123 }
124
125 $file = substr($backtrace[0]['file'], strlen($CFG->dirroot));
126 } else if (!is_readable($CFG->dirroot . $file)) {
127 throw new portfolio_button_exception('nocallbackfile', 'portfolio', $file);
128 }
129 $this->callbackfile = $file;
130 require_once($CFG->dirroot . $file);
131 if (!class_exists($class)) {
132 throw new portfolio_button_exception('nocallbackclass', 'portfolio', $class);
133 }
0d06b6fd 134
135 // this will throw exceptions
136 // but should not actually do anything other than verify callbackargs
137 $test = new $class($argarray);
138 unset($test);
139
ce09fecc 140 $this->callbackclass = $class;
141 $this->callbackargs = $argarray;
67a87e7d 142 }
143
ce09fecc 144 /*
9d7432f6 145 * sets the available export formats for this content
146 * this function will also poll the static function in the caller class
147 * and make sure we're not overriding a format that has nothing to do with mimetypes
148 * eg if you pass IMAGE here but the caller can export LEAP it will keep LEAP as well.
149 * see portfolio_most_specific_formats for more information
150 *
ce09fecc 151 * @param array $formats if the calling code knows better than the static method on the calling class (supported_formats)
152 * eg, if it's going to be a single file, or if you know it's HTML, you can pass it here instead
153 * this is almost always the case so you should always use this.
154 * {@see portfolio_format_from_file} for how to get the appropriate formats to pass here for uploaded files.
155 */
156 public function set_formats($formats=null) {
157 if (is_string($formats)) {
158 $formats = array($formats);
159 }
160 if (empty($formats)) {
9d7432f6 161 $formats = array();
ce09fecc 162 }
9d7432f6 163 if (empty($this->callbackclass)) {
164 throw new portfolio_button_exception('noclassbeforeformats', 'portfolio');
d1581fc5 165 }
9d7432f6 166 $callerformats = call_user_func(array($this->callbackclass, 'supported_formats'));
167 $this->formats = portfolio_most_specific_formats($formats, $callerformats);
6fdd8fa7 168 }
169
887160c7
PL
170 /**
171 * if we already know we have exactly one file,
172 * bypass set_formats and just pass the file
173 * so we can detect the formats by mimetype.
174 *
175 * @param stored_file $file
176 */
177 public function set_format_by_file(stored_file $file) {
178 $this->file = $file;
179 $this->formats = array(portfolio_format_from_file($file));
180 }
181
ce09fecc 182 /*
183 * echo the form/button/icon/text link to the page
184 *
185 * @param int $format format to display the button or form or icon or link.
186 * See constants PORTFOLIO_ADD_XXX for more info.
187 * optional, defaults to PORTFOLI_ADD_FULL_FORM
188 * @param str $addstr string to use for the button or icon alt text or link text.
189 * this is whole string, not key. optional, defaults to 'Add to portfolio';
190 */
191 public function render($format=null, $addstr=null) {
380a251f 192 echo $this->to_html($format, $addstr);
84a44985 193 }
194
ce09fecc 195 /*
196 * returns the form/button/icon/text link as html
197 *
198 * @param int $format format to display the button or form or icon or link.
199 * See constants PORTFOLIO_ADD_XXX for more info.
200 * optional, defaults to PORTFOLI_ADD_FULL_FORM
201 * @param str $addstr string to use for the button or icon alt text or link text.
202 * this is whole string, not key. optional, defaults to 'Add to portfolio';
203 */
204 public function to_html($format=null, $addstr=null) {
add93b8f 205 global $CFG, $COURSE, $OUTPUT, $USER;
ce09fecc 206 if (!$this->is_renderable()) {
ed1fcf79 207 return;
208 }
380a251f 209 if (empty($this->callbackclass) || empty($this->callbackfile)) {
210 throw new portfolio_button_exception('mustsetcallbackoptions', 'portfolio');
ce09fecc 211 }
212 if (empty($this->formats)) {
213 // use the caller defaults
214 $this->set_formats();
215 }
216 $formoutput = '<form method="post" action="' . $CFG->wwwroot . '/portfolio/add.php" id="portfolio-add-button">' . "\n";
217 $linkoutput = '<a href="' . $CFG->wwwroot . '/portfolio/add.php?';
218 foreach ($this->callbackargs as $key => $value) {
219 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
220 $a->key = $key;
221 $a->value = print_r($value, true);
222 debugging(get_string('nonprimative', 'portfolio', $a));
223 return;
224 }
225 $linkoutput .= 'ca_' . $key . '=' . $value . '&amp;';
226 $formoutput .= "\n" . '<input type="hidden" name="ca_' . $key . '" value="' . $value . '" />';
227 }
766d61cb 228 $formoutput .= "\n" . '<input type="hidden" name="sesskey" value="' . sesskey() . '" />';
229 $linkoutput .= 'sesskey=' . sesskey() . '&amp;';
ce09fecc 230 $formoutput .= "\n" . '<input type="hidden" name="callbackfile" value="' . $this->callbackfile . '" />';
231 $formoutput .= "\n" . '<input type="hidden" name="callbackclass" value="' . $this->callbackclass . '" />';
232 $formoutput .= "\n" . '<input type="hidden" name="course" value="' . (!empty($COURSE) ? $COURSE->id : 0) . '" />';
233 $linkoutput .= 'callbackfile=' . $this->callbackfile . '&amp;callbackclass='
234 . $this->callbackclass . '&amp;course=' . (!empty($COURSE) ? $COURSE->id : 0);
235 $selectoutput = '';
236 if (count($this->instances) == 1) {
6be1dcae 237 $tmp = array_values($this->instances);
238 $instance = $tmp[0];
c95a6095 239
ce09fecc 240 $formats = portfolio_supported_formats_intersect($this->formats, $instance->supported_formats());
241 if (count($formats) == 0) {
242 // bail. no common formats.
add93b8f 243 debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $this->callbackclass, 'formats' => implode(',', $this->formats))));
ce09fecc 244 return;
245 }
246 if ($error = portfolio_instance_sanity_check($instance)) {
247 // bail, plugin is misconfigured
248 debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
249 return;
250 }
c95a6095
PL
251 if (!$instance->allows_multiple_exports() && $already = portfolio_exporter::existing_exports($USER->id, $instance->get('plugin'))) {
252 debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
253 return;
254 }
887160c7
PL
255 if ($this->file && $this->file instanceof stored_file && !$instance->file_mime_check($this->file->get_mimetype())) {
256 // bail, we have a specific file and this plugin doesn't support it
add93b8f 257 debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $this->file->get_mimetype())));
887160c7
PL
258 return;
259 }
ce09fecc 260 $formoutput .= "\n" . '<input type="hidden" name="instance" value="' . $instance->get('id') . '" />';
261 $linkoutput .= '&amp;instance=' . $instance->get('id');
262 }
263 else {
887160c7 264 if (!$selectoutput = portfolio_instance_select($this->instances, $this->formats, $this->file, $this->callbackclass, 'instance', true)) {
3ec8d786
PL
265 return;
266 }
ed1fcf79 267 }
67a87e7d 268
ce09fecc 269 if (empty($addstr)) {
270 $addstr = get_string('addtoportfolio', 'portfolio');
271 }
272 if (empty($format)) {
273 $format = PORTFOLIO_ADD_FULL_FORM;
274 }
275 switch ($format) {
276 case PORTFOLIO_ADD_FULL_FORM:
277 $formoutput .= $selectoutput;
278 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
279 $formoutput .= "\n" . '</form>';
280 break;
281 case PORTFOLIO_ADD_ICON_FORM:
282 $formoutput .= $selectoutput;
f2a1963c 283 $formoutput .= "\n" . '<input type="image" src="' . $OUTPUT->old_icon_url('t/portfolio') . '" alt=' . $addstr .'" />';
ce09fecc 284 $formoutput .= "\n" . '</form>';
285 break;
286 case PORTFOLIO_ADD_ICON_LINK:
f2a1963c 287 $linkoutput .= '"><img src="' . $OUTPUT->old_icon_url('t/portfolio') . '" alt=' . $addstr .'" /></a>';
ce09fecc 288 break;
289 case PORTFOLIO_ADD_TEXT_LINK:
290 $linkoutput .= '">' . $addstr .'</a>';
291 break;
292 default:
293 debugging(get_string('invalidaddformat', 'portfolio', $format));
294 }
295 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
296 return $output;
349242a3 297 }
67a87e7d 298
ce09fecc 299 /**
300 * does some internal checks
301 * these are not errors, just situations
302 * where it's not appropriate to add the button
303 */
304 private function is_renderable() {
305 global $CFG;
306 if (empty($CFG->enableportfolios)) {
307 return false;
67a87e7d 308 }
ce09fecc 309 if (defined('PORTFOLIO_INTERNAL')) {
310 // something somewhere has detected a risk of this being called during inside the preparation
311 // eg forum_print_attachments
312 return false;
67a87e7d 313 }
380a251f 314 if (empty($this->instances) || count($this->instances) == 0) {
ce09fecc 315 return false;
67a87e7d 316 }
ce09fecc 317 return true;
67a87e7d 318 }
ef6f0f60 319
320 /**
321 * Getter for $format property
322 * @return array
323 */
324 public function get_formats() {
325 return $this->formats;
326 }
327
328 /**
329 * Getter for $callbackargs property
330 * @return array
331 */
332 public function get_callbackargs() {
333 return $this->callbackargs;
334 }
335
336 /**
337 * Getter for $callbackfile property
338 * @return array
339 */
340 public function get_callbackfile() {
341 return $this->callbackfile;
342 }
343
344 /**
345 * Getter for $callbackclass property
346 * @return array
347 */
348 public function get_callbackclass() {
349 return $this->callbackclass;
350 }
ce09fecc 351}
67a87e7d 352
67a87e7d 353/**
354* returns a drop menu with a list of available instances.
355*
887160c7
PL
356* @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
357* @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
358* @param array $callbackclass the callback class name - used for debugging only for when there are no common formats
359* @param stored_file $file if we already know we have exactly one file, pass it here to do mime filtering.
360* @param string $selectname the name of the select element. Optional, defaults to instance.
361* @param boolean $return whether to print or return the output. Optional, defaults to print.
362* @param booealn $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
67a87e7d 363*
364* @return string the html, from <select> to </select> inclusive.
365*/
887160c7 366function portfolio_instance_select($instances, $callerformats, $callbackclass, $file=null, $selectname='instance', $return=false, $returnarray=false) {
c95a6095 367 global $CFG, $USER;
9eb0a772 368
90658eef 369 if (empty($CFG->enableportfolios)) {
9eb0a772 370 return;
371 }
372
67a87e7d 373 $insane = portfolio_instance_sanity_check();
b816c08a 374 $pinsane = portfolio_plugin_sanity_check();
375
67a87e7d 376 $count = 0;
9eb0a772 377 $selectoutput = "\n" . '<select name="' . $selectname . '">' . "\n";
c95a6095 378 $existingexports = portfolio_exporter::existing_exports_by_plugin($USER->id);
67a87e7d 379 foreach ($instances as $instance) {
349242a3 380 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
381 if (count($formats) == 0) {
67a87e7d 382 // bail. no common formats.
383 continue;
384 }
385 if (array_key_exists($instance->get('id'), $insane)) {
386 // bail, plugin is misconfigured
b816c08a 387 debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
388 continue;
389 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
390 // bail, plugin is misconfigured
391 debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
67a87e7d 392 continue;
393 }
c95a6095
PL
394 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
395 // bail, already exporting something with this plugin and it doesn't support multiple exports
396 continue;
397 }
887160c7 398 if ($file && $file instanceof stored_file && !$instance->file_mime_check($file->get_mimetype())) {
add93b8f 399 debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $this->file->get_mimetype())));
887160c7
PL
400 // bail, we have a specific file and this plugin doesn't support it
401 continue;
402 }
67a87e7d 403 $count++;
9eb0a772 404 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
405 $options[$instance->get('id')] = $instance->get('name');
67a87e7d 406 }
407 if (empty($count)) {
408 // bail. no common formats.
add93b8f 409 debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
67a87e7d 410 return;
411 }
412 $selectoutput .= "\n" . "</select>\n";
9eb0a772 413 if (!empty($returnarray)) {
414 return $options;
415 }
416 if (!empty($return)) {
417 return $selectoutput;
418 }
419 echo $selectoutput;
67a87e7d 420}
421
422/**
423* return all portfolio instances
424*
87fcac8d 425* @todo check capabilities here - see MDL-15768
426*
427* @param boolean visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
428* @param boolean useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
429*
67a87e7d 430* @return array of portfolio instances (full objects, not just database records)
431*/
432function portfolio_instances($visibleonly=true, $useronly=true) {
433
434 global $DB, $USER;
435
436 $values = array();
437 $sql = 'SELECT * FROM {portfolio_instance}';
438
439 if ($visibleonly || $useronly) {
440 $values[] = 1;
441 $sql .= ' WHERE visible = ?';
442 }
443 if ($useronly) {
444 $sql .= ' AND id NOT IN (
445 SELECT instance FROM {portfolio_instance_user}
446 WHERE userid = ? AND name = ? AND value = ?
447 )';
448 $values = array_merge($values, array($USER->id, 'visible', 0));
449 }
450 $sql .= ' ORDER BY name';
451
452 $instances = array();
453 foreach ($DB->get_records_sql($sql, $values) as $instance) {
a50ef3d3 454 $instances[$instance->id] = portfolio_instance($instance->id, $instance);
67a87e7d 455 }
67a87e7d 456 return $instances;
457}
458
459/**
87fcac8d 460* Supported formats currently in use.
461*
462* Canonical place for a list of all formats
463* that portfolio plugins and callers
67a87e7d 464* can use for exporting content
465*
87fcac8d 466* @return keyed array of all the available export formats (constant => classname)
67a87e7d 467*/
468function portfolio_supported_formats() {
469 return array(
a9ec9031
DP
470 PORTFOLIO_FORMAT_FILE => 'portfolio_format_file',
471 PORTFOLIO_FORMAT_IMAGE => 'portfolio_format_image',
472 PORTFOLIO_FORMAT_RICHHTML => 'portfolio_format_richhtml',
473 PORTFOLIO_FORMAT_PLAINHTML => 'portfolio_format_plainhtml',
474 PORTFOLIO_FORMAT_TEXT => 'portfolio_format_text',
475 PORTFOLIO_FORMAT_VIDEO => 'portfolio_format_video',
476 PORTFOLIO_FORMAT_PDF => 'portfolio_format_pdf',
477 PORTFOLIO_FORMAT_DOCUMENT => 'portfolio_format_document',
478 PORTFOLIO_FORMAT_SPREADSHEET => 'portfolio_format_spreadsheet',
479 PORTFOLIO_FORMAT_PRESENTATION => 'portfolio_format_presentation',
5071079c 480 /*PORTFOLIO_FORMAT_MBKP, */ // later
6be1dcae 481 /*PORTFOLIO_FORMAT_LEAP, */ // also later
67a87e7d 482 );
483}
484
ea0de12f 485/**
87fcac8d 486* Deduce export format from file mimetype
487*
488* This function returns the revelant portfolio export format
ea0de12f 489* which is used to determine which portfolio plugins can be used
490* for exporting this content
491* according to the mime type of the given file
492* this only works when exporting exactly <b>one</b> file
493*
494* @param stored_file $file file to check mime type for
87fcac8d 495*
ea0de12f 496* @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
497*/
87fcac8d 498function portfolio_format_from_file(stored_file $file) {
ea0de12f 499 static $alreadymatched;
500 if (empty($alreadymatched)) {
501 $alreadymatched = array();
502 }
503 if (!($file instanceof stored_file)) {
504 throw new portfolio_exception('invalidfileargument', 'portfolio');
505 }
506 $mimetype = $file->get_mimetype();
507 if (array_key_exists($mimetype, $alreadymatched)) {
508 return $alreadymatched[$mimetype];
509 }
510 $allformats = portfolio_supported_formats();
511 foreach ($allformats as $format => $classname) {
512 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
513 if (!is_array($supportedmimetypes)) {
514 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
515 debugging(print_r($supportedmimetypes, true));
516 continue;
517 }
518 if (in_array($mimetype, $supportedmimetypes)) {
519 $alreadymatched[$mimetype] = $format;
520 return $format;
521 }
522 }
523 return PORTFOLIO_FORMAT_FILE; // base case for files...
524}
525
526/**
87fcac8d 527* Intersection of plugin formats and caller formats
528*
529* Walks both the caller formats and portfolio plugin formats
ea0de12f 530* and looks for matches (walking the hierarchy as well)
531* and returns the intersection
532*
533* @param array $callerformats formats the caller supports
534* @param array $pluginformats formats the portfolio plugin supports
535*/
7812e882 536function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
537 $allformats = portfolio_supported_formats();
538 $intersection = array();
539 foreach ($callerformats as $cf) {
540 if (!array_key_exists($cf, $allformats)) {
541 debugging(get_string('invalidformat', 'portfolio', $cf));
542 continue;
543 }
34035201 544 $cfobj = new $allformats[$cf]();
7812e882 545 foreach ($pluginformats as $p => $pf) {
546 if (!array_key_exists($pf, $allformats)) {
547 debugging(get_string('invalidformat', 'portfolio', $pf));
548 unset($pluginformats[$p]); // to avoid the same warning over and over
549 continue;
550 }
34035201 551 if ($cfobj instanceof $allformats[$pf]) {
7812e882 552 $intersection[] = $cf;
553 }
554 }
555 }
556 return $intersection;
557}
558
9d7432f6 559/**
560* return the combination of the two arrays of formats with duplicates in terms of specificity removed
561* use case: a module is exporting a single file, so the general formats would be FILE and MBKP
562* while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
563* and this function would return IMAGE and MBKP
564*
565* @param array $specificformats array of more specific formats (eg based on mime detection)
566* @param array $generalformats array of more general formats (usually more supported)
567*
568* @return array merged formats with dups removed
569*/
570function portfolio_most_specific_formats($specificformats, $generalformats) {
571 $allformats = portfolio_supported_formats();
572 foreach ($specificformats as $f) {
573 // look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
574 if (!array_key_exists($f, $allformats)) {
575 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
576 }
577 $fobj = new $allformats[$f];
578 foreach ($generalformats as $key => $cf) {
579 $cfclass = $allformats[$cf];
580 if ($fobj instanceof $cfclass) {
581 unset($generalformats[$cf]);
582 }
583 }
584 }
585 return array_merge(array_values($specificformats), array_values($generalformats));
586}
587
6be1dcae 588/**
589* helper function to return a format object from the constant
590*
591* @param string $name the constant PORTFOLIO_FORMAT_XXX
592*
593* @return portfolio_format object
594*/
595function portfolio_format_object($name) {
596 $formats = portfolio_supported_formats();
597 return new $formats[$name];
598}
599
67a87e7d 600/**
601* helper function to return an instance of a plugin (with config loaded)
602*
87fcac8d 603* @param int $instance id of instance
604* @param array $record database row that corresponds to this instance
605* this is passed to avoid unnecessary lookups
606* Optional, and the record will be retrieved if null.
67a87e7d 607*
608* @return subclass of portfolio_plugin_base
609*/
610function portfolio_instance($instanceid, $record=null) {
611 global $DB, $CFG;
612
613 if ($record) {
614 $instance = $record;
615 } else {
616 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
34035201 617 throw new portfolio_exception('invalidinstance', 'portfolio');
67a87e7d 618 }
619 }
edf1fc35 620 require_once($CFG->dirroot . '/portfolio/'. $instance->plugin . '/lib.php');
67a87e7d 621 $classname = 'portfolio_plugin_' . $instance->plugin;
622 return new $classname($instanceid, $instance);
623}
624
625/**
87fcac8d 626* Helper function to call a static function on a portfolio plugin class
627*
628* This will figure out the classname and require the right file and call the function.
67a87e7d 629* you can send a variable number of arguments to this function after the first two
630* and they will be passed on to the function you wish to call.
631*
87fcac8d 632* @param string $plugin name of plugin
67a87e7d 633* @param string $function function to call
634*/
635function portfolio_static_function($plugin, $function) {
636 global $CFG;
637
638 $pname = null;
639 if (is_object($plugin) || is_array($plugin)) {
640 $plugin = (object)$plugin;
641 $pname = $plugin->name;
642 } else {
643 $pname = $plugin;
644 }
645
646 $args = func_get_args();
647 if (count($args) <= 2) {
648 $args = array();
649 }
650 else {
651 array_shift($args);
652 array_shift($args);
653 }
654
edf1fc35 655 require_once($CFG->dirroot . '/portfolio/' . $plugin . '/lib.php');
67a87e7d 656 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
657}
658
659/**
660* helper function to check all the plugins for sanity and set any insane ones to invisible.
661*
662* @param array $plugins to check (if null, defaults to all)
663* one string will work too for a single plugin.
664*
665* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
666*/
667function portfolio_plugin_sanity_check($plugins=null) {
668 global $DB;
669 if (is_string($plugins)) {
98c8594a 670 $plugins = array($plugins);
67a87e7d 671 } else if (empty($plugins)) {
17da2e6f 672 $plugins = get_plugin_list('portfolio');
98c8594a 673 $plugins = array_keys($plugins);
67a87e7d 674 }
675
676 $insane = array();
98c8594a 677 foreach ($plugins as $plugin) {
67a87e7d 678 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
679 $insane[$plugin] = $result;
680 }
681 }
682 if (empty($insane)) {
683 return array();
684 }
685 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
686 $where = ' plugin ' . $where;
687 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
688 return $insane;
689}
690
691/**
692* helper function to check all the instances for sanity and set any insane ones to invisible.
693*
694* @param array $instances to check (if null, defaults to all)
695* one instance or id will work too
696*
697* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
698*/
699function portfolio_instance_sanity_check($instances=null) {
700 global $DB;
701 if (empty($instances)) {
702 $instances = portfolio_instances(false);
703 } else if (!is_array($instances)) {
704 $instances = array($instances);
705 }
706
707 $insane = array();
708 foreach ($instances as $instance) {
709 if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) {
710 $instance = portfolio_instance($instance->id, $instance);
711 } else if (is_numeric($instance)) {
712 $instance = portfolio_instance($instance);
713 }
714 if (!($instance instanceof portfolio_plugin_base)) {
715 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
716 continue;
717 }
718 if ($result = $instance->instance_sanity_check()) {
719 $insane[$instance->get('id')] = $result;
720 }
721 }
722 if (empty($insane)) {
723 return array();
724 }
725 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
726 $where = ' id ' . $where;
727 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
b816c08a 728 portfolio_insane_notify_admins($insane, true);
67a87e7d 729 return $insane;
730}
731
732/**
733* helper function to display a table of plugins (or instances) and reasons for disabling
734*
735* @param array $insane array of insane plugins (key = plugin (or instance id), value = reason)
736* @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
737*
738*/
a50ef3d3 739function portfolio_report_insane($insane, $instances=false, $return=false) {
aa9a6867 740 global $OUTPUT;
67a87e7d 741 if (empty($insane)) {
742 return;
743 }
744
745 static $pluginstr;
746 if (empty($pluginstr)) {
747 $pluginstr = get_string('plugin', 'portfolio');
748 }
749 if ($instances) {
750 $headerstr = get_string('someinstancesdisabled', 'portfolio');
751 } else {
752 $headerstr = get_string('somepluginsdisabled', 'portfolio');
753 }
754
aa9a6867 755 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
642816a6 756 $table = new html_table();
67a87e7d 757 $table->head = array($pluginstr, '');
758 $table->data = array();
759 foreach ($insane as $plugin => $reason) {
760 if ($instances) {
67a87e7d 761 $instance = $instances[$plugin];
762 $plugin = $instance->get('plugin');
763 $name = $instance->get('name');
764 } else {
765 $name = $plugin;
766 }
767 $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
768 }
642816a6 769 $output .= $OUTPUT->table($table);
a50ef3d3 770 $output .= '<br /><br /><br />';
771
772 if ($return) {
773 return $output;
774 }
775 echo $output;
67a87e7d 776}
777
9eb0a772 778/**
779* fake the url to portfolio/add.php from data from somewhere else
780* you should use portfolio_add_button instead 99% of the time
781*
87fcac8d 782* @param int $instanceid instanceid (optional, will force a new screen if not specified)
783* @param string $classname callback classname
784* @param string $classfile file containing the callback class definition
785* @param array $callbackargs arguments to pass to the callback class
9eb0a772 786*/
787function portfolio_fake_add_url($instanceid, $classname, $classfile, $callbackargs) {
788 global $CFG;
c95a6095 789 $url = $CFG->wwwroot . '/portfolio/add.php?instance=' . $instanceid . '&amp;callbackclass=' . $classname . '&amp;callbackfile=' . $classfile . '&sesskey=' . sesskey();
9eb0a772 790
791 if (is_object($callbackargs)) {
792 $callbackargs = (array)$callbackargs;
793 }
794 if (!is_array($callbackargs) || empty($callbackargs)) {
795 return $url;
796 }
797 foreach ($callbackargs as $key => $value) {
798 $url .= '&amp;ca_' . $key . '=' . urlencode($value);
799 }
800 return $url;
801}
67a87e7d 802
67a87e7d 803
67a87e7d 804
87fcac8d 805/**
806* event handler for the portfolio_send event
807*/
808function portfolio_handle_event($eventdata) {
809 global $CFG;
810 $exporter = portfolio_exporter::rewaken_object($eventdata);
811 $exporter->process_stage_package();
812 $exporter->process_stage_send();
813 $exporter->save();
814 $exporter->process_stage_cleanup();
815 return true;
67a87e7d 816}
817
87fcac8d 818/**
819* main portfolio cronjob
820* currently just cleans up expired transfer records.
821*
822* @todo add hooks in the plugins - either per instance or per plugin
823*/
824function portfolio_cron() {
825 global $DB;
9eb0a772 826
87fcac8d 827 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()), '', 'id')) {
828 foreach ($expired as $d) {
2512cb35 829 try {
830 $e = portfolio_exporter::rewaken_object($d->id);
831 $e->process_stage_cleanup(true);
832 } catch (Exception $e) {
833 mtrade('Exception thrown in portfolio cron while cleaning up ' . $d->id . ': ' . $e->getMessage());
834 }
9eb0a772 835 }
192ce92b 836 }
5071079c 837}
838
67a87e7d 839/**
50fcb1d8 840 * helper function to rethrow a caught portfolio_exception as an export exception
841 *
842 * used because when a portfolio_export exception is thrown the export is cancelled
843 *
844 * throws portfolio_export_exceptiog
845 *
846 * @param portfolio_exporter $exporter current exporter object
847 * @param exception $exception exception to rethrow
848 *
849 * @return void
850 */
87fcac8d 851function portfolio_export_rethrow_exception($exporter, $exception) {
852 throw new portfolio_export_exception($exporter, $exception->errorcode, $exception->module, $exception->link, $exception->a);
853}
67a87e7d 854
bee4bce2 855/**
856* try and determine expected_time for purely file based exports
857* or exports that might include large file attachments.
858*
50fcb1d8 859 * @global object
bee4bce2 860* @param mixed $totest - either an array of stored_file objects or a single stored_file object
bee4bce2 861* @return constant PORTFOLIO_TIME_XXX
862*/
863function portfolio_expected_time_file($totest) {
864 global $CFG;
865 if ($totest instanceof stored_file) {
866 $totest = array($totest);
867 }
868 $size = 0;
869 foreach ($totest as $file) {
870 if (!($file instanceof stored_file)) {
871 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
872 debugging(print_r($file, true));
873 continue;
874 }
875 $size += $file->get_filesize();
876 }
877
878 $fileinfo = portfolio_filesize_info();
879
880 $moderate = $high = 0; // avoid warnings
881
882 foreach (array('moderate', 'high') as $setting) {
883 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
884 if (empty($CFG->{$settingname}) || !array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
885 debugging("weird or unset admin value for $settingname, using default instead");
886 $$setting = $fileinfo[$setting];
887 } else {
888 $$setting = $CFG->{$settingname};
889 }
890 }
891
892 if ($size < $moderate) {
893 return PORTFOLIO_TIME_LOW;
894 } else if ($size < $high) {
895 return PORTFOLIO_TIME_MODERATE;
896 }
897 return PORTFOLIO_TIME_HIGH;
898}
899
900
901/**
902* the default filesizes and threshold information for file based transfers
903* this shouldn't need to be used outside the admin pages and the portfolio code
904*/
905function portfolio_filesize_info() {
906 $filesizes = array();
907 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
908 foreach ($sizelist as $size) {
909 $filesizes[$size] = display_size($size);
910 }
911 return array(
912 'options' => $filesizes,
913 'moderate' => 1048576,
914 'high' => 5242880,
915 );
916}
917
918/**
919* try and determine expected_time for purely database based exports
920* or exports that might include large parts of a database
921*
50fcb1d8 922 * @global object
bee4bce2 923* @param integer $recordcount - number of records trying to export
bee4bce2 924* @return constant PORTFOLIO_TIME_XXX
925*/
926function portfolio_expected_time_db($recordcount) {
927 global $CFG;
928
929 if (empty($CFG->portfolio_moderate_dbsize_threshold)) {
930 set_config('portfolio_moderate_dbsize_threshold', 10);
931 }
932 if (empty($CFG->portfolio_high_dbsize_threshold)) {
933 set_config('portfolio_high_dbsize_threshold', 50);
934 }
935 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold) {
936 return PORTFOLIO_TIME_LOW;
937 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold) {
938 return PORTFOLIO_TIME_MODERATE;
939 }
940 return PORTFOLIO_TIME_HIGH;
941}
67a87e7d 942
50fcb1d8 943/**
944 * @global object
945 */
b816c08a 946function portfolio_insane_notify_admins($insane, $instances=false) {
947
948 global $CFG;
949
950 if (defined('ADMIN_EDITING_PORTFOLIO')) {
951 return true;
952 }
953
954 $admins = get_admins();
955
956 if (empty($admins)) {
957 return;
958 }
959 if ($instances) {
960 $instances = portfolio_instances(false, false);
961 }
962
963 $site = get_site();
964
965 $a = new StdClass;
966 $a->sitename = $site->fullname;
d1aa1e48 967 $a->fixurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
b816c08a 968 $a->htmllist = portfolio_report_insane($insane, $instances, true);
969 $a->textlist = '';
970
971 foreach ($insane as $k => $reason) {
972 if ($instances) {
973 $a->textlist = $instances[$k]->get('name') . ': ' . $reason . "\n";
974 } else {
975 $a->textlist = $k . ': ' . $reason . "\n";
976 }
977 }
978
979 $subject = get_string('insanesubject', 'portfolio');
980 $plainbody = get_string('insanebody', 'portfolio', $a);
981 $htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
982 $smallbody = get_string('insanebodysmall', 'portfolio', $a);
983
984 foreach ($admins as $admin) {
985 $eventdata = new object();
986 $eventdata->modulename = 'portfolio';
987 $eventdata->component = 'portfolio';
988 $eventdata->name = 'notices';
989 $eventdata->userfrom = $admin;
990 $eventdata->userto = $admin;
991 $eventdata->subject = $subject;
992 $eventdata->fullmessage = $plainbody;
993 $eventdata->fullmessageformat = FORMAT_PLAIN;
994 $eventdata->fullmessagehtml = $htmlbody;
995 $eventdata->smallmessage = $smallbody;
7c7d3afa 996 message_send($eventdata);
b816c08a 997 }
998}
f1d2641d
PL
999
1000function portfolio_export_pagesetup($PAGE, $caller) {
1001 // for build navigation
1002 if (!$course = $caller->get('course')) {
1003 $course = $courseid;
1004 }
1005
1006 // set up the course so that build_navigation works nice
1007 $PAGE->set_course($course);
1008
1009 list($extranav, $cm) = $caller->get_navigation();
1010
1011 // and now we know the course for sure and maybe the cm, call require_login with it
1012 // todo this will have to change when we have things exporting content outside the course context (eg blogs)
1013 require_login($course, false, $cm);
1014
1015 foreach ($extranav as $navitem) {
1016 $PAGE->navbar->add($navitem['name']);
1017 }
1018 $PAGE->navbar->add(get_string('exporting', 'portfolio'));
1019}
b12fbe8e
PL
1020
1021function portfolio_export_type_to_id($type, $userid) {
1022 global $DB;
1023 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1024 return $DB->get_field_sql($sql, array($userid, $type));
1025}