MDL-8130
[moodle.git] / lib / portfoliolib.php
CommitLineData
67a87e7d 1<?php
67a87e7d 2/**
3* this file contains:
4* {@link portfolio_add_button} -entry point for callers
5* {@link class portfolio_plugin_base} - class plugins extend
6* {@link class portfolio_caller_base} - class callers extend
7* {@link class portfolio_admin_form} - base moodleform class for plugin administration
8* {@link class portfolio_user_form} - base moodleform class for plugin instance user config
9* {@link class portfolio_export_form} - base moodleform class for during-export configuration (eg metadata)
10* {@link class portfolio_exporter} - class used during export process
11*
12* and some helper functions:
13* {@link portfolio_instances - returns an array of all configured instances
14* {@link portfolio_instance - returns an instance of the right class given an id
15* {@link portfolio_instance_select} - returns a drop menu of available instances
16* {@link portfolio_static_function - requires the file, and calls a static function on the given class
17" {@link portfolio_plugin_sanity_check - polls given (or all) portfolio_plugins for sanity and disables insane ones
18" {@link portfolio_instance_sanity_check - polls given (or all) portfolio instances for sanity and disables insane ones
19* {@link portfolio_report_instane} - returns a table of insane plugins and the reasons (used for plugins or instances thereof)
20* {@link portfolio_supported_formats - returns array of all available formats for plugins and callers to use
21* {@link portfolio_handle_event} - event handler for queued transfers that get triggered on cron
22*
23*/
24require_once ($CFG->libdir.'/formslib.php');
25
26// **** EXPORT STAGE CONSTANTS **** //
27
28/**
29* display a form to the user
30* this one might not be used if neither
31* the plugin, or the caller has any config.
32*/
33define('PORTFOLIO_STAGE_CONFIG', 1);
34
35/**
36* summarise the form and ask for confirmation
37* if we skipped PORTFOLIO_STAGE_CONFIG,
38* just confirm the send.
39*/
40define('PORTFOLIO_STAGE_CONFIRM', 2);
41
42/**
43* either queue the event and skip to PORTFOLIO_STAGE_FINISHED
44* or continue to PORTFOLIO_STAGE_PACKAGE
45*/
46
47define('PORTFOLIO_STAGE_QUEUEORWAIT', 3);
48
49/**
50* package up the various bits
51* during this stage both the caller
52* and the plugin get their package methods called
53*/
54define('PORTFOLIO_STAGE_PACKAGE', 4);
55
56/*
57* the portfolio plugin must send the file
58*/
59define('PORTFOLIO_STAGE_SEND', 5);
60
61/**
62* cleanup the temporary area
63*/
64define('PORTFOLIO_STAGE_CLEANUP', 6);
65
66/**
67* display the "finished notification"
68*/
69define('PORTFOLIO_STAGE_FINISHED', 7);
70
71
72
73// **** EXPORT FORMAT CONSTANTS **** //
74// these should always correspond to a string
75// in the portfolio module, called format_{$value}
76// **** **** //
77
67a87e7d 78
79/**
80* file - the most basic fallback format.
81* this should always be supported
82* in remote system.s
83*/
84define('PORTFOLIO_FORMAT_FILE', 'file');
85
86/**
87* moodle backup - the plugin needs to be able to write a complete backup
88* the caller need to be able to export the particular XML bits to insert
89* into moodle.xml (?and the file bits if necessary)
90*/
91define('PORTFOLIO_FORMAT_MBKP', 'mbkp');
92
93
94// **** EXPORT TIME LEVELS **** //
95// these should correspond to a string
96// in the portfolio module, called time_{$value}
97
98/**
99* no delay. don't even offer the user the option
100* of not waiting for the transfer
101*/
102define('PORTFOLIO_TIME_LOW', 'low');
103
104/**
105* a small delay. user can still easily opt to
106* watch this transfer and wait.
107*/
108define('PORTFOLIO_TIME_MODERATE', 'moderate');
109
110/**
111* slow. the user really should not be given the option
112* to choose this.
113*/
114define('PORTFOLIO_TIME_HIGH', 'high');
115
866d543f 116// ************************************************** //
117// available ways to add the portfolio export to a page
118// ************************************************** //
119
120/**
121* a whole form, containing a drop down menu (where necessary)
122* and a submit button
123*/
124define('PORTFOLIO_ADD_FULL_FORM', 1);
125
126
127/**
128* a whole form, containing a drop down menu (where necessary)
129* but has an icon instead of a button to submit
130*/
131define('PORTFOLIO_ADD_ICON_FORM', 2);
132
133/**
134* just an icon with a link around it (yuk, as will result in a long url
135* only use where necessary)
136*/
137define('PORTFOLIO_ADD_ICON_LINK', 3);
138
139/**
140* just some text with a link around it (yuk, as will result in a long url
141* only use where necessary)
142*/
143define('PORTFOLIO_ADD_TEXT_LINK', 4);
67a87e7d 144
145/**
146* entry point to add an 'add to portfolio' button somewhere in moodle
147* this function does not check permissions. the caller must check permissions first.
148* later, during the export process, the caller class is instantiated and the check_permissions method is called
149* but not in this function.
150*
151* @param string $callbackclass name of the class containing the callback functions
152* activity modules should ALWAYS use their name_portfolio_caller
153* other locations must use something unique
154* @param mixed $callbackargs this can be an array or hash of arguments to pass
155* back to the callback functions (passed by reference)
156* these MUST be primatives to be added as hidden form fields.
157* and the values get cleaned to PARAM_ALPHAEXT or PARAM_NUMBER or PARAM_PATH
ed1fcf79 158* @param string $callbackfile this can be autodetected if it's in the same file as your caller,
159* but more often, the caller is a script.php and the class in a lib.php
160* so you can pass it here if necessary.
161* this path should be relative (ie, not include) dirroot
866d543f 162* @param int $format format to display the button or form or icon or link.
163* See constants PORTFOLIO_ADD_XXX for more info.
164* optional, defaults to PORTFOLI_ADD_FULL_FORM
165* @param str $addstr string to use for the button or icon alt text or link text.
166* this is whole string, not key. optional, defaults to 'Add to portfolio';
67a87e7d 167* @param boolean $return whether to echo or return content (optional defaults to false (echo)
168*/
866d543f 169function portfolio_add_button($callbackclass, $callbackargs, $callbackfile=null, $format=PORTFOLIO_ADD_FULL_FORM, $addstr=null, $return=false) {
67a87e7d 170
171 global $SESSION, $CFG, $COURSE, $USER;
172
a239f01e 173 if (empty($CFG->portfolioenabled)) {
174 return;
175 }
176
67a87e7d 177 if (!$instances = portfolio_instances()) {
178 return;
179 }
180
84a44985 181 if (defined('PORTFOLIO_INTERNAL')) {
6fdd8fa7 182 // something somewhere has detected a risk of this being called during inside the preparation
183 // eg forum_print_attachments
184 return;
185 }
186
84a44985 187 if (isset($SESSION->portfolioexport)) {
ac6a5492 188 $a = new StdClass;
189 $a->cancel = $CFG->wwwroot . '/portfolio/add.php?cancel=1';
190 $a->finish = $CFG->wwwroot . '/portfolio/add.php?id=' . $SESSION->portfolioexport;
191 print_error('alreadyexporting', 'portfolio', null, $a);
84a44985 192 }
193
ed1fcf79 194 if (empty($callbackfile)) {
195 $backtrace = debug_backtrace();
196 if (!array_key_exists(0, $backtrace) || !array_key_exists('file', $backtrace[0]) || !is_readable($backtrace[0]['file'])) {
197 debugging(get_string('nocallbackfile', 'portfolio'));
198 return;
199 }
200
201 $callbackfile = substr($backtrace[0]['file'], strlen($CFG->dirroot));
202 } else {
203 if (!is_readable($CFG->dirroot . $callbackfile)) {
204 debugging(get_string('nocallbackfile', 'portfolio'));
205 return;
206 }
67a87e7d 207 }
208
67a87e7d 209 require_once($CFG->dirroot . $callbackfile);
210
211 $callersupports = call_user_func(array($callbackclass, 'supported_formats'));
212
866d543f 213 $formoutput = '<form method="post" action="' . $CFG->wwwroot . '/portfolio/add.php" id="portfolio-add-button">' . "\n";
214 $linkoutput = '<a href="' . $CFG->wwwroot . '/portfolio/add.php?';
67a87e7d 215 foreach ($callbackargs as $key => $value) {
216 if (!empty($value) && !is_string($value) && !is_numeric($value)) {
217 $a->key = $key;
218 $a->value = print_r($value, true);
219 debugging(get_string('nonprimative', 'portfolio', $a));
220 return;
221 }
866d543f 222 $linkoutput .= 'ca_' . $key . '=' . $value . '&amp;';
223 $formoutput .= "\n" . '<input type="hidden" name="ca_' . $key . '" value="' . $value . '" />';
67a87e7d 224 }
866d543f 225 $formoutput .= "\n" . '<input type="hidden" name="callbackfile" value="' . $callbackfile . '" />';
226 $formoutput .= "\n" . '<input type="hidden" name="callbackclass" value="' . $callbackclass . '" />';
227 $formoutput .= "\n" . '<input type="hidden" name="course" value="' . (!empty($COURSE) ? $COURSE->id : 0) . '" />';
228 $linkoutput .= 'callbackfile=' . $callbackfile . '&amp;callbackclass='
229 . $callbackclass . '&amp;course=' . (!empty($COURSE) ? $COURSE->id : 0);
67a87e7d 230 $selectoutput = '';
231 if (count($instances) == 1) {
232 $instance = array_shift($instances);
233 if (count(array_intersect($callersupports, $instance->supported_formats())) == 0) {
234 // bail. no common formats.
235 debugging(get_string('nocommonformats', 'portfolio', $callbackclass));
236 return;
237 }
238 if ($error = portfolio_instance_sanity_check($instance)) {
239 // bail, plugin is misconfigured
240 debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
241 return;
242 }
866d543f 243 $formoutput .= "\n" . '<input type="hidden" name="instance" value="' . $instance->get('id') . '" />';
244 $linkoutput .= '&amp;instance=' . $instance->get('id');
67a87e7d 245 }
246 else {
7c61a8f0 247 $selectoutput = portfolio_instance_select($instances, $callersupports, $callbackclass, 'instance', true);
67a87e7d 248 }
249
866d543f 250 if (empty($addstr)) {
251 $addstr = get_string('addtoportfolio', 'portfolio');
67a87e7d 252 }
866d543f 253 if (empty($format)) {
254 $format = PORTFOLIO_ADD_FULL_FORM;
255 }
256 switch ($format) {
257 case PORTFOLIO_ADD_FULL_FORM:
258 $formoutput .= $selectoutput;
259 $formoutput .= "\n" . '<input type="submit" value="' . $addstr .'" />';
260 $formoutput .= "\n" . '</form>';
261 break;
262 case PORTFOLIO_ADD_ICON_FORM:
263 $formoutput .= $selectoutput;
264 $formoutput .= "\n" . '<input type="image" src="' . $CFG->pixpath . '/t/portfolio.gif" alt=' . $addstr .'" />';
265 $formoutput .= "\n" . '</form>';
266 break;
267 case PORTFOLIO_ADD_ICON_LINK:
268 $linkoutput .= '"><img src="' . $CFG->pixpath . '/t/portfolio.gif" alt=' . $addstr .'" /></a>';
269 break;
270 case PORTFOLIO_ADD_TEXT_LINK:
271 $linkoutput .= '">' . $addstr .'</a>';
272 break;
273 default:
274 debugging('asdfd');
275 print_error('invalidaddformat', 'portfolio', '', $format);
276 }
277 $output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
67a87e7d 278 if ($return) {
279 return $output;
280 } else {
281 echo $output;
282 }
283 return true;
284}
285
286/**
287* returns a drop menu with a list of available instances.
288*
289* @param array $instances the instances to put in the menu
290* @param array $callerformats the formats the caller supports
291 (this is used to filter plugins)
292* @param array $callbackclass the callback class name
293*
294* @return string the html, from <select> to </select> inclusive.
295*/
9eb0a772 296function portfolio_instance_select($instances, $callerformats, $callbackclass, $selectname='instance', $return=false, $returnarray=false) {
297 global $CFG;
298
299 if (empty($CFG->portfolioenabled)) {
300 return;
301 }
302
67a87e7d 303 $insane = portfolio_instance_sanity_check();
304 $count = 0;
9eb0a772 305 $selectoutput = "\n" . '<select name="' . $selectname . '">' . "\n";
67a87e7d 306 foreach ($instances as $instance) {
307 if (count(array_intersect($callerformats, $instance->supported_formats())) == 0) {
308 // bail. no common formats.
309 continue;
310 }
311 if (array_key_exists($instance->get('id'), $insane)) {
312 // bail, plugin is misconfigured
313 debugging(get_string('instancemisconfigured', 'portfolio', get_string($insane[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))));
314 continue;
315 }
316 $count++;
9eb0a772 317 $selectoutput .= "\n" . '<option value="' . $instance->get('id') . '">' . $instance->get('name') . '</option>' . "\n";
318 $options[$instance->get('id')] = $instance->get('name');
67a87e7d 319 }
320 if (empty($count)) {
321 // bail. no common formats.
322 debugging(get_string('nocommonformats', 'portfolio', $callbackclass));
323 return;
324 }
325 $selectoutput .= "\n" . "</select>\n";
9eb0a772 326 if (!empty($returnarray)) {
327 return $options;
328 }
329 if (!empty($return)) {
330 return $selectoutput;
331 }
332 echo $selectoutput;
67a87e7d 333}
334
335/**
336* return all portfolio instances
337*
338* @param boolean visibleonly don't include hidden instances (defaults to true and will be overridden to true if the next parameter is true)
339* @param boolean useronly check the visibility preferences and permissions of the logged in user
340* @return array of portfolio instances (full objects, not just database records)
341*/
342function portfolio_instances($visibleonly=true, $useronly=true) {
343
344 global $DB, $USER;
345
346 $values = array();
347 $sql = 'SELECT * FROM {portfolio_instance}';
348
349 if ($visibleonly || $useronly) {
350 $values[] = 1;
351 $sql .= ' WHERE visible = ?';
352 }
353 if ($useronly) {
354 $sql .= ' AND id NOT IN (
355 SELECT instance FROM {portfolio_instance_user}
356 WHERE userid = ? AND name = ? AND value = ?
357 )';
358 $values = array_merge($values, array($USER->id, 'visible', 0));
359 }
360 $sql .= ' ORDER BY name';
361
362 $instances = array();
363 foreach ($DB->get_records_sql($sql, $values) as $instance) {
a50ef3d3 364 $instances[$instance->id] = portfolio_instance($instance->id, $instance);
67a87e7d 365 }
366 // @todo check capabilities here - see MDL-15768
367 return $instances;
368}
369
370/**
371* supported formats that portfolio plugins and callers
372* can use for exporting content
373*
374* @return array of all the available export formats
375*/
376function portfolio_supported_formats() {
377 return array(
378 PORTFOLIO_FORMAT_FILE,
5071079c 379 /*PORTFOLIO_FORMAT_MBKP, */ // later
380 /*PORTFOLIO_FORMAT_PIOP, */ // also later
67a87e7d 381 );
382}
383
384/**
385* helper function to return an instance of a plugin (with config loaded)
386*
387* @param int $instance id of instance
388* @param array $record database row that corresponds to this instance
389* this is passed to avoid unnecessary lookups
390*
391* @return subclass of portfolio_plugin_base
392*/
393function portfolio_instance($instanceid, $record=null) {
394 global $DB, $CFG;
395
396 if ($record) {
397 $instance = $record;
398 } else {
399 if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
400 return false; // @todo throw exception?
401 }
402 }
403 require_once($CFG->dirroot . '/portfolio/type/'. $instance->plugin . '/lib.php');
404 $classname = 'portfolio_plugin_' . $instance->plugin;
405 return new $classname($instanceid, $instance);
406}
407
408/**
409* helper function to call a static function on a portfolio plugin class
410* this will figure out the classname and require the right file and call the function.
411* you can send a variable number of arguments to this function after the first two
412* and they will be passed on to the function you wish to call.
413*
414* @param string $plugin name of plugin
415* @param string $function function to call
416*/
417function portfolio_static_function($plugin, $function) {
418 global $CFG;
419
420 $pname = null;
421 if (is_object($plugin) || is_array($plugin)) {
422 $plugin = (object)$plugin;
423 $pname = $plugin->name;
424 } else {
425 $pname = $plugin;
426 }
427
428 $args = func_get_args();
429 if (count($args) <= 2) {
430 $args = array();
431 }
432 else {
433 array_shift($args);
434 array_shift($args);
435 }
436
437 require_once($CFG->dirroot . '/portfolio/type/' . $plugin . '/lib.php');
438 return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args);
439}
440
441/**
442* helper function to check all the plugins for sanity and set any insane ones to invisible.
443*
444* @param array $plugins to check (if null, defaults to all)
445* one string will work too for a single plugin.
446*
447* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
448*/
449function portfolio_plugin_sanity_check($plugins=null) {
450 global $DB;
451 if (is_string($plugins)) {
452 $plugins = array($plugins);
453 } else if (empty($plugins)) {
454 $plugins = get_list_of_plugins('portfolio/type');
455 }
456
457 $insane = array();
458 foreach ($plugins as $plugin) {
459 if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) {
460 $insane[$plugin] = $result;
461 }
462 }
463 if (empty($insane)) {
464 return array();
465 }
466 list($where, $params) = $DB->get_in_or_equal(array_keys($insane));
467 $where = ' plugin ' . $where;
468 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
469 return $insane;
470}
471
472/**
473* helper function to check all the instances for sanity and set any insane ones to invisible.
474*
475* @param array $instances to check (if null, defaults to all)
476* one instance or id will work too
477*
478* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang)
479*/
480function portfolio_instance_sanity_check($instances=null) {
481 global $DB;
482 if (empty($instances)) {
483 $instances = portfolio_instances(false);
484 } else if (!is_array($instances)) {
485 $instances = array($instances);
486 }
487
488 $insane = array();
489 foreach ($instances as $instance) {
490 if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) {
491 $instance = portfolio_instance($instance->id, $instance);
492 } else if (is_numeric($instance)) {
493 $instance = portfolio_instance($instance);
494 }
495 if (!($instance instanceof portfolio_plugin_base)) {
496 debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id');
497 continue;
498 }
499 if ($result = $instance->instance_sanity_check()) {
500 $insane[$instance->get('id')] = $result;
501 }
502 }
503 if (empty($insane)) {
504 return array();
505 }
506 list ($where, $params) = $DB->get_in_or_equal(array_keys($insane));
507 $where = ' id ' . $where;
508 $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params);
509 return $insane;
510}
511
512/**
513* helper function to display a table of plugins (or instances) and reasons for disabling
514*
515* @param array $insane array of insane plugins (key = plugin (or instance id), value = reason)
516* @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
517*
518*/
a50ef3d3 519function portfolio_report_insane($insane, $instances=false, $return=false) {
67a87e7d 520 if (empty($insane)) {
521 return;
522 }
523
524 static $pluginstr;
525 if (empty($pluginstr)) {
526 $pluginstr = get_string('plugin', 'portfolio');
527 }
528 if ($instances) {
529 $headerstr = get_string('someinstancesdisabled', 'portfolio');
530 } else {
531 $headerstr = get_string('somepluginsdisabled', 'portfolio');
532 }
533
a50ef3d3 534 $output = notify($headerstr, 'notifyproblem', 'center', true);
67a87e7d 535 $table = new StdClass;
536 $table->head = array($pluginstr, '');
537 $table->data = array();
538 foreach ($insane as $plugin => $reason) {
539 if ($instances) {
540 // @todo this isn't working
541 // because it seems the new recordset object
542 // doesn't implement the key correctly.
0082ed89 543 // see MDL-15798
67a87e7d 544 $instance = $instances[$plugin];
545 $plugin = $instance->get('plugin');
546 $name = $instance->get('name');
547 } else {
548 $name = $plugin;
549 }
550 $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
551 }
a50ef3d3 552 $output .= print_table($table, true);
553 $output .= '<br /><br /><br />';
554
555 if ($return) {
556 return $output;
557 }
558 echo $output;
67a87e7d 559}
560
9eb0a772 561/**
562* fake the url to portfolio/add.php from data from somewhere else
563* you should use portfolio_add_button instead 99% of the time
564*
565* @param int $instanceid instanceid (optional, will force a new screen if not specified)
566* @param string $classname callback classname
567* @param string $classfile file containing the callback class definition
568* @param array $callbackargs arguments to pass to the callback class
569*/
570function portfolio_fake_add_url($instanceid, $classname, $classfile, $callbackargs) {
571 global $CFG;
572 $url = $CFG->wwwroot . '/portfolio/add.php?instance=' . $instanceid . '&amp;callbackclass=' . $classname . '&amp;callbackfile=' . $classfile;
573
574 if (is_object($callbackargs)) {
575 $callbackargs = (array)$callbackargs;
576 }
577 if (!is_array($callbackargs) || empty($callbackargs)) {
578 return $url;
579 }
580 foreach ($callbackargs as $key => $value) {
581 $url .= '&amp;ca_' . $key . '=' . urlencode($value);
582 }
583 return $url;
584}
67a87e7d 585
586/**
587* base class for the caller
588* places in moodle that want to display
589* the add form should subclass this for their callback.
590*/
591abstract class portfolio_caller_base {
592
593 /**
594 * stdclass object
595 * course that was active during the caller
596 */
597 protected $course;
598
599 /**
600 * named array of export config
601 * use{@link set_export_config} and {@link get_export_config} to access
602 */
603 protected $exportconfig;
604
605 /**
606 * stdclass object
607 * user currently exporting content
608 */
609 protected $user;
610
d67bfc32 611 /**
612 * a reference to the exporter object
613 */
614 protected $exporter;
84a44985 615
04f35360 616 /**
84a44985 617 *
04f35360 618 */
84a44985 619 private $stage;
04f35360 620
67a87e7d 621 /**
622 * if this caller wants any additional config items
623 * they should be defined here.
624 *
625 * @param array $mform moodleform object (passed by reference) to add elements to
626 * @param object $instance subclass of portfolio_plugin_base
627 * @param integer $userid id of user exporting content
628 */
629 public function export_config_form(&$mform, $instance) {}
630
631
632 /**
633 * whether this caller wants any additional
634 * config during export (eg options or metadata)
635 *
636 * @return boolean
637 */
638 public function has_export_config() {
639 return false;
640 }
641
642 /**
643 * just like the moodle form validation function
644 * this is passed in the data array from the form
645 * and if a non empty array is returned, form processing will stop.
646 *
647 * @param array $data data from form.
648 * @return array keyvalue pairs - form element => error string
649 */
650 public function export_config_validation($data) {}
651
652 /**
653 * how long does this reasonably expect to take..
654 * should we offer the user the option to wait..
655 * this is deliberately nonstatic so it can take filesize into account
656 * the portfolio plugin can override this.
657 * (so for exmaple even if a huge file is being sent,
658 * the download portfolio plugin doesn't care )
659 *
660 * @return string (see PORTFOLIO_TIME_* constants)
661 */
662 public abstract function expected_time();
663
664 /**
665 * used for displaying the navigation during the export screens.
666 *
667 * this function must be implemented, but can really return anything.
668 * an Exporting.. string will be added on the end.
669 * @return array of $extranav and $cm
670 *
671 * to pass to build_navigation
672 *
673 */
674 public abstract function get_navigation();
675
ffcfd8a7 676 /**
677 *
678 */
679 public abstract function get_sha1();
680
67a87e7d 681 /*
682 * generic getter for properties belonging to this instance
683 * <b>outside</b> the subclasses
684 * like name, visible etc.
685 *
686 * @todo determine what to return in the error case
687 */
9eb0a772 688 public function get($field) {
67a87e7d 689 if (property_exists($this, $field)) {
690 return $this->{$field};
691 }
692 return false; // @todo throw exception?
693 }
694
695 /**
696 * generic setter for properties belonging to this instance
697 * <b>outside</b> the subclass
698 * like name, visible, etc.
699 *
700 * @todo determine what to return in the error case
701 */
d67bfc32 702 public final function set($field, &$value) {
67a87e7d 703 if (property_exists($this, $field)) {
d67bfc32 704 $this->{$field} =& $value;
67a87e7d 705 $this->dirty = true;
706 return true;
707 }
708 return false; // @todo throw exception?
709
710 }
711
712 /**
713 * stores the config generated at export time.
714 * subclasses can retrieve values using
715 * {@link get_export_config}
716 *
717 * @param array $config formdata
718 */
719 public final function set_export_config($config) {
720 $allowed = array_merge(
ffcfd8a7 721 array('wait', 'hidewait', 'format', 'hideformat'),
67a87e7d 722 $this->get_allowed_export_config()
723 );
724 foreach ($config as $key => $value) {
725 if (!in_array($key, $allowed)) {
726 continue; // @ todo throw exception
727 }
728 $this->exportconfig[$key] = $value;
729 }
730 }
731
732 /**
733 * returns a particular export config value.
734 * subclasses shouldn't need to override this
735 *
736 * @param string key the config item to fetch
737 * @todo figure out the error cases (item not found or not allowed)
738 */
739 public final function get_export_config($key) {
740 $allowed = array_merge(
ffcfd8a7 741 array('wait', 'hidewait', 'format', 'hideformat'),
67a87e7d 742 $this->get_allowed_export_config()
743 );
744 if (!in_array($key, $allowed)) {
745 return false; // @todo throw exception?
746 }
747 if (!array_key_exists($key, $this->exportconfig)) {
748 return null; // @todo what to return|
749 }
750 return $this->exportconfig[$key];
751 }
752
04f35360 753
04f35360 754
67a87e7d 755 /**
756 * Similar to the other allowed_config functions
757 * if you need export config, you must provide
758 * a list of what the fields are.
759 *
760 * even if you want to store stuff during export
761 * without displaying a form to the user,
762 * you can use this.
763 *
764 * @return array array of allowed keys
765 */
766 public function get_allowed_export_config() {
767 return array();
768 }
769
770 /**
771 * after the user submits their config
772 * they're given a confirm screen
773 * summarising what they've chosen.
774 *
775 * this function should return a table of nice strings => values
776 * of what they've chosen
777 * to be displayed in a table.
778 *
779 * @return array array of config items.
780 */
781 public function get_export_summary() {
782 return false;
783 }
784
785 /**
786 * called before the portfolio plugin gets control
787 * this function should copy all the files it wants to
d67bfc32 788 * the temporary directory, using {@see copy_existing_file}
789 * or {@see write_new_file}
67a87e7d 790 */
d67bfc32 791 public abstract function prepare_package();
67a87e7d 792
793 /**
794 * array of formats this caller supports
795 * the intersection of what this function returns
796 * and what the selected portfolio plugin supports
797 * will be used
798 * use the constants PORTFOLIO_FORMAT_*
799 *
800 * @return array list of formats
801 */
bb63fc3e 802 public static function supported_formats() {
803 return array(PORTFOLIO_FORMAT_FILE);
804 }
67a87e7d 805
806 /**
807 * this is the "return to where you were" url
808 *
809 * @return string url
810 */
811 public abstract function get_return_url();
812
813 /**
814 * callback to do whatever capability checks required
815 * in the caller (called during the export process
816 */
817 public abstract function check_permissions();
ffcfd8a7 818
819 /**
820 * nice name to display to the user about this caller location
821 */
822 public abstract static function display_name();
67a87e7d 823}
824
5071079c 825abstract class portfolio_module_caller_base extends portfolio_caller_base {
826
827 protected $cm;
9eb0a772 828 protected $course;
5071079c 829
830 public function get_navigation() {
831 $extranav = array('name' => $this->cm->name, 'link' => $this->get_return_url());
832 return array($extranav, $this->cm);
833 }
834
835 public function get_return_url() {
836 global $CFG;
837 return $CFG->wwwroot . '/mod/' . $this->cm->modname . '/view.php?id=' . $this->cm->id;
838 }
9eb0a772 839
840 public function get($key) {
841 if ($key != 'course') {
842 return parent::get($key);
843 }
844 global $DB;
845 if (empty($this->course)) {
846 $this->course = $DB->get_record('course', array('id' => $this->cm->course));
847 }
848 return $this->course;
849 }
5071079c 850}
851
67a87e7d 852/**
2876d73b 853* the base class for portfolio plugins
67a87e7d 854* all plugins must subclass this.
855*/
856abstract class portfolio_plugin_base {
857
858 /**
859 * boolean
860 * whether this object needs writing out to the database
861 */
862 protected $dirty;
863
864 /**
865 * integer
866 * id of instance
867 */
868 protected $id;
869
870 /**
871 * string
872 * name of instance
873 */
874 protected $name;
875
876 /**
877 * string
878 * plugin this instance belongs to
879 */
880 protected $plugin;
881
882 /**
883 * boolean
884 * whether this instance is visible or not
885 */
886 protected $visible;
887
888 /**
889 * named array
890 * admin configured config
891 * use {@link set_config} and {@get_config} to access
892 */
893 protected $config;
894
895 /**
896 *
897 * user config cache
898 * named array of named arrays
899 * keyed on userid and then on config field => value
900 * use {@link get_user_config} and {@link set_user_config} to access.
901 */
902 protected $userconfig;
903
904 /**
905 * named array
906 * export config during export
907 * use {@link get_export_config} and {@link set export_config} to access.
908 */
909 protected $exportconfig;
910
911 /**
912 * stdclass object
913 * user currently exporting data
914 */
915 protected $user;
916
d67bfc32 917 /**
918 * a reference to the exporter object
919 */
920 protected $exporter;
67a87e7d 921
922 /**
923 * array of formats this portfolio supports
924 * the intersection of what this function returns
925 * and what the caller supports will be used
926 * use the constants PORTFOLIO_FORMAT_*
927 *
928 * @return array list of formats
929 */
bb63fc3e 930 public static function supported_formats() {
931 return array(PORTFOLIO_FORMAT_FILE);
932 }
67a87e7d 933
934
935 /**
936 * how long does this reasonably expect to take..
937 * should we offer the user the option to wait..
938 * this is deliberately nonstatic so it can take filesize into account
939 *
940 * @param string $callertime - what the caller thinks
941 * the portfolio plugin instance
942 * is given the final say
943 * because it might be (for example) download.
944 * @return string (see PORTFOLIO_TIME_* constants)
945 */
946 public abstract function expected_time($callertime);
947
d96a1acc 948 /**
949 * is this plugin push or pill.
950 * if push, cleanup will be called directly after send_package
951 * if not, cleanup will be called after portfolio/file.php is requested
952 *
953 * @return boolean
954 */
955 public abstract function is_push();
956
67a87e7d 957 /**
958 * check sanity of plugin
959 * if this function returns something non empty, ALL instances of your plugin
960 * will be set to invisble and not be able to be set back until it's fixed
961 *
962 * @return mixed - string = error string KEY (must be inside plugin_$yourplugin) or 0/false if you're ok
963 */
964 public static function plugin_sanity_check() {
965 return 0;
966 }
967
968 /**
969 * check sanity of instances
970 * if this function returns something non empty, the instance will be
971 * set to invislbe and not be able to be set back until it's fixed.
972 *
973 * @return mixed - string = error string KEY (must be inside plugin_$yourplugin) or 0/false if you're ok
974 */
975 public function instance_sanity_check() {
976 return 0;
977 }
978
979 /**
980 * does this plugin need any configuration by the administrator?
981 *
982 * if you override this to return true,
983 * you <b>must</b> implement {@link} admin_config_form
984 */
985 public static function has_admin_config() {
986 return false;
987 }
988
989 /**
990 * can this plugin be configured by the user in their profile?
991 *
992 * if you override this to return true,
993 * you <b>must</b> implement {@link user_config_form
994 */
995 public function has_user_config() {
996 return false;
997 }
998
999 /**
1000 * does this plugin need configuration during export time?
1001 *
1002 * if you override this to return true,
1003 * you <b>must</b> implement {@link export_config_form}
1004 */
1005 public function has_export_config() {
1006 return false;
1007 }
1008
1009 /**
1010 * just like the moodle form validation function
1011 * this is passed in the data array from the form
1012 * and if a non empty array is returned, form processing will stop.
1013 *
1014 * @param array $data data from form.
1015 * @return array keyvalue pairs - form element => error string
1016 */
1017 public function export_config_validation() {}
1018
1019 /**
1020 * just like the moodle form validation function
1021 * this is passed in the data array from the form
1022 * and if a non empty array is returned, form processing will stop.
1023 *
1024 * @param array $data data from form.
1025 * @return array keyvalue pairs - form element => error string
1026 */
1027 public function user_config_validation() {}
1028
1029 /**
1030 * sets the export time config from the moodle form.
1031 * you can also use this to set export config that
1032 * isn't actually controlled by the user
1033 * eg things that your subclasses want to keep in state
1034 * across the export.
1035 * keys must be in {@link get_allowed_export_config}
1036 *
1037 * this is deliberately not final (see boxnet plugin)
1038 *
1039 * @param array $config named array of config items to set.
1040 */
1041 public function set_export_config($config) {
1042 $allowed = array_merge(
ffcfd8a7 1043 array('wait', 'hidewait', 'format', 'hideformat'),
67a87e7d 1044 $this->get_allowed_export_config()
1045 );
1046 foreach ($config as $key => $value) {
1047 if (!in_array($key, $allowed)) {
1048 continue; // @ todo throw exception
1049 }
1050 $this->exportconfig[$key] = $value;
1051 }
1052 }
1053
1054 /**
1055 * gets an export time config value.
1056 * subclasses should not override this.
1057 *
1058 * @param string key field to fetch
1059 *
1060 * @return string config value
1061 *
1062 * @todo figure out the error cases
1063 */
1064 public final function get_export_config($key) {
1065 $allowed = array_merge(
ffcfd8a7 1066 array('hidewait', 'wait', 'format', 'hideformat'),
67a87e7d 1067 $this->get_allowed_export_config()
1068 );
1069 if (!in_array($key, $allowed)) {
1070 return false; // @todo throw exception?
1071 }
1072 if (!array_key_exists($key, $this->exportconfig)) {
1073 return null; // @todo what to return|
1074 }
1075 return $this->exportconfig[$key];
1076 }
1077
1078 /**
1079 * after the user submits their config
1080 * they're given a confirm screen
1081 * summarising what they've chosen.
1082 *
1083 * this function should return a table of nice strings => values
1084 * of what they've chosen
1085 * to be displayed in a table.
1086 *
1087 * @return array array of config items.
1088 */
1089 public function get_export_summary() {
1090 return false;
1091 }
1092
1093 /**
d67bfc32 1094 * called after the caller has finished having control
1095 * of its prepare_package function.
1096 * this function should read all the files from the portfolio
1097 * working file area and zip them and send them or whatever it wants.
1098 * {@see get_tempfiles} to get the list of files.
67a87e7d 1099 *
67a87e7d 1100 */
d67bfc32 1101 public abstract function prepare_package();
67a87e7d 1102
1103 /**
1104 * this is the function that is responsible for sending
1105 * the package to the remote system,
1106 * or whatever request is necessary to initiate the transfer.
1107 *
1108 * @return boolean success
1109 */
1110 public abstract function send_package();
1111
1112
1113 /**
1114 * once everything is done and the user
1115 * has the finish page displayed to them
1116 * the base class takes care of printing them
1117 * "return to where you are" or "continue to portfolio" links
1118 * this function allows for exta finish options from the plugin
1119 *
1120 * @return array named array of links => titles
1121 */
1122 public function get_extra_finish_options() {
1123 return false;
1124 }
1125
1126 /**
1127 * the url for the user to continue to their portfolio
1128 *
1129 * @return string url or false.
1130 */
1131 public abstract function get_continue_url();
1132
1133 /**
1134 * mform to display to the user in their profile
1135 * if your plugin can't be configured by the user,
1136 * (see {@link has_user_config})
1137 * don't bother overriding this function
1138 *
1139 * @param moodleform $mform passed by reference, add elements to it
1140 */
1141 public function user_config_form(&$mform) {}
1142
1143 /**
1144 * mform to display to the admin configuring the plugin.
1145 * if your plugin can't be configured by the admin,
1146 * (see {@link} has_admin_config)
1147 * don't bother overriding this function
1148 *
1149 * this function can be called statically or non statically,
1150 * depending on whether it's creating a new instance (statically),
1151 * or editing an existing one (non statically)
1152 *
1153 * @param moodleform $mform passed by reference, add elements to it.
1154 * @return mixed - if a string is returned, it means the plugin cannot create an instance
1155 * and the string is an error code
1156 */
1157 public function admin_config_form(&$mform) {}
1158
1159 /**
1160 * just like the moodle form validation function
1161 * this is passed in the data array from the form
1162 * and if a non empty array is returned, form processing will stop.
1163 *
1164 * @param array $data data from form.
1165 * @return array keyvalue pairs - form element => error string
1166 */
d67bfc32 1167 public function admin_config_validation($data) {}
67a87e7d 1168 /**
1169 * mform to display to the user exporting data using this plugin.
1170 * if your plugin doesn't need user input at this time,
1171 * (see {@link has_export_config}
1172 * don't bother overrideing this function
1173 *
1174 * @param moodleform $mform passed by reference, add elements to it.
1175 */
1176 public function export_config_form(&$mform) {}
1177
1178 /**
1179 * override this if your plugin doesn't allow multiple instances
1180 *
1181 * @return boolean
1182 */
1183 public static function allows_multiple() {
1184 return true;
1185 }
1186
1187 /**
1188 *
1189 * If at any point the caller wants to steal control
1190 * it can, by returning something that isn't false
1191 * in this function
1192 * The controller will redirect to whatever url
1193 * this function returns.
1194 * Afterwards, you can redirect back to portfolio/add.php?postcontrol=1
1195 * and {@link post_control} is called before the rest of the processing
1196 * for the stage is done
1197 *
1198 * @param int stage to steal control *before* (see constants PARAM_STAGE_*}
1199 *
1200 * @return boolean or string url
1201 */
1202 public function steal_control($stage) {
1203 return false;
1204 }
1205
1206 /**
1207 * after a plugin has elected to steal control,
1208 * and control returns to portfolio/add.php|postcontrol=1,
1209 * this function is called, and passed the stage that was stolen control from
1210 * and the request (get and post but not cookie) parameters
1211 * this is useful for external systems that need to redirect the user back
1212 * with some extra data in the url (like auth tokens etc)
1213 * for an example implementation, see boxnet portfolio plugin.
1214 *
1215 * @param int $stage the stage before control was stolen
1216 * @param array $params a merge of $_GET and $_POST
1217 *
1218 */
1219
1220 public function post_control($stage, $params) { }
1221
1222 /**
1223 * this function creates a new instance of a plugin
1224 * saves it in the database, saves the config
1225 * and returns it.
1226 * you shouldn't need to override it
1227 * unless you're doing something really funky
1228 *
1229 * @return object subclass of portfolio_plugin_base
1230 */
1231 public static function create_instance($plugin, $name, $config) {
1232 global $DB, $CFG;
1233 $new = (object)array(
1234 'plugin' => $plugin,
1235 'name' => $name,
1236 );
1237 $newid = $DB->insert_record('portfolio_instance', $new);
1238 require_once($CFG->dirroot . '/portfolio/type/' . $plugin . '/lib.php');
1239 $classname = 'portfolio_plugin_' . $plugin;
1240 $obj = new $classname($newid);
1241 $obj->set_config($config);
1242 return $obj;
1243 }
1244
1245 /**
1246 * construct a plugin instance
1247 * subclasses should not need to override this unless they're doing something special
1248 * and should call parent::__construct afterwards
1249 *
1250 * @param int $instanceid id of plugin instance to construct
1251 * @param mixed $record stdclass object or named array - use this is you already have the record to avoid another query
1252 *
1253 * @return object subclass of portfolio_plugin_base
1254 */
1255 public function __construct($instanceid, $record=null) {
1256 global $DB;
1257 if (!$record) {
1258 if (!$record = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
1259 return false; // @todo throw exception?
1260 }
1261 }
1262 foreach ((array)$record as $key =>$value) {
1263 if (property_exists($this, $key)) {
1264 $this->{$key} = $value;
1265 }
1266 }
1267 $this->config = new StdClass;
1268 $this->userconfig = array();
1269 $this->exportconfig = array();
1270 foreach ($DB->get_records('portfolio_instance_config', array('instance' => $instanceid)) as $config) {
1271 $this->config->{$config->name} = $config->value;
1272 }
1273 return $this;
1274 }
1275
1276 /**
1277 * a list of fields that can be configured per instance.
1278 * this is used for the save handlers of the config form
1279 * and as checks in set_config and get_config
1280 *
1281 * @return array array of strings (config item names)
1282 */
1283 public static function get_allowed_config() {
1284 return array();
1285 }
1286
1287 /**
1288 * a list of fields that can be configured by the user.
1289 * this is used for the save handlers in the config form
1290 * and as checks in set_user_config and get_user_config.
1291 *
1292 * @return array array of strings (config field names)
1293 */
1294 public function get_allowed_user_config() {
1295 return array();
1296 }
1297
1298 /**
1299 * a list of fields that can be configured by the user.
1300 * this is used for the save handlers in the config form
1301 * and as checks in set_export_config and get_export_config.
1302 *
1303 * @return array array of strings (config field names)
1304 */
1305 public function get_allowed_export_config() {
1306 return array();
1307 }
1308
1309 /**
1310 * saves (or updates) the config stored in portfolio_instance_config.
1311 * you shouldn't need to override this unless you're doing something funky.
1312 *
1313 * @param array $config array of config items.
1314 */
1315 public final function set_config($config) {
1316 global $DB;
1317 foreach ($config as $key => $value) {
1318 // try set it in $this first
1319 if ($this->set($key, $value)) {
1320 continue;
1321 }
1322 if (!in_array($key, $this->get_allowed_config())) {
1323 continue; // @todo throw exception?
1324 }
1325 if (!isset($this->config->{$key})) {
1326 $DB->insert_record('portfolio_instance_config', (object)array(
1327 'instance' => $this->id,
1328 'name' => $key,
1329 'value' => $value,
1330 ));
1331 } else if ($this->config->{$key} != $value) {
1332 $DB->set_field('portfolio_instance_config', 'value', $value, array('name' => $key, 'instance' => $this->id));
1333 }
1334 $this->config->{$key} = $value;
1335 }
1336 return true; // @todo - if we're going to change here to throw exceptions, this can change
1337 }
1338
1339 /**
1340 * gets the value of a particular config item
1341 *
1342 * @param string $key key to fetch
1343 *
1344 * @return string the corresponding value
1345 *
1346 * @todo determine what to return in the error case.
1347 */
1348 public final function get_config($key) {
1349 if (!in_array($key, $this->get_allowed_config())) {
1350 return false; // @todo throw exception?
1351 }
1352 if (isset($this->config->{$key})) {
1353 return $this->config->{$key};
1354 }
1355 return false; // @todo null?
1356 }
1357
1358 /**
1359 * get the value of a config item for a particular user
1360 *
1361 * @param string $key key to fetch
1362 * @param integer $userid id of user (defaults to current)
1363 *
1364 * @return string the corresponding value
1365 *
1366 * @todo determine what to return in the error case
1367 */
1368 public final function get_user_config($key, $userid=0) {
1369 global $DB;
1370
1371 if (empty($userid)) {
1372 $userid = $this->user->id;
1373 }
1374
1375 if ($key != 'visible') { // handled by the parent class
1376 if (!in_array($key, $this->get_allowed_user_config())) {
1377 return false; // @todo throw exception?
1378 }
1379 }
1380 if (!array_key_exists($userid, $this->userconfig)) {
1381 $this->userconfig[$userid] = (object)array_fill_keys(array_merge(array('visible'), $this->get_allowed_user_config()), null);
1382 foreach ($DB->get_records('portfolio_instance_user', array('instance' => $this->id, 'userid' => $userid)) as $config) {
1383 $this->userconfig[$userid]->{$config->name} = $config->value;
1384 }
1385 }
1386 if ($this->userconfig[$userid]->visible === null) {
1387 $this->set_user_config(array('visible' => 1), $userid);
1388 }
1389 return $this->userconfig[$userid]->{$key};
1390
1391 }
1392
1393 /**
1394 *
1395 * sets config options for a given user
1396 *
1397 * @param mixed $config array or stdclass containing key/value pairs to set
1398 * @param integer $userid userid to set config for (defaults to current)
1399 *
1400 * @todo determine what to return in the error case
1401 */
1402 public final function set_user_config($config, $userid=0) {
1403 global $DB;
1404
1405 if (empty($userid)) {
1406 $userid = $this->user->id;
1407 }
1408
1409 foreach ($config as $key => $value) {
1410 if ($key != 'visible' && !in_array($key, $this->get_allowed_user_config())) {
1411 continue; // @todo throw exception?
1412 }
1413 if (!$existing = $DB->get_record('portfolio_instance_user', array('instance'=> $this->id, 'userid' => $userid, 'name' => $key))) {
1414 $DB->insert_record('portfolio_instance_user', (object)array(
1415 'instance' => $this->id,
1416 'name' => $key,
1417 'value' => $value,
1418 'userid' => $userid,
1419 ));
1420 } else if ($existing->value != $value) {
1421 $DB->set_field('portfolio_instance_user', 'value', $value, array('name' => $key, 'instance' => $this->id, 'userid' => $userid));
1422 }
1423 $this->userconfig[$userid]->{$key} = $value;
1424 }
1425 return true; // @todo
1426
1427 }
1428
1429 /**
1430 * generic getter for properties belonging to this instance
1431 * <b>outside</b> the subclasses
1432 * like name, visible etc.
1433 *
1434 * @todo determine what to return in the error case
1435 */
1436 public final function get($field) {
1437 if (property_exists($this, $field)) {
1438 return $this->{$field};
1439 }
1440 return false; // @todo throw exception?
1441 }
1442
1443 /**
1444 * generic setter for properties belonging to this instance
1445 * <b>outside</b> the subclass
1446 * like name, visible, etc.
1447 *
1448 * @todo determine what to return in the error case
1449 */
1450 public final function set($field, $value) {
1451 if (property_exists($this, $field)) {
d67bfc32 1452 $this->{$field} =& $value;
67a87e7d 1453 $this->dirty = true;
1454 return true;
1455 }
1456 return false; // @todo throw exception?
1457
1458 }
1459
1460 /**
1461 * saves stuff that's been stored in the object to the database
1462 * you shouldn't need to override this
1463 * unless you're doing something really funky.
1464 * and if so, call parent::save when you're done.
1465 */
1466 public function save() {
1467 global $DB;
1468 if (!$this->dirty) {
1469 return true;
1470 }
1471 $fordb = new StdClass();
1472 foreach (array('id', 'name', 'plugin', 'visible') as $field) {
1473 $fordb->{$field} = $this->{$field};
1474 }
1475 $DB->update_record('portfolio_instance', $fordb);
1476 $this->dirty = false;
1477 return true;
1478 }
1479
1480 /**
1481 * deletes everything from the database about this plugin instance.
1482 * you shouldn't need to override this unless you're storing stuff
1483 * in your own tables. and if so, call parent::delete when you're done.
1484 */
1485 public function delete() {
1486 global $DB;
1487 $DB->delete_records('portfolio_instance_config', array('instance' => $this->get('id')));
1488 $DB->delete_records('portfolio_instance_user', array('instance' => $this->get('id')));
1489 $DB->delete_records('portfolio_instance', array('id' => $this->get('id')));
1490 $this->dirty = false;
1491 return true;
1492 }
1493}
1494
d96a1acc 1495/**
1496* class to inherit from for 'push' type plugins
1497*/
1498abstract class portfolio_plugin_push_base extends portfolio_plugin_base {
1499
1500 public function is_push() {
1501 return true;
1502 }
1503}
1504
1505/**
1506* class to inherit from for 'pull' type plugins
1507*/
1508abstract class portfolio_plugin_pull_base extends portfolio_plugin_base {
1509
1510 private $file;
1511
1512 public function is_push() {
1513 return false;
1514 }
1515
1516
1517 /**
1518 * before sending the file when the pull is requested, verify the request parameters
1519 * these might include a token of some sort of whatever
1520 *
1521 * @param array request parameters (POST wins over GET)
1522 */
1523 public abstract function verify_file_request_params($params);
1524
1525}
1526
67a87e7d 1527/**
1528* this is the form that is actually used while exporting.
1529* plugins and callers don't get to define their own class
1530* as we have to handle form elements from both places
1531* see the docs for portfolio_plugin_base and portfolio_caller for more information
1532*/
1533final class portfolio_export_form extends moodleform {
1534
1535 public function definition() {
1536
1537 $mform =& $this->_form;
1538 $mform->addElement('hidden', 'stage', PORTFOLIO_STAGE_CONFIG);
1539 $mform->addElement('hidden', 'instance', $this->_customdata['instance']->get('id'));
1540
1541 if (array_key_exists('formats', $this->_customdata) && is_array($this->_customdata['formats'])) {
1542 if (count($this->_customdata['formats']) > 1) {
1543 $options = array();
1544 foreach ($this->_customdata['formats'] as $key) {
1545 $options[$key] = get_string('format_' . $key, 'portfolio');
1546 }
1547 $mform->addElement('select', 'format', get_string('availableformats', 'portfolio'), $options);
1548 } else {
1549 $f = array_shift($this->_customdata['formats']);
1550 $mform->addElement('hidden', 'format', $f);
1551 }
1552 }
1553
1554 if (array_key_exists('expectedtime', $this->_customdata) && $this->_customdata['expectedtime'] != PORTFOLIO_TIME_LOW) {
67a87e7d 1555 $radioarray = array();
1556 $radioarray[] = &MoodleQuickForm::createElement('radio', 'wait', '', get_string('wait', 'portfolio'), 1);
1557 $radioarray[] = &MoodleQuickForm::createElement('radio', 'wait', '', get_string('dontwait', 'portfolio'), 0);
1558 $mform->addGroup($radioarray, 'radioar', get_string('wanttowait_' . $this->_customdata['expectedtime'], 'portfolio') , array(' '), false);
1559
1560 $mform->setDefault('wait', 0);
1561 }
1562 else {
1563 $mform->addElement('hidden', 'wait', 1);
1564 }
1565
1566 if (array_key_exists('plugin', $this->_customdata) && is_object($this->_customdata['plugin'])) {
1567 $this->_customdata['plugin']->export_config_form($mform, $this->_customdata['userid']);
1568 }
1569
1570 if (array_key_exists('caller', $this->_customdata) && is_object($this->_customdata['caller'])) {
1571 $this->_customdata['caller']->export_config_form($mform, $this->_customdata['instance'], $this->_customdata['userid']);
1572 }
1573
1574 $this->add_action_buttons(true, get_string('next'));
1575 }
1576
1577 public function validation($data) {
1578
1579 $errors = array();
1580
1581 if (array_key_exists('plugin', $this->_customdata) && is_object($this->_customdata['plugin'])) {
1582 $pluginerrors = $this->_customdata['plugin']->export_config_validation($data);
1583 if (is_array($pluginerrors)) {
1584 $errors = $pluginerrors;
1585 }
1586 }
1587 if (array_key_exists('caller', $this->_customdata) && is_object($this->_customdata['caller'])) {
1588 $callererrors = $this->_customdata['caller']->export_config_validation($data);
1589 if (is_array($callererrors)) {
1590 $errors = array_merge($errors, $callererrors);
1591 }
1592 }
1593 return $errors;
1594 }
1595}
1596
1597/**
1598* this form is extendable by plugins
1599* who want the admin to be able to configure
1600* more than just the name of the instance.
1601* this is NOT done by subclassing this class,
1602* see the docs for portfolio_plugin_base for more information
1603*/
1604final class portfolio_admin_form extends moodleform {
1605
1606 protected $instance;
1607 protected $plugin;
1608
1609 public function definition() {
1610 global $CFG;
1611 $this->plugin = $this->_customdata['plugin'];
1612 $this->instance = (isset($this->_customdata['instance'])
1613 && is_subclass_of($this->_customdata['instance'], 'portfolio_plugin_base'))
1614 ? $this->_customdata['instance'] : null;
1615
1616 $mform =& $this->_form;
1617 $strrequired = get_string('required');
1618
1619 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->get('id') : 0);
1620 $mform->addElement('hidden', 'new', $this->plugin);
1621 $mform->addElement('hidden', 'plugin', $this->plugin);
1622
1623 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1624 $mform->addRule('name', $strrequired, 'required', null, 'client');
1625
1626 // let the plugin add the fields they want (either statically or not)
1627 if (portfolio_static_function($this->plugin, 'has_admin_config')) {
1628 if (!$this->instance) {
1629 $result = portfolio_static_function($this->plugin, 'admin_config_form', $mform);
1630 } else {
1631 $result = $this->instance->admin_config_form($mform);
1632 }
1633 }
1634
1635 if (isset($result) && is_string($result)) { // something went wrong, stop
1636 return $this->raise_error($result, 'portfolio_' . $this->plugin, $CFG->wwwroot . '/' . $CFG->admin . '/portfolio.php');
1637 }
1638
1639 // and set the data if we have some.
1640 if ($this->instance) {
1641 $data = array('name' => $this->instance->get('name'));
1642 foreach ($this->instance->get_allowed_config() as $config) {
1643 $data[$config] = $this->instance->get_config($config);
1644 }
1645 $this->set_data($data);
1646 }
1647 $this->add_action_buttons(true, get_string('save', 'portfolio'));
1648 }
1649
1650 public function validation($data) {
1651 global $DB;
1652
1653 $errors = array();
1654 if ($DB->count_records('portfolio_instance', array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
1655 $errors = array('name' => get_string('err_uniquename', 'portfolio'));
1656 }
1657
1658 $pluginerrors = array();
1659 if ($this->instance) {
1660 $pluginerrors = $this->instance->admin_config_validation($data);
1661 }
1662 else {
1663 $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data);
1664 }
1665 if (is_array($pluginerrors)) {
1666 $errors = array_merge($errors, $pluginerrors);
1667 }
1668 return $errors;
1669 }
1670}
1671
1672/**
1673* this is the form for letting the user configure an instance of a plugin.
1674* in order to extend this, you don't subclass this in the plugin..
1675* see the docs in portfolio_plugin_base for more information
1676*/
1677final class portfolio_user_form extends moodleform {
1678
1679 protected $instance;
1680 protected $userid;
1681
1682 public function definition() {
1683 $this->instance = $this->_customdata['instance'];
1684 $this->userid = $this->_customdata['userid'];
1685
1686 $this->_form->addElement('hidden', 'config', $this->instance->get('id'));
1687
1688 $this->instance->user_config_form($this->_form, $this->userid);
1689
1690 $data = array();
1691 foreach ($this->instance->get_allowed_user_config() as $config) {
1692 $data[$config] = $this->instance->get_user_config($config, $this->userid);
1693 }
1694 $this->set_data($data);
1695 $this->add_action_buttons(true, get_string('save', 'portfolio'));
1696 }
1697
1698 public function validation($data) {
1699
1700 $errors = $this->instance->user_config_validation($data);
1701
1702 }
1703}
1704
1705/**
1706*
1707* Class that handles the various stages of the actual export
1708*/
1709final class portfolio_exporter {
1710
1711 private $currentstage;
1712 private $caller;
1713 private $instance;
1714 private $noconfig;
1715 private $navigation;
67a87e7d 1716 private $user;
1717
1718 public $instancefile;
1719 public $callerfile;
1720
ac6a5492 1721 private $stage;
1722
84a44985 1723 /**
d67bfc32 1724 * id of this export
1725 * matches record in portfolio_tempdata table
1726 * and used for itemid for file storage.
84a44985 1727 */
1728 private $id;
1729
67a87e7d 1730 /**
1731 * construct a new exporter for use
1732 *
1733 * @param portfolio_plugin_base subclass $instance portfolio instance (passed by reference)
1734 * @param portfolio_caller_base subclass $caller portfolio caller (passed by reference)
2876d73b 1735 * @param string $callerfile @todo document
67a87e7d 1736 * @param string $navigation result of build_navigation (passed to print_header)
1737 */
1738 public function __construct(&$instance, &$caller, $callerfile, $navigation) {
1739 $this->instance =& $instance;
1740 $this->caller =& $caller;
1741 if ($instance) {
1742 $this->instancefile = 'portfolio/type/' . $instance->get('plugin') . '/lib.php';
d67bfc32 1743 $this->instance->set('exporter', $this);
67a87e7d 1744 }
1745 $this->callerfile = $callerfile;
1746 $this->stage = PORTFOLIO_STAGE_CONFIG;
1747 $this->navigation = $navigation;
d67bfc32 1748 $this->caller->set('exporter', $this);
67a87e7d 1749 }
1750
1751 /*
1752 * generic getter for properties belonging to this instance
1753 * <b>outside</b> the subclasses
1754 * like name, visible etc.
1755 *
1756 * @todo determine what to return in the error case
1757 */
1758 public function get($field) {
1759 if (property_exists($this, $field)) {
1760 return $this->{$field};
1761 }
1762 return false; // @todo throw exception?
1763 }
1764
1765 /**
1766 * generic setter for properties belonging to this instance
1767 * <b>outside</b> the subclass
1768 * like name, visible, etc.
1769 *
1770 * @todo determine what to return in the error case
1771 */
1772
d67bfc32 1773 public function set($field, &$value) {
67a87e7d 1774 if (property_exists($this, $field)) {
d67bfc32 1775 $this->{$field} =& $value;
67a87e7d 1776 if ($field == 'instance') {
1777 $this->instancefile = 'portfolio/type/' . $this->instance->get('plugin') . '/lib.php';
d67bfc32 1778 $this->instance->set('exporter', $this);
67a87e7d 1779 }
1780 $this->dirty = true;
1781 return true;
1782 }
1783 return false; // @todo throw exception?
1784
1785 }
1786 /**
1787 * process the given stage calling whatever functions are necessary
1788 *
1789 * @param int $stage (see PORTFOLIO_STAGE_* constants)
1790 * @param boolean $alreadystolen used to avoid letting plugins steal control twice.
1791 *
1792 * @return boolean whether or not to process the next stage. this is important as the function is called recursively.
1793 */
1794 public function process_stage($stage, $alreadystolen=false) {
ac6a5492 1795 $this->set('stage', $stage);
1796 $this->save();
67a87e7d 1797 if (!$alreadystolen && $url = $this->instance->steal_control($stage)) {
67a87e7d 1798 redirect($url);
1799 break;
1800 }
1801
1802 $waiting = $this->instance->get_export_config('wait');
1803 if ($stage > PORTFOLIO_STAGE_QUEUEORWAIT && empty($waiting)) {
1804 $stage = PORTFOLIO_STAGE_FINISHED;
1805 }
1806 $functionmap = array(
1807 PORTFOLIO_STAGE_CONFIG => 'config',
1808 PORTFOLIO_STAGE_CONFIRM => 'confirm',
1809 PORTFOLIO_STAGE_QUEUEORWAIT => 'queueorwait',
1810 PORTFOLIO_STAGE_PACKAGE => 'package',
1811 PORTFOLIO_STAGE_CLEANUP => 'cleanup',
1812 PORTFOLIO_STAGE_SEND => 'send',
1813 PORTFOLIO_STAGE_FINISHED => 'finished'
1814 );
1815
1816 $function = 'process_stage_' . $functionmap[$stage];
1817 if ($this->$function()) {
1818 // if we get through here it means control was returned
1819 // as opposed to wanting to stop processing
1820 // eg to wait for user input.
1821 $stage++;
1822 return $this->process_stage($stage);
1823 }
84a44985 1824 $this->save();
67a87e7d 1825 return false;
1826 }
1827
1828 /**
1829 * helper function to return the portfolio instance
1830 *
1831 * @return portfolio_plugin_base subclass
1832 */
1833 public function instance() {
1834 return $this->instance;
1835 }
1836
1837 /**
1838 * helper function to return the caller object
1839 *
1840 * @return portfolio_caller_base subclass
1841 */
1842 public function caller() {
1843 return $this->caller;
1844 }
1845
1846 /**
1847 * processes the 'config' stage of the export
1848 *
1849 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
1850 */
1851 public function process_stage_config() {
1852
67a87e7d 1853 $pluginobj = $callerobj = null;
1854 if ($this->instance->has_export_config()) {
1855 $pluginobj = $this->instance;
1856 }
1857 if ($this->caller->has_export_config()) {
1858 $callerobj = $this->caller;
1859 }
1860 $formats = array_intersect($this->instance->supported_formats(), $this->caller->supported_formats());
5071079c 1861 $allsupported = portfolio_supported_formats();
1862 foreach ($formats as $key => $format) {
1863 if (!in_array($format, $allsupported)) {
1864 debugging(get_string('invalidformat', 'portfolio', $format));
1865 unset($formats[$key]);
1866 }
1867 }
67a87e7d 1868 $expectedtime = $this->instance->expected_time($this->caller->expected_time());
1869 if (count($formats) == 0) {
1870 // something went wrong, we should not have gotten this far.
1871 return $this->raise_error('nocommonformats', 'portfolio', get_class($caller));
1872 }
1873 // even if neither plugin or caller wants any config, we have to let the user choose their format, and decide to wait.
1874 if ($pluginobj || $callerobj || count($formats) > 1 || $expectedtime != PORTFOLIO_TIME_LOW) {
1875 $customdata = array(
1876 'instance' => $this->instance,
1877 'plugin' => $pluginobj,
1878 'caller' => $callerobj,
1879 'userid' => $this->user->id,
1880 'formats' => $formats,
1881 'expectedtime' => $expectedtime,
1882 );
1883 $mform = new portfolio_export_form('', $customdata);
1884 if ($mform->is_cancelled()){
84a44985 1885 $this->cancel_request();
67a87e7d 1886 } else if ($fromform = $mform->get_data()){
1887 if (!confirm_sesskey()) {
1888 return $this->raise_error('confirmsesskeybad', '', $caller->get_return_url());
1889 }
1890 $pluginbits = array();
1891 $callerbits = array();
1892 foreach ($fromform as $key => $value) {
1893 if (strpos($key, 'plugin_') === 0) {
1894 $pluginbits[substr($key, 7)] = $value;
1895 } else if (strpos($key, 'caller_') === 0) {
1896 $callerbits[substr($key, 7)] = $value;
1897 }
1898 }
1899 $callerbits['format'] = $pluginbits['format'] = $fromform->format;
1900 $pluginbits['wait'] = $fromform->wait;
294b4928 1901 if ($expectedtime == PORTFOLIO_TIME_LOW) {
67a87e7d 1902 $pluginbits['wait'] = 1;
1903 $pluginbits['hidewait'] = 1;
1904 }
ffcfd8a7 1905 $callerbits['hideformat'] = $pluginbits['hideformat'] = (count($formats) == 1);
67a87e7d 1906 $this->caller->set_export_config($callerbits);
1907 $this->instance->set_export_config($pluginbits);
1908 return true;
1909 } else {
1910 $this->print_header();
1911 print_heading(get_string('configexport' ,'portfolio'));
1912 print_simple_box_start();
1913 $mform->display();
1914 print_simple_box_end();
1915 print_footer();
1916 return false;;
1917 }
1918 } else {
1919 $this->noexportconfig = true;
ffcfd8a7 1920 $format = array_shift($formats);
1921 $this->instance->set_export_config(array('hidewait' => 1, 'wait' => 1, 'format' => $format, 'hideformat' => 1));
1922 $this->caller->set_export_config(array('format' => $format, 'hideformat' => 1));
67a87e7d 1923 return true;
1924 // do not break - fall through to confirm
1925 }
1926 }
1927
67a87e7d 1928 /**
1929 * processes the 'confirm' stage of the export
1930 *
1931 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
1932 */
1933 public function process_stage_confirm() {
ffcfd8a7 1934 global $CFG, $DB;
1935
1936 $previous = $DB->get_records(
1937 'portfolio_log',
1938 array(
1939 'userid' => $this->user->id,
1940 'portfolio' => $this->instance->get('id'),
1941 'caller_sha1' => $this->caller->get_sha1(),
1942 )
1943 );
1944 if (isset($this->noexportconfig) && empty($previous)) {
67a87e7d 1945 return true;
1946 }
1947 $strconfirm = get_string('confirmexport', 'portfolio');
1948 $yesurl = $CFG->wwwroot . '/portfolio/add.php?stage=' . PORTFOLIO_STAGE_QUEUEORWAIT;
ffcfd8a7 1949 $nourl = $CFG->wwwroot . '/portfolio/add.php?cancel=1';
67a87e7d 1950 $this->print_header();
1951 print_heading($strconfirm);
1952 print_simple_box_start();
1953 print_heading(get_string('confirmsummary', 'portfolio'), '', 4);
ffcfd8a7 1954 $mainsummary = array();
1955 if (!$this->instance->get_export_config('hideformat')) {
1956 $mainsummary[get_string('selectedformat', 'portfolio')] = get_string('format_' . $this->instance->get_export_config('format'), 'portfolio');
1957 }
67a87e7d 1958 if (!$this->instance->get_export_config('hidewait')) {
ffcfd8a7 1959 $mainsummary[get_string('selectedwait', 'portfolio')] = get_string(($this->instance->get_export_config('wait') ? 'yes' : 'no'));
1960 }
1961 if ($previous) {
1962 $previousstr = '';
1963 foreach ($previous as $row) {
1964 $previousstr .= userdate($row->time);
1965 if ($row->caller_class != get_class($this->caller)) {
1966 require_once($CFG->dirroot . '/' . $row->caller_file);
1967 $previousstr .= ' (' . call_user_func(array($row->caller_class, 'display_name')) . ')';
1968 }
1969 $previousstr .= '<br />';
1970 }
1971 $mainsummary[get_string('exportedpreviously', 'portfolio')] = $previousstr;
67a87e7d 1972 }
1973 if (!$csummary = $this->caller->get_export_summary()) {
1974 $csummary = array();
1975 }
1976 if (!$isummary = $this->instance->get_export_summary()) {
1977 $isummary = array();
1978 }
1979 $mainsummary = array_merge($mainsummary, $csummary, $isummary);
ffcfd8a7 1980 $table = new StdClass;
1981 $table->data = array();
67a87e7d 1982 foreach ($mainsummary as $string => $value) {
ffcfd8a7 1983 $table->data[] = array($string, $value);
67a87e7d 1984 }
ffcfd8a7 1985 print_table($table);
67a87e7d 1986 notice_yesno($strconfirm, $yesurl, $nourl);
1987 print_simple_box_end();
1988 print_footer();
1989 return false;
1990 }
1991
1992 /**
1993 * processes the 'queueornext' stage of the export
1994 *
1995 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
1996 */
1997 public function process_stage_queueorwait() {
1998 global $SESSION;
1999 $wait = $this->instance->get_export_config('wait');
2000 if (empty($wait)) {
84a44985 2001 events_trigger('portfolio_send', $this->id);
2002 unset($SESSION->portfolioexport);
8f182eef 2003 return $this->process_stage_finished(true);
67a87e7d 2004 }
2005 return true;
2006 }
2007
2008 /**
2009 * processes the 'package' stage of the export
2010 *
2011 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
2012 */
2013 public function process_stage_package() {
2014 // now we've agreed on a format,
2015 // the caller is given control to package it up however it wants
2016 // and then the portfolio plugin is given control to do whatever it wants.
d67bfc32 2017 if (!$this->caller->prepare_package()) {
3f871282 2018 return $this->raise_error('callercouldnotpackage', 'portfolio', $this->caller->get_return_url());
67a87e7d 2019 }
d67bfc32 2020 if (!$package = $this->instance->prepare_package()) {
3f871282 2021 return $this->raise_error('plugincouldnotpackage', 'portfolio', $this->caller->get_return_url());
67a87e7d 2022 }
2023 return true;
2024 }
2025
2026 /**
2027 * processes the 'cleanup' stage of the export
2028 *
2029 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
2030 */
d96a1acc 2031 public function process_stage_cleanup($pullok=false) {
84a44985 2032 global $CFG, $DB, $SESSION;
d96a1acc 2033
2034 if (!$pullok && !$this->get('instance')->is_push()) {
2035 unset($SESSION->portfolioexport);
2036 return true;
2037 }
67a87e7d 2038 // @todo maybe add a hook in the plugin(s)
84a44985 2039 $DB->delete_records('portfolio_tempdata', array('id' => $this->id));
d67bfc32 2040 $fs = get_file_storage();
2041 $fs->delete_area_files(SYSCONTEXTID, 'portfolio_exporter', $this->id);
84a44985 2042 unset($SESSION->portfolioexport);
67a87e7d 2043 return true;
2044 }
2045
2046 /**
2047 * processes the 'send' stage of the export
2048 *
2049 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
2050 */
2051 public function process_stage_send() {
2052 // send the file
2053 if (!$this->instance->send_package()) {
2054 return $this->raise_error('failedtosendpackage', 'portfolio');
2055 }
ffcfd8a7 2056 // log the transfer
2057 global $DB;
2058 $l = array(
2059 'userid' => $this->user->id,
2060 'portfolio' => $this->instance->get('id'),
2061 'caller_file' => $this->callerfile,
2062 'caller_sha1' => $this->caller->get_sha1(),
2063 'caller_class' => get_class($this->caller),
2064 'time' => time(),
2065 );
2066 $DB->insert_record('portfolio_log', $l);
67a87e7d 2067 return true;
2068 }
2069
2070 /**
2071 * processes the 'finish' stage of the export
2072 *
2073 * @return boolean whether or not to process the next stage. this is important as the control function is called recursively.
2074 */
8f182eef 2075 public function process_stage_finished($queued=false) {
67a87e7d 2076 $returnurl = $this->caller->get_return_url();
2077 $continueurl = $this->instance->get_continue_url();
2078 $extras = $this->instance->get_extra_finish_options();
2079
2080 $this->print_header();
8f182eef 2081 if ($queued) {
2082 print_heading(get_string('exportqueued', 'portfolio'));
2083 } else {
2084 print_heading(get_string('exportcomplete', 'portfolio'));
2085 }
67a87e7d 2086 if ($returnurl) {
2087 echo '<a href="' . $returnurl . '">' . get_string('returntowhereyouwere', 'portfolio') . '</a><br />';
2088 }
2089 if ($continueurl) {
2090 echo '<a href="' . $continueurl . '">' . get_string('continuetoportfolio', 'portfolio') . '</a><br />';
2091 }
2092 if (is_array($extras)) {
2093 foreach ($extras as $link => $string) {
2094 echo '<a href="' . $link . '">' . $string . '</a><br />';
2095 }
2096 }
2097 print_footer();
67a87e7d 2098 return false;
2099 }
2100
2101
2102 /**
2103 * local print header function to be reused across the export
2104 *
2105 * @param string $titlestring key for a portfolio language string
2106 * @param string $headerstring key for a portfolio language string
2107 */
2108 public function print_header($titlestr='exporting', $headerstr='exporting') {
2109 $titlestr = get_string($titlestr, 'portfolio');
2110 $headerstr = get_string($headerstr, 'portfolio');
2111
2112 print_header($titlestr, $headerstr, $this->navigation);
2113 }
2114
2115 /**
2116 * error handler - decides whether we're running interactively or not
2117 * and behaves accordingly
2118 */
d96a1acc 2119 public function raise_error($string, $module='moodle', $continue=null, $a=null) {
67a87e7d 2120 if (defined('FULLME') && FULLME == 'cron') {
2121 debugging(get_string($string, $module));
2122 return false;
2123 }
f812bbe8 2124 if (isset($this) && $this instanceof portfolio_exporter) {
2125 // apparently even calling statically (with :: rather than ->
2126 // causes $this to be set in some php versions
2127 // (assuming this function is called from some other object - wtF?!)
d96a1acc 2128 $this->process_stage_cleanup(true);
84a44985 2129 }
d96a1acc 2130 print_error($string, $module, $continue, $a);
67a87e7d 2131 }
84a44985 2132
62a99dea 2133 /**
2134 * cancels a potfolio request and cleans up the tempdata
2135 * and redirects the user back to where they started
2136 */
84a44985 2137 public function cancel_request() {
2138 if (!isset($this)) {
2139 return;
2140 }
d96a1acc 2141 $this->process_stage_cleanup(true);
84a44985 2142 redirect($this->caller->get_return_url());
2143 exit;
2144 }
2145
2146 /**
2147 * writes out the contents of this object and all its data to the portfolio_tempdata table and sets the 'id' field.
2148 */
2149 public function save() {
2150 global $DB;
2151 if (empty($this->id)) {
2152 $r = (object)array(
2153 'data' => base64_encode(serialize($this)),
2154 'expirytime' => time() + (60*60*24),
2155 );
2156 $this->id = $DB->insert_record('portfolio_tempdata', $r);
d67bfc32 2157 $this->save(); // call again so that id gets added to the save data.
84a44985 2158 } else {
2159 $DB->set_field('portfolio_tempdata', 'data', base64_encode(serialize($this)), array('id' => $this->id));
2160 }
2161 }
2162
62a99dea 2163 /**
2164 * rewakens the data from the database given the id
2876d73b 2165 * makes sure to load the required files with the class definitions
62a99dea 2166 *
2167 * @param int $id id of data
2168 *
2169 * @return portfolio_exporter
2170 */
84a44985 2171 public static function rewaken_object($id) {
2172 global $DB, $CFG;
2173 if (!$data = $DB->get_record('portfolio_tempdata', array('id' => $id))) {
d96a1acc 2174 portfolio_exporter::raise_error('invalidtempid', 'portfolio');
84a44985 2175 }
2176 $exporter = unserialize(base64_decode($data->data));
2177 if ($exporter->instancefile) {
2178 require_once($CFG->dirroot . '/' . $exporter->instancefile);
2179 }
2180 require_once($CFG->dirroot . '/' . $exporter->callerfile);
2181 $exporter = unserialize(serialize($exporter));
2182 return $exporter;
2183 }
d67bfc32 2184
2185 /**
2186 * copies a file from somewhere else in moodle
2187 * to the portfolio temporary working directory
2188 * associated with this export
2189 *
2190 * @param $oldfile stored_file object
2191 */
2192 public function copy_existing_file($oldfile) {
2193 $fs = get_file_storage();
2194 $file_record = $this->new_file_record_base($oldfile->get_filename());
2195 try {
2196 return $fs->create_file_from_storedfile($file_record, $oldfile->get_id());
2197 } catch (file_exception $e) {
2198 return false;
2199 }
2200 }
2201
2202 /**
2203 * writes out some content to a file in the
2204 * portfolio temporary working directory
2205 * associated with this export
2206 *
2207 * @param string $content content to write
2208 * @param string $name filename to use
2209 */
2210 public function write_new_file($content, $name) {
2211 $fs = get_file_storage();
2212 $file_record = $this->new_file_record_base($name);
2213 return $fs->create_file_from_string($file_record, $content);
2214 }
2215
2216 /**
2217 * returns an arary of files in the temporary working directory
2218 * for this export
2219 * always use this instead of the files api directly
2220 *
2221 * @return arary
2222 */
2223 public function get_tempfiles() {
2224 $fs = get_file_storage();
2225 $files = $fs->get_area_files(SYSCONTEXTID, 'portfolio_exporter', $this->id, '', false);
2226 if (empty($files)) {
2227 return array();
2228 }
d96a1acc 2229 $returnfiles = array();
2230 foreach ($files as $f) {
2231 $returnfiles[$f->get_filename()] = $f;
2232 }
2233 return $returnfiles;
d67bfc32 2234 }
2235
2236 /**
2237 * helper function to create the beginnings of a file_record object
2238 * to create a new file in the portfolio_temporary working directory
2239 * use {@see write_new_file} or {@see copy_existing_file} externally
2240 *
2241 * @param string $name filename of new record
2242 */
2243 private function new_file_record_base($name) {
2244 return (object)array(
2245 'contextid' => SYSCONTEXTID,
2246 'filearea' => 'portfolio_exporter',
2247 'itemid' => $this->id,
2248 'filepath' => '/',
2249 'filename' => $name,
2250 );
2251 }
2252
67a87e7d 2253}
2254
62a99dea 2255/**
2256* form that just contains the dropdown menu of available instances
2257*/
6fdd8fa7 2258class portfolio_instance_select extends moodleform {
2259
2260 private $caller;
2261
2262 function definition() {
2263 $this->caller = $this->_customdata['caller'];
2264 $options = portfolio_instance_select(
2265 portfolio_instances(),
2266 $this->caller->supported_formats(),
2267 get_class($this->caller),
2268 'instance',
2269 true,
2270 true
2271 );
2272 if (empty($options)) {
2273 portfolio_exporter::raise_error('noavailableplugins', 'portfolio');
2274 }
2275 $mform =& $this->_form;
2276 $mform->addElement('select', 'instance', get_string('selectplugin', 'portfolio'), $options);
2277 $this->add_action_buttons(true, get_string('next'));
2278 }
2279}
2280
67a87e7d 2281/**
2282* event handler for the portfolio_send event
2283*/
2284function portfolio_handle_event($eventdata) {
2285 global $CFG;
84a44985 2286 $exporter = portfolio_exporter::rewaken_object($eventdata);
67a87e7d 2287 $exporter->process_stage_package();
2288 $exporter->process_stage_send();
2289 $exporter->process_stage_cleanup();
2290 return true;
2291}
2292
7e51bbce 2293/**
2294* main portfolio cronjob
2295*
2296*/
2297function portfolio_cron() {
2298 global $DB;
2299
2300 if ($expired = $DB->get_records_select('portfolio_tempdata', 'expirytime < ?', array(time()))) {
2301 foreach ($expired as $d) {
2302 $DB->delete_records('portfolio_tempdata', array('id' => $d->id));
2303 $fs = get_file_storage();
2304 $fs->delete_area_files(SYSCONTEXTID, 'portfolio_exporter', $d->id);
2305 }
2306 }
2307
2308 // @todo add hooks in the plugins
2309}
2310
2311
67a87e7d 2312?>