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