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