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