';
$addable = 0;
//if no type is set, we can create all type of instance
if (!$typename) {
$instancehtml .= '
';
$instancehtml .= get_string('createrepository', 'repository');
$instancehtml .= '
';
$types = repository::get_editable_types($context);
foreach ($types as $type) {
if (!empty($type) && $type->get_visible()) {
// If the user does not have the permission to view the repository, it won't be displayed in
// the list of instances. Hiding the link to create new instances will prevent the
// user from creating them without being able to find them afterwards, which looks like a bug.
if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
continue;
}
$instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
if (!empty($instanceoptionnames)) {
$baseurl->param('new', $type->get_typename());
$instancehtml .= '- '.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '
';
$baseurl->remove_params('new');
$addable++;
}
}
}
$instancehtml .= '
';
} else {
$instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
if (!empty($instanceoptionnames)) { //create a unique type of instance
$addable = 1;
$baseurl->param('new', $typename);
$output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
$baseurl->remove_params('new');
}
}
if ($addable) {
$instancehtml .= '
';
$output .= $instancehtml;
}
$output .= $OUTPUT->box_end();
//print the list + creation links
print($output);
}
/**
* Prepare file reference information
*
* @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
* @return string file reference, ready to be stored
*/
public function get_file_reference($source) {
if ($source && $this->has_moodle_files()) {
$params = @json_decode(base64_decode($source), true);
if (!is_array($params) || empty($params['contextid'])) {
throw new repository_exception('invalidparams', 'repository');
}
$params = array(
'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
'contextid' => clean_param($params['contextid'], PARAM_INT)
);
// Check if context exists.
if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
throw new repository_exception('invalidparams', 'repository');
}
return file_storage::pack_reference($params);
}
return $source;
}
/**
* Get a unique file path in which to save the file.
*
* The filename returned will be removed at the end of the request and
* should not be relied upon to exist in subsequent requests.
*
* @param string $filename file name
* @return file path
*/
public function prepare_file($filename) {
if (empty($filename)) {
$filename = 'file';
}
return sprintf('%s/%s', make_request_directory(), $filename);
}
/**
* Does this repository used to browse moodle files?
*
* @return bool
*/
public function has_moodle_files() {
return false;
}
/**
* Return file URL, for most plugins, the parameter is the original
* url, but some plugins use a file id, so we need this function to
* convert file id to original url.
*
* @param string $url the url of file
* @return string
*/
public function get_link($url) {
return $url;
}
/**
* Downloads a file from external repository and saves it in temp dir
*
* Function get_file() must be implemented by repositories that support returntypes
* FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
* to moodle. This function is not called for moodle repositories, the function
* {@link repository::copy_to_area()} is used instead.
*
* This function can be overridden by subclass if the files.reference field contains
* not just URL or if request should be done differently.
*
* @see curl
* @throws file_exception when error occured
*
* @param string $url the content of files.reference field, in this implementaion
* it is asssumed that it contains the string with URL of the file
* @param string $filename filename (without path) to save the downloaded file in the
* temporary directory, if omitted or file already exists the new filename will be generated
* @return array with elements:
* path: internal location of the file
* url: URL to the source (from parameters)
*/
public function get_file($url, $filename = '') {
global $CFG;
$path = $this->prepare_file($filename);
$c = new curl;
$result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorygetfiletimeout));
if ($result !== true) {
throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
}
return array('path'=>$path, 'url'=>$url);
}
/**
* Downloads the file from external repository and saves it in moodle filepool.
* This function is different from {@link repository::sync_reference()} because it has
* bigger request timeout and always downloads the content.
*
* This function is invoked when we try to unlink the file from the source and convert
* a reference into a true copy.
*
* @throws exception when file could not be imported
*
* @param stored_file $file
* @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
*/
public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
if (!$file->is_external_file()) {
// nothing to import if the file is not a reference
return;
} else if ($file->get_repository_id() != $this->id) {
// error
debugging('Repository instance id does not match');
return;
} else if ($this->has_moodle_files()) {
// files that are references to local files are already in moodle filepool
// just validate the size
if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
$maxbytesdisplay = display_size($maxbytes);
throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
'size' => $maxbytesdisplay));
}
return;
} else {
if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
// note that stored_file::get_filesize() also calls synchronisation
$maxbytesdisplay = display_size($maxbytes);
throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
'size' => $maxbytesdisplay));
}
$fs = get_file_storage();
// If a file has been downloaded, the file record should report both a positive file
// size, and a contenthash which does not related to empty content.
// If thereis no file size, or the contenthash is for an empty file, then the file has
// yet to be successfully downloaded.
$contentexists = $file->get_filesize() && !$file->compare_to_string('');
if (!$file->get_status() && $contentexists) {
// we already have the content in moodle filepool and it was synchronised recently.
// Repositories may overwrite it if they want to force synchronisation anyway!
return;
} else {
// attempt to get a file
try {
$fileinfo = $this->get_file($file->get_reference());
if (isset($fileinfo['path'])) {
$file->set_synchronised_content_from_file($fileinfo['path']);
} else {
throw new moodle_exception('errorwhiledownload', 'repository', '', '');
}
} catch (Exception $e) {
if ($contentexists) {
// better something than nothing. We have a copy of file. It's sync time
// has expired but it is still very likely that it is the last version
} else {
throw($e);
}
}
}
}
}
/**
* Return size of a file in bytes.
*
* @param string $source encoded and serialized data of file
* @return int file size in bytes
*/
public function get_file_size($source) {
// TODO MDL-33297 remove this function completely?
$browser = get_file_browser();
$params = unserialize(base64_decode($source));
$contextid = clean_param($params['contextid'], PARAM_INT);
$fileitemid = clean_param($params['itemid'], PARAM_INT);
$filename = clean_param($params['filename'], PARAM_FILE);
$filepath = clean_param($params['filepath'], PARAM_PATH);
$filearea = clean_param($params['filearea'], PARAM_AREA);
$component = clean_param($params['component'], PARAM_COMPONENT);
$context = context::instance_by_id($contextid);
$file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
if (!empty($file_info)) {
$filesize = $file_info->get_filesize();
} else {
$filesize = null;
}
return $filesize;
}
/**
* Return is the instance is visible
* (is the type visible ? is the context enable ?)
*
* @return bool
*/
public function is_visible() {
$type = repository::get_type_by_id($this->options['typeid']);
$instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
if ($type->get_visible()) {
//if the instance is unique so it's visible, otherwise check if the instance has a enabled context
if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
return true;
}
}
return false;
}
/**
* Can the instance be edited by the current user?
*
* The property $readonly must not be used within this method because
* it only controls if the options from self::get_instance_option_names()
* can be edited.
*
* @return bool true if the user can edit the instance.
* @since Moodle 2.5
*/
public final function can_be_edited_by_user() {
global $USER;
// We need to be able to explore the repository.
try {
$this->check_capability();
} catch (repository_exception $e) {
return false;
}
$repocontext = context::instance_by_id($this->instance->contextid);
if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
// If the context of this instance is a user context, we need to be this user.
return false;
} else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
// We need to have permissions on the course to edit the instance.
return false;
} else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
// Do not meet the requirements for the context system.
return false;
}
return true;
}
/**
* Return the name of this instance, can be overridden.
*
* @return string
*/
public function get_name() {
if ($name = $this->instance->name) {
return $name;
} else {
return get_string('pluginname', 'repository_' . $this->get_typename());
}
}
/**
* Is this repository accessing private data?
*
* This function should return true for the repositories which access external private
* data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
* which authenticate the user and then store the auth token.
*
* Of course, many repositories store 'private data', but we only want to set
* contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
* to by the users having the capability to 'login as' someone else. For instance, the repository
* 'Private files' is not considered as private because it's part of Moodle.
*
* You should not set contains_private_data() to true on repositories which allow different types
* of instances as the levels other than 'user' are, by definition, not private. Also
* the user instances will be protected when they need to.
*
* @return boolean True when the repository accesses private external data.
* @since Moodle 2.5
*/
public function contains_private_data() {
return true;
}
/**
* What kind of files will be in this repository?
*
* @return array return '*' means this repository support any files, otherwise
* return mimetypes of files, it can be an array
*/
public function supported_filetypes() {
// return array('text/plain', 'image/gif');
return '*';
}
/**
* Tells how the file can be picked from this repository
*
* Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
*
* @return int
*/
public function supported_returntypes() {
return (FILE_INTERNAL | FILE_EXTERNAL);
}
/**
* Tells how the file can be picked from this repository
*
* Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
*
* @return int
*/
public function default_returntype() {
return FILE_INTERNAL;
}
/**
* Provide repository instance information for Ajax
*
* @return stdClass
*/
final public function get_meta() {
global $CFG, $OUTPUT;
$meta = new stdClass();
$meta->id = $this->id;
$meta->name = format_string($this->get_name());
$meta->type = $this->get_typename();
$meta->icon = $OUTPUT->image_url('icon', 'repository_'.$meta->type)->out(false);
$meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
$meta->return_types = $this->supported_returntypes();
$meta->defaultreturntype = $this->default_returntype();
$meta->sortorder = $this->options['sortorder'];
return $meta;
}
/**
* Create an instance for this plug-in
*
* @static
* @param string $type the type of the repository
* @param int $userid the user id
* @param stdClass $context the context
* @param array $params the options for this instance
* @param int $readonly whether to create it readonly or not (defaults to not)
* @return mixed
*/
public static function create($type, $userid, $context, $params, $readonly=0) {
global $CFG, $DB;
$params = (array)$params;
require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
$classname = 'repository_' . $type;
if ($repo = $DB->get_record('repository', array('type'=>$type))) {
$record = new stdClass();
$record->name = $params['name'];
$record->typeid = $repo->id;
$record->timecreated = time();
$record->timemodified = time();
$record->contextid = $context->id;
$record->readonly = $readonly;
$record->userid = $userid;
$id = $DB->insert_record('repository_instances', $record);
cache::make('core', 'repositories')->purge();
$options = array();
$configs = call_user_func($classname . '::get_instance_option_names');
if (!empty($configs)) {
foreach ($configs as $config) {
if (isset($params[$config])) {
$options[$config] = $params[$config];
} else {
$options[$config] = null;
}
}
}
if (!empty($id)) {
unset($options['name']);
$instance = repository::get_instance($id);
$instance->set_option($options);
return $id;
} else {
return null;
}
} else {
return null;
}
}
/**
* delete a repository instance
*
* @param bool $downloadcontents
* @return bool
*/
final public function delete($downloadcontents = false) {
global $DB;
if ($downloadcontents) {
$this->convert_references_to_local();
} else {
$this->remove_files();
}
cache::make('core', 'repositories')->purge();
try {
$DB->delete_records('repository_instances', array('id'=>$this->id));
$DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
} catch (dml_exception $ex) {
return false;
}
return true;
}
/**
* Delete all the instances associated to a context.
*
* This method is intended to be a callback when deleting
* a course or a user to delete all the instances associated
* to their context. The usual way to delete a single instance
* is to use {@link self::delete()}.
*
* @param int $contextid context ID.
* @param boolean $downloadcontents true to convert references to hard copies.
* @return void
*/
final public static function delete_all_for_context($contextid, $downloadcontents = true) {
global $DB;
$repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
if ($downloadcontents) {
foreach ($repoids as $repoid) {
$repo = repository::get_repository_by_id($repoid, $contextid);
$repo->convert_references_to_local();
}
}
cache::make('core', 'repositories')->purge();
$DB->delete_records_list('repository_instances', 'id', $repoids);
$DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
}
/**
* Hide/Show a repository
*
* @param string $hide
* @return bool
*/
final public function hide($hide = 'toggle') {
global $DB;
if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
if ($hide === 'toggle' ) {
if (!empty($entry->visible)) {
$entry->visible = 0;
} else {
$entry->visible = 1;
}
} else {
if (!empty($hide)) {
$entry->visible = 0;
} else {
$entry->visible = 1;
}
}
return $DB->update_record('repository', $entry);
}
return false;
}
/**
* Save settings for repository instance
* $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
*
* @param array $options settings
* @return bool
*/
public function set_option($options = array()) {
global $DB;
if (!empty($options['name'])) {
$r = new stdClass();
$r->id = $this->id;
$r->name = $options['name'];
$DB->update_record('repository_instances', $r);
unset($options['name']);
}
foreach ($options as $name=>$value) {
if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
$DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
} else {
$config = new stdClass();
$config->instanceid = $this->id;
$config->name = $name;
$config->value = $value;
$DB->insert_record('repository_instance_config', $config);
}
}
cache::make('core', 'repositories')->purge();
return true;
}
/**
* Get settings for repository instance.
*
* @param string $config a specific option to get.
* @return mixed returns an array of options. If $config is not empty, then it returns that option,
* or null if the option does not exist.
*/
public function get_option($config = '') {
global $DB;
$cache = cache::make('core', 'repositories');
if (($entries = $cache->get('ops:'. $this->id)) === false) {
$entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
$cache->set('ops:'. $this->id, $entries);
}
$ret = array();
foreach($entries as $entry) {
$ret[$entry->name] = $entry->value;
}
if (!empty($config)) {
if (isset($ret[$config])) {
return $ret[$config];
} else {
return null;
}
} else {
return $ret;
}
}
/**
* Filter file listing to display specific types
*
* @param array $value
* @return bool
*/
public function filter(&$value) {
$accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
if (isset($value['children'])) {
if (!empty($value['children'])) {
$value['children'] = array_filter($value['children'], array($this, 'filter'));
}
return true; // always return directories
} else {
if ($accepted_types == '*' or empty($accepted_types)
or (is_array($accepted_types) and in_array('*', $accepted_types))) {
return true;
} else {
foreach ($accepted_types as $ext) {
if (preg_match('#'.$ext.'$#i', $value['title'])) {
return true;
}
}
}
}
return false;
}
/**
* Given a path, and perhaps a search, get a list of files.
*
* See details on {@link http://docs.moodle.org/dev/Repository_plugins}
*
* @param string $path this parameter can a folder name, or a identification of folder
* @param string $page the page number of file list
* @return array the list of files, including meta infomation, containing the following keys
* manage, url to manage url
* client_id
* login, login form
* repo_id, active repository id
* login_btn_action, the login button action
* login_btn_label, the login button label
* total, number of results
* perpage, items per page
* page
* pages, total pages
* issearchresult, is it a search result?
* list, file list
* path, current path and parent path
*/
public function get_listing($path = '', $page = '') {
}
/**
* Prepare the breadcrumb.
*
* @param array $breadcrumb contains each element of the breadcrumb.
* @return array of breadcrumb elements.
* @since Moodle 2.3.3
*/
protected static function prepare_breadcrumb($breadcrumb) {
global $OUTPUT;
$foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
$len = count($breadcrumb);
for ($i = 0; $i < $len; $i++) {
if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
$breadcrumb[$i]['icon'] = $foldericon;
} else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
$breadcrumb[$i]->icon = $foldericon;
}
}
return $breadcrumb;
}
/**
* Prepare the file/folder listing.
*
* @param array $list of files and folders.
* @return array of files and folders.
* @since Moodle 2.3.3
*/
protected static function prepare_list($list) {
global $OUTPUT;
$foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
// Reset the array keys because non-numeric keys will create an object when converted to JSON.
$list = array_values($list);
$len = count($list);
for ($i = 0; $i < $len; $i++) {
if (is_object($list[$i])) {
$file = (array)$list[$i];
$converttoobject = true;
} else {
$file =& $list[$i];
$converttoobject = false;
}
if (isset($file['source'])) {
$file['sourcekey'] = sha1($file['source'] . self::get_secret_key() . sesskey());
}
if (isset($file['size'])) {
$file['size'] = (int)$file['size'];
$file['size_f'] = display_size($file['size']);
}
if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
$file['license_f'] = get_string($file['license'], 'license');
}
if (isset($file['image_width']) && isset($file['image_height'])) {
$a = array('width' => $file['image_width'], 'height' => $file['image_height']);
$file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
}
foreach (array('date', 'datemodified', 'datecreated') as $key) {
if (!isset($file[$key]) && isset($file['date'])) {
$file[$key] = $file['date'];
}
if (isset($file[$key])) {
// must be UNIX timestamp
$file[$key] = (int)$file[$key];
if (!$file[$key]) {
unset($file[$key]);
} else {
$file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
$file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
}
}
}
$isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
$filename = null;
if (isset($file['title'])) {
$filename = $file['title'];
}
else if (isset($file['fullname'])) {
$filename = $file['fullname'];
}
if (!isset($file['mimetype']) && !$isfolder && $filename) {
$file['mimetype'] = get_mimetype_description(array('filename' => $filename));
}
if (!isset($file['icon'])) {
if ($isfolder) {
$file['icon'] = $foldericon;
} else if ($filename) {
$file['icon'] = $OUTPUT->image_url(file_extension_icon($filename, 24))->out(false);
}
}
// Recursively loop over children.
if (isset($file['children'])) {
$file['children'] = self::prepare_list($file['children']);
}
// Convert the array back to an object.
if ($converttoobject) {
$list[$i] = (object)$file;
}
}
return $list;
}
/**
* Prepares list of files before passing it to AJAX, makes sure data is in the correct
* format and stores formatted values.
*
* @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
* @return array
*/
public static function prepare_listing($listing) {
$wasobject = false;
if (is_object($listing)) {
$listing = (array) $listing;
$wasobject = true;
}
// Prepare the breadcrumb, passed as 'path'.
if (isset($listing['path']) && is_array($listing['path'])) {
$listing['path'] = self::prepare_breadcrumb($listing['path']);
}
// Prepare the listing of objects.
if (isset($listing['list']) && is_array($listing['list'])) {
$listing['list'] = self::prepare_list($listing['list']);
}
// Convert back to an object.
if ($wasobject) {
$listing = (object) $listing;
}
return $listing;
}
/**
* Search files in repository
* When doing global search, $search_text will be used as
* keyword.
*
* @param string $search_text search key word
* @param int $page page
* @return mixed see {@link repository::get_listing()}
*/
public function search($search_text, $page = 0) {
$list = array();
$list['list'] = array();
return false;
}
/**
* Logout from repository instance
* By default, this function will return a login form
*
* @return string
*/
public function logout(){
return $this->print_login();
}
/**
* To check whether the user is logged in.
*
* @return bool
*/
public function check_login(){
return true;
}
/**
* Show the login screen, if required
*
* @return string
*/
public function print_login(){
return $this->get_listing();
}
/**
* Show the search screen, if required
*
* @return string
*/
public function print_search() {
global $PAGE;
$renderer = $PAGE->get_renderer('core', 'files');
return $renderer->repository_default_searchform();
}
/**
* For oauth like external authentication, when external repository direct user back to moodle,
* this function will be called to set up token and token_secret
*/
public function callback() {
}
/**
* is it possible to do glboal search?
*
* @return bool
*/
public function global_search() {
return false;
}
/**
* Defines operations that happen occasionally on cron
*
* @return bool
*/
public function cron() {
return true;
}
/**
* function which is run when the type is created (moodle administrator add the plugin)
*
* @return bool success or fail?
*/
public static function plugin_init() {
return true;
}
/**
* Edit/Create Admin Settings Moodle form
*
* @param moodleform $mform Moodle form (passed by reference)
* @param string $classname repository class name
*/
public static function type_config_form($mform, $classname = 'repository') {
$instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
if (empty($instnaceoptions)) {
// this plugin has only one instance
// so we need to give it a name
// it can be empty, then moodle will look for instance name from language string
$mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
$mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
$mform->setType('pluginname', PARAM_TEXT);
}
}
/**
* Validate Admin Settings Moodle form
*
* @static
* @param moodleform $mform Moodle form (passed by reference)
* @param array $data array of ("fieldname"=>value) of submitted data
* @param array $errors array of ("fieldname"=>errormessage) of errors
* @return array array of errors
*/
public static function type_form_validation($mform, $data, $errors) {
return $errors;
}
/**
* Edit/Create Instance Settings Moodle form
*
* @param moodleform $mform Moodle form (passed by reference)
*/
public static function instance_config_form($mform) {
}
/**
* Return names of the general options.
* By default: no general option name
*
* @return array
*/
public static function get_type_option_names() {
return array('pluginname');
}
/**
* Return names of the instance options.
* By default: no instance option name
*
* @return array
*/
public static function get_instance_option_names() {
return array();
}
/**
* Validate repository plugin instance form
*
* @param moodleform $mform moodle form
* @param array $data form data
* @param array $errors errors
* @return array errors
*/
public static function instance_form_validation($mform, $data, $errors) {
return $errors;
}
/**
* Create a shorten filename
*
* @param string $str filename
* @param int $maxlength max file name length
* @return string short filename
*/
public function get_short_filename($str, $maxlength) {
if (core_text::strlen($str) >= $maxlength) {
return trim(core_text::substr($str, 0, $maxlength)).'...';
} else {
return $str;
}
}
/**
* Overwrite an existing file
*
* @param int $itemid
* @param string $filepath
* @param string $filename
* @param string $newfilepath
* @param string $newfilename
* @return bool
*/
public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
global $USER;
$fs = get_file_storage();
$user_context = context_user::instance($USER->id);
if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
// Remember original file source field.
$source = @unserialize($file->get_source());
// Remember the original sortorder.
$sortorder = $file->get_sortorder();
if ($tempfile->is_external_file()) {
// New file is a reference. Check that existing file does not have any other files referencing to it
if (isset($source->original) && $fs->search_references_count($source->original)) {
return (object)array('error' => get_string('errordoublereference', 'repository'));
}
}
// delete existing file to release filename
$file->delete();
// create new file
$newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
// Preserve original file location (stored in source field) for handling references
if (isset($source->original)) {
if (!($newfilesource = @unserialize($newfile->get_source()))) {
$newfilesource = new stdClass();
}
$newfilesource->original = $source->original;
$newfile->set_source(serialize($newfilesource));
}
$newfile->set_sortorder($sortorder);
// remove temp file
$tempfile->delete();
return true;
}
}
return false;
}
/**
* Updates a file in draft filearea.
*
* This function can only update fields filepath, filename, author, license.
* If anything (except filepath) is updated, timemodified is set to current time.
* If filename or filepath is updated the file unconnects from it's origin
* and therefore all references to it will be converted to copies when
* filearea is saved.
*
* @param int $draftid
* @param string $filepath path to the directory containing the file, or full path in case of directory
* @param string $filename name of the file, or '.' in case of directory
* @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
* @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
*/
public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
global $USER;
$fs = get_file_storage();
$usercontext = context_user::instance($USER->id);
// make sure filename and filepath are present in $updatedata
$updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
$filemodified = false;
if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
if ($filename === '.') {
throw new moodle_exception('foldernotfound', 'repository');
} else {
throw new moodle_exception('filenotfound', 'error');
}
}
if (!$file->is_directory()) {
// This is a file
if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
// Rename/move file: check that target file name does not exist.
if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
throw new moodle_exception('fileexists', 'repository');
}
if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
unset($filesource->original);
$file->set_source(serialize($filesource));
}
$file->rename($updatedata['filepath'], $updatedata['filename']);
// timemodified is updated only when file is renamed and not updated when file is moved.
$filemodified = $filemodified || ($updatedata['filename'] !== $filename);
}
if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
// Update license and timemodified.
$file->set_license($updatedata['license']);
$filemodified = true;
}
if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
// Update author and timemodified.
$file->set_author($updatedata['author']);
$filemodified = true;
}
// Update timemodified:
if ($filemodified) {
$file->set_timemodified(time());
}
} else {
// This is a directory - only filepath can be updated for a directory (it was moved).
if ($updatedata['filepath'] === $filepath) {
// nothing to update
return;
}
if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
// bad luck, we can not rename if something already exists there
throw new moodle_exception('folderexists', 'repository');
}
$xfilepath = preg_quote($filepath, '|');
if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
// we can not move folder to it's own subfolder
throw new moodle_exception('folderrecurse', 'repository');
}
// If directory changed the name, update timemodified.
$filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
// Now update directory and all children.
$files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
foreach ($files as $f) {
if (preg_match("|^$xfilepath|", $f->get_filepath())) {
$path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
// unset original so the references are not shown any more
unset($filesource->original);
$f->set_source(serialize($filesource));
}
$f->rename($path, $f->get_filename());
if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
$f->set_timemodified(time());
}
}
}
}
}
/**
* Delete a temp file from draft area
*
* @param int $draftitemid
* @param string $filepath
* @param string $filename
* @return bool
*/
public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
global $USER;
$fs = get_file_storage();
$user_context = context_user::instance($USER->id);
if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
$file->delete();
return true;
} else {
return false;
}
}
/**
* Find all external files in this repo and import them
*/
public function convert_references_to_local() {
$fs = get_file_storage();
$files = $fs->get_external_files($this->id);
foreach ($files as $storedfile) {
$fs->import_external_file($storedfile);
}
}
/**
* Find all external files linked to this repository and delete them.
*/
public function remove_files() {
$fs = get_file_storage();
$files = $fs->get_external_files($this->id);
foreach ($files as $storedfile) {
$storedfile->delete();
}
}
/**
* Function repository::reset_caches() is deprecated, cache is handled by MUC now.
* @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
*/
public static function reset_caches() {
throw new coding_exception('Function repository::reset_caches() can not be used any more, cache is handled by MUC now.');
}
/**
* Function repository::sync_external_file() is deprecated. Use repository::sync_reference instead
*
* @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
* @see repository::sync_reference()
*/
public static function sync_external_file($file, $resetsynchistory = false) {
throw new coding_exception('Function repository::sync_external_file() can not be used any more. ' .
'Use repository::sync_reference instead.');
}
/**
* Performs synchronisation of an external file if the previous one has expired.
*
* This function must be implemented for external repositories supporting
* FILE_REFERENCE, it is called for existing aliases when their filesize,
* contenthash or timemodified are requested. It is not called for internal
* repositories (see {@link repository::has_moodle_files()}), references to
* internal files are updated immediately when source is modified.
*
* Referenced files may optionally keep their content in Moodle filepool (for
* thumbnail generation or to be able to serve cached copy). In this
* case both contenthash and filesize need to be synchronized. Otherwise repositories
* should use contenthash of empty file and correct filesize in bytes.
*
* Note that this function may be run for EACH file that needs to be synchronised at the
* moment. If anything is being downloaded or requested from external sources there
* should be a small timeout. The synchronisation is performed to update the size of
* the file and/or to update image and re-generated image preview. There is nothing
* fatal if syncronisation fails but it is fatal if syncronisation takes too long
* and hangs the script generating a page.
*
* Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
* $file->get_timemodified() make sure that recursion does not happen.
*
* Called from {@link stored_file::sync_external_file()}
*
* @uses stored_file::set_missingsource()
* @uses stored_file::set_synchronized()
* @param stored_file $file
* @return bool false when file does not need synchronisation, true if it was synchronised
*/
public function sync_reference(stored_file $file) {
if ($file->get_repository_id() != $this->id) {
// This should not really happen because the function can be called from stored_file only.
return false;
}
if ($this->has_moodle_files()) {
// References to local files need to be synchronised only once.
// Later they will be synchronised automatically when the source is changed.
if ($file->get_referencelastsync()) {
return false;
}
$fs = get_file_storage();
$params = file_storage::unpack_reference($file->get_reference(), true);
if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
$params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
$params['filename']))) {
$file->set_missingsource();
} else {
$file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
}
return true;
}
return false;
}
/**
* Build draft file's source field
*
* {@link file_restore_source_field_from_draft_file()}
* XXX: This is a hack for file manager (MDL-28666)
* For newly created draft files we have to construct
* source filed in php serialized data format.
* File manager needs to know the original file information before copying
* to draft area, so we append these information in mdl_files.source field
*
* @param string $source
* @return string serialised source field
*/
public static function build_source_field($source) {
$sourcefield = new stdClass;
$sourcefield->source = $source;
return serialize($sourcefield);
}
/**
* Prepares the repository to be cached. Implements method from cacheable_object interface.
*
* @return array
*/
public function prepare_to_cache() {
return array(
'class' => get_class($this),
'id' => $this->id,
'ctxid' => $this->context->id,
'options' => $this->options,
'readonly' => $this->readonly
);
}
/**
* Restores the repository from cache. Implements method from cacheable_object interface.
*
* @return array
*/
public static function wake_from_cache($data) {
$classname = $data['class'];
return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
}
/**
* Gets a file relative to this file in the repository and sends it to the browser.
* Used to allow relative file linking within a repository without creating file records
* for linked files
*
* Repositories that overwrite this must be very careful - see filesystem repository for example.
*
* @param stored_file $mainfile The main file we are trying to access relative files for.
* @param string $relativepath the relative path to the file we are trying to access.
*
*/
public function send_relative_file(stored_file $mainfile, $relativepath) {
// This repository hasn't implemented this so send_file_not_found.
send_file_not_found();
}
/**
* helper function to check if the repository supports send_relative_file.
*
* @return true|false
*/
public function supports_relative_file() {
return false;
}
/**
* Helper function to indicate if this repository uses post requests for uploading files.
*
* @deprecated since Moodle 3.2, 3.1.1, 3.0.5
* @return bool
*/
public function uses_post_requests() {
debugging('The method repository::uses_post_requests() is deprecated and must not be used anymore.', DEBUG_DEVELOPER);
return false;
}
/**
* Generate a secret key to be used for passing sensitive information around.
*
* @return string repository secret key.
*/
final static public function get_secret_key() {
global $CFG;
if (!isset($CFG->reposecretkey)) {
set_config('reposecretkey', time() . random_string(32));
}
return $CFG->reposecretkey;
}
}
/**
* Exception class for repository api
*
* @since Moodle 2.0
* @package core_repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_exception extends moodle_exception {
}
/**
* This is a class used to define a repository instance form
*
* @since Moodle 2.0
* @package core_repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class repository_instance_form extends moodleform {
/** @var stdClass repository instance */
protected $instance;
/** @var string repository plugin type */
protected $plugin;
/**
* Added defaults to moodle form
*/
protected function add_defaults() {
$mform =& $this->_form;
$strrequired = get_string('required');
$mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
$mform->setType('edit', PARAM_INT);
$mform->addElement('hidden', 'new', $this->plugin);
$mform->setType('new', PARAM_ALPHANUMEXT);
$mform->addElement('hidden', 'plugin', $this->plugin);
$mform->setType('plugin', PARAM_PLUGIN);
$mform->addElement('hidden', 'typeid', $this->typeid);
$mform->setType('typeid', PARAM_INT);
$mform->addElement('hidden', 'contextid', $this->contextid);
$mform->setType('contextid', PARAM_INT);
$mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
$mform->addRule('name', $strrequired, 'required', null, 'client');
$mform->setType('name', PARAM_TEXT);
}
/**
* Define moodle form elements
*/
public function definition() {
global $CFG;
// type of plugin, string
$this->plugin = $this->_customdata['plugin'];
$this->typeid = $this->_customdata['typeid'];
$this->contextid = $this->_customdata['contextid'];
$this->instance = (isset($this->_customdata['instance'])
&& is_subclass_of($this->_customdata['instance'], 'repository'))
? $this->_customdata['instance'] : null;
$mform =& $this->_form;
$this->add_defaults();
// Add instance config options.
$result = repository::static_function($this->plugin, 'instance_config_form', $mform);
if ($result === false) {
// Remove the name element if no other config options.
$mform->removeElement('name');
}
if ($this->instance) {
$data = array();
$data['name'] = $this->instance->name;
if (!$this->instance->readonly) {
// and set the data if we have some.
foreach ($this->instance->get_instance_option_names() as $config) {
if (!empty($this->instance->options[$config])) {
$data[$config] = $this->instance->options[$config];
} else {
$data[$config] = '';
}
}
}
$this->set_data($data);
}
if ($result === false) {
$mform->addElement('cancel');
} else {
$this->add_action_buttons(true, get_string('save','repository'));
}
}
/**
* Validate moodle form data
*
* @param array $data form data
* @param array $files files in form
* @return array errors
*/
public function validation($data, $files) {
global $DB;
$errors = array();
$plugin = $this->_customdata['plugin'];
$instance = (isset($this->_customdata['instance'])
&& is_subclass_of($this->_customdata['instance'], 'repository'))
? $this->_customdata['instance'] : null;
if (!$instance) {
$errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
} else {
$errors = $instance->instance_form_validation($this, $data, $errors);
}
$sql = "SELECT count('x')
FROM {repository_instances} i, {repository} r
WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
$params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
if ($instance) {
$sql .= ' AND i.id != :instanceid';
$params['instanceid'] = $instance->id;
}
if ($DB->count_records_sql($sql, $params) > 0) {
$errors['name'] = get_string('erroruniquename', 'repository');
}
return $errors;
}
}
/**
* This is a class used to define a repository type setting form
*
* @since Moodle 2.0
* @package core_repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
final class repository_type_form extends moodleform {
/** @var stdClass repository instance */
protected $instance;
/** @var string repository plugin name */
protected $plugin;
/** @var string action */
protected $action;
/**
* Definition of the moodleform
*/
public function definition() {
global $CFG;
// type of plugin, string
$this->plugin = $this->_customdata['plugin'];
$this->instance = (isset($this->_customdata['instance'])
&& is_a($this->_customdata['instance'], 'repository_type'))
? $this->_customdata['instance'] : null;
$this->action = $this->_customdata['action'];
$this->pluginname = $this->_customdata['pluginname'];
$mform =& $this->_form;
$strrequired = get_string('required');
$mform->addElement('hidden', 'action', $this->action);
$mform->setType('action', PARAM_TEXT);
$mform->addElement('hidden', 'repos', $this->plugin);
$mform->setType('repos', PARAM_PLUGIN);
// let the plugin add its specific fields
$classname = 'repository_' . $this->plugin;
require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
//add "enable course/user instances" checkboxes if multiple instances are allowed
$instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
$result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
if (!empty($instanceoptionnames)) {
$sm = get_string_manager();
$component = 'repository';
if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
$component .= ('_' . $this->plugin);
}
$mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
$mform->setType('enablecourseinstances', PARAM_BOOL);
$component = 'repository';
if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
$component .= ('_' . $this->plugin);
}
$mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
$mform->setType('enableuserinstances', PARAM_BOOL);
}
// set the data if we have some.
if ($this->instance) {
$data = array();
$option_names = call_user_func(array($classname,'get_type_option_names'));
if (!empty($instanceoptionnames)){
$option_names[] = 'enablecourseinstances';
$option_names[] = 'enableuserinstances';
}
$instanceoptions = $this->instance->get_options();
foreach ($option_names as $config) {
if (!empty($instanceoptions[$config])) {
$data[$config] = $instanceoptions[$config];
} else {
$data[$config] = '';
}
}
// XXX: set plugin name for plugins which doesn't have muliti instances
if (empty($instanceoptionnames)){
$data['pluginname'] = $this->pluginname;
}
$this->set_data($data);
}
$this->add_action_buttons(true, get_string('save','repository'));
}
/**
* Validate moodle form data
*
* @param array $data moodle form data
* @param array $files
* @return array errors
*/
public function validation($data, $files) {
$errors = array();
$plugin = $this->_customdata['plugin'];
$instance = (isset($this->_customdata['instance'])
&& is_subclass_of($this->_customdata['instance'], 'repository'))
? $this->_customdata['instance'] : null;
if (!$instance) {
$errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
} else {
$errors = $instance->type_form_validation($this, $data, $errors);
}
return $errors;
}
}
/**
* Generate all options needed by filepicker
*
* @param array $args including following keys
* context
* accepted_types
* return_types
*
* @return array the list of repository instances, including meta infomation, containing the following keys
* externallink
* repositories
* accepted_types
*/
function initialise_filepicker($args) {
global $CFG, $USER, $PAGE, $OUTPUT;
static $templatesinitialized = array();
require_once($CFG->libdir . '/licenselib.php');
$return = new stdClass();
$licenses = array();
if (!empty($CFG->licenses)) {
$array = explode(',', $CFG->licenses);
foreach ($array as $license) {
$l = new stdClass();
$l->shortname = $license;
$l->fullname = get_string($license, 'license');
$licenses[] = $l;
}
}
if (!empty($CFG->sitedefaultlicense)) {
$return->defaultlicense = $CFG->sitedefaultlicense;
}
$return->licenses = $licenses;
$return->author = fullname($USER);
if (empty($args->context)) {
$context = $PAGE->context;
} else {
$context = $args->context;
}
$disable_types = array();
if (!empty($args->disable_types)) {
$disable_types = $args->disable_types;
}
$user_context = context_user::instance($USER->id);
list($context, $course, $cm) = get_context_info_array($context->id);
$contexts = array($user_context, context_system::instance());
if (!empty($course)) {
// adding course context
$contexts[] = context_course::instance($course->id);
}
$externallink = (int)get_config(null, 'repositoryallowexternallinks');
$repositories = repository::get_instances(array(
'context'=>$contexts,
'currentcontext'=> $context,
'accepted_types'=>$args->accepted_types,
'return_types'=>$args->return_types,
'disable_types'=>$disable_types
));
$return->repositories = array();
if (empty($externallink)) {
$return->externallink = false;
} else {
$return->externallink = true;
}
$return->userprefs = array();
$return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
$return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
$return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
// provided by form element
$return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
$return->return_types = $args->return_types;
$templates = array();
foreach ($repositories as $repository) {
$meta = $repository->get_meta();
// Please note that the array keys for repositories are used within
// JavaScript a lot, the key NEEDS to be the repository id.
$return->repositories[$repository->id] = $meta;
// Register custom repository template if it has one
if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
$templates['uploadform_' . $meta->type] = $repository->get_upload_template();
$templatesinitialized['uploadform_' . $meta->type] = true;
}
}
if (!array_key_exists('core', $templatesinitialized)) {
// we need to send each filepicker template to the browser just once
$fprenderer = $PAGE->get_renderer('core', 'files');
$templates = array_merge($templates, $fprenderer->filepicker_js_templates());
$templatesinitialized['core'] = true;
}
if (sizeof($templates)) {
$PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
}
return $return;
}