From 67a87e7db2e81b3450c95837a3dab85cf82e0cc0 Mon Sep 17 00:00:00 2001 From: mjollnir_ Date: Fri, 25 Jul 2008 08:14:11 +0000 Subject: [PATCH] portfolio checkin- see http://git.catalyst.net.nz/gw?p=moodle-r2.git;a=shortlog;h=refs/heads/portfolio for changelog commit point is this hash on that branch: f9642af4e8bd319d4ecdfd83589db61a8fa6fef2 This comes with two plugins, box.net & download --- admin/index.php | 2 + admin/portfolio.php | 156 ++ admin/settings/plugins.php | 26 + lang/en_utf8/portfolio.php | 53 + lang/en_utf8/portfolio_boxnet.php | 18 + lang/en_utf8/portfolio_download.php | 5 + lib/db/events.php | 10 + lib/moodlelib.php | 1 + lib/portfoliolib.php | 1904 +++++++++++++++++ mod/assignment/lib.php | 101 +- .../type/online/assignment.class.php | 10 +- .../type/upload/assignment.class.php | 21 +- .../type/uploadsingle/assignment.class.php | 4 + portfolio/add.php | 112 + portfolio/type/boxnet/lib.php | 202 ++ portfolio/type/boxnet/version.php | 7 + portfolio/type/download/lib.php | 57 + portfolio/type/download/version.php | 7 + theme/standard/styles_layout.css | 3 + user/portfolio.php | 96 + user/tabs.php | 7 + version.php | 2 +- 22 files changed, 2800 insertions(+), 4 deletions(-) create mode 100644 admin/portfolio.php create mode 100644 lang/en_utf8/portfolio.php create mode 100644 lang/en_utf8/portfolio_boxnet.php create mode 100644 lang/en_utf8/portfolio_download.php create mode 100644 lib/portfoliolib.php create mode 100644 portfolio/add.php create mode 100644 portfolio/type/boxnet/lib.php create mode 100644 portfolio/type/boxnet/version.php create mode 100644 portfolio/type/download/lib.php create mode 100644 portfolio/type/download/version.php create mode 100644 user/portfolio.php diff --git a/admin/index.php b/admin/index.php index 7529d336eb..1cc36e72e8 100644 --- a/admin/index.php +++ b/admin/index.php @@ -431,6 +431,8 @@ /// Check all quiz report plugins and upgrade if necessary upgrade_plugins('quizreport', 'mod/quiz/report', "$CFG->wwwroot/$CFG->admin/index.php"); +/// Check all portfolio plugins and upgrade if necessary + upgrade_plugins('portfolio', 'portfolio/type', "$CFG->wwwroot/$CFG->admin/index.php"); /// just make sure upgrade logging is properly terminated upgrade_log_finish(); diff --git a/admin/portfolio.php b/admin/portfolio.php new file mode 100644 index 0000000000..42abe00258 --- /dev/null +++ b/admin/portfolio.php @@ -0,0 +1,156 @@ +libdir . '/portfoliolib.php'); +require_once($CFG->libdir . '/adminlib.php'); + +admin_externalpage_setup('portfoliosettingsall'); + +$edit = optional_param('edit', 0, PARAM_INT); +$new = optional_param('new', '', PARAM_FORMAT); +$hide = optional_param('hide', 0, PARAM_INT); +$delete = optional_param('delete', 0, PARAM_INT); +$sure = optional_param('sure', '', PARAM_ALPHA); + +$display = true; // fall through to normal display + +require_login(SITEID, false); +require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); + +$baseurl = $CFG->wwwroot . '/' . $CFG->admin . '/portfolio.php'; +$sesskeyurl = $CFG->wwwroot . '/' . $CFG->admin . '/portfolio.php?sesskey=' . sesskey(); +$configstr = get_string('manageportfolios', 'portfolio'); + +if (!empty($edit) || !empty($new)) { + if (!empty($edit)) { + $instance = portfolio_instance($edit); + $plugin = $instance->get('plugin'); + } else { + $plugin = $new; + $instance = null; + } + // display the edit form for this instance + $mform = new portfolio_admin_form('', array('plugin' => $plugin, 'instance' => $instance)); + // end setup, begin output + if ($mform->is_cancelled()){ + redirect($baseurl); + exit; + } else if ($fromform = $mform->get_data()){ + if (!confirm_sesskey()) { + print_error('confirmsesskeybad', '', $baseurl); + } + //this branch is where you process validated data. + if ($edit) { + $success = $instance->set_config($fromform); + $success = $success && $instance->save(); + } + else { + $success = portfolio_static_function($plugin, 'create_instance', $plugin, $fromform->name, $fromform); + } + if ($success) { + $savedstr = get_string('instancesaved', 'portfolio'); + print_heading($savedstr); + redirect($baseurl, $savedstr, 3); + } else { + print_error('instancenotsaved', 'portfolio', $baseurl); + } + exit; + } else { + admin_externalpage_print_header(); + print_heading(get_string('configplugin', 'portfolio')); + print_simple_box_start(); + $mform->display(); + print_simple_box_end(); + $display = false; + } +} else if (!empty($hide)) { + if (!confirm_sesskey()) { + print_error('confirmsesskeybad', '', $baseurl); + } + $instance = portfolio_instance($hide); + $current = $instance->get('visible'); + if (empty($current) && $instance->instance_sanity_check()) { + print_error('cannotsetvisible', 'portfolio', $baseurl); + } + $instance->set('visible', !$instance->get('visible')); + $instance->save(); +} else if (!empty($delete)) { + admin_externalpage_print_header(); + $instance = portfolio_instance($delete); + if ($sure) { + if (!confirm_sesskey()) { + print_error('confirmsesskeybad', '', $baseurl); + } + if ($instance->delete()) { + $deletedstr = get_string('instancedeleted', 'portfolio'); + print_heading($deletedstr); + redirect($baseurl, $deletedstr, 3); + } else { + print_error('instancenotdeleted', 'portfolio', $baseurl); + } + exit; + } + notice_yesno(get_string('sure', 'portfolio', $instance->get('name')), $sesskeyurl . '&delete=' . $delete . '&sure=yes', $baseurl); + $display = false; +} + +// normal display. fall through to here (don't call exit) if you want this to run +if ($display) { + admin_externalpage_print_header(); + print_heading($configstr); + print_simple_box_start(); + + $namestr = get_string('name'); + $pluginstr = get_string('plugin', 'portfolio'); + + $plugins = get_list_of_plugins('portfolio/type'); + $instances = portfolio_instances(false, false); + $alreadyplugins = array(); + + $insane = portfolio_plugin_sanity_check($plugins); + $insaneinstances = portfolio_instance_sanity_check($instances); + + portfolio_report_insane($insane); + portfolio_report_insane($insaneinstances, $instances); + + $table = new StdClass; + $table->head = array($namestr, $pluginstr, ''); + $table->data = array(); + + foreach ($instances as $i) { + $row = '' . get_string('edit') . ' + ' . get_string('delete') . ''; + if (array_key_exists($i->get('plugin'), $insane) || array_key_exists($i->get('id'), $insaneinstances)) { + $row .= '' . get_string('hidden', 'portfolio') . '
'; + } else { + $row .= ' ' . get_string($i->get('visible') ? 'hide' : 'show') . '
'; + } + $table->data[] = array($i->get('name'), $i->get('plugin'), $row); + if (!in_array($i->get('plugin'), $alreadyplugins)) { + $alreadyplugins[] = $i->get('plugin'); + } + } + + print_table($table); + + $instancehtml = '
' . get_string('addnewportfolio', 'portfolio') . ':
'; + echo $instancehtml; + } + print_simple_box_end(); +} +print_footer(); +?> diff --git a/admin/settings/plugins.php b/admin/settings/plugins.php index cbc6132e19..d95876b417 100644 --- a/admin/settings/plugins.php +++ b/admin/settings/plugins.php @@ -144,5 +144,31 @@ if ($hassiteconfig) { } } } + + $catname =get_string('portfolios', 'portfolio'); + $manage = get_string('manageportfolios', 'portfolio'); + $url = "$CFG->wwwroot/$CFG->admin/portfolio.php"; + + $ADMIN->add('modules', new admin_category('portfoliosettings', $catname)); + + $ADMIN->add( + 'portfoliosettings', + new admin_externalpage('portfoliosettingsall', $manage, $url), + $manage, + $url + ); + require_once($CFG->libdir. '/portfoliolib.php'); + foreach (portfolio_instances() as $portfolio) { + require_once($CFG->dirroot . '/portfolio/type/' . $portfolio->get('plugin') . '/lib.php'); + $classname = 'portfolio_plugin_' . $portfolio->get('plugin'); + if (call_user_func(array($classname, 'has_admin_config'))) { + $ADMIN->add( + 'portfoliosettings', + new admin_externalpage('portfoliosettings' . $portfolio->get('id'), get_string('configure', 'portfolio') . ' ' . $portfolio->get('name'), $url . '?edit=' . $portfolio->get('id')), + $portfolio->get('name'), + $url . ' ?edit=' . $portfolio->get('id') + ); + } + } } ?> diff --git a/lang/en_utf8/portfolio.php b/lang/en_utf8/portfolio.php new file mode 100644 index 0000000000..64a38d735f --- /dev/null +++ b/lang/en_utf8/portfolio.php @@ -0,0 +1,53 @@ +key and the value was $a->value'; +$string['notexportable'] = 'Sorry, but the type of content you are trying to export is not exportable'; +$string['nouploaddirectory'] = 'Could not create a temporary directory to package your data into'; +$string['portfolio'] = 'Portfolio'; +$string['portfolios'] = 'Portfolios'; +$string['plugin'] = 'Portfolio Plugin'; +$string['plugincouldnotpackage'] = 'Failed to package up your data for export'; +$string['returntowhereyouwere'] = 'Return to where you were'; +$string['save'] = 'Save'; +$string['selectedformat'] = 'Selected export format'; +$string['selectedwait'] = 'Selected to wait?'; +$string['selectplugin'] = 'Select portfolio plugin to export to'; +$string['someinstancesdisabled'] = 'Some configured plugin instances have been disabled either because they are misconfigured or rely on something else that is'; +$string['somepluginsdisabled'] = 'Some entire plugins have been disabled because they are either misconfigured or rely on something else that is:'; +$string['sure'] = 'Are you sure you want to delete \'$a\'? This cannot be undone.'; +$string['wanttowait_moderate'] = 'Do you want to wait for this transfer? It might take a few minutes'; +$string['wanttowait_high'] = 'It is not recommended that you wait for this transfer to complete, but you can if you\'re sure and know what you\'re doing'; +$string['wait'] = 'Wait'; +?> diff --git a/lang/en_utf8/portfolio_boxnet.php b/lang/en_utf8/portfolio_boxnet.php new file mode 100644 index 0000000000..7fea7fb71f --- /dev/null +++ b/lang/en_utf8/portfolio_boxnet.php @@ -0,0 +1,18 @@ + diff --git a/lang/en_utf8/portfolio_download.php b/lang/en_utf8/portfolio_download.php new file mode 100644 index 0000000000..3f7e50bbf0 --- /dev/null +++ b/lang/en_utf8/portfolio_download.php @@ -0,0 +1,5 @@ + diff --git a/lib/db/events.php b/lib/db/events.php index deecbf448b..49db794761 100644 --- a/lib/db/events.php +++ b/lib/db/events.php @@ -121,7 +121,17 @@ groups_groupings_deleted - int course id - deleted all course groupings role_assigned - object role_assignments table record role_unassigned - object role_assignments table record +==== portfolio related events ==== + +portfolio_send - when a user wants to send some content to a portfolio */ +$handlers = array ( + 'portfolio_send' => array ( + 'handlerfile' => '/lib/portfolio.php', + 'handlerfunction' => 'portfolio_handle_event', // argument to call_user_func(), could be an array + 'schedule' => 'cron' + ) +); ?> diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 61b787024e..503a66f129 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -5016,6 +5016,7 @@ function places_to_search_for_lang_strings() { 'gradeimport_' => array('grade/import'), 'gradeexport_' => array('grade/export'), 'profilefield_' => array('user/profile/field'), + 'portfolio_' => array('portfolio/type'), '' => array('mod') ); } diff --git a/lib/portfoliolib.php b/lib/portfoliolib.php new file mode 100644 index 0000000000..8e9b25bb5a --- /dev/null +++ b/lib/portfoliolib.php @@ -0,0 +1,1904 @@ +libdir.'/formslib.php'); + +// **** EXPORT STAGE CONSTANTS **** // + +/** +* display a form to the user +* this one might not be used if neither +* the plugin, or the caller has any config. +*/ +define('PORTFOLIO_STAGE_CONFIG', 1); + +/** +* summarise the form and ask for confirmation +* if we skipped PORTFOLIO_STAGE_CONFIG, +* just confirm the send. +*/ +define('PORTFOLIO_STAGE_CONFIRM', 2); + +/** +* either queue the event and skip to PORTFOLIO_STAGE_FINISHED +* or continue to PORTFOLIO_STAGE_PACKAGE +*/ + +define('PORTFOLIO_STAGE_QUEUEORWAIT', 3); + +/** +* package up the various bits +* during this stage both the caller +* and the plugin get their package methods called +*/ +define('PORTFOLIO_STAGE_PACKAGE', 4); + +/* +* the portfolio plugin must send the file +*/ +define('PORTFOLIO_STAGE_SEND', 5); + +/** +* cleanup the temporary area +*/ +define('PORTFOLIO_STAGE_CLEANUP', 6); + +/** +* display the "finished notification" +*/ +define('PORTFOLIO_STAGE_FINISHED', 7); + + + +// **** EXPORT FORMAT CONSTANTS **** // +// these should always correspond to a string +// in the portfolio module, called format_{$value} +// **** **** // + +/** +* html - this is the second most basic fallback +* after {@link PORTFOLIO_FORMAT_FILE} +* for export. This should always be supported +* in remote systems +*/ +define('PORTFOLIO_FORMAT_HTML', 'html'); + +/** +* file - the most basic fallback format. +* this should always be supported +* in remote system.s +*/ +define('PORTFOLIO_FORMAT_FILE', 'file'); + +/** +* moodle backup - the plugin needs to be able to write a complete backup +* the caller need to be able to export the particular XML bits to insert +* into moodle.xml (?and the file bits if necessary) +*/ +define('PORTFOLIO_FORMAT_MBKP', 'mbkp'); + + +// **** EXPORT TIME LEVELS **** // +// these should correspond to a string +// in the portfolio module, called time_{$value} + +/** +* no delay. don't even offer the user the option +* of not waiting for the transfer +*/ +define('PORTFOLIO_TIME_LOW', 'low'); + +/** +* a small delay. user can still easily opt to +* watch this transfer and wait. +*/ +define('PORTFOLIO_TIME_MODERATE', 'moderate'); + +/** +* slow. the user really should not be given the option +* to choose this. +*/ +define('PORTFOLIO_TIME_HIGH', 'high'); + + +/** +* entry point to add an 'add to portfolio' button somewhere in moodle +* this function does not check permissions. the caller must check permissions first. +* later, during the export process, the caller class is instantiated and the check_permissions method is called +* but not in this function. +* +* @param string $callbackclass name of the class containing the callback functions +* activity modules should ALWAYS use their name_portfolio_caller +* other locations must use something unique +* @param mixed $callbackargs this can be an array or hash of arguments to pass +* back to the callback functions (passed by reference) +* these MUST be primatives to be added as hidden form fields. +* and the values get cleaned to PARAM_ALPHAEXT or PARAM_NUMBER or PARAM_PATH +* @param boolean $fullform either display the fullform with the dropmenu of available instances +* or just a small icon (which will trigger instance selection in a new screen) +* optional, defaults to true. +* @param boolean $return whether to echo or return content (optional defaults to false (echo) +*/ +function portfolio_add_button($callbackclass, $callbackargs, $fullform=true, $return=false) { + + global $SESSION, $CFG, $COURSE, $USER; + + if (!$instances = portfolio_instances()) { + return; + } + + $backtrace = debug_backtrace(); + if (!array_key_exists(0, $backtrace) || !array_key_exists('file', $backtrace[0]) || !is_readable($backtrace[0]['file'])) { + debugging(get_string('nocallbackfile', 'portfolio')); + return; + } + + $callbackfile = substr($backtrace[0]['file'], strlen($CFG->dirroot)); + + require_once($CFG->dirroot . $callbackfile); + + $callersupports = call_user_func(array($callbackclass, 'supported_formats')); + + if (isset($SESSION->portfolio)) { + return portfolio_exporter::raise_error('alreadyexporting', 'portfolio'); + } + + $output = '
' . "\n"; + foreach ($callbackargs as $key => $value) { + if (!empty($value) && !is_string($value) && !is_numeric($value)) { + $a->key = $key; + $a->value = print_r($value, true); + debugging(get_string('nonprimative', 'portfolio', $a)); + return; + } + $output .= "\n" . ''; + } + $output .= "\n" . ''; + $output .= "\n" . ''; + $output .= "\n" . ''; + $selectoutput = ''; + if (count($instances) == 1) { + $instance = array_shift($instances); + if (count(array_intersect($callersupports, $instance->supported_formats())) == 0) { + // bail. no common formats. + debugging(get_string('nocommonformats', 'portfolio', $callbackclass)); + return; + } + if ($error = portfolio_instance_sanity_check($instance)) { + // bail, plugin is misconfigured + debugging(get_string('instancemisconfigured', 'portfolio', get_string($error[$instance->get('id')], 'portfolio_' . $instance->get('plugin')))); + return; + } + $output .= "\n" . ''; + } + else { + $selectoutput = portfolio_instance_select($instances, $callersupports, $callbackclass); + } + + if ($fullform) { + $output .= $selectoutput; + $output .= "\n" . ''; + } else { + $output .= "\n" . ''; + //@todo replace this with a little icon + } + + $output .= "\n" . '
'; + + if ($return) { + return $output; + } else { + echo $output; + } + return true; +} + +/** +* returns a drop menu with a list of available instances. +* +* @param array $instances the instances to put in the menu +* @param array $callerformats the formats the caller supports + (this is used to filter plugins) +* @param array $callbackclass the callback class name +* +* @return string the html, from inclusive. +*/ +function portfolio_instance_select($instances, $callerformats, $callbackclass) { + $insane = portfolio_instance_sanity_check(); + $count = 0; + $selectoutput = "\n" . '\n"; + return $selectoutput; +} + +/** +* return all portfolio instances +* +* @param boolean visibleonly don't include hidden instances (defaults to true and will be overridden to true if the next parameter is true) +* @param boolean useronly check the visibility preferences and permissions of the logged in user +* @return array of portfolio instances (full objects, not just database records) +*/ +function portfolio_instances($visibleonly=true, $useronly=true) { + + global $DB, $USER; + + $values = array(); + $sql = 'SELECT * FROM {portfolio_instance}'; + + if ($visibleonly || $useronly) { + $values[] = 1; + $sql .= ' WHERE visible = ?'; + } + if ($useronly) { + $sql .= ' AND id NOT IN ( + SELECT instance FROM {portfolio_instance_user} + WHERE userid = ? AND name = ? AND value = ? + )'; + $values = array_merge($values, array($USER->id, 'visible', 0)); + } + $sql .= ' ORDER BY name'; + + $instances = array(); + foreach ($DB->get_records_sql($sql, $values) as $instance) { + $instances[] = portfolio_instance($instance->id, $instance); + } + // @todo check capabilities here - see MDL-15768 + return $instances; +} + +/** +* supported formats that portfolio plugins and callers +* can use for exporting content +* +* @return array of all the available export formats +*/ +function portfolio_supported_formats() { + return array( + PORTFOLIO_FORMAT_FILE, + PORTFOLIO_FORMAT_HTML, + PORTFOLIO_FORMAT_MBKP, + ); +} + +/** +* helper function to return an instance of a plugin (with config loaded) +* +* @param int $instance id of instance +* @param array $record database row that corresponds to this instance +* this is passed to avoid unnecessary lookups +* +* @return subclass of portfolio_plugin_base +*/ +function portfolio_instance($instanceid, $record=null) { + global $DB, $CFG; + + if ($record) { + $instance = $record; + } else { + if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) { + return false; // @todo throw exception? + } + } + require_once($CFG->dirroot . '/portfolio/type/'. $instance->plugin . '/lib.php'); + $classname = 'portfolio_plugin_' . $instance->plugin; + return new $classname($instanceid, $instance); +} + +/** +* helper function to call a static function on a portfolio plugin class +* this will figure out the classname and require the right file and call the function. +* you can send a variable number of arguments to this function after the first two +* and they will be passed on to the function you wish to call. +* +* @param string $plugin name of plugin +* @param string $function function to call +*/ +function portfolio_static_function($plugin, $function) { + global $CFG; + + $pname = null; + if (is_object($plugin) || is_array($plugin)) { + $plugin = (object)$plugin; + $pname = $plugin->name; + } else { + $pname = $plugin; + } + + $args = func_get_args(); + if (count($args) <= 2) { + $args = array(); + } + else { + array_shift($args); + array_shift($args); + } + + require_once($CFG->dirroot . '/portfolio/type/' . $plugin . '/lib.php'); + return call_user_func_array(array('portfolio_plugin_' . $plugin, $function), $args); +} + +/** +* helper function to check all the plugins for sanity and set any insane ones to invisible. +* +* @param array $plugins to check (if null, defaults to all) +* one string will work too for a single plugin. +* +* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang) +*/ +function portfolio_plugin_sanity_check($plugins=null) { + global $DB; + if (is_string($plugins)) { + $plugins = array($plugins); + } else if (empty($plugins)) { + $plugins = get_list_of_plugins('portfolio/type'); + } + + $insane = array(); + foreach ($plugins as $plugin) { + if ($result = portfolio_static_function($plugin, 'plugin_sanity_check')) { + $insane[$plugin] = $result; + } + } + if (empty($insane)) { + return array(); + } + list($where, $params) = $DB->get_in_or_equal(array_keys($insane)); + $where = ' plugin ' . $where; + $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params); + return $insane; +} + +/** +* helper function to check all the instances for sanity and set any insane ones to invisible. +* +* @param array $instances to check (if null, defaults to all) +* one instance or id will work too +* +* @return array array of insane instances (keys= id, values = reasons (keys for plugin lang) +*/ +function portfolio_instance_sanity_check($instances=null) { + global $DB; + if (empty($instances)) { + $instances = portfolio_instances(false); + } else if (!is_array($instances)) { + $instances = array($instances); + } + + $insane = array(); + foreach ($instances as $instance) { + if (is_object($instance) && !($instance instanceof portfolio_plugin_base)) { + $instance = portfolio_instance($instance->id, $instance); + } else if (is_numeric($instance)) { + $instance = portfolio_instance($instance); + } + if (!($instance instanceof portfolio_plugin_base)) { + debugging('something weird passed to portfolio_instance_sanity_check, not subclass or id'); + continue; + } + if ($result = $instance->instance_sanity_check()) { + $insane[$instance->get('id')] = $result; + } + } + if (empty($insane)) { + return array(); + } + list ($where, $params) = $DB->get_in_or_equal(array_keys($insane)); + $where = ' id ' . $where; + $DB->set_field_select('portfolio_instance', 'visible', 0, $where, $params); + return $insane; +} + +/** +* helper function to display a table of plugins (or instances) and reasons for disabling +* +* @param array $insane array of insane plugins (key = plugin (or instance id), value = reason) +* @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here +* +*/ +function portfolio_report_insane($insane, $instances=false) { + if (empty($insane)) { + return; + } + + static $pluginstr; + if (empty($pluginstr)) { + $pluginstr = get_string('plugin', 'portfolio'); + } + if ($instances) { + $headerstr = get_string('someinstancesdisabled', 'portfolio'); + } else { + $headerstr = get_string('somepluginsdisabled', 'portfolio'); + } + + notify($headerstr); + $table = new StdClass; + $table->head = array($pluginstr, ''); + $table->data = array(); + foreach ($insane as $plugin => $reason) { + if ($instances) { + // @todo this isn't working + // because it seems the new recordset object + // doesn't implement the key correctly. + $instance = $instances[$plugin]; + $plugin = $instance->get('plugin'); + $name = $instance->get('name'); + } else { + $name = $plugin; + } + $table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin)); + } + print_table($table); + echo '


'; +} + +/** +* temporary functions until the File API settles +* to do with moving files around +*/ +function temp_portfolio_working_directory($unique) { + return make_upload_directory('temp/portfolio/export/' . $unique); +} + +function temp_portfolio_usertemp_directory($userid) { + return make_upload_directory('userdata/' . $userid . '/temp'); +} + +/** +*cleans up the working directory +*/ +function temp_portfolio_cleanup($unique) { + $workdir = temp_portfolio_working_directory($unique); + return remove_dir($workdir); +} + + +/** +* base class for the caller +* places in moodle that want to display +* the add form should subclass this for their callback. +*/ +abstract class portfolio_caller_base { + + /** + * stdclass object + * course that was active during the caller + */ + protected $course; + + /** + * named array of export config + * use{@link set_export_config} and {@link get_export_config} to access + */ + protected $exportconfig; + + /** + * stdclass object + * user currently exporting content + */ + protected $user; + + /** + * if this caller wants any additional config items + * they should be defined here. + * + * @param array $mform moodleform object (passed by reference) to add elements to + * @param object $instance subclass of portfolio_plugin_base + * @param integer $userid id of user exporting content + */ + public function export_config_form(&$mform, $instance) {} + + + /** + * whether this caller wants any additional + * config during export (eg options or metadata) + * + * @return boolean + */ + public function has_export_config() { + return false; + } + + /** + * just like the moodle form validation function + * this is passed in the data array from the form + * and if a non empty array is returned, form processing will stop. + * + * @param array $data data from form. + * @return array keyvalue pairs - form element => error string + */ + public function export_config_validation($data) {} + + /** + * how long does this reasonably expect to take.. + * should we offer the user the option to wait.. + * this is deliberately nonstatic so it can take filesize into account + * the portfolio plugin can override this. + * (so for exmaple even if a huge file is being sent, + * the download portfolio plugin doesn't care ) + * + * @return string (see PORTFOLIO_TIME_* constants) + */ + public abstract function expected_time(); + + /** + * used for displaying the navigation during the export screens. + * + * this function must be implemented, but can really return anything. + * an Exporting.. string will be added on the end. + * @return array of $extranav and $cm + * + * to pass to build_navigation + * + */ + public abstract function get_navigation(); + + /* + * generic getter for properties belonging to this instance + * outside the subclasses + * like name, visible etc. + * + * @todo determine what to return in the error case + */ + public final function get($field) { + if (property_exists($this, $field)) { + return $this->{$field}; + } + return false; // @todo throw exception? + } + + /** + * generic setter for properties belonging to this instance + * outside the subclass + * like name, visible, etc. + * + * @todo determine what to return in the error case + */ + public final function set($field, $value) { + if (property_exists($this, $field)) { + $this->{$field} = $value; + $this->dirty = true; + return true; + } + return false; // @todo throw exception? + + } + + /** + * stores the config generated at export time. + * subclasses can retrieve values using + * {@link get_export_config} + * + * @param array $config formdata + */ + public final function set_export_config($config) { + $allowed = array_merge( + array('wait', 'hidewait', 'format'), + $this->get_allowed_export_config() + ); + foreach ($config as $key => $value) { + if (!in_array($key, $allowed)) { + continue; // @ todo throw exception + } + $this->exportconfig[$key] = $value; + } + } + + /** + * returns a particular export config value. + * subclasses shouldn't need to override this + * + * @param string key the config item to fetch + * @todo figure out the error cases (item not found or not allowed) + */ + public final function get_export_config($key) { + $allowed = array_merge( + array('wait', 'hidewait', 'format'), + $this->get_allowed_export_config() + ); + if (!in_array($key, $allowed)) { + return false; // @todo throw exception? + } + if (!array_key_exists($key, $this->exportconfig)) { + return null; // @todo what to return| + } + return $this->exportconfig[$key]; + } + + /** + * Similar to the other allowed_config functions + * if you need export config, you must provide + * a list of what the fields are. + * + * even if you want to store stuff during export + * without displaying a form to the user, + * you can use this. + * + * @return array array of allowed keys + */ + public function get_allowed_export_config() { + return array(); + } + + /** + * after the user submits their config + * they're given a confirm screen + * summarising what they've chosen. + * + * this function should return a table of nice strings => values + * of what they've chosen + * to be displayed in a table. + * + * @return array array of config items. + */ + public function get_export_summary() { + return false; + } + + /** + * called before the portfolio plugin gets control + * this function should copy all the files it wants to + * the temporary directory. + * + * @param string $tempdir path to tempdir to put files in + */ + public abstract function prepare_package($tempdir); + + /** + * array of formats this caller supports + * the intersection of what this function returns + * and what the selected portfolio plugin supports + * will be used + * use the constants PORTFOLIO_FORMAT_* + * + * @return array list of formats + */ + public abstract static function supported_formats(); + + /** + * this is the "return to where you were" url + * + * @return string url + */ + public abstract function get_return_url(); + + /** + * callback to do whatever capability checks required + * in the caller (called during the export process + */ + public abstract function check_permissions(); +} + +/** +* the base class for portfolio plguins +* all plugins must subclass this. +*/ +abstract class portfolio_plugin_base { + + /** + * boolean + * whether this object needs writing out to the database + */ + protected $dirty; + + /** + * integer + * id of instance + */ + protected $id; + + /** + * string + * name of instance + */ + protected $name; + + /** + * string + * plugin this instance belongs to + */ + protected $plugin; + + /** + * boolean + * whether this instance is visible or not + */ + protected $visible; + + /** + * named array + * admin configured config + * use {@link set_config} and {@get_config} to access + */ + protected $config; + + /** + * + * user config cache + * named array of named arrays + * keyed on userid and then on config field => value + * use {@link get_user_config} and {@link set_user_config} to access. + */ + protected $userconfig; + + /** + * named array + * export config during export + * use {@link get_export_config} and {@link set export_config} to access. + */ + protected $exportconfig; + + /** + * stdclass object + * user currently exporting data + */ + protected $user; + + + /** + * array of formats this portfolio supports + * the intersection of what this function returns + * and what the caller supports will be used + * use the constants PORTFOLIO_FORMAT_* + * + * @return array list of formats + */ + public abstract static function supported_formats(); + + + /** + * how long does this reasonably expect to take.. + * should we offer the user the option to wait.. + * this is deliberately nonstatic so it can take filesize into account + * + * @param string $callertime - what the caller thinks + * the portfolio plugin instance + * is given the final say + * because it might be (for example) download. + * @return string (see PORTFOLIO_TIME_* constants) + */ + public abstract function expected_time($callertime); + + /** + * check sanity of plugin + * if this function returns something non empty, ALL instances of your plugin + * will be set to invisble and not be able to be set back until it's fixed + * + * @return mixed - string = error string KEY (must be inside plugin_$yourplugin) or 0/false if you're ok + */ + public static function plugin_sanity_check() { + return 0; + } + + /** + * check sanity of instances + * if this function returns something non empty, the instance will be + * set to invislbe and not be able to be set back until it's fixed. + * + * @return mixed - string = error string KEY (must be inside plugin_$yourplugin) or 0/false if you're ok + */ + public function instance_sanity_check() { + return 0; + } + + /** + * does this plugin need any configuration by the administrator? + * + * if you override this to return true, + * you must implement {@link} admin_config_form + */ + public static function has_admin_config() { + return false; + } + + /** + * can this plugin be configured by the user in their profile? + * + * if you override this to return true, + * you must implement {@link user_config_form + */ + public function has_user_config() { + return false; + } + + /** + * does this plugin need configuration during export time? + * + * if you override this to return true, + * you must implement {@link export_config_form} + */ + public function has_export_config() { + return false; + } + + /** + * just like the moodle form validation function + * this is passed in the data array from the form + * and if a non empty array is returned, form processing will stop. + * + * @param array $data data from form. + * @return array keyvalue pairs - form element => error string + */ + public function export_config_validation() {} + + /** + * just like the moodle form validation function + * this is passed in the data array from the form + * and if a non empty array is returned, form processing will stop. + * + * @param array $data data from form. + * @return array keyvalue pairs - form element => error string + */ + public function user_config_validation() {} + + /** + * sets the export time config from the moodle form. + * you can also use this to set export config that + * isn't actually controlled by the user + * eg things that your subclasses want to keep in state + * across the export. + * keys must be in {@link get_allowed_export_config} + * + * this is deliberately not final (see boxnet plugin) + * + * @param array $config named array of config items to set. + */ + public function set_export_config($config) { + $allowed = array_merge( + array('wait', 'format'), + $this->get_allowed_export_config() + ); + foreach ($config as $key => $value) { + if (!in_array($key, $allowed)) { + continue; // @ todo throw exception + } + $this->exportconfig[$key] = $value; + } + } + + /** + * gets an export time config value. + * subclasses should not override this. + * + * @param string key field to fetch + * + * @return string config value + * + * @todo figure out the error cases + */ + public final function get_export_config($key) { + $allowed = array_merge( + array('wait', 'format'), + $this->get_allowed_export_config() + ); + if (!in_array($key, $allowed)) { + return false; // @todo throw exception? + } + if (!array_key_exists($key, $this->exportconfig)) { + return null; // @todo what to return| + } + return $this->exportconfig[$key]; + } + + /** + * after the user submits their config + * they're given a confirm screen + * summarising what they've chosen. + * + * this function should return a table of nice strings => values + * of what they've chosen + * to be displayed in a table. + * + * @return array array of config items. + */ + public function get_export_summary() { + return false; + } + + /** + * called before the portfolio plugin gets control + * this function should copy all the files it wants to + * the temporary directory. + * + * @param string $tempdir path to temporary directory + */ + public abstract function prepare_package($tempdir); + + /** + * this is the function that is responsible for sending + * the package to the remote system, + * or whatever request is necessary to initiate the transfer. + * + * @return boolean success + */ + public abstract function send_package(); + + + /** + * once everything is done and the user + * has the finish page displayed to them + * the base class takes care of printing them + * "return to where you are" or "continue to portfolio" links + * this function allows for exta finish options from the plugin + * + * @return array named array of links => titles + */ + public function get_extra_finish_options() { + return false; + } + + /** + * the url for the user to continue to their portfolio + * + * @return string url or false. + */ + public abstract function get_continue_url(); + + /** + * mform to display to the user in their profile + * if your plugin can't be configured by the user, + * (see {@link has_user_config}) + * don't bother overriding this function + * + * @param moodleform $mform passed by reference, add elements to it + */ + public function user_config_form(&$mform) {} + + /** + * mform to display to the admin configuring the plugin. + * if your plugin can't be configured by the admin, + * (see {@link} has_admin_config) + * don't bother overriding this function + * + * this function can be called statically or non statically, + * depending on whether it's creating a new instance (statically), + * or editing an existing one (non statically) + * + * @param moodleform $mform passed by reference, add elements to it. + * @return mixed - if a string is returned, it means the plugin cannot create an instance + * and the string is an error code + */ + public function admin_config_form(&$mform) {} + + /** + * just like the moodle form validation function + * this is passed in the data array from the form + * and if a non empty array is returned, form processing will stop. + * + * @param array $data data from form. + * @return array keyvalue pairs - form element => error string + */ + public static function admin_config_validation($data) {} + /** + * mform to display to the user exporting data using this plugin. + * if your plugin doesn't need user input at this time, + * (see {@link has_export_config} + * don't bother overrideing this function + * + * @param moodleform $mform passed by reference, add elements to it. + */ + public function export_config_form(&$mform) {} + + /** + * override this if your plugin doesn't allow multiple instances + * + * @return boolean + */ + public static function allows_multiple() { + return true; + } + + /** + * + * If at any point the caller wants to steal control + * it can, by returning something that isn't false + * in this function + * The controller will redirect to whatever url + * this function returns. + * Afterwards, you can redirect back to portfolio/add.php?postcontrol=1 + * and {@link post_control} is called before the rest of the processing + * for the stage is done + * + * @param int stage to steal control *before* (see constants PARAM_STAGE_*} + * + * @return boolean or string url + */ + public function steal_control($stage) { + return false; + } + + /** + * after a plugin has elected to steal control, + * and control returns to portfolio/add.php|postcontrol=1, + * this function is called, and passed the stage that was stolen control from + * and the request (get and post but not cookie) parameters + * this is useful for external systems that need to redirect the user back + * with some extra data in the url (like auth tokens etc) + * for an example implementation, see boxnet portfolio plugin. + * + * @param int $stage the stage before control was stolen + * @param array $params a merge of $_GET and $_POST + * + */ + + public function post_control($stage, $params) { } + + /** + * this function creates a new instance of a plugin + * saves it in the database, saves the config + * and returns it. + * you shouldn't need to override it + * unless you're doing something really funky + * + * @return object subclass of portfolio_plugin_base + */ + public static function create_instance($plugin, $name, $config) { + global $DB, $CFG; + $new = (object)array( + 'plugin' => $plugin, + 'name' => $name, + ); + $newid = $DB->insert_record('portfolio_instance', $new); + require_once($CFG->dirroot . '/portfolio/type/' . $plugin . '/lib.php'); + $classname = 'portfolio_plugin_' . $plugin; + $obj = new $classname($newid); + $obj->set_config($config); + return $obj; + } + + /** + * construct a plugin instance + * subclasses should not need to override this unless they're doing something special + * and should call parent::__construct afterwards + * + * @param int $instanceid id of plugin instance to construct + * @param mixed $record stdclass object or named array - use this is you already have the record to avoid another query + * + * @return object subclass of portfolio_plugin_base + */ + public function __construct($instanceid, $record=null) { + global $DB; + if (!$record) { + if (!$record = $DB->get_record('portfolio_instance', array('id' => $instanceid))) { + return false; // @todo throw exception? + } + } + foreach ((array)$record as $key =>$value) { + if (property_exists($this, $key)) { + $this->{$key} = $value; + } + } + $this->config = new StdClass; + $this->userconfig = array(); + $this->exportconfig = array(); + foreach ($DB->get_records('portfolio_instance_config', array('instance' => $instanceid)) as $config) { + $this->config->{$config->name} = $config->value; + } + return $this; + } + + /** + * a list of fields that can be configured per instance. + * this is used for the save handlers of the config form + * and as checks in set_config and get_config + * + * @return array array of strings (config item names) + */ + public static function get_allowed_config() { + return array(); + } + + /** + * a list of fields that can be configured by the user. + * this is used for the save handlers in the config form + * and as checks in set_user_config and get_user_config. + * + * @return array array of strings (config field names) + */ + public function get_allowed_user_config() { + return array(); + } + + /** + * a list of fields that can be configured by the user. + * this is used for the save handlers in the config form + * and as checks in set_export_config and get_export_config. + * + * @return array array of strings (config field names) + */ + public function get_allowed_export_config() { + return array(); + } + + /** + * saves (or updates) the config stored in portfolio_instance_config. + * you shouldn't need to override this unless you're doing something funky. + * + * @param array $config array of config items. + */ + public final function set_config($config) { + global $DB; + foreach ($config as $key => $value) { + // try set it in $this first + if ($this->set($key, $value)) { + continue; + } + if (!in_array($key, $this->get_allowed_config())) { + continue; // @todo throw exception? + } + if (!isset($this->config->{$key})) { + $DB->insert_record('portfolio_instance_config', (object)array( + 'instance' => $this->id, + 'name' => $key, + 'value' => $value, + )); + } else if ($this->config->{$key} != $value) { + $DB->set_field('portfolio_instance_config', 'value', $value, array('name' => $key, 'instance' => $this->id)); + } + $this->config->{$key} = $value; + } + return true; // @todo - if we're going to change here to throw exceptions, this can change + } + + /** + * gets the value of a particular config item + * + * @param string $key key to fetch + * + * @return string the corresponding value + * + * @todo determine what to return in the error case. + */ + public final function get_config($key) { + if (!in_array($key, $this->get_allowed_config())) { + return false; // @todo throw exception? + } + if (isset($this->config->{$key})) { + return $this->config->{$key}; + } + return false; // @todo null? + } + + /** + * get the value of a config item for a particular user + * + * @param string $key key to fetch + * @param integer $userid id of user (defaults to current) + * + * @return string the corresponding value + * + * @todo determine what to return in the error case + */ + public final function get_user_config($key, $userid=0) { + global $DB; + + if (empty($userid)) { + $userid = $this->user->id; + } + + if ($key != 'visible') { // handled by the parent class + if (!in_array($key, $this->get_allowed_user_config())) { + return false; // @todo throw exception? + } + } + if (!array_key_exists($userid, $this->userconfig)) { + $this->userconfig[$userid] = (object)array_fill_keys(array_merge(array('visible'), $this->get_allowed_user_config()), null); + foreach ($DB->get_records('portfolio_instance_user', array('instance' => $this->id, 'userid' => $userid)) as $config) { + $this->userconfig[$userid]->{$config->name} = $config->value; + } + } + if ($this->userconfig[$userid]->visible === null) { + $this->set_user_config(array('visible' => 1), $userid); + } + return $this->userconfig[$userid]->{$key}; + + } + + /** + * + * sets config options for a given user + * + * @param mixed $config array or stdclass containing key/value pairs to set + * @param integer $userid userid to set config for (defaults to current) + * + * @todo determine what to return in the error case + */ + public final function set_user_config($config, $userid=0) { + global $DB; + + if (empty($userid)) { + $userid = $this->user->id; + } + + foreach ($config as $key => $value) { + if ($key != 'visible' && !in_array($key, $this->get_allowed_user_config())) { + continue; // @todo throw exception? + } + if (!$existing = $DB->get_record('portfolio_instance_user', array('instance'=> $this->id, 'userid' => $userid, 'name' => $key))) { + $DB->insert_record('portfolio_instance_user', (object)array( + 'instance' => $this->id, + 'name' => $key, + 'value' => $value, + 'userid' => $userid, + )); + } else if ($existing->value != $value) { + $DB->set_field('portfolio_instance_user', 'value', $value, array('name' => $key, 'instance' => $this->id, 'userid' => $userid)); + } + $this->userconfig[$userid]->{$key} = $value; + } + return true; // @todo + + } + + /** + * generic getter for properties belonging to this instance + * outside the subclasses + * like name, visible etc. + * + * @todo determine what to return in the error case + */ + public final function get($field) { + if (property_exists($this, $field)) { + return $this->{$field}; + } + return false; // @todo throw exception? + } + + /** + * generic setter for properties belonging to this instance + * outside the subclass + * like name, visible, etc. + * + * @todo determine what to return in the error case + */ + public final function set($field, $value) { + if (property_exists($this, $field)) { + $this->{$field} = $value; + $this->dirty = true; + return true; + } + return false; // @todo throw exception? + + } + + /** + * saves stuff that's been stored in the object to the database + * you shouldn't need to override this + * unless you're doing something really funky. + * and if so, call parent::save when you're done. + */ + public function save() { + global $DB; + if (!$this->dirty) { + return true; + } + $fordb = new StdClass(); + foreach (array('id', 'name', 'plugin', 'visible') as $field) { + $fordb->{$field} = $this->{$field}; + } + $DB->update_record('portfolio_instance', $fordb); + $this->dirty = false; + return true; + } + + /** + * deletes everything from the database about this plugin instance. + * you shouldn't need to override this unless you're storing stuff + * in your own tables. and if so, call parent::delete when you're done. + */ + public function delete() { + global $DB; + $DB->delete_records('portfolio_instance_config', array('instance' => $this->get('id'))); + $DB->delete_records('portfolio_instance_user', array('instance' => $this->get('id'))); + $DB->delete_records('portfolio_instance', array('id' => $this->get('id'))); + $this->dirty = false; + return true; + } +} + +/** +* this is the form that is actually used while exporting. +* plugins and callers don't get to define their own class +* as we have to handle form elements from both places +* see the docs for portfolio_plugin_base and portfolio_caller for more information +*/ +final class portfolio_export_form extends moodleform { + + public function definition() { + + $mform =& $this->_form; + $mform->addElement('hidden', 'stage', PORTFOLIO_STAGE_CONFIG); + $mform->addElement('hidden', 'instance', $this->_customdata['instance']->get('id')); + + if (array_key_exists('formats', $this->_customdata) && is_array($this->_customdata['formats'])) { + if (count($this->_customdata['formats']) > 1) { + $options = array(); + foreach ($this->_customdata['formats'] as $key) { + $options[$key] = get_string('format_' . $key, 'portfolio'); + } + $mform->addElement('select', 'format', get_string('availableformats', 'portfolio'), $options); + } else { + $f = array_shift($this->_customdata['formats']); + $mform->addElement('hidden', 'format', $f); + } + } + + if (array_key_exists('expectedtime', $this->_customdata) && $this->_customdata['expectedtime'] != PORTFOLIO_TIME_LOW) { + //$mform->addElement('select', 'wait', get_string('waitlevel_' . $this->_customdata['expectedtime'], 'portfolio'), $options); + + + $radioarray = array(); + $radioarray[] = &MoodleQuickForm::createElement('radio', 'wait', '', get_string('wait', 'portfolio'), 1); + $radioarray[] = &MoodleQuickForm::createElement('radio', 'wait', '', get_string('dontwait', 'portfolio'), 0); + $mform->addGroup($radioarray, 'radioar', get_string('wanttowait_' . $this->_customdata['expectedtime'], 'portfolio') , array(' '), false); + + $mform->setDefault('wait', 0); + } + else { + $mform->addElement('hidden', 'wait', 1); + } + + if (array_key_exists('plugin', $this->_customdata) && is_object($this->_customdata['plugin'])) { + $this->_customdata['plugin']->export_config_form($mform, $this->_customdata['userid']); + } + + if (array_key_exists('caller', $this->_customdata) && is_object($this->_customdata['caller'])) { + $this->_customdata['caller']->export_config_form($mform, $this->_customdata['instance'], $this->_customdata['userid']); + } + + $this->add_action_buttons(true, get_string('next')); + } + + public function validation($data) { + + $errors = array(); + + if (array_key_exists('plugin', $this->_customdata) && is_object($this->_customdata['plugin'])) { + $pluginerrors = $this->_customdata['plugin']->export_config_validation($data); + if (is_array($pluginerrors)) { + $errors = $pluginerrors; + } + } + if (array_key_exists('caller', $this->_customdata) && is_object($this->_customdata['caller'])) { + $callererrors = $this->_customdata['caller']->export_config_validation($data); + if (is_array($callererrors)) { + $errors = array_merge($errors, $callererrors); + } + } + return $errors; + } +} + +/** +* this form is extendable by plugins +* who want the admin to be able to configure +* more than just the name of the instance. +* this is NOT done by subclassing this class, +* see the docs for portfolio_plugin_base for more information +*/ +final class portfolio_admin_form extends moodleform { + + protected $instance; + protected $plugin; + + public function definition() { + global $CFG; + $this->plugin = $this->_customdata['plugin']; + $this->instance = (isset($this->_customdata['instance']) + && is_subclass_of($this->_customdata['instance'], 'portfolio_plugin_base')) + ? $this->_customdata['instance'] : null; + + $mform =& $this->_form; + $strrequired = get_string('required'); + + $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->get('id') : 0); + $mform->addElement('hidden', 'new', $this->plugin); + $mform->addElement('hidden', 'plugin', $this->plugin); + + $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"'); + $mform->addRule('name', $strrequired, 'required', null, 'client'); + + // let the plugin add the fields they want (either statically or not) + if (portfolio_static_function($this->plugin, 'has_admin_config')) { + if (!$this->instance) { + $result = portfolio_static_function($this->plugin, 'admin_config_form', $mform); + } else { + $result = $this->instance->admin_config_form($mform); + } + } + + if (isset($result) && is_string($result)) { // something went wrong, stop + return $this->raise_error($result, 'portfolio_' . $this->plugin, $CFG->wwwroot . '/' . $CFG->admin . '/portfolio.php'); + } + + // and set the data if we have some. + if ($this->instance) { + $data = array('name' => $this->instance->get('name')); + foreach ($this->instance->get_allowed_config() as $config) { + $data[$config] = $this->instance->get_config($config); + } + $this->set_data($data); + } + $this->add_action_buttons(true, get_string('save', 'portfolio')); + } + + public function validation($data) { + global $DB; + + $errors = array(); + if ($DB->count_records('portfolio_instance', array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) { + $errors = array('name' => get_string('err_uniquename', 'portfolio')); + } + + $pluginerrors = array(); + if ($this->instance) { + $pluginerrors = $this->instance->admin_config_validation($data); + } + else { + $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data); + } + if (is_array($pluginerrors)) { + $errors = array_merge($errors, $pluginerrors); + } + return $errors; + } +} + +/** +* this is the form for letting the user configure an instance of a plugin. +* in order to extend this, you don't subclass this in the plugin.. +* see the docs in portfolio_plugin_base for more information +*/ +final class portfolio_user_form extends moodleform { + + protected $instance; + protected $userid; + + public function definition() { + $this->instance = $this->_customdata['instance']; + $this->userid = $this->_customdata['userid']; + + $this->_form->addElement('hidden', 'config', $this->instance->get('id')); + + $this->instance->user_config_form($this->_form, $this->userid); + + $data = array(); + foreach ($this->instance->get_allowed_user_config() as $config) { + $data[$config] = $this->instance->get_user_config($config, $this->userid); + } + $this->set_data($data); + $this->add_action_buttons(true, get_string('save', 'portfolio')); + } + + public function validation($data) { + + $errors = $this->instance->user_config_validation($data); + + } +} + +/** +* +* Class that handles the various stages of the actual export +*/ +final class portfolio_exporter { + + private $currentstage; + private $caller; + private $instance; + private $noconfig; + private $navigation; + private $uniquekey; + private $tempdir; + private $user; + + public $instancefile; + public $callerfile; + + /** + * construct a new exporter for use + * + * @param portfolio_plugin_base subclass $instance portfolio instance (passed by reference) + * @param portfolio_caller_base subclass $caller portfolio caller (passed by reference) + * @param string $navigation result of build_navigation (passed to print_header) + */ + public function __construct(&$instance, &$caller, $callerfile, $navigation) { + $this->instance =& $instance; + $this->caller =& $caller; + if ($instance) { + $this->instancefile = 'portfolio/type/' . $instance->get('plugin') . '/lib.php'; + } + $this->callerfile = $callerfile; + $this->stage = PORTFOLIO_STAGE_CONFIG; + $this->navigation = $navigation; + } + + /* + * generic getter for properties belonging to this instance + * outside the subclasses + * like name, visible etc. + * + * @todo determine what to return in the error case + */ + public function get($field) { + if (property_exists($this, $field)) { + return $this->{$field}; + } + return false; // @todo throw exception? + } + + /** + * generic setter for properties belonging to this instance + * outside the subclass + * like name, visible, etc. + * + * @todo determine what to return in the error case + */ + + public function set($field, $value) { + if (property_exists($this, $field)) { + $this->{$field} = $value; + if ($field == 'instance') { + $this->instancefile = 'portfolio/type/' . $this->instance->get('plugin') . '/lib.php'; + } + $this->dirty = true; + return true; + } + return false; // @todo throw exception? + + } + /** + * process the given stage calling whatever functions are necessary + * + * @param int $stage (see PORTFOLIO_STAGE_* constants) + * @param boolean $alreadystolen used to avoid letting plugins steal control twice. + * + * @return boolean whether or not to process the next stage. this is important as the function is called recursively. + */ + public function process_stage($stage, $alreadystolen=false) { + global $SESSION; + if (!$alreadystolen && $url = $this->instance->steal_control($stage)) { + $SESSION->portfolio->stagepresteal = $stage; + redirect($url); + break; + } + + $waiting = $this->instance->get_export_config('wait'); + if ($stage > PORTFOLIO_STAGE_QUEUEORWAIT && empty($waiting)) { + $stage = PORTFOLIO_STAGE_FINISHED; + } + $functionmap = array( + PORTFOLIO_STAGE_CONFIG => 'config', + PORTFOLIO_STAGE_CONFIRM => 'confirm', + PORTFOLIO_STAGE_QUEUEORWAIT => 'queueorwait', + PORTFOLIO_STAGE_PACKAGE => 'package', + PORTFOLIO_STAGE_CLEANUP => 'cleanup', + PORTFOLIO_STAGE_SEND => 'send', + PORTFOLIO_STAGE_FINISHED => 'finished' + ); + + $function = 'process_stage_' . $functionmap[$stage]; + if ($this->$function()) { + // if we get through here it means control was returned + // as opposed to wanting to stop processing + // eg to wait for user input. + $stage++; + return $this->process_stage($stage); + } + return false; + } + + /** + * helper function to return the portfolio instance + * + * @return portfolio_plugin_base subclass + */ + public function instance() { + return $this->instance; + } + + /** + * helper function to return the caller object + * + * @return portfolio_caller_base subclass + */ + public function caller() { + return $this->caller; + } + + /** + * processes the 'config' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_config() { + + global $SESSION; + + $pluginobj = $callerobj = null; + if ($this->instance->has_export_config()) { + $pluginobj = $this->instance; + } + if ($this->caller->has_export_config()) { + $callerobj = $this->caller; + } + $formats = array_intersect($this->instance->supported_formats(), $this->caller->supported_formats()); + $expectedtime = $this->instance->expected_time($this->caller->expected_time()); + if (count($formats) == 0) { + // something went wrong, we should not have gotten this far. + return $this->raise_error('nocommonformats', 'portfolio', get_class($caller)); + } + // even if neither plugin or caller wants any config, we have to let the user choose their format, and decide to wait. + if ($pluginobj || $callerobj || count($formats) > 1 || $expectedtime != PORTFOLIO_TIME_LOW) { + $customdata = array( + 'instance' => $this->instance, + 'plugin' => $pluginobj, + 'caller' => $callerobj, + 'userid' => $this->user->id, + 'formats' => $formats, + 'expectedtime' => $expectedtime, + ); + $mform = new portfolio_export_form('', $customdata); + if ($mform->is_cancelled()){ + unset($SESSION->portfolio); + redirect($this->caller->get_return_url()); + exit; + } else if ($fromform = $mform->get_data()){ + if (!confirm_sesskey()) { + return $this->raise_error('confirmsesskeybad', '', $caller->get_return_url()); + } + $pluginbits = array(); + $callerbits = array(); + foreach ($fromform as $key => $value) { + if (strpos($key, 'plugin_') === 0) { + $pluginbits[substr($key, 7)] = $value; + } else if (strpos($key, 'caller_') === 0) { + $callerbits[substr($key, 7)] = $value; + } + } + $callerbits['format'] = $pluginbits['format'] = $fromform->format; + $pluginbits['wait'] = $fromform->wait; + if ($expectedtime = PORTFOLIO_TIME_LOW) { + $pluginbits['wait'] = 1; + $pluginbits['hidewait'] = 1; + } + $this->caller->set_export_config($callerbits); + $this->instance->set_export_config($pluginbits); + return true; + } else { + $this->print_header(); + print_heading(get_string('configexport' ,'portfolio')); + print_simple_box_start(); + $mform->display(); + print_simple_box_end(); + print_footer(); + return false;; + } + } else { + $this->noexportconfig = true; + $this->instance->set_export_config(array('wait' => 1)); + return true; + // do not break - fall through to confirm + } + } + + + /** + * processes the 'confirm' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_confirm() { + global $CFG; + if ($this->noexportconfig) { + return true; + } + $strconfirm = get_string('confirmexport', 'portfolio'); + $yesurl = $CFG->wwwroot . '/portfolio/add.php?stage=' . PORTFOLIO_STAGE_QUEUEORWAIT; + $nourl = $this->caller->get_return_url(); + $this->print_header(); + print_heading($strconfirm); + print_simple_box_start(); + print_heading(get_string('confirmsummary', 'portfolio'), '', 4); + $mainsummary = array( + // @todo do something cleverer about wait + get_string('selectedformat', 'portfolio') => get_string('format_' . $this->instance->get_export_config('format'), 'portfolio'), + ); + if (!$this->instance->get_export_config('hidewait')) { + $mainsummary[get_string('selectedwait', 'portfolio')] = get_string($this->instance->get_export_config('wait') ? 'yes' : 'no'); + } + if (!$csummary = $this->caller->get_export_summary()) { + $csummary = array(); + } + if (!$isummary = $this->instance->get_export_summary()) { + $isummary = array(); + } + $mainsummary = array_merge($mainsummary, $csummary, $isummary); + foreach ($mainsummary as $string => $value) { + echo '' . $string . ':' . $value . '
' . "\n"; + } + notice_yesno($strconfirm, $yesurl, $nourl); + print_simple_box_end(); + print_footer(); + return false; + } + + /** + * processes the 'queueornext' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_queueorwait() { + global $SESSION; + $wait = $this->instance->get_export_config('wait'); + if (empty($wait)) { + error_log(print_r(serialize($this), true)); + events_trigger('portfolio_send', $this); + unset($SESSION->portfolio); + return $this->process_stage_finished(); + } + return true; + } + + /** + * processes the 'package' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_package() { + // now we've agreed on a format, + // the caller is given control to package it up however it wants + // and then the portfolio plugin is given control to do whatever it wants. + $unique = $this->user->id . '-' . time(); + $tempdir = temp_portfolio_working_directory($unique); + $this->uniquekey = $unique; + $this->tempdir = $tempdir; + if (!$this->caller->prepare_package($tempdir)) { + return $this->raise_error('callercouldnotpackage', 'portfolio'); + } + if (!$package = $this->instance->prepare_package($tempdir)) { + return $this->raise_error('plugincouldnotpackage', 'portfolio'); + } + return true; + } + + /** + * processes the 'cleanup' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_cleanup() { + global $CFG; + // @todo this is unpleasant. fix it. + require_once($CFG->dirroot . '/backup/lib.php'); + delete_dir_contents($this->tempdir); + // @todo maybe add a hook in the plugin(s) + return true; + } + + /** + * processes the 'send' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_send() { + // send the file + if (!$this->instance->send_package()) { + return $this->raise_error('failedtosendpackage', 'portfolio'); + } + return true; + } + + /** + * processes the 'finish' stage of the export + * + * @return boolean whether or not to process the next stage. this is important as the control function is called recursively. + */ + public function process_stage_finished() { + global $SESSION; + $returnurl = $this->caller->get_return_url(); + $continueurl = $this->instance->get_continue_url(); + $extras = $this->instance->get_extra_finish_options(); + + $this->print_header(); + //@todo do something different here if we're queueing. + print_heading(get_string('exportcomplete', 'portfolio')); + if ($returnurl) { + echo '' . get_string('returntowhereyouwere', 'portfolio') . '
'; + } + if ($continueurl) { + echo '' . get_string('continuetoportfolio', 'portfolio') . '
'; + } + if (is_array($extras)) { + foreach ($extras as $link => $string) { + echo '' . $string . '
'; + } + } + print_footer(); + unset($SESSION->portfolio); + return false; + } + + + /** + * local print header function to be reused across the export + * + * @param string $titlestring key for a portfolio language string + * @param string $headerstring key for a portfolio language string + */ + public function print_header($titlestr='exporting', $headerstr='exporting') { + $titlestr = get_string($titlestr, 'portfolio'); + $headerstr = get_string($headerstr, 'portfolio'); + + print_header($titlestr, $headerstr, $this->navigation); + } + + /** + * error handler - decides whether we're running interactively or not + * and behaves accordingly + */ + public static function raise_error($string, $module, $continue=null) { + if (defined('FULLME') && FULLME == 'cron') { + debugging(get_string($string, $module)); + return false; + } + global $SESSION; + unset($SESSION->portfolio); + print_error($string, $module, $continue); + } +} + +/** +* event handler for the portfolio_send event +*/ +function portfolio_handle_event($eventdata) { + global $CFG; + require_once($CFG->dirroot . '/' . $eventdata->instancefile); + require_once($CFG->dirroot . '/' . $eventdata->callerfile); + $exporter = unserialize(serialize($eventdata)); + $exporter->process_stage_package(); + $exporter->process_stage_send(); + $exporter->process_stage_cleanup(); + return true; +} + +?> + diff --git a/mod/assignment/lib.php b/mod/assignment/lib.php index 0e48422a90..c4d32032ce 100644 --- a/mod/assignment/lib.php +++ b/mod/assignment/lib.php @@ -1699,13 +1699,26 @@ class assignment_base { if ($basedir = $this->file_area($userid)) { if ($files = get_directory_list($basedir)) { require_once($CFG->libdir.'/filelib.php'); + $p = array( + 'userid' => $userid, + 'assignmentid' => $this->cm->id, + ); foreach ($files as $key => $file) { $icon = mimeinfo('icon', $file); $ffurl = get_file_url("$filearea/$file", array('forcedownload'=>1)); $output .= ''.$icon.''. - ''.$file.'
'; + ''.$file.''; + if ($this->portfolio_exportable() && true) { // @todo replace with capability check + $p['file'] = $file; + $output .= portfolio_add_button('assignment_portfolio_caller', $p, false, true); + } + $output .= '
'; + } + if ($this->portfolio_exportable() && true) { //@todo replace with check capability + unset($p['file']);// for all files + $output .= '
' . portfolio_add_button('assignment_portfolio_caller', $p, true, true); } } } @@ -1942,6 +1955,11 @@ class assignment_base { return $status; } + + + function portfolio_exportable() { + return false; + } } ////// End of the assignment_base class @@ -3096,4 +3114,85 @@ function assignment_get_extra_capabilities() { return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames'); } +require_once($CFG->libdir . '/portfoliolib.php'); +class assignment_portfolio_caller extends portfolio_caller_base { + + private $assignment; + private $assignmentfile; + private $userid; + private $file; + + public function __construct($callbackargs) { + global $DB, $CFG; + + if (! $cm = get_coursemodule_from_id('assignment', $callbackargs['assignmentid'])) { + print_error('invalidcoursemodule'); + } + + if (! $assignment = $DB->get_record("assignment", array("id"=>$cm->instance))) { + print_error('invalidid', 'assignment'); + } + + $this->assignmentfile = $CFG->dirroot . '/mod/assignment/type/' . $assignment->assignmenttype . '/assignment.class.php'; + require_once($this->assignmentfile); + $assignmentclass = "assignment_$assignment->assignmenttype"; + $this->assignment= new $assignmentclass($cm->id, $assignment, $cm); + if (!$this->assignment->portfolio_exportable()) { + print_error('notexportable', 'portfolio', $this->get_return_url()); + } + $this->userid = $callbackargs['userid']; + $this->file = (array_key_exists('file', $callbackargs)) ? $callbackargs['file'] : null; + } + + public function prepare_package($tempdir) { + global $CFG; + if ($this->assignment->assignment->assignmenttype == 'online') { + $submission = $this->assignment->get_submission(); + $handle = fopen($tempdir . '/assignment.html', 'w'); + $status = $handle && fwrite($handle, format_text($submission->data1, $submission->data2)); + $status = $status && fclose($handle); + return $status; + } + $filearea = $CFG->dataroot . '/' . $this->assignment->file_area_name($this->userid); + //@todo this is a dreadful thing to have to call. + require_once($CFG->dirroot . '/backup/lib.php'); + if ($this->file) { + return backup_copy_file($filearea . '/' . $this->file, $tempdir . '/' . $this->file); + } + return backup_copy_file($filearea, $tempdir); + } + + public static function supported_formats() { + // try and cheat + if (isset($this) && $this->assignment->assignment->assignmenttype == 'online') { + return array(PORTFOLIO_FORMAT_HTML); + } + return array(PORTFOLIO_FORMAT_FILE); + } + + public function get_return_url() { + global $CFG; + return $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->assignment->cm->id; + } + + public function get_navigation() { + $extranav = array('name' => $this->assignment->cm->name, 'link' => $this->get_return_url()); + return array($extranav, $this->assignment->cm); + } + + public function expected_time() { + return PORTFOLIO_TIME_MODERATE; // @TODO check uploaded file size + } + + public function check_permissions() { + return has_capability('mod/assignment:export-upload-files', get_context_instance(CONTEXT_MODULE, $this->assignment->cm->id)); + } + + public function __wakeup() { + require_once($this->assignmentfile); + $this->assignment = unserialize(serialize($this->assignment)); + } +} + + ?> diff --git a/mod/assignment/type/online/assignment.class.php b/mod/assignment/type/online/assignment.class.php index 6b33757e04..b7c9ca5694 100644 --- a/mod/assignment/type/online/assignment.class.php +++ b/mod/assignment/type/online/assignment.class.php @@ -1,6 +1,6 @@ libdir.'/formslib.php'); - +require_once($CFG->dirroot . '/mod/assignment/lib.php'); /** * Extend the base assignment class for assignments where you upload a single file * @@ -103,6 +103,11 @@ class assignment_online extends assignment_base { print_box_start('generalbox boxwidthwide boxaligncenter', 'online'); if ($submission) { echo format_text($submission->data1, $submission->data2); + $p = array( + 'userid' => $USER->id, + 'assignmentid' => $this->cm->id, + ); + portfolio_add_button('assignment_portfolio_caller', $p); } else if (!has_capability('mod/assignment:submit', $context)) { //fix for #4604 echo '
'. get_string('guestnosubmit', 'assignment').'
'; } else if ($this->isopen()){ //fix for #4206 @@ -261,6 +266,9 @@ class assignment_online extends assignment_base { } + function portfolio_exportable() { + return true; + } } class mod_assignment_online_edit_form extends moodleform { diff --git a/mod/assignment/type/upload/assignment.class.php b/mod/assignment/type/upload/assignment.class.php index ada594bee7..c9753d2b85 100644 --- a/mod/assignment/type/upload/assignment.class.php +++ b/mod/assignment/type/upload/assignment.class.php @@ -1,5 +1,7 @@ libdir.'/formslib.php'); +require_once($CFG->libdir . '/portfoliolib.php'); +require_once($CFG->dirroot . '/mod/assignment/lib.php'); define('ASSIGNMENT_STATUS_SUBMITTED', 'submitted'); // student thinks it is finished define('ASSIGNMENT_STATUS_CLOSED', 'closed'); // teacher prevents more submissions @@ -358,6 +360,10 @@ class assignment_upload extends assignment_base { if ($basedir = $this->file_area($userid)) { if ($files = get_directory_list($basedir, 'responses')) { require_once($CFG->libdir.'/filelib.php'); + $p = array( + 'userid' => $userid, + 'assignmentid' => $this->cm->id, + ); foreach ($files as $key => $file) { $icon = mimeinfo('icon', $file); @@ -371,9 +377,16 @@ class assignment_upload extends assignment_base { $output .= ' ' .' '; } - + if (true) { // @todo replace with capability check + $p['file'] = $file; + $output .= portfolio_add_button('assignment_portfolio_caller', $p, false, true); + } $output .= '
'; } + if (true) { //@todo replace with check capability + unset($p['file']);// for all files + $output .= '
' . portfolio_add_button('assignment_portfolio_caller', $p, true, true); + } } } @@ -1057,6 +1070,10 @@ class assignment_upload extends assignment_base { } + function portfolio_exportable() { + return true; + } + } class mod_assignment_upload_notes_form extends moodleform { @@ -1079,4 +1096,6 @@ class mod_assignment_upload_notes_form extends moodleform { } } + + ?> diff --git a/mod/assignment/type/uploadsingle/assignment.class.php b/mod/assignment/type/uploadsingle/assignment.class.php index 12c13e4aa6..886117b587 100644 --- a/mod/assignment/type/uploadsingle/assignment.class.php +++ b/mod/assignment/type/uploadsingle/assignment.class.php @@ -179,6 +179,10 @@ class assignment_uploadsingle extends assignment_base { } + function portfolio_exportable() { + return true; + } + } ?> diff --git a/portfolio/add.php b/portfolio/add.php new file mode 100644 index 0000000000..0f9edae5c2 --- /dev/null +++ b/portfolio/add.php @@ -0,0 +1,112 @@ +libdir . '/portfoliolib.php'); + +$exporter = null; +if (isset($SESSION->portfolio) && isset($SESSION->portfolio->exporter)) { + $exporter = unserialize(serialize($SESSION->portfolio->exporter)); + if ($exporter->instancefile) { + require_once($CFG->dirroot . '/' . $exporter->instancefile); + } + require_once($CFG->dirroot . '/' . $exporter->callerfile); + $exporter = unserialize(serialize($SESSION->portfolio->exporter)); + $SESSION->portfolio->exporter =& $exporter; + if ($instance = optional_param('instance', 0, PARAM_INT)) { + $instance = portfolio_instance($instance); + if ($broken = portfolio_instance_sanity_check($instance)) { + print_error(get_string($broken[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))); + } + $instance->set('user', $USER); + $exporter->set('instance', $instance); + + } +} else { + // we'e just posted here for the first time and have might the instance already + if ($instance = optional_param('instance', 0, PARAM_INT)) { + $instance = portfolio_instance($instance); + if ($broken = portfolio_instance_sanity_check($instance)) { + print_error(get_string($broken[$instance->get('id')], 'portfolio_' . $instance->get('plugin'))); + } + $instance->set('user', $USER); + } else { + $instance = null; + } + + $callbackfile = required_param('callbackfile', PARAM_PATH); + $callbackclass = required_param('callbackclass', PARAM_ALPHAEXT); + + $callbackargs = array(); + foreach (array_keys($_POST) as $key) { + if (strpos($key, 'ca_') === 0) { + if (!$value = optional_param($key, false, PARAM_ALPHAEXT)) { + if (!$value = optional_param($key, false, PARAM_NUMBER)) { + $value = optional_param($key, false, PARAM_PATH); + } + } + $callbackargs[substr($key, 3)] = $value; + } + } + require_once($CFG->dirroot . $callbackfile); + $caller = new $callbackclass($callbackargs); + if (!$caller->check_permissions()) { + print_error('nopermissions', 'portfolio', $caller->get_return_url()); + } + $caller->set('user', $USER); + + // for build navigation + if (!$course = $caller->get('course')) { + $course = optional_param('course', 0, PARAM_INT); + } + + if (!empty($course)) { + $COURSE = $DB->get_record('course', array('id' => $course), 'id,shortname,fullname'); + // this is yuk but used in build_navigation + } + + list($extranav, $cm) = $caller->get_navigation(); + $extranav[] = array('type' => 'title', 'name' => get_string('exporting', 'portfolio')); + $navigation = build_navigation($extranav, $cm); + + $exporter = new portfolio_exporter($instance, $caller, $callbackfile, $navigation); + $exporter->set('user', $USER); + $SESSION->portfolio = new StdClass; + $SESSION->portfolio->exporter =& $exporter; +} + + +$stage = optional_param('stage', PORTFOLIO_STAGE_CONFIG); +$alreadystolen = false; +// for places returning control to pass (rather than PORTFOLIO_STAGE_PACKAGE +// which is unstable if they can't get to the constant (eg external system) +if ($postcontrol = optional_param('postcontrol', 0, PARAM_INT)) { + $stage = $SESSION->portfolio->stagepresteal; + $exporter->instance()->post_control($stage, array_merge($_GET, $_POST)); + $alreadystolen = true; +} + +if (!$exporter->get('instance')) { + // we've just arrived but have no instance + // so retrieve everything from the request, + // add them as hidden fields in a new form + // to select the instance and post back here again + // for the next block to catch + $form = '
' . "\n"; + + if (!$select = portfolio_instance_select(portfolio_instances(), $exporter->get('caller')->supported_formats(), get_class($exporter->get('caller')))) { + print_error('noavailableplugins', 'portfolio'); + } + $form .= $select; + $form .= ''; + $form .= '
' . "\n"; + $exporter->print_header(); + print_heading(get_string('selectplugin', 'portfolio')); + print_simple_box_start(); + echo $form; + print_simple_box_end(); + print_footer(); + exit; +} + +$exporter->process_stage($stage, $alreadystolen); + +?> diff --git a/portfolio/type/boxnet/lib.php b/portfolio/type/boxnet/lib.php new file mode 100644 index 0000000000..c8d8ff1d37 --- /dev/null +++ b/portfolio/type/boxnet/lib.php @@ -0,0 +1,202 @@ +libdir.'/filelib.php'); +require_once($CFG->dirroot.'/repository/boxnet/boxlibphp5.php'); + +class portfolio_plugin_boxnet extends portfolio_plugin_base { + + private $boxclient; + private $ticket; + private $authtoken; + private $workdir; + private $folders; + + public static function supported_formats() { + return array(PORTFOLIO_FORMAT_FILE, PORTFOLIO_FORMAT_HTML); + } + + public function prepare_package($tempdir) { + $this->workdir = $tempdir; + return true; // don't do anything else for this plugin, we want to send all files as they are. + } + + public function send_package() { + $ret = array(); + foreach (get_directory_list($this->workdir) as $file) { + $file = $this->workdir . '/' . $file; + $ret[] = $this->boxclient->uploadFile( + array( + 'file' => $file, + 'folder_id' => $this->get_export_config('folder') + ) + ); + } + if ($this->boxclient->isError()) { + return false; + } + return is_array($ret) && !empty($ret); + } + + public function set_export_config($config) { + parent::set_export_config($config); + if (array_key_exists('newfolder', $config) && !empty($config['newfolder'])) { + if (!$created = $this->boxclient->createFolder($config['newfolder'])) { + portfolio_exporter::raise_error('foldercreatefailed', 'portfolio_boxnet'); + } + $this->folders[$created['folder_id']] = $created['folder_type']; + parent::set_export_config(array('folder' => $created['folder_id'])); + } + } + + public function get_export_summary() { + $allfolders = $this->get_folder_list(); + return array( + get_string('targetfolder', 'portfolio_boxnet') => $allfolders[$this->get_export_config('folder')] + ); + } + + public function get_continue_url() { + // @todo this was a *guess* based on what urls I got clicking around the interface. + // the #0:f: part seems fragile... + // but I couldn't find a documented permalink scheme. + return 'http://box.net/files#0:f:' . $this->get_export_config('folder'); + } + + public function expected_time($callertime) { + return $callertime; + } + + public static function has_admin_config() { + return true; + } + + public static function get_allowed_config() { + return array('apikey'); + } + + public function has_export_config() { + return true; + } + + public function get_allowed_user_config() { + return array('authtoken', 'authtokenctime'); + } + + public function get_allowed_export_config() { + return array('folder', 'newfolder'); + } + + public function export_config_form(&$mform) { + $folders = $this->get_folder_list(); + $strrequired = get_string('required'); + $mform->addElement('text', 'plugin_newfolder', get_string('newfolder', 'portfolio_boxnet')); + if (empty($folders)) { + $mform->addRule('plugin_newfolder', $strrequired, 'required', null, 'client'); + } + else { + $mform->addElement('select', 'plugin_folder', get_string('existingfolder', 'portfolio_boxnet'), $folders); + } + } + + public function export_config_validation($data) { + if ((!array_key_exists('plugin_folder', $data) || empty($data['plugin_folder'])) + && (!array_key_exists('plugin_newfolder', $data) || empty($data['plugin_newfolder']))) { + return array( + 'plugin_folder' => get_string('notarget', 'portfolio_boxnet'), + 'plugin_newfolder' => get_string('notarget', 'portfolio_boxnet')); + } + $allfolders = $this->get_folder_list(); + if (in_array($data['plugin_newfolder'], $allfolders)) { + return array('plugin_newfolder' => get_string('folderclash', 'portfolio_boxnet')); + } + } + + public function admin_config_form(&$mform) { + $strrequired = get_string('required'); + $mform->addElement('text', 'apikey', get_string('apikey', 'portfolio_boxnet')); + $mform->addRule('apikey', $strrequired, 'required', null, 'client'); + } + + public function steal_control($stage) { + if ($stage != PORTFOLIO_STAGE_CONFIG) { + return false; + } + if ($this->authtoken) { + return false; + } + if (!$this->ensure_ticket()) { + portfolio_exporter::raise_error('noticket', 'portfolio_boxnet'); + } + $token = $this->get_user_config('authtoken', $this->get('user')->id); + $ctime= $this->get_user_config('authtokenctime', $this->get('user')->id); + if (!empty($token) && (($ctime + 60*60*20) > time())) { + $this->authtoken = $token; + $this->boxclient->auth_token = $token; + return false; + } + return 'http://www.box.net/api/1.0/auth/'.$this->ticket; + } + + public function post_control($stage, $params) { + if ($stage != PORTFOLIO_STAGE_CONFIG) { + return; + } + if (!array_key_exists('auth_token', $params) || empty($params['auth_token'])) { + portfolio_exporter::raise_error('noauthtoken', 'portfolio_boxnet'); + } + $this->authtoken = $params['auth_token']; + $this->boxclient->auth_token = $this->authtoken; + $this->set_user_config(array('authtoken' => $this->authtoken, 'authtokenctime' => time()), $this->get('user')->id); + } + + private function ensure_ticket() { + if (!empty($this->boxclient)) { + return true; + } + $this->boxclient = new boxclient($this->get_config('apikey'), ''); + $ticket_return = $this->boxclient->getTicket(); + if ($this->boxclient->isError() || empty($ticket_return)) { + portfolio_exporter::raise_error('noticket', 'portfolio_boxnet'); + } + $this->ticket = $ticket_return['ticket']; + } + + private function get_folder_list() { + if (!empty($this->folders)) { + return $this->folders; + } + if (empty($this->ticket) + || empty($this->authtoken) + || empty($this->boxclient)) { + // if we don't have these we're pretty much screwed + portfolio_exporter::raise_error('folderlistfailed', 'portfolio_boxnet'); + return false; + } + $rawfolders = $this->boxclient->getAccountTree(); + if ($this->boxclient->isError()) { + portfolio_exporter::raise_error('folderlistfailed', 'portfolio_boxnet'); + } + if (!is_array($rawfolders)) { + return false; + } + $folders = array(); + foreach ($rawfolders['folder_id'] as $key => $id) { + if (empty($id)) { + continue; + } + $name = $rawfolders['folder_name'][$key]; + if (!empty($rawfolders['shared'][$key])) { + $name .= ' (' . get_string('sharedfolder', 'portfolio_boxnet') . ')'; + } + $folders[$id] = $name; + } + $this->folders = $folders; + return $folders; + } + + public function instance_sanity_check() { + if (!$this->get_config('apikey')) { + return 'err_noapikey'; + } + //@TODO see if we can verify the api key without actually getting an authentication token + } +} diff --git a/portfolio/type/boxnet/version.php b/portfolio/type/boxnet/version.php new file mode 100644 index 0000000000..1a00826079 --- /dev/null +++ b/portfolio/type/boxnet/version.php @@ -0,0 +1,7 @@ +version = 2008072500; +$plugin->requires = 2008072500; +$plugin->cron = 0; + +?> diff --git a/portfolio/type/download/lib.php b/portfolio/type/download/lib.php new file mode 100644 index 0000000000..7031857427 --- /dev/null +++ b/portfolio/type/download/lib.php @@ -0,0 +1,57 @@ +libdir . '/portfoliolib.php'); + +class portfolio_plugin_download extends portfolio_plugin_base { + + protected $zipfile; + protected $exportconfig; + + public static function supported_formats() { + return array(PORTFOLIO_FORMAT_FILE, PORTFOLIO_FORMAT_HTML); + // @todo more later, like moodle backup for example + } + + public static function allows_multiple() { + return false; + } + + public function expected_time($callertime) { + return PORTFOLIO_TIME_LOW; + } + + public function prepare_package($tempdir) { + // just zip up whatever files the caller has created for us + // and move them to the user's temporary area. + $userdir = temp_portfolio_usertemp_directory($this->get('user')->id); + + $newfile = 'portfolio_export_' . time() . '.zip'; + $files = get_directory_list($tempdir); + foreach ($files as $key => $file) { + $files[$key] = $tempdir . '/' . $file; + } + + zip_files($files, $userdir . '/' . $newfile); + $this->set('zipfile', $newfile); + + return true; + } + + public function send_package() { + return true; + } + + public function get_extra_finish_options() { + global $CFG; + return array( + // @todo this will go through files api later, this is a (nonworking) hack for now. + $CFG->wwwroot . '/file.php?file=' . $this->zipfile => get_string('downloadfile', 'portfolio_download'), + ); + } + + public function get_continue_url() { + return false; + } +} + +?> diff --git a/portfolio/type/download/version.php b/portfolio/type/download/version.php new file mode 100644 index 0000000000..1a00826079 --- /dev/null +++ b/portfolio/type/download/version.php @@ -0,0 +1,7 @@ +version = 2008072500; +$plugin->requires = 2008072500; +$plugin->cron = 0; + +?> diff --git a/theme/standard/styles_layout.css b/theme/standard/styles_layout.css index 18ad6f39e5..c8e580cd67 100644 --- a/theme/standard/styles_layout.css +++ b/theme/standard/styles_layout.css @@ -661,6 +661,9 @@ div.phpinfo .center th { margin:0px 20px 0px 20px; } +#portfolio-add-button { + display:inline; +} /*** *** Header diff --git a/user/portfolio.php b/user/portfolio.php new file mode 100644 index 0000000000..934427abf0 --- /dev/null +++ b/user/portfolio.php @@ -0,0 +1,96 @@ +libdir . '/portfoliolib.php'); + +$config = optional_param('config', 0, PARAM_INT); +$hide = optional_param('hide', 0, PARAM_INT); + +$course = optional_param('course', SITEID, PARAM_INT); + +if (! $course = $DB->get_record("course", array("id"=>$course))) { + print_error('invalidcourseid'); +} + +$user = $USER; +$fullname = fullname($user); +$strportfolios = get_string('portfolios', 'portfolio'); +$configstr = get_string('manageyourportfolios', 'portfolio'); +$namestr = get_string('name'); +$pluginstr = get_string('plugin', 'portfolio'); +$baseurl = $CFG->wwwroot . '/user/portfolio.php'; + +$display = true; // set this to false in the conditions to stop processing + +require_login($course, false); + +$navlinks[] = array('name' => $fullname, 'link' => $CFG->wwwroot . '/user/view.php?id=' . $user->id, 'type' => 'misc'); +$navlinks[] = array('name' => $strportfolios, 'link' => null, 'type' => 'misc'); + +$navigation = build_navigation($navlinks); + +print_header("$course->fullname: $fullname: $strportfolios", $course->fullname, + $navigation, "", "", true, " ", navmenu($course)); + +$currenttab = 'portfolios'; +$showroles = 1; +include('tabs.php'); + +if (!empty($config)) { + $instance = portfolio_instance($config); + $mform = new portfolio_user_form('', array('instance' => $instance, 'userid' => $user->id)); + if ($mform->is_cancelled()){ + redirect($baseurl); + exit; + } else if ($fromform = $mform->get_data()){ + if (!confirm_sesskey()) { + print_error('confirmsesskeybad', '', $baseurl); + } + //this branch is where you process validated data. + $success = $instance->set_user_config($fromform, $USER->id); + //$success = $success && $instance->save(); + if ($success) { + redirect($baseurl, get_string('instancesaved', 'portfolio'), 3); + } else { + print_error('instancenotsaved', 'portfolio', $baseurl); + } + exit; + } else { + print_heading(get_string('configplugin', 'portfolio')); + print_simple_box_start(); + $mform->display(); + print_simple_box_end(); + $display = false; + } + +} else if (!empty($hide)) { + $instance = portfolio_instance($hide); + $instance->set_user_config(array('visible' => !$instance->get_user_config('visible', $USER->id)), $USER->id); +} + +if ($display) { + print_heading($configstr); + print_simple_box_start(); + + if (!$instances = portfolio_instances(true, false)) { + print_error('noinstances', 'portfolio', $CFG->wwwroot . '/user/view.php'); + } + + $table = new StdClass; + $table->head = array($namestr, $pluginstr, ''); + $table->data = array(); + + foreach ($instances as $i) { + $visible = $i->get_user_config('visible', $USER->id); + $table->data[] = array($i->get('name'), $i->get('plugin'), + ($i->has_user_config()) + ? '' . get_string('configure') . '' : '') . + ' ' . get_string($visible ? 'hide' : 'show') . '
' + ); + } + + print_table($table); +} +print_footer(); + +?> diff --git a/user/tabs.php b/user/tabs.php index 8dc6152f41..815d909094 100644 --- a/user/tabs.php +++ b/user/tabs.php @@ -238,6 +238,13 @@ } } } + + if ($user->id == $USER->id) { + require_once($CFG->libdir . '/portfoliolib.php'); + if (portfolio_instances(true, false)) { + // @todo permissions check? + $toprow[] = new tabobject('portfolios', $CFG->wwwroot .'/user/portfolio.php', get_string('portfolios', 'portfolio')); + } ///added a new messaging tab if (has_capability('moodle/user:editownmessageprofile', $systemcontext)) { diff --git a/version.php b/version.php index 7eb78d0d8d..8105688185 100644 --- a/version.php +++ b/version.php @@ -6,7 +6,7 @@ // This is compared against the values stored in the database to determine // whether upgrades should be performed (see lib/db/*.php) - $version = 2008072403; // YYYYMMDD = date of the last version bump + $version = 2008072500; // YYYYMMDD = date of the last version bump // XX = daily increments $release = '2.0 dev (Build: 20080725)'; // Human-friendly version name -- 2.39.5