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