';
break;
case PORTFOLIO_ADD_ICON_LINK:
$linkoutput = $OUTPUT->action_icon($url, new pix_icon('t/portfolioadd', $addstr, '',
array('class' => 'portfolio-add-icon smallicon')));
break;
case PORTFOLIO_ADD_TEXT_LINK:
$linkoutput = html_writer::link($url, $addstr, array('class' => 'portfolio-add-link',
'title' => $addstr));
break;
default:
debugging(get_string('invalidaddformat', 'portfolio', $format));
}
$output = (in_array($format, array(PORTFOLIO_ADD_FULL_FORM, PORTFOLIO_ADD_ICON_FORM)) ? $formoutput : $linkoutput);
return $output;
}
/**
* Perform some internal checks.
* These are not errors, just situations
* where it's not appropriate to add the button
*
* @return bool
*/
private function is_renderable() {
global $CFG;
if (empty($CFG->enableportfolios)) {
return false;
}
if (defined('PORTFOLIO_INTERNAL')) {
// something somewhere has detected a risk of this being called during inside the preparation
// eg forum_print_attachments
return false;
}
if (empty($this->instances) || count($this->instances) == 0) {
return false;
}
return true;
}
/**
* Getter for $format property
*
* @return array
*/
public function get_formats() {
return $this->formats;
}
/**
* Getter for $callbackargs property
*
* @return array
*/
public function get_callbackargs() {
return $this->callbackargs;
}
/**
* Getter for $callbackcomponent property
*
* @return string
*/
public function get_callbackcomponent() {
return $this->callbackcomponent;
}
/**
* Getter for $callbackclass property
*
* @return string
*/
public function get_callbackclass() {
return $this->callbackclass;
}
}
/**
* Returns a drop menu with a list of available instances.
*
* @param array $instances array of portfolio plugin instance objects - the instances to put in the menu
* @param array $callerformats array of PORTFOLIO_FORMAT_XXX constants - the formats the caller supports (this is used to filter plugins)
* @param string $callbackclass the callback class name - used for debugging only for when there are no common formats
* @param string $mimetype if we already know we have exactly one file, or are going to write one, pass it here to do mime filtering.
* @param string $selectname the name of the select element. Optional, defaults to instance.
* @param bool $return whether to print or return the output. Optional, defaults to print.
* @param bool $returnarray if returning, whether to return the HTML or the array of options. Optional, defaults to HTML.
* @return void|array|string the html, from inclusive.
*/
function portfolio_instance_select($instances, $callerformats, $callbackclass, $mimetype=null, $selectname='instance', $return=false, $returnarray=false) {
global $CFG, $USER;
if (empty($CFG->enableportfolios)) {
return;
}
$insane = portfolio_instance_sanity_check();
$pinsane = portfolio_plugin_sanity_check();
$count = 0;
$selectoutput = "\n" . '';
$selectoutput .= "\n" . '\n";
if (!empty($returnarray)) {
return $options;
}
if (!empty($return)) {
return $selectoutput;
}
echo $selectoutput;
}
/**
* Return all portfolio instances
*
* @todo MDL-15768 - check capabilities here
* @param bool $visibleonly Don't include hidden instances. Defaults to true and will be overridden to true if the next parameter is true
* @param bool $useronly Check the visibility preferences and permissions of the logged in user. Defaults to true.
* @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 ' . $DB->sql_compare_text('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[$instance->id] = portfolio_instance($instance->id, $instance);
}
return $instances;
}
/**
* Return whether there are visible instances in portfolio.
*
* @return bool true when there are some visible instances.
*/
function portfolio_has_visible_instances() {
global $DB;
return $DB->record_exists('portfolio_instance', array('visible' => 1));
}
/**
* Supported formats currently in use.
* Canonical place for a list of all formats
* that portfolio plugins and callers
* can use for exporting content
*
* @return array keyed array of all the available export formats (constant => classname)
*/
function portfolio_supported_formats() {
return array(
PORTFOLIO_FORMAT_FILE => 'portfolio_format_file',
PORTFOLIO_FORMAT_IMAGE => 'portfolio_format_image',
PORTFOLIO_FORMAT_RICHHTML => 'portfolio_format_richhtml',
PORTFOLIO_FORMAT_PLAINHTML => 'portfolio_format_plainhtml',
PORTFOLIO_FORMAT_TEXT => 'portfolio_format_text',
PORTFOLIO_FORMAT_VIDEO => 'portfolio_format_video',
PORTFOLIO_FORMAT_PDF => 'portfolio_format_pdf',
PORTFOLIO_FORMAT_DOCUMENT => 'portfolio_format_document',
PORTFOLIO_FORMAT_SPREADSHEET => 'portfolio_format_spreadsheet',
PORTFOLIO_FORMAT_PRESENTATION => 'portfolio_format_presentation',
/*PORTFOLIO_FORMAT_MBKP, */ // later
PORTFOLIO_FORMAT_LEAP2A => 'portfolio_format_leap2a',
PORTFOLIO_FORMAT_RICH => 'portfolio_format_rich',
);
}
/**
* Deduce export format from file mimetype
* This function returns the revelant portfolio export format
* which is used to determine which portfolio plugins can be used
* for exporting this content
* according to the given mime type
* this only works when exporting exactly one file, or generating a new one
* (like a pdf or csv export)
*
* @param string $mimetype (usually $file->get_mimetype())
* @return string the format constant (see PORTFOLIO_FORMAT_XXX constants)
*/
function portfolio_format_from_mimetype($mimetype) {
global $CFG;
static $alreadymatched;
if (empty($alreadymatched)) {
$alreadymatched = array();
}
if (array_key_exists($mimetype, $alreadymatched)) {
return $alreadymatched[$mimetype];
}
$allformats = portfolio_supported_formats();
require_once($CFG->libdir . '/portfolio/formats.php');
foreach ($allformats as $format => $classname) {
$supportedmimetypes = call_user_func(array($classname, 'mimetypes'));
if (!is_array($supportedmimetypes)) {
debugging("one of the portfolio format classes, $classname, said it supported something funny for mimetypes, should have been array...");
debugging(print_r($supportedmimetypes, true));
continue;
}
if (in_array($mimetype, $supportedmimetypes)) {
$alreadymatched[$mimetype] = $format;
return $format;
}
}
return PORTFOLIO_FORMAT_FILE; // base case for files...
}
/**
* Intersection of plugin formats and caller formats.
* Walks both the caller formats and portfolio plugin formats
* and looks for matches (walking the hierarchy as well)
* and returns the intersection
*
* @param array $callerformats formats the caller supports
* @param array $pluginformats formats the portfolio plugin supports
* @return array
*/
function portfolio_supported_formats_intersect($callerformats, $pluginformats) {
global $CFG;
$allformats = portfolio_supported_formats();
$intersection = array();
foreach ($callerformats as $cf) {
if (!array_key_exists($cf, $allformats)) {
if (!portfolio_format_is_abstract($cf)) {
debugging(get_string('invalidformat', 'portfolio', $cf));
}
continue;
}
require_once($CFG->libdir . '/portfolio/formats.php');
$cfobj = new $allformats[$cf]();
foreach ($pluginformats as $p => $pf) {
if (!array_key_exists($pf, $allformats)) {
if (!portfolio_format_is_abstract($pf)) {
debugging(get_string('invalidformat', 'portfolio', $pf));
}
unset($pluginformats[$p]); // to avoid the same warning over and over
continue;
}
if ($cfobj instanceof $allformats[$pf]) {
$intersection[] = $cf;
}
}
}
return $intersection;
}
/**
* Tiny helper to figure out whether a portfolio format is abstract
*
* @param string $format the format to test
* @return bool
*/
function portfolio_format_is_abstract($format) {
if (class_exists($format)) {
$class = $format;
} else if (class_exists('portfolio_format_' . $format)) {
$class = 'portfolio_format_' . $format;
} else {
$allformats = portfolio_supported_formats();
if (array_key_exists($format, $allformats)) {
$class = $allformats[$format];
}
}
if (empty($class)) {
return true; // it may as well be, we can't instantiate it :)
}
$rc = new ReflectionClass($class);
return $rc->isAbstract();
}
/**
* Return the combination of the two arrays of formats with duplicates in terms of specificity removed
* and also removes conflicting formats.
* Use case: a module is exporting a single file, so the general formats would be FILE and MBKP
* while the specific formats would be the specific subclass of FILE based on mime (say IMAGE)
* and this function would return IMAGE and MBKP
*
* @param array $specificformats array of more specific formats (eg based on mime detection)
* @param array $generalformats array of more general formats (usually more supported)
* @return array merged formats with dups removed
*/
function portfolio_most_specific_formats($specificformats, $generalformats) {
global $CFG;
$allformats = portfolio_supported_formats();
if (empty($specificformats)) {
return $generalformats;
} else if (empty($generalformats)) {
return $specificformats;
}
$removedformats = array();
foreach ($specificformats as $k => $f) {
// look for something less specific and remove it, ie outside of the inheritance tree of the current formats.
if (!array_key_exists($f, $allformats)) {
if (!portfolio_format_is_abstract($f)) {
throw new portfolio_button_exception('invalidformat', 'portfolio', $f);
}
}
if (in_array($f, $removedformats)) {
// already been removed from the general list
//debugging("skipping $f because it was already removed");
unset($specificformats[$k]);
}
require_once($CFG->libdir . '/portfolio/formats.php');
$fobj = new $allformats[$f];
foreach ($generalformats as $key => $cf) {
if (in_array($cf, $removedformats)) {
//debugging("skipping $cf because it was already removed");
continue;
}
$cfclass = $allformats[$cf];
$cfobj = new $allformats[$cf];
if ($fobj instanceof $cfclass && $cfclass != get_class($fobj)) {
//debugging("unsetting $key $cf because it's not specific enough ($f is better)");
unset($generalformats[$key]);
$removedformats[] = $cf;
continue;
}
// check for conflicts
if ($fobj->conflicts($cf)) {
//debugging("unsetting $key $cf because it conflicts with $f");
unset($generalformats[$key]);
$removedformats[] = $cf;
continue;
}
if ($cfobj->conflicts($f)) {
//debugging("unsetting $key $cf because it reverse-conflicts with $f");
$removedformats[] = $cf;
unset($generalformats[$key]);
continue;
}
}
//debugging('inside loop');
//print_object($generalformats);
}
//debugging('final formats');
$finalformats = array_unique(array_merge(array_values($specificformats), array_values($generalformats)));
//print_object($finalformats);
return $finalformats;
}
/**
* Helper function to return a format object from the constant
*
* @param string $name the constant PORTFOLIO_FORMAT_XXX
* @return portfolio_format
*/
function portfolio_format_object($name) {
global $CFG;
require_once($CFG->libdir . '/portfolio/formats.php');
$formats = portfolio_supported_formats();
return new $formats[$name];
}
/**
* Helper function to return an instance of a plugin (with config loaded)
*
* @param int $instanceid id of instance
* @param object $record database row that corresponds to this instance
* this is passed to avoid unnecessary lookups
* Optional, and the record will be retrieved if null.
* @return object of portfolio_plugin_XXX
*/
function portfolio_instance($instanceid, $record=null) {
global $DB, $CFG;
if ($record) {
$instance = $record;
} else {
if (!$instance = $DB->get_record('portfolio_instance', array('id' => $instanceid))) {
throw new portfolio_exception('invalidinstance', 'portfolio');
}
}
require_once($CFG->libdir . '/portfolio/plugin.php');
require_once($CFG->dirroot . '/portfolio/'. $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
* @return mixed
*/
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->libdir . '/portfolio/plugin.php');
require_once($CFG->dirroot . '/portfolio/' . $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 array of supported plugin types
* @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 = core_component::get_plugin_list('portfolio');
$plugins = array_keys($plugins);
}
$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 array of plugin instances
* @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);
portfolio_insane_notify_admins($insane, true);
return $insane;
}
/**
* Helper function to display a table of plugins (or instances) and reasons for disabling
*
* @param array $insane array of portfolio plugin
* @param array $instances if reporting instances rather than whole plugins, pass the array (key = id, value = object) here
* @param bool $return option to deliver the report in html format or print it out directly to the page.
* @return void|string of portfolio report in html table format
*/
function portfolio_report_insane($insane, $instances=false, $return=false) {
global $OUTPUT;
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');
}
$output = $OUTPUT->notification($headerstr, 'notifyproblem');
$table = new html_table();
$table->head = array($pluginstr, '');
$table->data = array();
foreach ($insane as $plugin => $reason) {
if ($instances) {
$instance = $instances[$plugin];
$plugin = $instance->get('plugin');
$name = $instance->get('name');
} else {
$name = $plugin;
}
$table->data[] = array($name, get_string($reason, 'portfolio_' . $plugin));
}
$output .= html_writer::table($table);
$output .= '
';
if ($return) {
return $output;
}
echo $output;
}
/**
* Helper function to rethrow a caught portfolio_exception as an export exception.
* Used because when a portfolio_export exception is thrown the export is cancelled
* throws portfolio_export_exceptiog
*
* @param portfolio_exporter $exporter current exporter object
* @param object $exception exception to rethrow
*/
function portfolio_export_rethrow_exception($exporter, $exception) {
throw new portfolio_export_exception($exporter, $exception->errorcode, $exception->module, $exception->link, $exception->a);
}
/**
* Try and determine expected_time for purely file based exports
* or exports that might include large file attachments.
*
* @param stored_file|array $totest - either an array of stored_file objects or a single stored_file object
* @return string PORTFOLIO_TIME_XXX
*/
function portfolio_expected_time_file($totest) {
global $CFG;
if ($totest instanceof stored_file) {
$totest = array($totest);
}
$size = 0;
foreach ($totest as $file) {
if (!($file instanceof stored_file)) {
debugging('something weird passed to portfolio_expected_time_file - not stored_file object');
debugging(print_r($file, true));
continue;
}
$size += $file->get_filesize();
}
$fileinfo = portfolio_filesize_info();
$moderate = $high = 0; // avoid warnings
foreach (array('moderate', 'high') as $setting) {
$settingname = 'portfolio_' . $setting . '_filesize_threshold';
if (empty($CFG->{$settingname}) || !array_key_exists($CFG->{$settingname}, $fileinfo['options'])) {
debugging("weird or unset admin value for $settingname, using default instead");
$$setting = $fileinfo[$setting];
} else {
$$setting = $CFG->{$settingname};
}
}
if ($size < $moderate) {
return PORTFOLIO_TIME_LOW;
} else if ($size < $high) {
return PORTFOLIO_TIME_MODERATE;
}
return PORTFOLIO_TIME_HIGH;
}
/**
* The default filesizes and threshold information for file based transfers.
* This shouldn't need to be used outside the admin pages and the portfolio code
*
* @return array
*/
function portfolio_filesize_info() {
$filesizes = array();
$sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152, 5242880, 10485760, 20971520, 52428800);
foreach ($sizelist as $size) {
$filesizes[$size] = display_size($size);
}
return array(
'options' => $filesizes,
'moderate' => 1048576,
'high' => 5242880,
);
}
/**
* Try and determine expected_time for purely database based exports
* or exports that might include large parts of a database.
*
* @param int $recordcount number of records trying to export
* @return string PORTFOLIO_TIME_XXX
*/
function portfolio_expected_time_db($recordcount) {
global $CFG;
if (empty($CFG->portfolio_moderate_dbsize_threshold)) {
set_config('portfolio_moderate_dbsize_threshold', 10);
}
if (empty($CFG->portfolio_high_dbsize_threshold)) {
set_config('portfolio_high_dbsize_threshold', 50);
}
if ($recordcount < $CFG->portfolio_moderate_dbsize_threshold) {
return PORTFOLIO_TIME_LOW;
} else if ($recordcount < $CFG->portfolio_high_dbsize_threshold) {
return PORTFOLIO_TIME_MODERATE;
}
return PORTFOLIO_TIME_HIGH;
}
/**
* Function to send portfolio report to admins
*
* @param array $insane array of insane plugins
* @param array $instances (optional) if reporting instances rather than whole plugins
*/
function portfolio_insane_notify_admins($insane, $instances=false) {
global $CFG;
if (defined('ADMIN_EDITING_PORTFOLIO')) {
return true;
}
$admins = get_admins();
if (empty($admins)) {
return;
}
if ($instances) {
$instances = portfolio_instances(false, false);
}
$site = get_site();
$a = new StdClass;
$a->sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID)));
$a->fixurl = "$CFG->wwwroot/$CFG->admin/settings.php?section=manageportfolios";
$a->htmllist = portfolio_report_insane($insane, $instances, true);
$a->textlist = '';
foreach ($insane as $k => $reason) {
if ($instances) {
$a->textlist = $instances[$k]->get('name') . ': ' . $reason . "\n";
} else {
$a->textlist = $k . ': ' . $reason . "\n";
}
}
$subject = get_string('insanesubject', 'portfolio');
$plainbody = get_string('insanebody', 'portfolio', $a);
$htmlbody = get_string('insanebodyhtml', 'portfolio', $a);
$smallbody = get_string('insanebodysmall', 'portfolio', $a);
foreach ($admins as $admin) {
$eventdata = new \core\message\message();
$eventdata->courseid = SITEID;
$eventdata->modulename = 'portfolio';
$eventdata->component = 'portfolio';
$eventdata->name = 'notices';
$eventdata->userfrom = get_admin();
$eventdata->userto = $admin;
$eventdata->subject = $subject;
$eventdata->fullmessage = $plainbody;
$eventdata->fullmessageformat = FORMAT_PLAIN;
$eventdata->fullmessagehtml = $htmlbody;
$eventdata->smallmessage = $smallbody;
message_send($eventdata);
}
}
/**
* Setup page export
*
* @param moodle_page $PAGE global variable from page object
* @param portfolio_caller_base $caller plugin type caller
*/
function portfolio_export_pagesetup($PAGE, $caller) {
// set up the context so that build_navigation works nice
$caller->set_context($PAGE);
list($extranav, $cm) = $caller->get_navigation();
// and now we know the course for sure and maybe the cm, call require_login with it
require_login($PAGE->course, false, $cm);
foreach ($extranav as $navitem) {
$PAGE->navbar->add($navitem['name']);
}
$PAGE->navbar->add(get_string('exporting', 'portfolio'));
}
/**
* Get export type id
*
* @param string $type plugin type
* @param int $userid the user to check for
* @return mixed|bool
*/
function portfolio_export_type_to_id($type, $userid) {
global $DB;
$sql = 'SELECT t.id FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? AND i.plugin = ?';
return $DB->get_field_sql($sql, array($userid, $type));
}
/**
* Return a list of current exports for the given user.
* This will not go through and call rewaken_object, because it's heavy.
* It's really just used to figure out what exports are currently happening.
* This is useful for plugins that don't support multiple exports per session
*
* @param int $userid the user to check for
* @param string $type (optional) the portfolio plugin to filter by
* @return array
*/
function portfolio_existing_exports($userid, $type=null) {
global $DB;
$sql = 'SELECT t.*,t.instance,i.plugin,i.name FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
$values = array($userid);
if ($type) {
$sql .= ' AND i.plugin = ?';
$values[] = $type;
}
return $DB->get_records_sql($sql, $values);
}
/**
* Return an array of existing exports by type for a given user.
* This is much more lightweight than existing_exports because it only returns the types, rather than the whole serialised data
* so can be used for checking availability of multiple plugins at the same time.
* @see existing_exports
*
* @param int $userid the user to check for
* @return array
*/
function portfolio_existing_exports_by_plugin($userid) {
global $DB;
$sql = 'SELECT t.id,i.plugin FROM {portfolio_tempdata} t JOIN {portfolio_instance} i ON t.instance = i.id WHERE t.userid = ? ';
$values = array($userid);
return $DB->get_records_sql_menu($sql, $values);
}
/**
* Return default common options for {@link format_text()} when preparing a content to be exported.
* It is important not to apply filters and not to clean the HTML in format_text()
*
* @return stdClass
*/
function portfolio_format_text_options() {
$options = new stdClass();
$options->para = false;
$options->newlines = true;
$options->filter = false;
$options->noclean = true;
$options->overflowdiv = false;
return $options;
}
/**
* callback function from {@link portfolio_rewrite_pluginfile_urls}
* looks through preg_replace matches and replaces content with whatever the active portfolio export format says
*
* @param int $contextid module context id
* @param string $component module name (eg:mod_assignment)
* @param string $filearea normal file_area arguments
* @param int $itemid component item id
* @param portfolio_format $format exporter format type
* @param array $options extra options to pass through to the file_output function in the format (optional)
* @param array $matches internal matching
* @return object|array|string
*/
function portfolio_rewrite_pluginfile_url_callback($contextid, $component, $filearea, $itemid, $format, $options, $matches) {
$matches = $matches[0]; // No internal matching.
// Loads the HTML.
$dom = new DomDocument();
if (!$dom->loadHTML($matches)) {
return $matches;
}
// Navigates to the node.
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('/html/body/child::*');
if (empty($nodes) || count($nodes) > 1) {
// Unexpected sequence, none or too many nodes.
return $matches;
}
$dom = $nodes->item(0);
$attributes = array();
foreach ($dom->attributes as $attr => $node) {
$attributes[$attr] = $node->value;
}
// now figure out the file
$fs = get_file_storage();
$key = 'href';
if (!array_key_exists('href', $attributes) && array_key_exists('src', $attributes)) {
$key = 'src';
}
if (!array_key_exists($key, $attributes)) {
debugging('Couldn\'t find an attribute to use that contains @@PLUGINFILE@@ in portfolio_rewrite_pluginfile');
return $matches;
}
$filename = substr($attributes[$key], strpos($attributes[$key], '@@PLUGINFILE@@') + strlen('@@PLUGINFILE@@'));
$filepath = '/';
if (strpos($filename, '/') !== 0) {
$bits = explode('/', $filename);
$filename = array_pop($bits);
$filepath = implode('/', $bits);
}
if (!$file = $fs->get_file($contextid, $component, $filearea, $itemid, $filepath, urldecode($filename))) {
debugging("Couldn't find a file from the embedded path info context $contextid component $component filearea $filearea itemid $itemid filepath $filepath name $filename");
return $matches;
}
if (empty($options)) {
$options = array();
}
$options['attributes'] = $attributes;
return $format->file_output($file, $options);
}
/**
* Function to require any potential callback files, throwing exceptions
* if an issue occurs.
*
* @param string $component This is the name of the component in Moodle, eg 'mod_forum'
* @param string $class Name of the class containing the callback functions
* activity components should ALWAYS use their name_portfolio_caller
* other locations must use something unique
*/
function portfolio_include_callback_file($component, $class = null) {
global $CFG;
require_once($CFG->libdir . '/adminlib.php');
// It's possible that they are passing a file path rather than passing a component.
// We want to try and convert this to a component name, eg. mod_forum.
$pos = strrpos($component, '/');
if ($pos !== false) {
// Get rid of the first slash (if it exists).
$component = ltrim($component, '/');
// Get a list of valid plugin types.
$plugintypes = core_component::get_plugin_types();
// Assume it is not valid for now.
$isvalid = false;
// Go through the plugin types.
foreach ($plugintypes as $type => $path) {
// Getting the path relative to the dirroot.
$path = preg_replace('|^' . preg_quote($CFG->dirroot, '|') . '/|', '', $path);
if (strrpos($component, $path) === 0) {
// Found the plugin type.
$isvalid = true;
$plugintype = $type;
$pluginpath = $path;
}
}
// Throw exception if not a valid component.
if (!$isvalid) {
throw new coding_exception('Somehow a non-valid plugin path was passed, could be a hackz0r attempt, exiting.');
}
// Remove the file name.
$component = trim(substr($component, 0, $pos), '/');
// Replace the path with the type.
$component = str_replace($pluginpath, $plugintype, $component);
// Ok, replace '/' with '_'.
$component = str_replace('/', '_', $component);
// Place a debug message saying the third parameter should be changed.
debugging('The third parameter sent to the function set_callback_options should be the component name, not a file path, please update this.', DEBUG_DEVELOPER);
}
// Check that it is a valid component.
if (!get_component_version($component)) {
throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
}
// Obtain the component's location.
if (!$componentloc = core_component::get_component_directory($component)) {
throw new portfolio_button_exception('nocallbackcomponent', 'portfolio', '', $component);
}
// Check if the component contains the necessary file for the portfolio plugin.
// These are locallib.php, portfoliolib.php and portfolio_callback.php.
$filefound = false;
if (file_exists($componentloc . '/locallib.php')) {
$filefound = true;
require_once($componentloc . '/locallib.php');
}
if (file_exists($componentloc . '/portfoliolib.php')) {
$filefound = true;
debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
require_once($componentloc . '/portfoliolib.php');
}
if (file_exists($componentloc . '/portfolio_callback.php')) {
$filefound = true;
debugging('Please standardise your plugin by renaming your portfolio callback file to locallib.php, or if that file already exists moving the portfolio functionality there.', DEBUG_DEVELOPER);
require_once($componentloc . '/portfolio_callback.php');
}
// Ensure that we found a file we can use, if not throw an exception.
if (!$filefound) {
throw new portfolio_button_exception('nocallbackfile', 'portfolio', '', $component);
}
if (!is_null($class)) {
// If class is specified, check it exists and extends portfolio_caller_base.
if (!class_exists($class) || !is_subclass_of($class, 'portfolio_caller_base')) {
throw new portfolio_button_exception('nocallbackclass', 'portfolio', '', $class);
}
}
}
/**
* Go through all the @@PLUGINFILE@@ matches in some text,
* extract the file information and pass it back to the portfolio export format
* to regenerate the html to output
*
* @param string $text the text to search through
* @param int $contextid normal file_area arguments
* @param string $component module name
* @param string $filearea normal file_area arguments
* @param int $itemid normal file_area arguments
* @param portfolio_format $format the portfolio export format
* @param array $options additional options to be included in the plugin file url (optional)
* @return mixed
*/
function portfolio_rewrite_pluginfile_urls($text, $contextid, $component, $filearea, $itemid, $format, $options=null) {
$patterns = array(
'(<(a|A)[^<]*?href="@@PLUGINFILE@@/[^>]*?>.*?(a|A)>)',
'(<(img|IMG)\s[^<]*?src="@@PLUGINFILE@@/[^>]*?/?>)',
);
$pattern = '~' . implode('|', $patterns) . '~';
$callback = partial('portfolio_rewrite_pluginfile_url_callback', $contextid, $component, $filearea, $itemid, $format, $options);
return preg_replace_callback($pattern, $callback, $text);
}
// this function has to go last, because the regexp screws up syntax highlighting in some editors