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