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