Example #1
0
 public function __construct(stdClass $options)
 {
     global $CFG, $USER, $PAGE;
     require_once $CFG->dirroot . '/repository/lib.php';
     $defaults = array('accepted_types' => '*', 'return_types' => FILE_INTERNAL, 'env' => 'filepicker', 'client_id' => uniqid(), 'itemid' => 0, 'maxbytes' => -1, 'maxfiles' => 1, 'buttonname' => false);
     foreach ($defaults as $key => $value) {
         if (empty($options->{$key})) {
             $options->{$key} = $value;
         }
     }
     $options->currentfile = '';
     if (!empty($options->itemid)) {
         $fs = get_file_storage();
         $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
         if (empty($options->filename)) {
             if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
                 $file = reset($files);
             }
         } else {
             $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
         }
         if (!empty($file)) {
             $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
         }
     }
     // initilise options, getting files in root path
     $this->options = initialise_filepicker($options);
     // copying other options
     foreach ($options as $name => $value) {
         if (!isset($this->options->{$name})) {
             $this->options->{$name} = $value;
         }
     }
 }
 function display_add_field($recordid = 0)
 {
     global $CFG, $DB, $OUTPUT, $PAGE, $USER;
     $file = false;
     $content = false;
     $displayname = '';
     $fs = get_file_storage();
     $context = $PAGE->context;
     $itemid = null;
     // editing an existing database entry
     if ($recordid) {
         if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
             file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
             if (!empty($content->content)) {
                 if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                     $usercontext = context_user::instance($USER->id);
                     if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                         return false;
                     }
                     if (empty($content->content1)) {
                         // Print icon if file already exists
                         $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                         $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                     } else {
                         $displayname = 'no file added';
                     }
                 }
             }
         }
     } else {
         $itemid = file_get_unused_draft_itemid();
     }
     $html = '';
     // database entry label
     $html .= '<div title="' . s($this->field->description) . '">';
     $html .= '<fieldset><legend><span class="accesshide">' . $this->field->name . '</span></legend>';
     // itemid element
     $html .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->maxfiles = 1;
     // Limit to one file for the moment, this may be changed if requested as a feature in the future.
     $options->itemid = $itemid;
     $options->accepted_types = '*';
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     $fm = new form_filemanager($options);
     // Print out file manager.
     $output = $PAGE->get_renderer('core', 'files');
     $html .= $output->render($fm);
     $html .= '</fieldset>';
     $html .= '</div>';
     $module = array('name' => 'form_filemanager', 'fullpath' => '/lib/form/filemanager.js', 'requires' => array('core_filepicker', 'base', 'io-base', 'node', 'json', 'core_dndupload', 'panel', 'resize-plugin', 'dd-plugin'), 'strings' => array(array('error', 'moodle'), array('info', 'moodle'), array('confirmdeletefile', 'repository'), array('draftareanofiles', 'repository'), array('entername', 'repository'), array('enternewname', 'repository'), array('invalidjson', 'repository'), array('popupblockeddownload', 'repository'), array('unknownoriginal', 'repository'), array('confirmdeletefolder', 'repository'), array('confirmdeletefilewithhref', 'repository'), array('confirmrenamefolder', 'repository'), array('confirmrenamefile', 'repository'), array('edit', 'moodle')));
     $PAGE->requires->js_init_call('M.form_filemanager.init', array($fm->options), true, $module);
     return $html;
 }
 function display_add_field($recordid = 0)
 {
     global $CFG, $DB, $OUTPUT, $PAGE, $USER;
     $file = false;
     $content = false;
     $displayname = '';
     $fs = get_file_storage();
     $context = $PAGE->context;
     $itemid = null;
     // editing an existing database entry
     if ($recordid) {
         if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
             file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
             if (!empty($content->content)) {
                 if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                     $usercontext = context_user::instance($USER->id);
                     if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                         return false;
                     }
                     if (empty($content->content1)) {
                         // Print icon if file already exists
                         $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                         $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                     } else {
                         $displayname = 'no file added';
                     }
                 }
             }
         }
     } else {
         $itemid = file_get_unused_draft_itemid();
     }
     $html = '';
     // database entry label
     $html .= '<div title="' . s($this->field->description) . '">';
     $html .= '<fieldset><legend><span class="accesshide">' . $this->field->name . '</span></legend>';
     // itemid element
     $html .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->maxfiles = 1;
     // Limit to one file for the moment, this may be changed if requested as a feature in the future.
     $options->itemid = $itemid;
     $options->accepted_types = '*';
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     $fm = new form_filemanager($options);
     // Print out file manager.
     $output = $PAGE->get_renderer('core', 'files');
     $html .= $output->render($fm);
     $html .= '</fieldset>';
     $html .= '</div>';
     return $html;
 }
Example #4
0
 function display_add_field($recordid = 0)
 {
     global $CFG, $DB, $OUTPUT, $PAGE, $USER;
     $file = false;
     $content = false;
     $displayname = '';
     $fs = get_file_storage();
     $context = $PAGE->context;
     $itemid = null;
     // editing an existing database entry
     if ($recordid) {
         if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
             file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
             if (!empty($content->content)) {
                 if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
                     if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                         return false;
                     }
                     if (empty($content->content1)) {
                         // Print icon if file already exists
                         $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                         $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                     } else {
                         $displayname = 'no file added';
                     }
                 }
             }
         }
     } else {
         $itemid = file_get_unused_draft_itemid();
     }
     $html = '';
     // database entry label
     $html .= '<div title="' . s($this->field->description) . '">';
     $html .= '<fieldset><legend><span class="accesshide">' . $this->field->name . '</span></legend>';
     // itemid element
     $html .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->itemid = $itemid;
     $options->accepted_types = '*';
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     $fp = new file_picker($options);
     // print out file picker
     $html .= $OUTPUT->render($fp);
     $html .= '</fieldset>';
     $html .= '</div>';
     $module = array('name' => 'data_filepicker', 'fullpath' => '/mod/data/data.js', 'requires' => array('core_filepicker'));
     $PAGE->requires->js_init_call('M.data_filepicker.init', array($fp->options), true, $module);
     return $html;
 }
Example #5
0
 /**
  * Get file listing
  *
  * @param string $path
  * @param string $path not used by this plugin
  * @return mixed
  */
 public function get_listing($path = '', $page = '')
 {
     global $USER, $OUTPUT;
     $itemid = optional_param('itemid', 0, PARAM_INT);
     $env = optional_param('env', 'filepicker', PARAM_ALPHA);
     $ret = array('dynload' => true, 'nosearch' => true, 'nologin' => true, 'list' => array());
     if (empty($itemid) || $env !== 'editor') {
         return $ret;
     }
     // In the most cases files embedded in textarea do not have subfolders. Do not show path by default.
     $retpath = array(array('name' => get_string('files'), 'path' => ''));
     if (!empty($path)) {
         $pathchunks = preg_split('|/|', trim($path, '/'));
         foreach ($pathchunks as $i => $chunk) {
             $retpath[] = array('name' => $chunk, 'path' => '/' . join('/', array_slice($pathchunks, 0, $i + 1)) . '/');
         }
         $ret['path'] = $retpath;
         // Show path if already inside subfolder.
     }
     $context = context_user::instance($USER->id);
     $fs = get_file_storage();
     $files = $fs->get_directory_files($context->id, 'user', 'draft', $itemid, empty($path) ? '/' : $path, false, true);
     foreach ($files as $file) {
         if ($file->is_directory()) {
             $node = array('title' => basename($file->get_filepath()), 'path' => $file->get_filepath(), 'children' => array(), 'datemodified' => $file->get_timemodified(), 'datecreated' => $file->get_timecreated(), 'icon' => $OUTPUT->pix_url(file_folder_icon(24))->out(false), 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false));
             $ret['list'][] = $node;
             $ret['path'] = $retpath;
             // Show path if subfolders exist.
             continue;
         }
         $fileurl = moodle_url::make_draftfile_url($itemid, $file->get_filepath(), $file->get_filename());
         $node = array('title' => $file->get_filename(), 'size' => $file->get_filesize(), 'source' => $fileurl->out(), 'datemodified' => $file->get_timemodified(), 'datecreated' => $file->get_timecreated(), 'author' => $file->get_author(), 'license' => $file->get_license(), 'isref' => $file->is_external_file(), 'icon' => $OUTPUT->pix_url(file_file_icon($file, 24))->out(false), 'thumbnail' => $OUTPUT->pix_url(file_file_icon($file, 90))->out(false));
         if ($file->get_status() == 666) {
             $node['originalmissing'] = true;
         }
         if ($imageinfo = $file->get_imageinfo()) {
             $node['realthumbnail'] = $fileurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
             $node['realicon'] = $fileurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
             $node['image_width'] = $imageinfo['width'];
             $node['image_height'] = $imageinfo['height'];
         }
         $ret['list'][] = $node;
     }
     $ret['list'] = array_filter($ret['list'], array($this, 'filter'));
     return $ret;
 }
Example #6
0
         $record->filename = $unused_filename;
         // Create a file copy using unused filename.
         $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
         $event = array();
         $event['event'] = 'fileexists';
         $event['newfile'] = new stdClass();
         $event['newfile']->filepath = $saveas_path;
         $event['newfile']->filename = $unused_filename;
         $event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();
         $event['existingfile'] = new stdClass();
         $event['existingfile']->filepath = $saveas_path;
         $event['existingfile']->filename = $saveas_filename;
         $event['existingfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();
     } else {
         $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
         $event = array('url' => moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(), 'id' => $storedfile->get_itemid(), 'file' => $storedfile->get_filename(), 'icon' => $OUTPUT->pix_url(file_file_icon($storedfile, 32))->out());
     }
     // Repository plugin callback
     // You can cache reository file in this callback
     // or complete other tasks.
     $repo->cache_file_by_reference($reference, $storedfile);
     echo json_encode($event);
     die;
 } else {
     if ($repo->has_moodle_files()) {
         // Some repository plugins (local, user, coursefiles, recent) are hosting moodle
         // internal files, we cannot use get_file method, so we use copy_to_area method
         // If the moodle file is an alias we copy this alias, otherwise we copy the file
         // {@link repository::copy_to_area()}.
         $fileinfo = $repo->copy_to_area($reference, $record, $maxbytes, $areamaxbytes);
         echo json_encode($fileinfo);
Example #7
0
/**
 * Listing all files (including folders) in current path (draft area)
 * used by file manager
 * @param int $draftitemid
 * @param string $filepath
 * @return mixed
 */
function file_get_drafarea_files($draftitemid, $filepath = '/')
{
    global $USER, $OUTPUT, $CFG;
    $context = get_context_instance(CONTEXT_USER, $USER->id);
    $fs = get_file_storage();
    $data = new stdClass();
    $data->path = array();
    $data->path[] = array('name' => get_string('files'), 'path' => '/');
    // will be used to build breadcrumb
    $trail = '';
    if ($filepath !== '/') {
        $filepath = file_correct_filepath($filepath);
        $parts = explode('/', $filepath);
        foreach ($parts as $part) {
            if ($part != '' && $part != null) {
                $trail .= '/' . $part . '/';
                $data->path[] = array('name' => $part, 'path' => $trail);
            }
        }
    }
    $list = array();
    $maxlength = 12;
    if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
        foreach ($files as $file) {
            $item = new stdClass();
            $item->filename = $file->get_filename();
            $item->filepath = $file->get_filepath();
            $item->fullname = trim($item->filename, '/');
            $filesize = $file->get_filesize();
            $item->filesize = $filesize ? display_size($filesize) : '';
            $icon = mimeinfo_from_type('icon', $file->get_mimetype());
            $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
            $item->sortorder = $file->get_sortorder();
            if ($icon == 'zip') {
                $item->type = 'zip';
            } else {
                $item->type = 'file';
            }
            if ($file->is_directory()) {
                $item->filesize = 0;
                $item->icon = $OUTPUT->pix_url('f/folder')->out();
                $item->type = 'folder';
                $foldername = explode('/', trim($item->filepath, '/'));
                $item->fullname = trim(array_pop($foldername), '/');
            } else {
                // do NOT use file browser here!
                $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
            }
            $list[] = $item;
        }
    }
    $data->itemid = $draftitemid;
    $data->list = $list;
    return $data;
}
Example #8
0
 function display_add_field($recordid = 0, $formdata = null)
 {
     global $CFG, $DB, $OUTPUT, $USER, $PAGE;
     $file = false;
     $content = false;
     $displayname = '';
     $alttext = '';
     $itemid = null;
     $fs = get_file_storage();
     if ($formdata) {
         $fieldname = 'field_' . $this->field->id . '_file';
         $itemid = $formdata->{$fieldname};
         $fieldname = 'field_' . $this->field->id . '_alttext';
         if (isset($formdata->{$fieldname})) {
             $alttext = $formdata->{$fieldname};
         }
     } else {
         if ($recordid) {
             if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
                 file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
                 if (!empty($content->content)) {
                     if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                         $usercontext = context_user::instance($USER->id);
                         if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                             return false;
                         }
                         if ($thumbfile = $fs->get_file($usercontext->id, 'user', 'draft', $itemid, '/', 'thumb_' . $content->content)) {
                             $thumbfile->delete();
                         }
                         if (empty($content->content1)) {
                             // Print icon if file already exists
                             $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                             $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                         } else {
                             $displayname = get_string('nofilesattached', 'repository');
                         }
                     }
                 }
                 $alttext = $content->content1;
             }
         } else {
             $itemid = file_get_unused_draft_itemid();
         }
     }
     $str = '<div title="' . s($this->field->description) . '">';
     $str .= '<fieldset><legend><span class="accesshide">' . $this->field->name;
     if ($this->field->required) {
         $str .= '&nbsp;' . get_string('requiredelement', 'form') . '</span></legend>';
         $image = html_writer::img($OUTPUT->pix_url('req'), get_string('requiredelement', 'form'), array('class' => 'req', 'title' => get_string('requiredelement', 'form')));
         $str .= html_writer::div($image, 'inline-req');
     } else {
         $str .= '</span></legend>';
     }
     $str .= '<noscript>';
     if ($file) {
         $src = file_encode_url($CFG->wwwroot . '/pluginfile.php/', $this->context->id . '/mod_data/content/' . $content->id . '/' . $file->get_filename());
         $str .= '<img width="' . s($this->previewwidth) . '" height="' . s($this->previewheight) . '" src="' . $src . '" alt="" />';
     }
     $str .= '</noscript>';
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->maxfiles = 1;
     // Only one picture permitted.
     $options->itemid = $itemid;
     $options->accepted_types = array('web_image');
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     if (!empty($file)) {
         $options->filename = $file->get_filename();
         $options->filepath = '/';
     }
     $fm = new form_filemanager($options);
     // Print out file manager.
     $output = $PAGE->get_renderer('core', 'files');
     $str .= '<div class="mod-data-input">';
     $str .= $output->render($fm);
     $str .= '<div class="mdl-left">';
     $str .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $str .= '<label for="field_' . $this->field->id . '_alttext">' . get_string('alttext', 'data') . '</label>&nbsp;<input type="text" name="field_' . $this->field->id . '_alttext" id="field_' . $this->field->id . '_alttext" value="' . s($alttext) . '" />';
     $str .= '</div>';
     $str .= '</div>';
     $str .= '</fieldset>';
     $str .= '</div>';
     return $str;
 }
Example #9
0
                    $event = array();
                    $event['event'] = 'fileexists';
                    $event['newfile'] = new stdClass;
                    $event['newfile']->filepath = $saveas_path;
                    $event['newfile']->filename = $unused_filename;
                    $event['newfile']->url = moodle_url::make_draftfile_url($itemid, $saveas_path, $unused_filename)->out();

                    $event['existingfile'] = new stdClass;
                    $event['existingfile']->filepath = $saveas_path;
                    $event['existingfile']->filename = $saveas_filename;
                    $event['existingfile']->url      = moodle_url::make_draftfile_url($itemid, $saveas_path, $saveas_filename)->out();;
                } else {

                    $storedfile = $fs->create_file_from_reference($record, $repo_id, $reference);
                    $event = array(
                        'url'=>moodle_url::make_draftfile_url($storedfile->get_itemid(), $storedfile->get_filepath(), $storedfile->get_filename())->out(),
                        'id'=>$storedfile->get_itemid(),
                        'file'=>$storedfile->get_filename(),
                        'icon' => $OUTPUT->pix_url(file_file_icon($storedfile, 32))->out(),
                    );
                }
                // Repository plugin callback
                // You can cache reository file in this callback
                // or complete other tasks.
                $repo->cache_file_by_reference($reference, $storedfile);
                echo json_encode($event);
                die;
            } else if ($repo->has_moodle_files()) {
                // Some repository plugins (local, user, coursefiles, recent) are hosting moodle
                // internal files, we cannot use get_file method, so we use copy_to_area method
Example #10
0
    /**
     * This function overwrite the default implement to copying file using file_storage
     *
     * @global object $USER
     * @global object $DB
     * @param string $encoded The information of file, it is base64 encoded php serialized data
     * @param string $draftitemid itemid
     * @param string $new_filename The intended name of file
     * @param string $new_filepath the new path in draft area
     * @return array The information of file
     */
    public function copy_to_area($encoded, $draftitemid, $new_filepath, $new_filename) {
        global $USER, $DB;

        $user_context = get_context_instance(CONTEXT_USER, $USER->id);

        $fs = get_file_storage();

        $params = unserialize(base64_decode($encoded));

        $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);

        // XXX:
        // When user try to pick a file from other filearea, normally file api will use file browse to
        // operate the files with capability check, but in some areas, users don't have permission to
        // browse the files (for example, forum_attachment area).
        //
        // To get 'recent' plugin working, we need to use lower level file_stoarge class to bypass the
        // capability check, we will use a better workaround to improve it.
        if ($stored_file = $fs->get_file($contextid, $component, $filearea, $fileitemid, $filepath, $filename)) {
            // verify user id
            if ($USER->id != $stored_file->get_userid()) {
                throw new moodle_exception('errornotyourfile', 'repository');
            }
            $file_record = array('contextid'=>$user_context->id, 'component'=>'user', 'filearea'=>'draft',
                'itemid'=>$draftitemid, 'filepath'=>$new_filepath, 'filename'=>$new_filename, 'sortorder'=>0);

            // test if file already exists
            if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
                // create new file
                $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
                $file_record['filename'] = $unused_filename;
                // create a tmp file
                $fs->create_file_from_storedfile($file_record, $stored_file);
                $event = array();
                $event['event'] = 'fileexists';
                $event['newfile'] = new stdClass;
                $event['newfile']->filepath = $new_filepath;
                $event['newfile']->filename = $unused_filename;
                $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
                $event['existingfile'] = new stdClass;
                $event['existingfile']->filepath = $new_filepath;
                $event['existingfile']->filename = $new_filename;
                $event['existingfile']->url      = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
                return $event;
            } else {
                $fs->create_file_from_storedfile($file_record, $stored_file);
                $info = array();
                $info['title']  = $new_filename;
                $info['itemid'] = $draftitemid;
                $info['filesize']  = $stored_file->get_filesize();
                $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
                $info['contextid'] = $user_context->id;
                return $info;
            }
        }
        return false;

    }
 /**
  * Process uploaded file
  * @return array|bool
  */
 public function upload($search_text)
 {
     global $USER, $CFG;
     $record = new stdClass();
     $record->filearea = 'draft';
     $record->component = 'user';
     $record->filepath = optional_param('savepath', '/', PARAM_PATH);
     $record->itemid = optional_param('itemid', 0, PARAM_INT);
     $record->license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
     $record->author = optional_param('author', '', PARAM_TEXT);
     $context = get_context_instance(CONTEXT_USER, $USER->id);
     $filename = required_param('recordaudio_filename', PARAM_FILE);
     $filedata = required_param('recordaudio_filedata', PARAM_RAW);
     $filedata = base64_decode($filedata);
     $fs = get_file_storage();
     $sm = get_string_manager();
     if ($record->filepath !== '/') {
         $record->filepath = file_correct_filepath($record->filepath);
     }
     $record->filename = $filename;
     if (empty($record->itemid)) {
         $record->itemid = 0;
     }
     $record->contextid = $context->id;
     $record->userid = $USER->id;
     $record->source = '';
     if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
         $existingfilename = $record->filename;
         $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
         $record->filename = $unused_filename;
         $stored_file = $fs->create_file_from_string($record, $filedata);
         $event = array();
         $event['event'] = 'fileexists';
         $event['newfile'] = new stdClass();
         $event['newfile']->filepath = $record->filepath;
         $event['newfile']->filename = $unused_filename;
         $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out();
         $event['existingfile'] = new stdClass();
         $event['existingfile']->filepath = $record->filepath;
         $event['existingfile']->filename = $existingfilename;
         $event['existingfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out();
         return $event;
     } else {
         $stored_file = $fs->create_file_from_string($record, $filedata);
         return array('url' => moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(), 'id' => $record->itemid, 'file' => $record->filename);
     }
 }
Example #12
0
 /**
  * Do the actual processing of the uploaded file
  * @param string $saveas_filename name to give to the file
  * @param int $maxbytes maximum file size
  * @param mixed $types optional array of file extensions that are allowed or '*' for all
  * @param string $savepath optional path to save the file to
  * @param int $itemid optional the ID for this item within the file area
  * @param string $license optional the license to use for this file
  * @param string $author optional the name of the author of this file
  * @param bool $overwriteexisting optional user has asked to overwrite the existing file
  * @param int $areamaxbytes maximum size of the file area.
  * @return object containing details of the file uploaded
  */
 public function process_upload($saveas_filename, $maxbytes, $types = '*', $savepath = '/', $itemid = 0, $license = null, $author = '', $overwriteexisting = false, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED)
 {
     global $USER, $CFG;
     if (is_array($types) and in_array('*', $types) or $types == '*') {
         $this->mimetypes = '*';
     } else {
         foreach ($types as $type) {
             $this->mimetypes[] = mimeinfo('type', $type);
         }
     }
     if ($license == null) {
         $license = $CFG->sitedefaultlicense;
     }
     $record = new stdClass();
     $record->filearea = 'draft';
     $record->component = 'user';
     $record->filepath = $savepath;
     $record->itemid = $itemid;
     $record->license = $license;
     $record->author = $author;
     $context = context_user::instance($USER->id);
     $elname = 'repo_upload_file';
     $fs = get_file_storage();
     $sm = get_string_manager();
     if ($record->filepath !== '/') {
         $record->filepath = file_correct_filepath($record->filepath);
     }
     if (!isset($_FILES[$elname])) {
         throw new moodle_exception('nofile');
     }
     if (!empty($_FILES[$elname]['error'])) {
         switch ($_FILES[$elname]['error']) {
             case UPLOAD_ERR_INI_SIZE:
                 throw new moodle_exception('upload_error_ini_size', 'repository_upload');
                 break;
             case UPLOAD_ERR_FORM_SIZE:
                 throw new moodle_exception('upload_error_form_size', 'repository_upload');
                 break;
             case UPLOAD_ERR_PARTIAL:
                 throw new moodle_exception('upload_error_partial', 'repository_upload');
                 break;
             case UPLOAD_ERR_NO_FILE:
                 throw new moodle_exception('upload_error_no_file', 'repository_upload');
                 break;
             case UPLOAD_ERR_NO_TMP_DIR:
                 throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
                 break;
             case UPLOAD_ERR_CANT_WRITE:
                 throw new moodle_exception('upload_error_cant_write', 'repository_upload');
                 break;
             case UPLOAD_ERR_EXTENSION:
                 throw new moodle_exception('upload_error_extension', 'repository_upload');
                 break;
             default:
                 throw new moodle_exception('nofile');
         }
     }
     \core\antivirus\manager::scan_file($_FILES[$elname]['tmp_name'], $_FILES[$elname]['name'], true);
     // {@link repository::build_source_field()}
     $sourcefield = $this->get_file_source_info($_FILES[$elname]['name']);
     $record->source = self::build_source_field($sourcefield);
     if (empty($saveas_filename)) {
         $record->filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
     } else {
         $ext = '';
         $match = array();
         $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
         if (strpos($filename, '.') === false) {
             // File has no extension at all - do not add a dot.
             $record->filename = $saveas_filename;
         } else {
             if (preg_match('/\\.([a-z0-9]+)$/i', $filename, $match)) {
                 if (isset($match[1])) {
                     $ext = $match[1];
                 }
             }
             $ext = !empty($ext) ? $ext : '';
             if (preg_match('#\\.(' . $ext . ')$#i', $saveas_filename)) {
                 // saveas filename contains file extension already
                 $record->filename = $saveas_filename;
             } else {
                 $record->filename = $saveas_filename . '.' . $ext;
             }
         }
     }
     // Check the file has some non-null contents - usually an indication that a user has
     // tried to upload a folder by mistake
     if (!$this->check_valid_contents($_FILES[$elname]['tmp_name'])) {
         throw new moodle_exception('upload_error_invalid_file', 'repository_upload', '', $record->filename);
     }
     if ($this->mimetypes != '*') {
         // check filetype
         $filemimetype = file_storage::mimetype($_FILES[$elname]['tmp_name'], $record->filename);
         if (!in_array($filemimetype, $this->mimetypes)) {
             throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $_FILES[$elname]['name'])));
         }
     }
     if (empty($record->itemid)) {
         $record->itemid = 0;
     }
     if ($maxbytes !== -1 && filesize($_FILES[$elname]['tmp_name']) > $maxbytes) {
         $maxbytesdisplay = display_size($maxbytes);
         throw new file_exception('maxbytesfile', (object) array('file' => $record->filename, 'size' => $maxbytesdisplay));
     }
     if (file_is_draft_area_limit_reached($record->itemid, $areamaxbytes, filesize($_FILES[$elname]['tmp_name']))) {
         throw new file_exception('maxareabytes');
     }
     $record->contextid = $context->id;
     $record->userid = $USER->id;
     if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
         $existingfilename = $record->filename;
         $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
         $record->filename = $unused_filename;
         $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
         if ($overwriteexisting) {
             repository::overwrite_existing_draftfile($record->itemid, $record->filepath, $existingfilename, $record->filepath, $record->filename);
             $record->filename = $existingfilename;
         } else {
             $event = array();
             $event['event'] = 'fileexists';
             $event['newfile'] = new stdClass();
             $event['newfile']->filepath = $record->filepath;
             $event['newfile']->filename = $unused_filename;
             $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out(false);
             $event['existingfile'] = new stdClass();
             $event['existingfile']->filepath = $record->filepath;
             $event['existingfile']->filename = $existingfilename;
             $event['existingfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out(false);
             return $event;
         }
     } else {
         $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
     }
     return array('url' => moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(false), 'id' => $record->itemid, 'file' => $record->filename);
 }
     $home_url->param('action', 'browse');
     $home_url->param('draftpath', $draftpath);
     redirect($home_url);
     break;
 case 'downloaddir':
     $zipper = new zip_packer();
     $file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $draftpath, '.');
     if ($draftpath === '/') {
         $filename = get_string('files') . '.zip';
     } else {
         $filename = explode('/', trim($draftpath, '/'));
         $filename = array_pop($filename) . '.zip';
     }
     $newdraftitemid = file_get_unused_draft_itemid();
     if ($newfile = $zipper->archive_to_storage(array('/' => $file), $user_context->id, 'user', 'draft', $newdraftitemid, '/', $filename, $USER->id)) {
         $fileurl = moodle_url::make_draftfile_url($newdraftitemid, '/', $filename)->out();
         header('Location: ' . $fileurl);
     } else {
         print_error('cannotdownloaddir', 'repository');
     }
     break;
 case 'zip':
     $zipper = new zip_packer();
     $file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $draftpath, '.');
     if (!$file->get_parent_directory()) {
         $parent_path = '/';
         $filepath = '/';
         $filename = get_string('files') . '.zip';
     } else {
         $parent_path = $file->get_parent_directory()->get_filepath();
         $filepath = explode('/', trim($file->get_filepath(), '/'));
Example #14
0
/**
 * Listing all files (including folders) in current path (draft area)
 * used by file manager
 * @param int $draftitemid
 * @param string $filepath
 * @return stdClass
 */
function file_get_drafarea_files($draftitemid, $filepath = '/')
{
    global $USER, $OUTPUT, $CFG;
    $context = context_user::instance($USER->id);
    $fs = get_file_storage();
    $data = new stdClass();
    $data->path = array();
    $data->path[] = array('name' => get_string('files'), 'path' => '/');
    // will be used to build breadcrumb
    $trail = '/';
    if ($filepath !== '/') {
        $filepath = file_correct_filepath($filepath);
        $parts = explode('/', $filepath);
        foreach ($parts as $part) {
            if ($part != '' && $part != null) {
                $trail .= $part . '/';
                $data->path[] = array('name' => $part, 'path' => $trail);
            }
        }
    }
    $list = array();
    $maxlength = 12;
    if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
        foreach ($files as $file) {
            $item = new stdClass();
            $item->filename = $file->get_filename();
            $item->filepath = $file->get_filepath();
            $item->fullname = trim($item->filename, '/');
            $filesize = $file->get_filesize();
            $item->size = $filesize ? $filesize : null;
            $item->filesize = $filesize ? display_size($filesize) : '';
            $item->sortorder = $file->get_sortorder();
            $item->author = $file->get_author();
            $item->license = $file->get_license();
            $item->datemodified = $file->get_timemodified();
            $item->datecreated = $file->get_timecreated();
            $item->isref = $file->is_external_file();
            if ($item->isref && $file->get_status() == 666) {
                $item->originalmissing = true;
            }
            // find the file this draft file was created from and count all references in local
            // system pointing to that file
            $source = @unserialize($file->get_source());
            if (isset($source->original)) {
                $item->refcount = $fs->search_references_count($source->original);
            }
            if ($file->is_directory()) {
                $item->filesize = 0;
                $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
                $item->type = 'folder';
                $foldername = explode('/', trim($item->filepath, '/'));
                $item->fullname = trim(array_pop($foldername), '/');
                $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
            } else {
                // do NOT use file browser here!
                $item->mimetype = get_mimetype_description($file);
                if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
                    $item->type = 'zip';
                } else {
                    $item->type = 'file';
                }
                $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
                $item->url = $itemurl->out();
                $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
                $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
                if ($imageinfo = $file->get_imageinfo()) {
                    $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
                    $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
                    $item->image_width = $imageinfo['width'];
                    $item->image_height = $imageinfo['height'];
                }
            }
            $list[] = $item;
        }
    }
    $data->itemid = $draftitemid;
    $data->list = $list;
    return $data;
}
Example #15
0
    /**
     * Process a message received and validated by the Inbound Message processor.
     *
     * @throws \core\message\inbound\processing_failed_exception
     * @param \stdClass $messagedata The Inbound Message record
     * @param \stdClass $messagedata The message data packet
     * @return bool Whether the message was successfully processed.
     */
    public function process_message(\stdClass $record, \stdClass $messagedata) {
        global $DB, $USER;

        // Load the post being replied to.
        $post = $DB->get_record('forum_posts', array('id' => $record->datavalue));
        if (!$post) {
            mtrace("--> Unable to find a post matching with id {$record->datavalue}");
            return false;
        }

        // Load the discussion that this post is in.
        $discussion = $DB->get_record('forum_discussions', array('id' => $post->discussion));
        if (!$post) {
            mtrace("--> Unable to find the discussion for post {$record->datavalue}");
            return false;
        }

        // Load the other required data.
        $forum = $DB->get_record('forum', array('id' => $discussion->forum));
        $course = $DB->get_record('course', array('id' => $forum->course));
        $cm = get_fast_modinfo($course->id)->instances['forum'][$forum->id];
        $modcontext = \context_module::instance($cm->id);
        $usercontext = \context_user::instance($USER->id);

        // Make sure user can post in this discussion.
        $canpost = true;
        if (!forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext)) {
            $canpost = false;
        }

        if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
            $groupmode = $cm->groupmode;
        } else {
            $groupmode = $course->groupmode;
        }
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
            if ($discussion->groupid == -1) {
                $canpost = false;
            } else {
                if (!groups_is_member($discussion->groupid)) {
                    $canpost = false;
                }
            }
        }

        if (!$canpost) {
            $data = new \stdClass();
            $data->forum = $forum;
            throw new \core\message\inbound\processing_failed_exception('messageinboundnopostforum', 'mod_forum', $data);
        }

        // And check the availability.
        if (!\core_availability\info_module::is_user_visible($cm, $USER, true)) {
            $data = new \stdClass();
            $data->forum = $forum;
            throw new \core\message\inbound\processing_failed_exception('messageinboundforumhidden', 'mod_forum', $data);
        }

        // Before we add this we must check that the user will not exceed the blocking threshold.
        // This should result in an appropriate reply.
        $thresholdwarning = forum_check_throttling($forum, $cm);
        if (!empty($thresholdwarning) && !$thresholdwarning->canpost) {
            $data = new \stdClass();
            $data->forum = $forum;
            $data->message = get_string($thresholdwarning->errorcode, $thresholdwarning->module, $thresholdwarning->additional);
            throw new \core\message\inbound\processing_failed_exception('messageinboundthresholdhit', 'mod_forum', $data);
        }

        $addpost = new \stdClass();
        $addpost->course       = $course->id;
        $addpost->forum        = $forum->id;
        $addpost->discussion   = $discussion->id;
        $addpost->modified     = $messagedata->timestamp;
        $addpost->subject      = clean_param($messagedata->envelope->subject, PARAM_TEXT);
        $addpost->parent       = $post->id;
        $addpost->itemid       = file_get_unused_draft_itemid();

        if (!empty($messagedata->html)) {
            $addpost->message = $messagedata->html;
            $addpost->messageformat = FORMAT_HTML;
        } else {
            $addpost->message = $messagedata->plain;
            $addpost->messageformat = FORMAT_PLAIN;
        }

        // We don't trust text coming from e-mail.
        $addpost->messagetrust = false;

        // Add attachments to the post.
        if (!empty($messagedata->attachments['attachment']) && count($messagedata->attachments['attachment'])) {
            $attachmentcount = count($messagedata->attachments['attachment']);
            if (empty($forum->maxattachments) || $forum->maxbytes == 1 ||
                    !has_capability('mod/forum:createattachment', $modcontext)) {
                // Attachments are not allowed.
                mtrace("--> User does not have permission to attach files in this forum. Rejecting e-mail.");

                $data = new \stdClass();
                $data->forum = $forum;
                $data->attachmentcount = $attachmentcount;
                throw new \core\message\inbound\processing_failed_exception('messageinboundattachmentdisallowed', 'mod_forum', $data);
            }

            if ($forum->maxattachments < $attachmentcount) {
                // Too many attachments.
                mtrace("--> User attached {$attachmentcount} files when only {$forum->maxattachments} where allowed. "
                     . " Rejecting e-mail.");

                $data = new \stdClass();
                $data->forum = $forum;
                $data->attachmentcount = $attachmentcount;
                throw new \core\message\inbound\processing_failed_exception('messageinboundfilecountexceeded', 'mod_forum', $data);
            }

            $filesize = 0;
            $addpost->attachments  = file_get_unused_draft_itemid();
            foreach ($messagedata->attachments['attachment'] as $attachment) {
                mtrace("--> Processing {$attachment->filename} as an attachment.");
                $this->process_attachment('*', $usercontext, $addpost->attachments, $attachment);
                $filesize += $attachment->filesize;
            }

            if ($forum->maxbytes < $filesize) {
                // Too many attachments.
                mtrace("--> User attached {$filesize} bytes of files when only {$forum->maxbytes} where allowed. "
                     . "Rejecting e-mail.");
                $data = new \stdClass();
                $data->forum = $forum;
                $data->maxbytes = display_size($forum->maxbytes);
                $data->filesize = display_size($filesize);
                throw new \core\message\inbound\processing_failed_exception('messageinboundfilesizeexceeded', 'mod_forum', $data);
            }
        }

        // Process any files in the message itself.
        if (!empty($messagedata->attachments['inline'])) {
            foreach ($messagedata->attachments['inline'] as $attachment) {
                mtrace("--> Processing {$attachment->filename} as an inline attachment.");
                $this->process_attachment('*', $usercontext, $addpost->itemid, $attachment);

                // Convert the contentid link in the message.
                $draftfile = \moodle_url::make_draftfile_url($addpost->itemid, '/', $attachment->filename);
                $addpost->message = preg_replace('/cid:' . $attachment->contentid . '/', $draftfile, $addpost->message);
            }
        }

        // Insert the message content now.
        $addpost->id = forum_add_new_post($addpost, true);

        // Log the new post creation.
        $params = array(
            'context' => $modcontext,
            'objectid' => $addpost->id,
            'other' => array(
                'discussionid'  => $discussion->id,
                'forumid'       => $forum->id,
                'forumtype'     => $forum->type,
            )
        );
        $event = \mod_forum\event\post_created::create($params);
        $event->add_record_snapshot('forum_posts', $addpost);
        $event->add_record_snapshot('forum_discussions', $discussion);
        $event->trigger();

        mtrace("--> Created a post {$addpost->id} in {$discussion->id}.");
        return $addpost;
    }
Example #16
0
 /**
  * Do the actual processing of the uploaded file
  * @param string $saveas_filename name to give to the file
  * @param int $maxbytes maximum file size
  * @param mixed $types optional array of file extensions that are allowed or '*' for all
  * @param string $savepath optional path to save the file to
  * @param int $itemid optional the ID for this item within the file area
  * @param string $license optional the license to use for this file
  * @param string $author optional the name of the author of this file
  * @return object containing details of the file uploaded
  */
 public function process_upload($saveas_filename, $maxbytes, $types = '*', $savepath = '/', $itemid = 0, $license = null, $author = '')
 {
     global $USER, $CFG;
     if (is_array($types) and in_array('*', $types) or $types == '*') {
         $this->mimetypes = '*';
     } else {
         foreach ($types as $type) {
             $this->mimetypes[] = mimeinfo('type', $type);
         }
     }
     if ($license == null) {
         $license = $CFG->sitedefaultlicense;
     }
     $record = new stdClass();
     $record->filearea = 'draft';
     $record->component = 'user';
     $record->filepath = $savepath;
     $record->itemid = $itemid;
     $record->license = $license;
     $record->author = $author;
     $context = get_context_instance(CONTEXT_USER, $USER->id);
     $elname = 'repo_upload_file';
     $fs = get_file_storage();
     $sm = get_string_manager();
     if ($record->filepath !== '/') {
         $record->filepath = file_correct_filepath($record->filepath);
     }
     if (!isset($_FILES[$elname])) {
         throw new moodle_exception('nofile');
     }
     if (!empty($_FILES[$elname]['error'])) {
         switch ($_FILES[$elname]['error']) {
             case UPLOAD_ERR_INI_SIZE:
                 throw new moodle_exception('upload_error_ini_size', 'repository_upload');
                 break;
             case UPLOAD_ERR_FORM_SIZE:
                 throw new moodle_exception('upload_error_form_size', 'repository_upload');
                 break;
             case UPLOAD_ERR_PARTIAL:
                 throw new moodle_exception('upload_error_partial', 'repository_upload');
                 break;
             case UPLOAD_ERR_NO_FILE:
                 throw new moodle_exception('upload_error_no_file', 'repository_upload');
                 break;
             case UPLOAD_ERR_NO_TMP_DIR:
                 throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
                 break;
             case UPLOAD_ERR_CANT_WRITE:
                 throw new moodle_exception('upload_error_cant_write', 'repository_upload');
                 break;
             case UPLOAD_ERR_EXTENSION:
                 throw new moodle_exception('upload_error_extension', 'repository_upload');
                 break;
             default:
                 throw new moodle_exception('nofile');
         }
     }
     // scan the files, throws exception and deletes if virus found
     // this is tricky because clamdscan daemon might not be able to access the files
     $permissions = fileperms($_FILES[$elname]['tmp_name']);
     @chmod($_FILES[$elname]['tmp_name'], $CFG->filepermissions);
     self::antivir_scan_file($_FILES[$elname]['tmp_name'], $_FILES[$elname]['name'], true);
     @chmod($_FILES[$elname]['tmp_name'], $permissions);
     if (empty($saveas_filename)) {
         $record->filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
     } else {
         $ext = '';
         $match = array();
         $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
         if (preg_match('/\\.([a-z0-9]+)$/i', $filename, $match)) {
             if (isset($match[1])) {
                 $ext = $match[1];
             }
         }
         $ext = !empty($ext) ? $ext : '';
         if (preg_match('#\\.(' . $ext . ')$#i', $saveas_filename)) {
             // saveas filename contains file extension already
             $record->filename = $saveas_filename;
         } else {
             $record->filename = $saveas_filename . '.' . $ext;
         }
     }
     // Check the file has some non-null contents - usually an indication that a user has
     // tried to upload a folder by mistake
     if (!$this->check_valid_contents($_FILES[$elname]['tmp_name'])) {
         throw new moodle_exception('upload_error_invalid_file', 'repository_upload', '', $record->filename);
     }
     if ($this->mimetypes != '*') {
         // check filetype
         $filemimetype = mimeinfo('type', $_FILES[$elname]['name']);
         if (!in_array($filemimetype, $this->mimetypes)) {
             throw new moodle_exception('invalidfiletype', 'repository', '', get_mimetype_description(array('filename' => $_FILES[$elname]['name'])));
         }
     }
     if (empty($record->itemid)) {
         $record->itemid = 0;
     }
     if ($maxbytes !== -1 && filesize($_FILES[$elname]['tmp_name']) > $maxbytes) {
         throw new file_exception('maxbytes');
     }
     $record->contextid = $context->id;
     $record->userid = $USER->id;
     $record->source = '';
     if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
         $existingfilename = $record->filename;
         $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
         $record->filename = $unused_filename;
         $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
         $event = array();
         $event['event'] = 'fileexists';
         $event['newfile'] = new stdClass();
         $event['newfile']->filepath = $record->filepath;
         $event['newfile']->filename = $unused_filename;
         $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out(false);
         $event['existingfile'] = new stdClass();
         $event['existingfile']->filepath = $record->filepath;
         $event['existingfile']->filename = $existingfilename;
         $event['existingfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out(false);
         return $event;
     } else {
         $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
         return array('url' => moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(false), 'id' => $record->itemid, 'file' => $record->filename);
     }
 }
Example #17
0
    /**
     * Move file from download folder to file pool using FILE API
     * @global object $DB
     * @global object $CFG
     * @global object $USER
     * @global object $OUTPUT
     * @param string $thefile file path in download folder
     * @param object $record
     * @return array containing the following keys:
     *           icon
     *           file
     *           id
     *           url
     */
    public static function move_to_filepool($thefile, $record) {
        global $DB, $CFG, $USER, $OUTPUT;

        // scan for viruses if possible, throws exception if problem found
        self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!

        if ($record->filepath !== '/') {
            $record->filepath = trim($record->filepath, '/');
            $record->filepath = '/'.$record->filepath.'/';
        }
        $context = get_context_instance(CONTEXT_USER, $USER->id);
        $now = time();

        $record->contextid = $context->id;
        $record->component = 'user';
        $record->filearea  = 'draft';
        $record->timecreated  = $now;
        $record->timemodified = $now;
        $record->userid       = $USER->id;
        $record->mimetype     = mimeinfo('type', $thefile);
        if(!is_numeric($record->itemid)) {
            $record->itemid = 0;
        }
        $fs = get_file_storage();
        if ($existingfile = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
            $draftitemid = $record->itemid;
            $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
            $old_filename = $record->filename;
            // create a tmp file
            $record->filename = $new_filename;
            $newfile = $fs->create_file_from_pathname($record, $thefile);
            $event = array();
            $event['event'] = 'fileexists';
            $event['newfile'] = new stdClass;
            $event['newfile']->filepath = $record->filepath;
            $event['newfile']->filename = $new_filename;
            $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();

            $event['existingfile'] = new stdClass;
            $event['existingfile']->filepath = $record->filepath;
            $event['existingfile']->filename = $old_filename;
            $event['existingfile']->url      = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
            return $event;
        }
        if ($file = $fs->create_file_from_pathname($record, $thefile)) {
            if (empty($CFG->repository_no_delete)) {
                $delete = unlink($thefile);
                unset($CFG->repository_no_delete);
            }
            return array(
                'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
                'id'=>$file->get_itemid(),
                'file'=>$file->get_filename(),
                'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
            );
        } else {
            return null;
        }
    }
 function display_add_field($recordid = 0)
 {
     global $CFG, $DB, $OUTPUT, $USER, $PAGE;
     $file = false;
     $content = false;
     $displayname = '';
     $alttext = '';
     $itemid = null;
     $fs = get_file_storage();
     if ($recordid) {
         if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
             file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
             if (!empty($content->content)) {
                 if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                     $usercontext = context_user::instance($USER->id);
                     if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                         return false;
                     }
                     if ($thumbfile = $fs->get_file($usercontext->id, 'user', 'draft', $itemid, '/', 'thumb_' . $content->content)) {
                         $thumbfile->delete();
                     }
                     if (empty($content->content1)) {
                         // Print icon if file already exists
                         $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                         $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                     } else {
                         $displayname = get_string('nofilesattached', 'repository');
                     }
                 }
             }
             $alttext = $content->content1;
         }
     } else {
         $itemid = file_get_unused_draft_itemid();
     }
     $str = '<div title="' . s($this->field->description) . '">';
     $str .= '<fieldset><legend><span class="accesshide">' . $this->field->name . '</span></legend>';
     $str .= '<noscript>';
     if ($file) {
         $src = file_encode_url($CFG->wwwroot . '/pluginfile.php/', $this->context->id . '/mod_data/content/' . $content->id . '/' . $file->get_filename());
         $str .= '<img width="' . s($this->previewwidth) . '" height="' . s($this->previewheight) . '" src="' . $src . '" alt="" />';
     }
     $str .= '</noscript>';
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->maxfiles = 1;
     // Only one picture permitted.
     $options->itemid = $itemid;
     $options->accepted_types = array('web_image');
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     if (!empty($file)) {
         $options->filename = $file->get_filename();
         $options->filepath = '/';
     }
     $fm = new form_filemanager($options);
     // Print out file manager.
     $output = $PAGE->get_renderer('core', 'files');
     $str .= $output->render($fm);
     $str .= '<div class="mdl-left">';
     $str .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $str .= '<label for="field_' . $this->field->id . '_alttext">' . get_string('alttext', 'data') . '</label>&nbsp;<input type="text" name="field_' . $this->field->id . '_alttext" id="field_' . $this->field->id . '_alttext" value="' . s($alttext) . '" />';
     $str .= '</div>';
     $str .= '</fieldset>';
     $str .= '</div>';
     $module = array('name' => 'form_filemanager', 'fullpath' => '/lib/form/filemanager.js', 'requires' => array('core_filepicker', 'base', 'io-base', 'node', 'json', 'core_dndupload', 'panel', 'resize-plugin', 'dd-plugin'), 'strings' => array(array('error', 'moodle'), array('info', 'moodle'), array('confirmdeletefile', 'repository'), array('draftareanofiles', 'repository'), array('entername', 'repository'), array('enternewname', 'repository'), array('invalidjson', 'repository'), array('popupblockeddownload', 'repository'), array('unknownoriginal', 'repository'), array('confirmdeletefolder', 'repository'), array('confirmdeletefilewithhref', 'repository'), array('confirmrenamefolder', 'repository'), array('confirmrenamefile', 'repository'), array('edit', 'moodle')));
     $PAGE->requires->js_init_call('M.form_filemanager.init', array($fm->options), true, $module);
     return $str;
 }
Example #19
0
 /**
  * Move file from download folder to file pool using FILE API
  * @global object $DB
  * @global object $CFG
  * @global object $USER
  * @global object $OUTPUT
  * @param string $thefile file path in download folder
  * @param object $record
  * @return array containing the following keys:
  *           icon
  *           file
  *           id
  *           url
  */
 public static function move_to_filepool($thefile, $record)
 {
     global $DB, $CFG, $USER, $OUTPUT;
     if ($record->filepath !== '/') {
         $record->filepath = trim($record->filepath, '/');
         $record->filepath = '/' . $record->filepath . '/';
     }
     $context = get_context_instance(CONTEXT_USER, $USER->id);
     $now = time();
     $record->contextid = $context->id;
     $record->component = 'user';
     $record->filearea = 'draft';
     $record->timecreated = $now;
     $record->timemodified = $now;
     $record->userid = $USER->id;
     $record->mimetype = mimeinfo('type', $thefile);
     if (!is_numeric($record->itemid)) {
         $record->itemid = 0;
     }
     $fs = get_file_storage();
     if ($existingfile = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
         throw new moodle_exception('fileexists');
     }
     if ($file = $fs->create_file_from_pathname($record, $thefile)) {
         if (empty($CFG->repository_no_delete)) {
             $delete = unlink($thefile);
             unset($CFG->repository_no_delete);
         }
         return array('url' => moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(), 'id' => $file->get_itemid(), 'file' => $file->get_filename(), 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out());
     } else {
         return null;
     }
 }
Example #20
0
 function display_add_field($recordid = 0)
 {
     global $CFG, $DB, $OUTPUT, $USER, $PAGE;
     $file = false;
     $content = false;
     $displayname = '';
     $alttext = '';
     $itemid = null;
     $fs = get_file_storage();
     if ($recordid) {
         if ($content = $DB->get_record('data_content', array('fieldid' => $this->field->id, 'recordid' => $recordid))) {
             file_prepare_draft_area($itemid, $this->context->id, 'mod_data', 'content', $content->id);
             if (!empty($content->content)) {
                 if ($file = $fs->get_file($this->context->id, 'mod_data', 'content', $content->id, '/', $content->content)) {
                     $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
                     if (!($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $itemid, 'id DESC', false))) {
                         return false;
                     }
                     if ($thumbfile = $fs->get_file($usercontext->id, 'user', 'draft', $itemid, '/', 'thumb_' . $content->content)) {
                         $thumbfile->delete();
                     }
                     if (empty($content->content1)) {
                         // Print icon if file already exists
                         $src = moodle_url::make_draftfile_url($itemid, '/', $file->get_filename());
                         $displayname = $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')) . '<a href="' . $src . '" >' . s($file->get_filename()) . '</a>';
                     } else {
                         $displayname = get_string('nofilesattached', 'repository');
                     }
                 }
             }
             $alttext = $content->content1;
         }
     } else {
         $itemid = file_get_unused_draft_itemid();
     }
     $str = '<div title="' . s($this->field->description) . '">';
     $str .= '<fieldset><legend><span class="accesshide">' . $this->field->name . '</span></legend>';
     if ($file) {
         $src = file_encode_url($CFG->wwwroot . '/pluginfile.php/', $this->context->id . '/mod_data/content/' . $content->id . '/' . $file->get_filename());
         $str .= '<img width="' . s($this->previewwidth) . '" height="' . s($this->previewheight) . '" src="' . $src . '" alt="" />';
     }
     $options = new stdClass();
     $options->maxbytes = $this->field->param3;
     $options->itemid = $itemid;
     $options->accepted_types = array('web_image');
     $options->return_types = FILE_INTERNAL;
     $options->context = $PAGE->context;
     if (!empty($file)) {
         $options->filename = $file->get_filename();
         $options->filepath = '/';
     }
     $fp = new file_picker($options);
     $str .= $OUTPUT->render($fp);
     $str .= '<div class="mdl-left">';
     $str .= '<input type="hidden" name="field_' . $this->field->id . '_file" value="' . $itemid . '" />';
     $str .= '<label for="field_' . $this->field->id . '_alttext">' . get_string('alttext', 'data') . '</label>&nbsp;<input type="text" name="field_' . $this->field->id . '_alttext" id="field_' . $this->field->id . '_alttext" value="' . s($alttext) . '" />';
     $str .= '</div>';
     $str .= '</fieldset>';
     $str .= '</div>';
     $module = array('name' => 'data_imagepicker', 'fullpath' => '/mod/data/data.js', 'requires' => array('core_filepicker'));
     $PAGE->requires->js_init_call('M.data_imagepicker.init', array($fp->options), true, $module);
     return $str;
 }
Example #21
0
 /**
  * Private method to fetch details on our recorded file,
  * and filter options
  * @param string $keyword
  * @param int $start
  * @param int $max max results
  * @param string $sort
  * @return array
  */
 private function fetch_filelist($filename)
 {
     global $CFG, $USER;
     $hideoptions = false;
     if (!empty($this->options['hide_player_opts'])) {
         $hideoptions = $this->options['hide_player_opts'];
     }
     $list = array();
     //if user did not record anything, or the recording copy failed can out sadly.
     if (!$filename) {
         return $list;
     }
     //if(!$filename){$filename="houses.jpg";}
     //determine the file extension
     $ext = substr($filename, -4);
     //determine the download source
     switch ($this->options['recording_format']) {
         case self::POODLLAUDIO:
         case self::POODLLVIDEO:
             if (\filter_poodll\poodlltools::isMobile($CFG->filter_poodll_html5rec)) {
                 $urltofile = moodle_url::make_draftfile_url("0", "/", $filename)->out(false);
                 $source = $urltofile;
             } else {
                 //set up auto transcoding (mp3) or not
                 //The jsp to call is different.
                 $jsp = "download.jsp";
                 if ($ext == ".mp4" || $ext == ".mp3") {
                     $jsp = "convert.jsp";
                 }
                 $source = "http://" . $CFG->filter_poodll_servername . ":" . $CFG->filter_poodll_serverhttpport . "/poodll/" . $jsp . "?poodllserverid=" . $CFG->filter_poodll_serverid . "&filename=" . $filename . "&caller=" . urlencode($CFG->wwwroot);
             }
             break;
             //this was the download script for snapshots and direct uploads
             //the upload script is the same file, called from widget directly. Callback posted filename back to form
             //case self::POODLLSNAPSHOT:
             //	$source=$CFG->wwwroot . '/repository/poodll/uploadHandler.php?filename=' . $filename;
             //	break;
         //this was the download script for snapshots and direct uploads
         //the upload script is the same file, called from widget directly. Callback posted filename back to form
         //case self::POODLLSNAPSHOT:
         //	$source=$CFG->wwwroot . '/repository/poodll/uploadHandler.php?filename=' . $filename;
         //	break;
         case self::POODLLSNAPSHOT:
         case self::MP3AUDIO:
         case self::POODLLWHITEBOARD:
             //$source=$CFG->wwwroot . '/repository/poodll/uploadHandler.php?filename=' . $filename;
             //$source = $filename;
             /*
             				$browser = get_file_browser();
             				$fileinfo = $browser->get_file_info($context->id,"user","draft","0","/",$filename );
             				$context = get_context_instance(CONTEXT_USER, $USER->id);
             //If we could get an info object, process. But if we couldn't, although we have info via $f, we don't have permissions
             				//so we don't reveal it
             				$urltofile = "no title";
             				if($fileinfo){
             					$urltofile = $fileinfo->get_url();
             				}
             */
             $urltofile = moodle_url::make_draftfile_url("0", "/", $filename)->out(false);
             $source = $urltofile;
     }
     //determine the player options
     switch ($this->options['recording_format']) {
         case self::POODLLAUDIO:
         case self::MP3AUDIO:
             //normal player
             if ($ext == ".mp3") {
                 $list[] = array('title' => $filename, 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/audionormal.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
             } else {
                 $list[] = array('title' => substr_replace($filename, '.audio' . $ext, -4), 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/audionormal.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
             }
             if (!$hideoptions) {
                 $list[] = array('title' => substr_replace($filename, '.mini' . $ext, -4), 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/miniplayer.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
                 $list[] = array('title' => substr_replace($filename, '.word' . $ext, -4), 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/wordplayer.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
                 $list[] = array('title' => substr_replace($filename, '.inlineword' . $ext, -4), 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/inlinewordplayer.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
                 $list[] = array('title' => substr_replace($filename, '.once' . $ext, -4), 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/onceplayer.jpg", 'thumbnail_width' => 280, 'thumbnail_height' => 100, 'size' => '', 'date' => '', 'source' => $source);
             }
             break;
         default:
             $list[] = array('title' => $filename, 'thumbnail' => "{$CFG->wwwroot}/repository/poodll/pix/bigicon.png", 'thumbnail_width' => 330, 'thumbnail_height' => 115, 'size' => '', 'date' => '', 'source' => $source);
     }
     //return the list of files/player options
     return $list;
 }
Example #22
0
 /**
  * Move file from download folder to file pool using FILE API
  *
  * @todo MDL-28637
  * @static
  * @param string $thefile file path in download folder
  * @param stdClass $record
  * @return array containing the following keys:
  *           icon
  *           file
  *           id
  *           url
  */
 public static function move_to_filepool($thefile, $record)
 {
     global $DB, $CFG, $USER, $OUTPUT;
     // scan for viruses if possible, throws exception if problem found
     self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete));
     //TODO: MDL-28637 this repository_no_delete is a bloody hack!
     $fs = get_file_storage();
     // If file name being used.
     if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
         $draftitemid = $record->itemid;
         $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
         $old_filename = $record->filename;
         // Create a tmp file.
         $record->filename = $new_filename;
         $newfile = $fs->create_file_from_pathname($record, $thefile);
         $event = array();
         $event['event'] = 'fileexists';
         $event['newfile'] = new stdClass();
         $event['newfile']->filepath = $record->filepath;
         $event['newfile']->filename = $new_filename;
         $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
         $event['existingfile'] = new stdClass();
         $event['existingfile']->filepath = $record->filepath;
         $event['existingfile']->filename = $old_filename;
         $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
         return $event;
     }
     if ($file = $fs->create_file_from_pathname($record, $thefile)) {
         if (empty($CFG->repository_no_delete)) {
             $delete = unlink($thefile);
             unset($CFG->repository_no_delete);
         }
         return array('url' => moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(), 'id' => $file->get_itemid(), 'file' => $file->get_filename(), 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out());
     } else {
         return null;
     }
 }
Example #23
0
/**
 * Resize the image, if required, then generate an img tag and, if required, a link to the full-size image
 * @param stored_file $file the image file to process
 * @param int $maxwidth the maximum width allowed for the image
 * @param int $maxheight the maximum height allowed for the image
 * @return string HTML fragment to add to the label
 */
function label_generate_resized_image(stored_file $file, $maxwidth, $maxheight)
{
    global $CFG;
    $fullurl = moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename());
    $link = null;
    $attrib = array('alt' => $file->get_filename(), 'src' => $fullurl);
    if ($imginfo = $file->get_imageinfo()) {
        // Work out the new width / height, bounded by maxwidth / maxheight
        $width = $imginfo['width'];
        $height = $imginfo['height'];
        if (!empty($maxwidth) && $width > $maxwidth) {
            $height *= (double) $maxwidth / $width;
            $width = $maxwidth;
        }
        if (!empty($maxheight) && $height > $maxheight) {
            $width *= (double) $maxheight / $height;
            $height = $maxheight;
        }
        $attrib['width'] = $width;
        $attrib['height'] = $height;
        // If the size has changed and the image is of a suitable mime type, generate a smaller version
        if ($width != $imginfo['width']) {
            $mimetype = $file->get_mimetype();
            if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
                require_once $CFG->libdir . '/gdlib.php';
                $tmproot = make_temp_directory('mod_label');
                $tmpfilepath = $tmproot . '/' . $file->get_contenthash();
                $file->copy_content_to($tmpfilepath);
                $data = generate_image_thumbnail($tmpfilepath, $width, $height);
                unlink($tmpfilepath);
                if (!empty($data)) {
                    $fs = get_file_storage();
                    $record = array('contextid' => $file->get_contextid(), 'component' => $file->get_component(), 'filearea' => $file->get_filearea(), 'itemid' => $file->get_itemid(), 'filepath' => '/', 'filename' => 's_' . $file->get_filename());
                    $smallfile = $fs->create_file_from_string($record, $data);
                    // Replace the image 'src' with the resized file and link to the original
                    $attrib['src'] = moodle_url::make_draftfile_url($smallfile->get_itemid(), $smallfile->get_filepath(), $smallfile->get_filename());
                    $link = $fullurl;
                }
            }
        }
    } else {
        // Assume this is an image type that get_imageinfo cannot handle (e.g. SVG)
        $attrib['width'] = $maxwidth;
    }
    $img = html_writer::empty_tag('img', $attrib);
    if ($link) {
        return html_writer::link($link, $img);
    } else {
        return $img;
    }
}
Example #24
0
    /**
     * Process uploaded file
     * @return array|bool
     */
    public function upload($saveas_filename, $maxbytes) {
        global $USER, $CFG;

        $types = optional_param('accepted_types', '*', PARAM_RAW);
        if ((is_array($types) and in_array('*', $types)) or $types == '*') {
            $this->mimetypes = '*';
        } else {
            foreach ($types as $type) {
                $this->mimetypes[] = mimeinfo('type', $type);
            }
        }

        $record = new stdClass();
        $record->filearea = 'draft';
        $record->component = 'user';
        $record->filepath = optional_param('savepath', '/', PARAM_PATH);
        $record->itemid   = optional_param('itemid', 0, PARAM_INT);
        $record->license  = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
        $record->author   = optional_param('author', '', PARAM_TEXT);

        $context = get_context_instance(CONTEXT_USER, $USER->id);
        $elname = 'repo_upload_file';

        $fs = get_file_storage();
        $sm = get_string_manager();

        if ($record->filepath !== '/') {
            $record->filepath = file_correct_filepath($record->filepath);
        }

        if (!isset($_FILES[$elname])) {
            throw new moodle_exception('nofile');
        }
        if (!empty($_FILES[$elname]['error'])) {
            switch ($_FILES[$elname]['error']) {
            case UPLOAD_ERR_INI_SIZE:
                throw new moodle_exception('upload_error_ini_size', 'repository_upload');
                break;
            case UPLOAD_ERR_FORM_SIZE:
                throw new moodle_exception('upload_error_form_size', 'repository_upload');
                break;
            case UPLOAD_ERR_PARTIAL:
                throw new moodle_exception('upload_error_partial', 'repository_upload');
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new moodle_exception('upload_error_no_file', 'repository_upload');
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
                break;
            case UPLOAD_ERR_CANT_WRITE:
                throw new moodle_exception('upload_error_cant_write', 'repository_upload');
                break;
            case UPLOAD_ERR_EXTENSION:
                throw new moodle_exception('upload_error_extension', 'repository_upload');
                break;
            default:
                throw new moodle_exception('nofile');
            }
        }

        if (empty($saveas_filename)) {
            $record->filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
        } else {
            $ext = '';
            $match = array();
            $filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
            if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
                if (isset($match[1])) {
                    $ext = $match[1];
                }
            }
            $ext = !empty($ext) ? $ext : '';
            if (preg_match('#\.(' . $ext . ')$#i', $saveas_filename)) {
                // saveas filename contains file extension already
                $record->filename = $saveas_filename;
            } else {
                $record->filename = $saveas_filename . '.' . $ext;
            }
        }

        if ($this->mimetypes != '*') {
            // check filetype
            $filemimetype = mimeinfo('type', $_FILES[$elname]['name']);
            if (!in_array($filemimetype, $this->mimetypes)) {
                if ($sm->string_exists($filemimetype, 'mimetypes')) {
                    $filemimetype = get_string($filemimetype, 'mimetypes');
                }
                throw new moodle_exception('invalidfiletype', 'repository', '', $filemimetype);
            }
        }

        if (empty($record->itemid)) {
            $record->itemid = 0;
        }

        if (($maxbytes!==-1) && (filesize($_FILES[$elname]['tmp_name']) > $maxbytes)) {
            throw new file_exception('maxbytes');
        }

        if ($file = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
            throw new moodle_exception('fileexists', 'repository');
        }

        $record->contextid = $context->id;
        $record->userid    = $USER->id;
        $record->source    = '';

        $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);

        return array(
            'url'=>moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(),
            'id'=>$record->itemid,
            'file'=>$record->filename);
    }
Example #25
0
 /**
  * Process uploaded file
  * @return array|bool
  */
 public function upload($saveas_filename, $maxbytes)
 {
     global $USER, $CFG;
     $types = optional_param('accepted_types', '*', PARAM_RAW);
     if (is_array($types) and in_array('*', $types) or $types == '*') {
         $this->mimetypes = '*';
     } else {
         foreach ($types as $type) {
             $this->mimetypes[] = mimeinfo('type', $type);
         }
     }
     $record = new stdClass();
     $record->filearea = 'draft';
     $record->component = 'user';
     $record->filepath = optional_param('savepath', '/', PARAM_PATH);
     $record->itemid = optional_param('itemid', 0, PARAM_INT);
     $record->license = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
     $record->author = optional_param('author', '', PARAM_TEXT);
     $context = get_context_instance(CONTEXT_USER, $USER->id);
     $elname = 'repo_upload_file';
     $fs = get_file_storage();
     $sm = get_string_manager();
     if ($record->filepath !== '/') {
         $record->filepath = file_correct_filepath($record->filepath);
     }
     if (!isset($_FILES[$elname])) {
         throw new moodle_exception('nofile');
     }
     if (!empty($_FILES[$elname]['error'])) {
         throw new moodle_exception('maxbytes');
     }
     if (empty($saveas_filename)) {
         $record->filename = clean_param($_FILES[$elname]['name'], PARAM_FILE);
     } else {
         $record->filename = $saveas_filename;
     }
     if ($this->mimetypes != '*') {
         // check filetype
         $filemimetype = mimeinfo('type', $_FILES[$elname]['name']);
         if (!in_array($filemimetype, $this->mimetypes)) {
             if ($sm->string_exists($filemimetype, 'mimetypes')) {
                 $filemimetype = get_string($filemimetype, 'mimetypes');
             }
             throw new moodle_exception('invalidfiletype', 'repository', '', $filemimetype);
         }
     }
     if (empty($record->itemid)) {
         $record->itemid = 0;
     }
     if ($maxbytes !== -1 && filesize($_FILES[$elname]['tmp_name']) > $maxbytes) {
         throw new file_exception('maxbytes');
     }
     if ($file = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
         throw new moodle_exception('fileexists', 'repository');
     }
     $record->contextid = $context->id;
     $record->userid = $USER->id;
     $record->source = '';
     $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
     return array('url' => moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(), 'id' => $record->itemid, 'file' => $record->filename);
 }