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