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