MDL-33791 Portfolio: Fixed security issue with passing file paths.
[moodle.git] / lib / portfoliolib.php
CommitLineData
67a87e7d 1<?php
50fcb1d8 2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
67a87e7d 17/**
93dd2725
RW
18 * This file contains all global functions to do with manipulating portfolios.
19 *
20 * Everything else that is logically namespaced by class is in its own file
87fcac8d 21 * in lib/portfolio/ directory.
50fcb1d8 22 *
23 * Major Contributors
24 * - Penny Leach <penny@catalyst.net.nz>
25 *
93dd2725
RW
26 * @package core_portfolio
27 * @category portfolio
50fcb1d8 28 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
93dd2725 29 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
87fcac8d 30 */
31
78bfb562
PS
32defined('MOODLE_INTERNAL') || die();
33
24ba58ee
PL
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
37
38// very lightweight list of constants. always needed and no further dependencies
39require_once($CFG->libdir . '/portfolio/constants.php');
40// a couple of exception deinitions. always needed and no further dependencies
87fcac8d 41require_once($CFG->libdir . '/portfolio/exceptions.php'); // exception classes used by portfolio code
24ba58ee
PL
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.
45require_once($CFG->libdir . '/portfolio/caller.php');
46
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
52
87fcac8d 53
54/**
93dd2725 55 * Use this to add a portfolio button or icon or form to a page.
18cdcdbf 56 *
50fcb1d8 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
887160c7 59 * If you are exporting a single file, you should always call set_format_by_file($file)
50fcb1d8 60 * This class can be used like this:
61 * <code>
62 * $button = new portfolio_add_button();
37743241
MN
63 * $button->set_callback_options('name_of_caller_class', array('id' => 6), 'yourcomponent'); eg. mod_forum
64 * $button->render(PORTFOLIO_ADD_FULL_FORM, get_string('addeverythingtoportfolio', 'yourcomponent'));
50fcb1d8 65 * </code>
50fcb1d8 66 * or like this:
67 * <code>
37743241 68 * $button = new portfolio_add_button(array('callbackclass' => 'name_of_caller_class', 'callbackargs' => array('id' => 6), 'callbackcomponent' => 'yourcomponent')); eg. mod_forum
50fcb1d8 69 * $somehtml .= $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
70 * </code>
93dd2725 71 *{@link http://docs.moodle.org/dev/Adding_a_Portfolio_Button_to_a_page} for more information
50fcb1d8 72 *
93dd2725
RW
73 * @package core_portfolio
74 * @category portfolio
50fcb1d8 75 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93dd2725 77 */
ce09fecc 78class portfolio_add_button {
67a87e7d 79
93dd2725 80 /** @var string the name of the callback functions */
ce09fecc 81 private $callbackclass;
93dd2725
RW
82
83 /** @var array can be an array of arguments to pass back to the callback functions (passed by reference)*/
ce09fecc 84 private $callbackargs;
93dd2725
RW
85
86 /** @var string caller file */
37743241 87 private $callbackcomponent;
93dd2725
RW
88
89 /** @var array array of more specific formats (eg based on mime detection) */
ce09fecc 90 private $formats;
93dd2725
RW
91
92 /** @var array array of portfolio instances */
ce09fecc 93 private $instances;
93dd2725
RW
94
95 /** @var stored_file for single-file exports */
96 private $file;
97
98 /** @var string for writing specific types of files*/
99 private $intendedmimetype;
67a87e7d 100
ce09fecc 101 /**
93dd2725
RW
102 * Constructor. Either pass the options here or set them using the helper methods.
103 * Generally the code will be clearer if you use the helper methods.
104 *
105 * @param array $options keyed array of options:
106 * key 'callbackclass': name of the caller class (eg forum_portfolio_caller')
107 * key 'callbackargs': the array of callback arguments your caller class wants passed to it in the constructor
37743241 108 * key 'callbackcomponent': the file containing the class definition of your caller class.
93dd2725
RW
109 * See set_callback_options for more information on these three.
110 * key 'formats': an array of PORTFOLIO_FORMATS this caller will support
111 * See set_formats or set_format_by_file for more information on this.
112 */
ce09fecc 113 public function __construct($options=null) {
11ae365c 114 global $SESSION, $CFG;
6708a1f5
SH
115
116 if (empty($CFG->enableportfolios)) {
117 debugging('Building portfolio add button while portfolios is disabled. This code can be optimised.', DEBUG_DEVELOPER);
118 }
119
380a251f 120 $this->instances = portfolio_instances();
ce09fecc 121 if (empty($options)) {
122 return true;
123 }
37743241 124 $constructoroptions = array('callbackclass', 'callbackargs', 'callbackcomponent');
ce09fecc 125 foreach ((array)$options as $key => $value) {
126 if (!in_array($key, $constructoroptions)) {
127 throw new portfolio_button_exception('invalidbuttonproperty', 'portfolio', $key);
128 }
ce09fecc 129 }
37743241
MN
130
131 $this->set_callback_options($options['callbackclass'], $options['callbackargs'], $options['callbackcomponent']);
a239f01e 132 }
133
93dd2725
RW
134 /**
135 * Function to set the callback options
136 *
37743241
MN
137 * @param string $class Name of the class containing the callback functions
138 * activity components should ALWAYS use their name_portfolio_caller
139 * other locations must use something unique
93dd2725 140 * @param array $argarray This can be an array or hash of arguments to pass
37743241
MN
141 * back to the callback functions (passed by reference)
142 * these MUST be primatives to be added as hidden form fields.
143 * and the values get cleaned to PARAM_ALPHAEXT or PARAM_FLOAT or PARAM_PATH
144 * @param string $component This is the name of the component in Moodle, eg 'mod_forum'
93dd2725 145 */
37743241 146 public function set_callback_options($class, array $argarray, $component) {
ce09fecc 147 global $CFG;
ce09fecc 148
37743241
MN
149 // Require the base class first before any other files.
150 require_once($CFG->libdir . '/portfolio/caller.php');
0d06b6fd 151
37743241
MN
152 // Include any potential callback files and check for errors.
153 portfolio_include_callback_file($component, $class);
154
155 // This will throw exceptions but should not actually do anything other than verify callbackargs.
0d06b6fd 156 $test = new $class($argarray);
157 unset($test);
158
37743241 159 $this->callbackcomponent = $component;
ce09fecc 160 $this->callbackclass = $class;
161 $this->callbackargs = $argarray;
67a87e7d 162 }
163
93dd2725
RW
164 /**
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.
18cdcdbf
SH
169 * @see portfolio_most_specific_formats for more information
170 * @see portfolio_format_from_mimetype
93dd2725
RW
171 *
172 * @param array $formats if the calling code knows better than the static method on the calling class (base_supported_formats).
173 * Eg: if it's going to be a single file, or if you know it's HTML, you can pass it here instead.
174 * This is almost always the case so it should be use all the times
18cdcdbf 175 * portfolio_format_from_mimetype for how to get the appropriate formats to pass here for uploaded files.
93dd2725
RW
176 * or just call set_format_by_file instead
177 */
ce09fecc 178 public function set_formats($formats=null) {
179 if (is_string($formats)) {
180 $formats = array($formats);
181 }
182 if (empty($formats)) {
9d7432f6 183 $formats = array();
ce09fecc 184 }
9d7432f6 185 if (empty($this->callbackclass)) {
186 throw new portfolio_button_exception('noclassbeforeformats', 'portfolio');
d1581fc5 187 }
59dd457e 188 $callerformats = call_user_func(array($this->callbackclass, 'base_supported_formats'));
9d7432f6 189 $this->formats = portfolio_most_specific_formats($formats, $callerformats);
6fdd8fa7 190 }
191
521a6ab0 192 /**
93dd2725 193 * Reset formats to the default,
521a6ab0
PL
194 * which is usually what base_supported_formats returns
195 */
59dd457e
PL
196 public function reset_formats() {
197 $this->set_formats();
198 }
199
200
887160c7 201 /**
93dd2725 202 * If we already know we have exactly one file,
887160c7
PL
203 * bypass set_formats and just pass the file
204 * so we can detect the formats by mimetype.
205 *
93dd2725
RW
206 * @param stored_file $file file to set the format from
207 * @param array $extraformats any additional formats other than by mimetype
208 * eg leap2a etc
887160c7 209 */
59dd457e 210 public function set_format_by_file(stored_file $file, $extraformats=null) {
887160c7 211 $this->file = $file;
521a6ab0
PL
212 $fileformat = portfolio_format_from_mimetype($file->get_mimetype());
213 if (is_string($extraformats)) {
214 $extraformats = array($extraformats);
215 } else if (!is_array($extraformats)) {
216 $extraformats = array();
217 }
218 $this->set_formats(array_merge(array($fileformat), $extraformats));
219 }
220
221 /**
93dd2725 222 * Correllary this is use to set_format_by_file, but it is also used when there is no stored_file and
521a6ab0
PL
223 * when we're writing out a new type of file (like csv or pdf)
224 *
225 * @param string $extn the file extension we intend to generate
93dd2725
RW
226 * @param array $extraformats any additional formats other than by mimetype
227 * eg leap2a etc
521a6ab0
PL
228 */
229 public function set_format_by_intended_file($extn, $extraformats=null) {
230 $mimetype = mimeinfo('type', 'something. ' . $extn);
231 $fileformat = portfolio_format_from_mimetype($mimetype);
232 $this->intendedmimetype = $fileformat;
59dd457e 233 if (is_string($extraformats)) {
521a6ab0
PL
234 $extraformats = array($extraformats);
235 } else if (!is_array($extraformats)) {
236 $extraformats = array();
59dd457e 237 }
521a6ab0 238 $this->set_formats(array_merge(array($fileformat), $extraformats));
887160c7
PL
239 }
240
93dd2725
RW
241 /**
242 * Echo the form/button/icon/text link to the page
243 *
244 * @param int $format format to display the button or form or icon or link.
245 * See constants PORTFOLIO_ADD_XXX for more info.
246 * optional, defaults to PORTFOLIO_ADD_FULL_FORM
247 * @param string $addstr string to use for the button or icon alt text or link text.
248 * this is whole string, not key. optional, defaults to 'Export to portfolio';
249 */
ce09fecc 250 public function render($format=null, $addstr=null) {
380a251f 251 echo $this->to_html($format, $addstr);
84a44985 252 }
253
93dd2725
RW
254 /**
255 * Returns the form/button/icon/text link as html
256 *
257 * @param int $format format to display the button or form or icon or link.
258 * See constants PORTFOLIO_ADD_XXX for more info.
259 * Optional, defaults to PORTFOLIO_ADD_FULL_FORM
260 * @param string $addstr string to use for the button or icon alt text or link text.
261 * This is whole string, not key. optional, defaults to 'Add to portfolio';
262 * @return void|string
263 */
ce09fecc 264 public function to_html($format=null, $addstr=null) {
add93b8f 265 global $CFG, $COURSE, $OUTPUT, $USER;
ce09fecc 266 if (!$this->is_renderable()) {
ed1fcf79 267 return;
268 }
37743241 269 if (empty($this->callbackclass) || empty($this->callbackcomponent)) {
380a251f 270 throw new portfolio_button_exception('mustsetcallbackoptions', 'portfolio');
ce09fecc 271 }
272 if (empty($this->formats)) {
273 // use the caller defaults
274 $this->set_formats();
275 }
521a6ab0 276 $url = new moodle_url('/portfolio/add.php');
ce09fecc 277 foreach ($this->callbackargs as $key => $value) {
278 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
365a5941 279 $a = new stdClass();
ce09fecc 280 $a->key = $key;
281 $a->value = print_r($value, true);
282 debugging(get_string('nonprimative', 'portfolio', $a));
283 return;
284 }
521a6ab0
PL
285 $url->param('ca_' . $key, $value);
286 }
287 $url->param('sesskey', sesskey());
37743241 288 $url->param('callbackcomponent', $this->callbackcomponent);
521a6ab0
PL
289 $url->param('callbackclass', $this->callbackclass);
290 $url->param('course', (!empty($COURSE)) ? $COURSE->id : 0);
291 $url->param('callerformats', implode(',', $this->formats));
292 $mimetype = null;
293 if ($this->file instanceof stored_file) {
294 $mimetype = $this->file->get_mimetype();
295 } else if ($this->intendedmimetype) {
296 $mimetype = $this->intendedmimetype;
297 }
ce09fecc 298 $selectoutput = '';
299 if (count($this->instances) == 1) {
6be1dcae 300 $tmp = array_values($this->instances);
301 $instance = $tmp[0];
c95a6095 302
ce09fecc 303 $formats = portfolio_supported_formats_intersect($this->formats, $instance->supported_formats());
304 if (count($formats) == 0) {
305 // bail. no common formats.
3cec7552 306 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $this->callbackclass, 'formats' => implode(',', $this->formats))));
ce09fecc 307 return;
308 }
309 if ($error = portfolio_instance_sanity_check($instance)) {
310 // bail, plugin is misconfigured
3cec7552 311 //debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
ce09fecc 312 return;
313 }
24ba58ee 314 if (!$instance->allows_multiple_exports() && $already = portfolio_existing_exports($USER->id, $instance->get('plugin'))) {
3cec7552 315 //debugging(get_string('singleinstancenomultiallowed', 'portfolio'));
c95a6095
PL
316 return;
317 }
521a6ab0
PL
318 if ($mimetype&& !$instance->file_mime_check($mimetype)) {
319 // bail, we have a specific file or mimetype and this plugin doesn't support it
3cec7552 320 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype)));
887160c7
PL
321 return;
322 }
521a6ab0 323 $url->param('instance', $instance->get('id'));
ce09fecc 324 }
325 else {
521a6ab0 326 if (!$selectoutput = portfolio_instance_select($this->instances, $this->formats, $this->callbackclass, $mimetype, 'instance', true)) {
3ec8d786
PL
327 return;
328 }
ed1fcf79 329 }
521a6ab0
PL
330 // if we just want a url to redirect to, do it now
331 if ($format == PORTFOLIO_ADD_FAKE_URL) {
b9bc2019 332 return $url->out(false);
521a6ab0 333 }
67a87e7d 334
ce09fecc 335 if (empty($addstr)) {
336 $addstr = get_string('addtoportfolio', 'portfolio');
337 }
338 if (empty($format)) {
339 $format = PORTFOLIO_ADD_FULL_FORM;
340 }
521a6ab0
PL
341
342 $formoutput = '<form method="post" action="' . $CFG->wwwroot . '/portfolio/add.php" id="portfolio-add-button">' . "\n";
6ea66ff3 343 $formoutput .= html_writer::input_hidden_params($url);
628c7840 344 $linkoutput = '<a class="portfolio-add-link" title="'.$addstr.'" href="' . $url->out();
521a6ab0 345
ce09fecc 346 switch ($format) {
347 case PORTFOLIO_ADD_FULL_FORM:
348 $formoutput .= $selectoutput;
349 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
350 $formoutput .= "\n" . '</form>';
351 break;
352 case PORTFOLIO_ADD_ICON_FORM:
353 $formoutput .= $selectoutput;
628c7840 354 $formoutput .= "\n" . '<input class="portfolio-add-icon" type="image" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt=' . $addstr .'" />';
ce09fecc 355 $formoutput .= "\n" . '</form>';
356 break;
357 case PORTFOLIO_ADD_ICON_LINK:
696c748d 358 $linkoutput .= '"><img class="portfolio-add-icon iconsmall" src="' . $OUTPUT->pix_url('t/portfolioadd') . '" alt="' . $addstr .'" /></a>';
ce09fecc 359 break;
360 case PORTFOLIO_ADD_TEXT_LINK:
361 $linkoutput .= '">' . $addstr .'</a>';
362 break;
363 default:
364 debugging(get_string('invalidaddformat', 'portfolio', $format));
365 }
366 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
367 return $output;
349242a3 368 }
67a87e7d 369
ce09fecc 370 /**
93dd2725
RW
371 * Perform some internal checks.
372 * These are not errors, just situations
373 * where it's not appropriate to add the button
374 *
375 * @return bool
376 */
ce09fecc 377 private function is_renderable() {
378 global $CFG;
379 if (empty($CFG->enableportfolios)) {
380 return false;
67a87e7d 381 }
ce09fecc 382 if (defined('PORTFOLIO_INTERNAL')) {
383 // something somewhere has detected a risk of this being called during inside the preparation
384 // eg forum_print_attachments
385 return false;
67a87e7d 386 }
380a251f 387 if (empty($this->instances) || count($this->instances) == 0) {
ce09fecc 388 return false;
67a87e7d 389 }
ce09fecc 390 return true;
67a87e7d 391 }
ef6f0f60 392
393 /**
394 * Getter for $format property
93dd2725 395 *
ef6f0f60 396 * @return array
397 */
398 public function get_formats() {
399 return $this->formats;
400 }
401
402 /**
403 * Getter for $callbackargs property
93dd2725 404 *
ef6f0f60 405 * @return array
406 */
407 public function get_callbackargs() {
408 return $this->callbackargs;
409 }
410
411 /**
37743241 412 * Getter for $callbackcomponent property
93dd2725
RW
413 *
414 * @return string
ef6f0f60 415 */
37743241
MN
416 public function get_callbackcomponent() {
417 return $this->callbackcomponent;
ef6f0f60 418 }
419
420 /**
421 * Getter for $callbackclass property
93dd2725
RW
422 *
423 * @return string
ef6f0f60 424 */
425 public function get_callbackclass() {
426 return $this->callbackclass;
427 }
ce09fecc 428}
67a87e7d 429
67a87e7d 430/**
93dd2725
RW
431 * Returns a drop menu with a list of available instances.
432 *
433 * @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
434 * @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
435 * @param string $callbackclass the callback class name - used for debugging only for when there are no common formats
436 * @param string $mimetype if we already know we have exactly one file, or are going to write one, pass it here to do mime filtering.
437 * @param string $selectname the name of the select element. Optional, defaults to instance.
438 * @param bool $return whether to print or return the output. Optional, defaults to print.
439 * @param bool $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
440 * @return void|array|string the html, from <select> to </select> inclusive.
441 */
521a6ab0 442function portfolio_instance_select($instances, $callerformats, $callbackclass, $mimetype=null, $selectname='instance', $return=false, $returnarray=false) {
c95a6095 443 global $CFG, $USER;
9eb0a772 444
90658eef 445 if (empty($CFG->enableportfolios)) {
9eb0a772 446 return;
447 }
448
67a87e7d 449 $insane = portfolio_instance_sanity_check();
b816c08a 450 $pinsane = portfolio_plugin_sanity_check();
451
67a87e7d 452 $count = 0;
ecc5cc31
RW
453 $selectoutput = "\n" . '<label class="accesshide" for="instanceid">' . get_string('plugin', 'portfolio') . '</label>';
454 $selectoutput .= "\n" . '<select id="instanceid" name="' . $selectname . '">' . "\n";
24ba58ee 455 $existingexports = portfolio_existing_exports_by_plugin($USER->id);
67a87e7d 456 foreach ($instances as $instance) {
349242a3 457 $formats = portfolio_supported_formats_intersect($callerformats, $instance->supported_formats());
458 if (count($formats) == 0) {
67a87e7d 459 // bail. no common formats.
460 continue;
461 }
462 if (array_key_exists($instance->get('id'), $insane)) {
463 // bail, plugin is misconfigured
3cec7552 464 //debugging(get_string('instanceismisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
b816c08a 465 continue;
466 } else if (array_key_exists($instance->get('plugin'), $pinsane)) {
467 // bail, plugin is misconfigured
3cec7552 468 //debugging(get_string('pluginismisconfigured', 'portfolio', get_string($pinsane[$instance->get('plugin')], 'portfolio_' . $instance->get('plugin'))));
67a87e7d 469 continue;
470 }
c95a6095
PL
471 if (!$instance->allows_multiple_exports() && in_array($instance->get('plugin'), $existingexports)) {
472 // bail, already exporting something with this plugin and it doesn't support multiple exports
473 continue;
474 }
521a6ab0 475 if ($mimetype && !$instance->file_mime_check($mimetype)) {
3cec7552 476 //debugging(get_string('mimecheckfail', 'portfolio', (object)array('plugin' => $instance->get('plugin'), 'mimetype' => $mimetype())));
887160c7
PL
477 // bail, we have a specific file and this plugin doesn't support it
478 continue;
479 }
67a87e7d 480 $count++;
9eb0a772 481 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
482 $options[$instance->get('id')] = $instance->get('name');
67a87e7d 483 }
484 if (empty($count)) {
485 // bail. no common formats.
3cec7552 486 //debugging(get_string('nocommonformats', 'portfolio', (object)array('location' => $callbackclass, 'formats' => implode(',', $callerformats))));
67a87e7d 487 return;
488 }
489 $selectoutput .= "\n" . "</select>\n";
9eb0a772 490 if (!empty($returnarray)) {
491 return $options;
492 }
493 if (!empty($return)) {
494 return $selectoutput;
495 }
496 echo $selectoutput;
67a87e7d 497}
498
499/**
93dd2725
RW
500 * Return all portfolio instances
501 *
502 * @todo MDL-15768 - check capabilities here
503 * @param bool $visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
504 * @param bool $useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
505 * @return array of portfolio instances (full objects, not just database records)
506 */
67a87e7d 507function portfolio_instances($visibleonly=true, $useronly=true) {
508
509 global $DB, $USER;
510
511 $values = array();
512 $sql = 'SELECT * FROM {portfolio_instance}';
513
514 if ($visibleonly || $useronly) {
515 $values[] = 1;
516 $sql .= ' WHERE visible = ?';
517 }
518 if ($useronly) {
519 $sql .= ' AND id NOT IN (
520 SELECT instance FROM {portfolio_instance_user}
b11bbdd1 521 WHERE userid = ? AND name = ? AND ' . $DB->sql_compare_text('value') . ' = ?
67a87e7d 522 )';
523 $values = array_merge($values, array($USER->id, 'visible', 0));
524 }
525 $sql .= ' ORDER BY name';
526
527 $instances = array();
528 foreach ($DB->get_records_sql($sql, $values) as $instance) {
a50ef3d3 529 $instances[$instance->id] = portfolio_instance($instance->id, $instance);
67a87e7d 530 }
67a87e7d 531 return $instances;
532}
533
534/**
93dd2725
RW
535 * Supported formats currently in use.
536 * Canonical place for a list of all formats
537 * that portfolio plugins and callers
538 * can use for exporting content
539 *
540 * @return array keyed array of all the available export formats (constant => classname)
541 */
67a87e7d 542function portfolio_supported_formats() {
543 return array(
a9ec9031
DP
544 PORTFOLIO_FORMAT_FILE => 'portfolio_format_file',
545 PORTFOLIO_FORMAT_IMAGE => 'portfolio_format_image',
546 PORTFOLIO_FORMAT_RICHHTML => 'portfolio_format_richhtml',
547 PORTFOLIO_FORMAT_PLAINHTML => 'portfolio_format_plainhtml',
548 PORTFOLIO_FORMAT_TEXT => 'portfolio_format_text',
549 PORTFOLIO_FORMAT_VIDEO => 'portfolio_format_video',
550 PORTFOLIO_FORMAT_PDF => 'portfolio_format_pdf',
551 PORTFOLIO_FORMAT_DOCUMENT => 'portfolio_format_document',
552 PORTFOLIO_FORMAT_SPREADSHEET => 'portfolio_format_spreadsheet',
553 PORTFOLIO_FORMAT_PRESENTATION => 'portfolio_format_presentation',
5071079c 554 /*PORTFOLIO_FORMAT_MBKP, */ // later
59dd457e
PL
555 PORTFOLIO_FORMAT_LEAP2A => 'portfolio_format_leap2a',
556 PORTFOLIO_FORMAT_RICH => 'portfolio_format_rich',
67a87e7d 557 );
558}
559
ea0de12f 560/**
93dd2725
RW
561 * Deduce export format from file mimetype
562 * This function returns the revelant portfolio export format
563 * which is used to determine which portfolio plugins can be used
564 * for exporting this content
565 * according to the given mime type
566 * this only works when exporting exactly <b>one</b> file, or generating a new one
567 * (like a pdf or csv export)
568 *
569 * @param string $mimetype (usually $file->get_mimetype())
570 * @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
571 */
521a6ab0 572function portfolio_format_from_mimetype($mimetype) {
24ba58ee 573 global $CFG;
ea0de12f 574 static $alreadymatched;
575 if (empty($alreadymatched)) {
576 $alreadymatched = array();
577 }
ea0de12f 578 if (array_key_exists($mimetype, $alreadymatched)) {
579 return $alreadymatched[$mimetype];
580 }
581 $allformats = portfolio_supported_formats();
24ba58ee 582 require_once($CFG->libdir . '/portfolio/formats.php');
ea0de12f 583 foreach ($allformats as $format => $classname) {
584 $supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
585 if (!is_array($supportedmimetypes)) {
586 debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
587 debugging(print_r($supportedmimetypes, true));
588 continue;
589 }
590 if (in_array($mimetype, $supportedmimetypes)) {
591 $alreadymatched[$mimetype] = $format;
592 return $format;
593 }
594 }
595 return PORTFOLIO_FORMAT_FILE; // base case for files...
596}
597
598/**
93dd2725
RW
599 * Intersection of plugin formats and caller formats.
600 * Walks both the caller formats and portfolio plugin formats
601 * and looks for matches (walking the hierarchy as well)
602 * and returns the intersection
603 *
604 * @param array $callerformats formats the caller supports
605 * @param array $pluginformats formats the portfolio plugin supports
606 * @return array
607 */
7812e882 608function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
24ba58ee 609 global $CFG;
7812e882 610 $allformats = portfolio_supported_formats();
611 $intersection = array();
612 foreach ($callerformats as $cf) {
613 if (!array_key_exists($cf, $allformats)) {
59dd457e
PL
614 if (!portfolio_format_is_abstract($cf)) {
615 debugging(get_string('invalidformat', 'portfolio', $cf));
616 }
7812e882 617 continue;
618 }
24ba58ee 619 require_once($CFG->libdir . '/portfolio/formats.php');
34035201 620 $cfobj = new $allformats[$cf]();
7812e882 621 foreach ($pluginformats as $p => $pf) {
622 if (!array_key_exists($pf, $allformats)) {
59dd457e
PL
623 if (!portfolio_format_is_abstract($pf)) {
624 debugging(get_string('invalidformat', 'portfolio', $pf));
625 }
7812e882 626 unset($pluginformats[$p]); // to avoid the same warning over and over
627 continue;
628 }
34035201 629 if ($cfobj instanceof $allformats[$pf]) {
7812e882 630 $intersection[] = $cf;
631 }
632 }
633 }
634 return $intersection;
635}
636
59dd457e 637/**
93dd2725 638 * Tiny helper to figure out whether a portfolio format is abstract
59dd457e
PL
639 *
640 * @param string $format the format to test
18cdcdbf 641 * @return bool
59dd457e
PL
642 */
643function portfolio_format_is_abstract($format) {
644 if (class_exists($format)) {
645 $class = $format;
646 } else if (class_exists('portfolio_format_' . $format)) {
647 $class = 'portfolio_format_' . $format;
648 } else {
649 $allformats = portfolio_supported_formats();
650 if (array_key_exists($format, $allformats)) {
651 $class = $allformats[$format];
652 }
653 }
654 if (empty($class)) {
655 return true; // it may as well be, we can't instantiate it :)
656 }
657 $rc = new ReflectionClass($class);
658 return $rc->isAbstract();
659}
660
9d7432f6 661/**
93dd2725
RW
662 * Return the combination of the two arrays of formats with duplicates in terms of specificity removed
663 * and also removes conflicting formats.
664 * Use case: a module is exporting a single file, so the general formats would be FILE and MBKP
665 * while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
666 * and this function would return IMAGE and MBKP
667 *
668 * @param array $specificformats array of more specific formats (eg based on mime detection)
669 * @param array $generalformats array of more general formats (usually more supported)
670 * @return array merged formats with dups removed
671 */
9d7432f6 672function portfolio_most_specific_formats($specificformats, $generalformats) {
24ba58ee 673 global $CFG;
9d7432f6 674 $allformats = portfolio_supported_formats();
59dd457e
PL
675 if (empty($specificformats)) {
676 return $generalformats;
677 } else if (empty($generalformats)) {
678 return $specificformats;
679 }
a1e1af19
PL
680 $removedformats = array();
681 foreach ($specificformats as $k => $f) {
9d7432f6 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)) {
24ba58ee 684 if (!portfolio_format_is_abstract($f)) {
59dd457e
PL
685 throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
686 }
9d7432f6 687 }
a1e1af19
PL
688 if (in_array($f, $removedformats)) {
689 // already been removed from the general list
3cec7552 690 //debugging("skipping $f because it was already removed");
a1e1af19
PL
691 unset($specificformats[$k]);
692 }
24ba58ee 693 require_once($CFG->libdir . '/portfolio/formats.php');
9d7432f6 694 $fobj = new $allformats[$f];
695 foreach ($generalformats as $key => $cf) {
a1e1af19 696 if (in_array($cf, $removedformats)) {
3cec7552 697 //debugging("skipping $cf because it was already removed");
a1e1af19
PL
698 continue;
699 }
9d7432f6 700 $cfclass = $allformats[$cf];
549c1ae6 701 $cfobj = new $allformats[$cf];
59dd457e 702 if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
3cec7552 703 //debugging("unsetting $key $cf because it's not specific enough ($f is better)");
59dd457e 704 unset($generalformats[$key]);
a1e1af19 705 $removedformats[] = $cf;
549c1ae6 706 continue;
59dd457e
PL
707 }
708 // check for conflicts
709 if ($fobj->conflicts($cf)) {
3cec7552 710 //debugging("unsetting $key $cf because it conflicts with $f");
59dd457e 711 unset($generalformats[$key]);
a1e1af19 712 $removedformats[] = $cf;
549c1ae6
PL
713 continue;
714 }
715 if ($cfobj->conflicts($f)) {
3cec7552 716 //debugging("unsetting $key $cf because it reverse-conflicts with $f");
a1e1af19 717 $removedformats[] = $cf;
549c1ae6
PL
718 unset($generalformats[$key]);
719 continue;
9d7432f6 720 }
721 }
59dd457e
PL
722 //debugging('inside loop');
723 //print_object($generalformats);
9d7432f6 724 }
59dd457e
PL
725
726 //debugging('final formats');
727 $finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
728 //print_object($finalformats);
729 return $finalformats;
9d7432f6 730}
731
6be1dcae 732/**
93dd2725
RW
733 * Helper function to return a format object from the constant
734 *
735 * @param string $name the constant PORTFOLIO_FORMAT_XXX
736 * @return portfolio_format
737 */
6be1dcae 738function portfolio_format_object($name) {
24ba58ee
PL
739 global $CFG;
740 require_once($CFG->libdir . '/portfolio/formats.php');
6be1dcae 741 $formats = portfolio_supported_formats();
742 return new $formats[$name];
743}
744
67a87e7d 745/**
93dd2725
RW
746 * Helper function to return an instance of a plugin (with config loaded)
747 *
748 * @param int $instanceid id of instance
749 * @param object $record database row that corresponds to this instance
750 * this is passed to avoid unnecessary lookups
751 * Optional, and the record will be retrieved if null.
752 * @return object of portfolio_plugin_XXX
753 */
67a87e7d 754function portfolio_instance($instanceid, $record=null) {
755 global $DB, $CFG;
756
757 if ($record) {
758 $instance = $record;
759 } else {
760 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
34035201 761 throw new portfolio_exception('invalidinstance', 'portfolio');
67a87e7d 762 }
763 }
24ba58ee 764 require_once($CFG->libdir . '/portfolio/plugin.php');
edf1fc35 765 require_once($CFG->dirroot . '/portfolio/'. $instance->plugin . '/lib.php');
67a87e7d 766 $classname = 'portfolio_plugin_' . $instance->plugin;
767 return new $classname($instanceid, $instance);
768}
769
770/**
93dd2725
RW
771 * Helper function to call a static function on a portfolio plugin class.
772 * This will figure out the classname and require the right file and call the function.
773 * You can send a variable number of arguments to this function after the first two
774 * and they will be passed on to the function you wish to call.
775 *
776 * @param string $plugin name of plugin
777 * @param string $function function to call
778 * @return mixed
779 */
67a87e7d 780function portfolio_static_function($plugin, $function) {
781 global $CFG;
782
783 $pname = null;
784 if (is_object($plugin) || is_array($plugin)) {
785 $plugin = (object)$plugin;
786 $pname = $plugin->name;
787 } else {
788 $pname = $plugin;
789 }
790
791 $args = func_get_args();
792 if (count($args) <= 2) {
793 $args = array();
794 }
795 else {
796 array_shift($args);
797 array_shift($args);
798 }
799
24ba58ee 800 require_once($CFG->libdir . '/portfolio/plugin.php');
edf1fc35 801 require_once($CFG->dirroot . '/portfolio/' . $plugin . '/lib.php');
67a87e7d 802 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
803}
804
805/**
93dd2725
RW
806 * Helper function to check all the plugins for sanity and set any insane ones to invisible.
807 *
808 * @param array $plugins array of supported plugin types
809 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
810 */
67a87e7d 811function portfolio_plugin_sanity_check($plugins=null) {
812 global $DB;
813 if (is_string($plugins)) {
98c8594a 814 $plugins = array($plugins);
67a87e7d 815 } else if (empty($plugins)) {
17da2e6f 816 $plugins = get_plugin_list('portfolio');
98c8594a 817 $plugins = array_keys($plugins);
67a87e7d 818 }
819
820 $insane = array();
98c8594a 821 foreach ($plugins as $plugin) {
67a87e7d 822 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
823 $insane[$plugin] = $result;
824 }
825 }
826 if (empty($insane)) {
827 return array();
828 }
829 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
830 $where = ' plugin ' . $where;
831 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
832 return $insane;
833}
834
835/**
93dd2725
RW
836 * Helper function to check all the instances for sanity and set any insane ones to invisible.
837 *
838 * @param array $instances array of plugin instances
839 * @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
840 */
67a87e7d 841function portfolio_instance_sanity_check($instances=null) {
842 global $DB;
843 if (empty($instances)) {
844 $instances = portfolio_instances(false);
845 } else if (!is_array($instances)) {
846 $instances = array($instances);
847 }
848
849 $insane = array();
850 foreach ($instances as $instance) {
851 if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) {
852 $instance = portfolio_instance($instance->id, $instance);
853 } else if (is_numeric($instance)) {
854 $instance = portfolio_instance($instance);
855 }
856 if (!($instance instanceof portfolio_plugin_base)) {
857 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
858 continue;
859 }
860 if ($result = $instance->instance_sanity_check()) {
861 $insane[$instance->get('id')] = $result;
862 }
863 }
864 if (empty($insane)) {
865 return array();
866 }
867 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
868 $where = ' id ' . $where;
869 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
b816c08a 870 portfolio_insane_notify_admins($insane, true);
67a87e7d 871 return $insane;
872}
873
874/**
93dd2725
RW
875 * Helper function to display a table of plugins (or instances) and reasons for disabling
876 *
877 * @param array $insane array of portfolio plugin
878 * @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
879 * @param bool $return option to deliver the report in html format or print it out directly to the page.
880 * @return void|string of portfolio report in html table format
881 */
a50ef3d3 882function portfolio_report_insane($insane, $instances=false, $return=false) {
aa9a6867 883 global $OUTPUT;
67a87e7d 884 if (empty($insane)) {
885 return;
886 }
887
888 static $pluginstr;
889 if (empty($pluginstr)) {
890 $pluginstr = get_string('plugin', 'portfolio');
891 }
892 if ($instances) {
893 $headerstr = get_string('someinstancesdisabled', 'portfolio');
894 } else {
895 $headerstr = get_string('somepluginsdisabled', 'portfolio');
896 }
897
aa9a6867 898 $output = $OUTPUT->notification($headerstr, 'notifyproblem');
642816a6 899 $table = new html_table();
67a87e7d 900 $table->head = array($pluginstr, '');
901 $table->data = array();
902 foreach ($insane as $plugin => $reason) {
903 if ($instances) {
67a87e7d 904 $instance = $instances[$plugin];
905 $plugin = $instance->get('plugin');
906 $name = $instance->get('name');
907 } else {
908 $name = $plugin;
909 }
910 $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
911 }
16be8974 912 $output .= html_writer::table($table);
a50ef3d3 913 $output .= '<br /><br /><br />';
914
915 if ($return) {
916 return $output;
917 }
918 echo $output;
67a87e7d 919}
920
67a87e7d 921
87fcac8d 922/**
93dd2725
RW
923 * Event handler for the portfolio_send event
924 *
925 * @param int $eventdata event id
926 * @return bool
927 */
87fcac8d 928function portfolio_handle_event($eventdata) {
929 global $CFG;
24ba58ee
PL
930
931 require_once($CFG->libdir . '/portfolio/exporter.php');
87fcac8d 932 $exporter = portfolio_exporter::rewaken_object($eventdata);
933 $exporter->process_stage_package();
934 $exporter->process_stage_send();
935 $exporter->save();
936 $exporter->process_stage_cleanup();
937 return true;
67a87e7d 938}
939
87fcac8d 940/**
93dd2725
RW
941 * Main portfolio cronjob.
942 * Currently just cleans up expired transfer records.
943 *
944 * @todo - MDL-15997 - Add hooks in the plugins - either per instance or per plugin
945 */
87fcac8d 946function portfolio_cron() {
b73d1651
MD
947 global $DB, $CFG;
948
24ba58ee 949 require_once($CFG->libdir . '/portfolio/exporter.php');
87fcac8d 950 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()), '', 'id')) {
951 foreach ($expired as $d) {
2512cb35 952 try {
953 $e = portfolio_exporter::rewaken_object($d->id);
954 $e->process_stage_cleanup(true);
955 } catch (Exception $e) {
90b2d8f0 956 mtrace('Exception thrown in portfolio cron while cleaning up ' . $d->id . ': ' . $e->getMessage());
2512cb35 957 }
9eb0a772 958 }
192ce92b 959 }
5071079c 960}
961
67a87e7d 962/**
93dd2725
RW
963 * Helper function to rethrow a caught portfolio_exception as an export exception.
964 * Used because when a portfolio_export exception is thrown the export is cancelled
50fcb1d8 965 * throws portfolio_export_exceptiog
966 *
967 * @param portfolio_exporter $exporter current exporter object
93dd2725 968 * @param object $exception exception to rethrow
50fcb1d8 969 */
87fcac8d 970function portfolio_export_rethrow_exception($exporter, $exception) {
971 throw new portfolio_export_exception($exporter, $exception->errorcode, $exception->module, $exception->link, $exception->a);
972}
67a87e7d 973
bee4bce2 974/**
93dd2725
RW
975 * Try and determine expected_time for purely file based exports
976 * or exports that might include large file attachments.
977 *
978 * @param stored_file|array $totest - either an array of stored_file objects or a single stored_file object
979 * @return string PORTFOLIO_TIME_XXX
980 */
bee4bce2 981function portfolio_expected_time_file($totest) {
982 global $CFG;
983 if ($totest instanceof stored_file) {
984 $totest = array($totest);
985 }
986 $size = 0;
987 foreach ($totest as $file) {
988 if (!($file instanceof stored_file)) {
989 debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
990 debugging(print_r($file, true));
991 continue;
992 }
993 $size += $file->get_filesize();
994 }
995
996 $fileinfo = portfolio_filesize_info();
997
998 $moderate = $high = 0; // avoid warnings
999
1000 foreach (array('moderate', 'high') as $setting) {
1001 $settingname = 'portfolio_' . $setting . '_filesize_threshold';
1002 if (empty($CFG->{$settingname}) || !array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
1003 debugging("weird or unset admin value for $settingname, using default instead");
1004 $$setting = $fileinfo[$setting];
1005 } else {
1006 $$setting = $CFG->{$settingname};
1007 }
1008 }
1009
1010 if ($size < $moderate) {
1011 return PORTFOLIO_TIME_LOW;
1012 } else if ($size < $high) {
1013 return PORTFOLIO_TIME_MODERATE;
1014 }
1015 return PORTFOLIO_TIME_HIGH;
1016}
1017
1018
1019/**
93dd2725
RW
1020 * The default filesizes and threshold information for file based transfers.
1021 * This shouldn't need to be used outside the admin pages and the portfolio code
1022 *
1023 * @return array
1024 */
bee4bce2 1025function portfolio_filesize_info() {
1026 $filesizes = array();
1027 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
1028 foreach ($sizelist as $size) {
1029 $filesizes[$size] = display_size($size);
1030 }
1031 return array(
1032 'options' => $filesizes,
1033 'moderate' => 1048576,
1034 'high' => 5242880,
1035 );
1036}
1037
1038/**
93dd2725
RW
1039 * Try and determine expected_time for purely database based exports
1040 * or exports that might include large parts of a database.
1041 *
1042 * @param int $recordcount number of records trying to export
1043 * @return string PORTFOLIO_TIME_XXX
1044 */
bee4bce2 1045function portfolio_expected_time_db($recordcount) {
1046 global $CFG;
1047
1048 if (empty($CFG->portfolio_moderate_dbsize_threshold)) {
1049 set_config('portfolio_moderate_dbsize_threshold', 10);
1050 }
1051 if (empty($CFG->portfolio_high_dbsize_threshold)) {
1052 set_config('portfolio_high_dbsize_threshold', 50);
1053 }
1054 if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold) {
1055 return PORTFOLIO_TIME_LOW;
1056 } else if ($recordcount < $CFG->portfolio_high_dbsize_threshold) {
1057 return PORTFOLIO_TIME_MODERATE;
1058 }
1059 return PORTFOLIO_TIME_HIGH;
1060}
67a87e7d 1061
50fcb1d8 1062/**
93dd2725
RW
1063 * Function to send portfolio report to admins
1064 *
1065 * @param array $insane array of insane plugins
1066 * @param array $instances (optional) if reporting instances rather than whole plugins
50fcb1d8 1067 */
b816c08a 1068function portfolio_insane_notify_admins($insane, $instances=false) {
1069
1070 global $CFG;
1071
1072 if (defined('ADMIN_EDITING_PORTFOLIO')) {
1073 return true;
1074 }
1075
1076 $admins = get_admins();
1077
1078 if (empty($admins)) {
1079 return;
1080 }
1081 if ($instances) {
1082 $instances = portfolio_instances(false, false);
1083 }
1084
1085 $site = get_site();
1086
1087 $a = new StdClass;
b0c6dc1c 1088 $a->sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID)));
d1aa1e48 1089 $a->fixurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
b816c08a 1090 $a->htmllist = portfolio_report_insane($insane, $instances, true);
1091 $a->textlist = '';
1092
1093 foreach ($insane as $k => $reason) {
1094 if ($instances) {
1095 $a->textlist = $instances[$k]->get('name') . ': ' . $reason . "\n";
1096 } else {
1097 $a->textlist = $k . ': ' . $reason . "\n";
1098 }
1099 }
1100
1101 $subject = get_string('insanesubject', 'portfolio');
1102 $plainbody = get_string('insanebody', 'portfolio', $a);
1103 $htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
1104 $smallbody = get_string('insanebodysmall', 'portfolio', $a);
1105
1106 foreach ($admins as $admin) {
365a5941 1107 $eventdata = new stdClass();
b816c08a 1108 $eventdata->modulename = 'portfolio';
1109 $eventdata->component = 'portfolio';
1110 $eventdata->name = 'notices';
55079015 1111 $eventdata->userfrom = get_admin();
b816c08a 1112 $eventdata->userto = $admin;
1113 $eventdata->subject = $subject;
1114 $eventdata->fullmessage = $plainbody;
1115 $eventdata->fullmessageformat = FORMAT_PLAIN;
1116 $eventdata->fullmessagehtml = $htmlbody;
1117 $eventdata->smallmessage = $smallbody;
7c7d3afa 1118 message_send($eventdata);
b816c08a 1119 }
1120}
f1d2641d 1121
93dd2725
RW
1122/**
1123 * Setup page export
1124 *
1125 * @param moodle_page $PAGE global variable from page object
1126 * @param portfolio_caller_base $caller plugin type caller
1127 */
f1d2641d 1128function portfolio_export_pagesetup($PAGE, $caller) {
90636e2b
PL
1129 // set up the context so that build_navigation works nice
1130 $caller->set_context($PAGE);
f1d2641d
PL
1131
1132 list($extranav, $cm) = $caller->get_navigation();
1133
1134 // and now we know the course for sure and maybe the cm, call require_login with it
90636e2b 1135 require_login($PAGE->course, false, $cm);
f1d2641d
PL
1136
1137 foreach ($extranav as $navitem) {
1138 $PAGE->navbar->add($navitem['name']);
1139 }
1140 $PAGE->navbar->add(get_string('exporting', 'portfolio'));
1141}
b12fbe8e 1142
93dd2725
RW
1143/**
1144 * Get export type id
1145 *
1146 * @param string $type plugin type
1147 * @param int $userid the user to check for
1148 * @return mixed|bool
1149 */
b12fbe8e
PL
1150function portfolio_export_type_to_id($type, $userid) {
1151 global $DB;
1152 $sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
1153 return $DB->get_field_sql($sql, array($userid, $type));
1154}
24ba58ee
PL
1155
1156/**
93dd2725
RW
1157 * Return a list of current exports for the given user.
1158 * This will not go through and call rewaken_object, because it's heavy.
1159 * It's really just used to figure out what exports are currently happening.
1160 * This is useful for plugins that don't support multiple exports per session
24ba58ee 1161 *
93dd2725 1162 * @param int $userid the user to check for
24ba58ee 1163 * @param string $type (optional) the portfolio plugin to filter by
24ba58ee
PL
1164 * @return array
1165 */
1166function portfolio_existing_exports($userid, $type=null) {
1167 global $DB;
1168 $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 = ? ';
1169 $values = array($userid);
1170 if ($type) {
1171 $sql .= ' AND i.plugin = ?';
1172 $values[] = $type;
1173 }
1174 return $DB->get_records_sql($sql, $values);
1175}
1176
1177/**
1178 * Return an array of existing exports by type for a given user.
18cdcdbf 1179 * This is much more lightweight than existing_exports because it only returns the types, rather than the whole serialised data
24ba58ee 1180 * so can be used for checking availability of multiple plugins at the same time.
18cdcdbf 1181 * @see existing_exports
93dd2725
RW
1182 *
1183 * @param int $userid the user to check for
1184 * @return array
24ba58ee
PL
1185 */
1186function portfolio_existing_exports_by_plugin($userid) {
1187 global $DB;
1188 $sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
1189 $values = array($userid);
1190 return $DB->get_records_sql_menu($sql, $values);
1191}
8192522e 1192
7e514cd7 1193/**
93dd2725 1194 * Return default common options for {@link format_text()} when preparing a content to be exported.
7e514cd7
DM
1195 * It is important not to apply filters and not to clean the HTML in format_text()
1196 *
1197 * @return stdClass
1198 */
1199function portfolio_format_text_options() {
1200
1201 $options = new stdClass();
1202 $options->para = false;
1203 $options->newlines = true;
1204 $options->filter = false;
1205 $options->noclean = true;
1206 $options->overflowdiv = false;
1207
1208 return $options;
1209}
8192522e
PL
1210
1211/**
1212 * callback function from {@link portfolio_rewrite_pluginfile_urls}
1213 * looks through preg_replace matches and replaces content with whatever the active portfolio export format says
93dd2725
RW
1214 *
1215 * @param int $contextid module context id
1216 * @param string $component module name (eg:mod_assignment)
1217 * @param string $filearea normal file_area arguments
1218 * @param int $itemid component item id
1219 * @param portfolio_format $format exporter format type
1220 * @param array $options extra options to pass through to the file_output function in the format (optional)
1221 * @param array $matches internal matching
1222 * @return object|array|string
8192522e 1223 */
64f93798 1224function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
8192522e
PL
1225 $matches = $matches[0]; // no internal matching
1226 $dom = new DomDocument();
1227 if (!$dom->loadXML($matches)) {
1228 return $matches;
1229 }
1230 $attributes = array();
1231 foreach ($dom->documentElement->attributes as $attr => $node) {
1232 $attributes[$attr] = $node->value;
1233 }
1234 // now figure out the file
1235 $fs = get_file_storage();
1236 $key = 'href';
1237 if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
1238 $key = 'src';
1239 }
1240 if (!array_key_exists($key, $attributes)) {
1241 debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
1242 return $matches;
1243 }
1244 $filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') + strlen('@@PLUGINFILE@@'));
1245 $filepath = '/';
1246 if (strpos($filename, '/') !== 0) {
1247 $bits = explode('/', $filename);
1248 $filename = array_pop($bits);
1249 $filepath = implode('/', $bits);
1250 }
64f93798 1251 if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
d39c6513 1252 debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
8192522e
PL
1253 return $matches;
1254 }
1255 if (empty($options)) {
1256 $options = array();
1257 }
1258 $options['attributes'] = $attributes;
1259 return $format->file_output($file, $options);
1260}
1261
37743241
MN
1262/**
1263 * Function to require any potential callback files, throwing exceptions
1264 * if an issue occurs.
1265 *
1266 * @param string $component This is the name of the component in Moodle, eg 'mod_forum'
1267 * @param string $class Name of the class containing the callback functions
1268 * activity components should ALWAYS use their name_portfolio_caller
1269 * other locations must use something unique
1270 */
1271function portfolio_include_callback_file($component, $class = null) {
1272 global $CFG;
1273 require_once($CFG->libdir . '/adminlib.php');
1274
1275 // It's possible that they are passing a file path rather than passing a component.
1276 // We want to try and convert this to a component name, eg. mod_forum.
1277 $pos = strrpos($component, '/');
1278 if ($pos !== false) {
1279 // Get rid of the first slash (if it exists).
1280 $component = ltrim($component, '/');
1281 // Get a list of valid plugin types.
1282 $plugintypes = get_plugin_types(false);
1283 // Assume it is not valid for now.
1284 $isvalid = false;
1285 // Go through the plugin types.
1286 foreach ($plugintypes as $type => $path) {
1287 if (strrpos($component, $path) === 0) {
1288 // Found the plugin type.
1289 $isvalid = true;
1290 $plugintype = $type;
1291 $pluginpath = $path;
1292 }
1293 }
1294 // Throw exception if not a valid component.
1295 if (!$isvalid) {
1296 throw new coding_exception('Somehow a non-valid plugin path was passed, could be a hackz0r attempt, exiting.');
1297 }
1298 // Remove the file name.
1299 $component = trim(substr($component, 0, $pos), '/');
1300 // Replace the path with the type.
1301 $component = str_replace($pluginpath, $plugintype, $component);
1302 // Ok, replace '/' with '_'.
1303 $component = str_replace('/', '_', $component);
1304 // Place a debug message saying the third parameter should be changed.
1305 debugging('The third parameter sent to the function set_callback_options should be the component name, not a file path, please update this.', DEBUG_DEVELOPER);
1306 }
1307
1308 // Check that it is a valid component.
1309 if (!get_component_version($component)) {
1310 throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
1311 }
1312
1313 // Obtain the component's location.
1314 if (!$componentloc = get_component_directory($component)) {
1315 throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
1316 }
1317
1318 // Check if the component contains the necessary file for the portfolio plugin.
1319 // These are locallib.php, portfoliolib.php and portfolio_callback.php.
1320 $filefound = false;
1321 if (file_exists($componentloc . '/locallib.php')) {
1322 $filefound = true;
1323 require_once($componentloc . '/locallib.php');
1324 }
1325 if (file_exists($componentloc . '/portfoliolib.php')) {
1326 $filefound = true;
1327 debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
1328 require_once($componentloc . '/portfoliolib.php');
1329 }
1330 if (file_exists($componentloc . '/portfolio_callback.php')) {
1331 $filefound = true;
1332 debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
1333 require_once($componentloc . '/portfolio_callback.php');
1334 }
1335
1336 // Ensure that we found a file we can use, if not throw an exception.
1337 if (!$filefound) {
1338 throw new portfolio_button_exception('nocallbackfile', 'portfolio', '', $component);
1339 }
1340
1341 if (!is_null($class) && !class_exists($class)) {
1342 throw new portfolio_button_exception('nocallbackclass', 'portfolio', '', $class);
1343 }
1344}
8192522e
PL
1345
1346/**
93dd2725 1347 * Go through all the @@PLUGINFILE@@ matches in some text,
8192522e
PL
1348 * extract the file information and pass it back to the portfolio export format
1349 * to regenerate the html to output
1350 *
93dd2725
RW
1351 * @param string $text the text to search through
1352 * @param int $contextid normal file_area arguments
1353 * @param string $component module name
1354 * @param string $filearea normal file_area arguments
1355 * @param int $itemid normal file_area arguments
1356 * @param portfolio_format $format the portfolio export format
1357 * @param array $options additional options to be included in the plugin file url (optional)
1358 * @return mixed
8192522e 1359 */
64f93798 1360function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
8192522e 1361 $pattern = '/(<[^<]*?="@@PLUGINFILE@@\/[^>]*?(?:\/>|>.*?<\/[^>]*?>))/';
64f93798 1362 $callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
8192522e
PL
1363 return preg_replace_callback($pattern, $callback, $text);
1364}
1365// this function has to go last, because the regexp screws up syntax highlighting in some editors
1366