Exemple #1
1
 public function render_files_tree_viewer(files_tree_viewer $tree)
 {
     $html = $this->output->heading_with_help(get_string('coursefiles'), 'courselegacyfiles', 'moodle');
     $html .= $this->output->container_start('coursefilesbreadcrumb');
     foreach ($tree->path as $path) {
         $html .= $path;
         $html .= ' / ';
     }
     $html .= $this->output->container_end();
     $html .= $this->output->box_start();
     $table = new html_table();
     $table->head = array(get_string('filename', 'backup'), get_string('size'), get_string('modified'));
     $table->align = array('left', 'right', 'right');
     $table->width = '100%';
     $table->data = array();
     foreach ($tree->tree as $file) {
         if (!empty($file['isdir'])) {
             $table->data[] = array(html_writer::link($file['url'], $this->output->pix_icon('f/folder', 'icon') . ' ' . $file['filename']), '', $file['filedate']);
         } else {
             $table->data[] = array(html_writer::link($file['url'], $this->output->pix_icon('f/' . mimeinfo('icon', $file['filename']), get_string('icon')) . ' ' . $file['filename']), $file['filesize'], $file['filedate']);
         }
     }
     $html .= html_writer::table($table);
     $html .= $this->output->single_button(new moodle_url('/files/coursefilesedit.php', array('contextid' => $tree->context->id)), get_string('coursefilesedit'), 'get');
     $html .= $this->output->box_end();
     return $html;
 }
Exemple #2
0
 public function can_import_file($file) {
     $mimetypes = array(
         mimeinfo('type', '.dat'),
         mimeinfo('type', '.zip')
     );
     return in_array($file->get_mimetype(), $mimetypes);
 }
 /**
  * Internal function - creates htmls structure suitable for YUI tree.
  */
 protected function htmllize_tree($tree, $dir)
 {
     global $CFG;
     $yuiconfig = array();
     $yuiconfig['type'] = 'html';
     if (empty($dir['subdirs']) and empty($dir['files'])) {
         return '';
     }
     $result = '<ul>';
     foreach ($dir['subdirs'] as $subdir) {
         $image = $this->output->pix_icon("f/folder", $subdir['dirname'], 'moodle', array('class' => 'icon'));
         $result .= '<li yuiConfig=\'' . json_encode($yuiconfig) . '\'><div>' . $image . ' ' . s($subdir['dirname']) . '</div> ' . $this->htmllize_tree($tree, $subdir) . '</li>';
     }
     foreach ($dir['files'] as $file) {
         $url = file_encode_url("{$CFG->wwwroot}/blocks/csv_enrol/getfile.php", '/' . $tree->context->id . '/user/csvenrol' . $file->get_filepath() . $file->get_filename(), true);
         $filename = $file->get_filename();
         $icon = mimeinfo("icon", $filename);
         if (strlen($filename) > 10) {
             $pi = pathinfo($filename);
             $txt = $pi['filename'];
             $ext = $pi['extension'];
             $filename = substr($filename, 0, 14) . '...' . $ext;
         }
         $image = $this->output->pix_icon("f/{$icon}", $filename, 'moodle', array('class' => 'icon'));
         $result .= '<li yuiConfig=\'' . json_encode($yuiconfig) . '\'><div>' . html_writer::link($url, $image . '&nbsp;' . $filename) . '</div></li>';
     }
     $result .= '</ul>';
     return $result;
 }
 public function get_listing($path = '', $page = '')
 {
     global $CFG;
     $list = array();
     $list['list'] = array();
     // the management interface url
     $list['manage'] = false;
     // dynamically loading
     $list['dynload'] = true;
     // the current path of this list.
     // set to true, the login link will be removed
     $list['nologin'] = true;
     // set to true, the search button will be removed
     $list['nosearch'] = true;
     $tree = array();
     if (empty($path)) {
         $buckets = $this->s->listBuckets();
         foreach ($buckets as $bucket) {
             $folder = array('title' => $bucket, 'children' => array(), 'thumbnail' => $CFG->pixpath . '/f/folder-32.png', 'path' => $bucket);
             $tree[] = $folder;
         }
     } else {
         $contents = $this->s->getBucket($path);
         foreach ($contents as $file) {
             $info = $this->s->getObjectInfo($path, baseName($file['name']));
             $tree[] = array('title' => $file['name'], 'size' => $file['size'], 'date' => userdate($file['time']), 'source' => $path . '/' . $file['name'], 'thumbnail' => $CFG->pixpath . '/f/' . mimeinfo('icon32', $file['name']));
         }
     }
     $list['list'] = $tree;
     return $list;
 }
/**
 * Returns the HTML to display the file submitted by the student
 * (adapted from mod/assignment/lib.php)
 *
 * @param int $attemptid attempt id
 * @param int $questionid question id
 * @return string string to print to display file list
 */
function get_student_answer($attemptid, $questionid)
{
    global $CFG;
    $filearea = quiz_file_area_name($attemptid, $questionid);
    $output = '';
    if ($basedir = quiz_file_area($filearea)) {
        if ($files = get_directory_list($basedir)) {
            if (count($files) == 0) {
                return false;
            }
            foreach ($files as $key => $file) {
                require_once $CFG->libdir . '/filelib.php';
                $icon = mimeinfo('icon', $file);
                // remove "questionattempt", the first dir in the path, from the URL
                $filearealist = explode('/', $filearea);
                $fileareaurl = implode('/', array_slice($filearealist, 1));
                if ($CFG->slasharguments) {
                    $ffurl = "{$CFG->wwwroot}/question/file.php/{$fileareaurl}/{$file}";
                } else {
                    $ffurl = "{$CFG->wwwroot}/question/file.php?file=/{$fileareaurl}/{$file}";
                }
                $output .= '<img align="middle" src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . '<a href="' . $ffurl . '" >' . $file . '</a><br />';
            }
        }
    }
    // (Is this desired for theme reasons?)
    //$output = '<div class="files">'.$output.'</div>';
    return $output;
}
function block_exabis_eportfolio_print_extern_item($item, $access)
{
    global $CFG;
    print_heading(format_string($item->name));
    $box_content = '';
    if ($item->type == 'link') {
        $link = clean_param($item->url, PARAM_URL);
        $link_js = str_replace('http://', '', $link);
        if ($link) {
            $box_content .= '<p><a href="#" onclick="window.open(\'http://' . addslashes_js($link_js) . '\',\'validate\',\'width=620,height=450,scrollbars=yes,status=yes,resizable=yes,menubar=yes,location=yes\');return true;">' . $link . '</a></p>';
        }
    } elseif ($item->type == 'file') {
        if ($item->attachment) {
            $type = mimeinfo("type", $item->attachment);
            $ffurl = "{$CFG->wwwroot}/blocks/exabis_eportfolio/portfoliofile.php?access=" . $access . "&itemid=" . $item->id;
            if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) {
                // Image attachments don't get printed as links
                $box_content .= "<img width=\"100%\" src=\"{$ffurl}\" alt=\"" . format_string($item->name) . "\" /><br/>";
            } else {
                $box_content .= "<p>" . link_to_popup_window("{$ffurl}", 'popup', "{$ffurl}", $height = 400, $width = 500, format_string($item->name), 'none', true) . "</p>";
            }
        }
    }
    $box_content .= format_text($item->intro, FORMAT_HTML);
    print_box($box_content);
}
Exemple #7
0
    /**
     * Internal function - creates htmls structure suitable for YUI tree.
     */
    protected function htmllize_tree($tree, $dir) {
        global $CFG;
        $yuiconfig = array();
        $yuiconfig['type'] = 'html';

        if (empty($dir['subdirs']) and empty($dir['files'])) {
            return '';
        }

        $result = '<ul>';
        foreach ($dir['subdirs'] as $subdir) {
            $image = $this->output->pix_icon("f/folder", $subdir['dirname'], 'moodle', array('class'=>'icon'));
            $result .= '<li yuiConfig=\''.json_encode($yuiconfig).'\'><div>'.$image.' '.s($subdir['dirname']).'</div> '.$this->htmllize_tree($tree, $subdir).'</li>';
        }

        foreach ($dir['files'] as $file) {
            $filename = $file->get_filename();
            $icon = mimeinfo("icon", $filename);
            if ($CFG->enableplagiarism) {
                require_once($CFG->libdir.'/plagiarismlib.php');
                $plagiarsmlinks = plagiarism_get_links(array('userid'=>$file->get_userid(), 'file'=>$file, 'cmid'=>$tree->cm->id, 'course'=>$tree->course));
            } else {
                $plagiarsmlinks = '';
            }
            $image = $this->output->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
            $result .= '<li yuiConfig=\''.json_encode($yuiconfig).'\'><div>'.$image.' '.$file->fileurl.' '.$plagiarsmlinks.$file->portfoliobutton.'</div></li>';
        }

        $result .= '</ul>';

        return $result;
    }
 function definition()
 {
     global $CFG;
     $mform =& $this->_form;
     //--------------------------------------------------------------------------------
     $urls = $this->_customdata['urls'];
     $fromareaname = $this->_customdata['fromareaname'];
     $toareaname = $this->_customdata['toareaname'];
     $fileoptions = array(QUESTION_FILEDONOTHING => get_string('donothing', 'question'), QUESTION_FILECOPY => get_string('copy', 'question', $fromareaname), QUESTION_FILEMOVE => get_string('move', 'question', $fromareaname), QUESTION_FILEMOVELINKSONLY => get_string('movelinksonly', 'question', $fromareaname));
     $brokenfileoptions = array(QUESTION_FILEDONOTHING => get_string('donothing', 'question'), QUESTION_FILEMOVELINKSONLY => get_string('movelinksonly', 'question', $fromareaname));
     $brokenurls = $this->_customdata['brokenurls'];
     if (count($urls)) {
         $mform->addElement('header', 'general', get_string('filestomove', 'question', $toareaname));
         $i = 0;
         foreach (array_keys($urls) as $url) {
             $iconname = mimeinfo('icon', $url);
             $icontype = mimeinfo('type', $url);
             $img = "<img src=\"{$CFG->pixpath}/f/{$iconname}\"  class=\"icon\" alt=\"{$icontype}\" />";
             if (in_array($url, $brokenurls)) {
                 $mform->addElement('select', "urls[{$i}]", $img . $url, $brokenfileoptions);
             } else {
                 $mform->addElement('select', "urls[{$i}]", $img . $url, $fileoptions);
             }
             $i++;
         }
     }
     if (count($brokenurls)) {
         $mform->addElement('advcheckbox', 'ignorebroken', get_string('ignorebroken', 'question'));
     }
     //--------------------------------------------------------------------------------
     $this->add_action_buttons(true, get_string('movecategory', 'question'));
 }
 public function get_listing($path = '', $page = '')
 {
     global $CFG;
     $client = new wikimedia();
     $result = $client->search_images($this->keyword);
     $list = array();
     $list['list'] = array();
     foreach ($result as $title => $url) {
         $list['list'][] = array('title' => substr($title, 5), 'thumbnail' => $CFG->pixpath . '/f/' . mimeinfo('icon32', 'xx.jpg'), 'source' => $url, 'url' => $url);
     }
     return $list;
 }
 function definition()
 {
     global $CFG;
     global $COURSE;
     $mform =& $this->_form;
     //-- General --------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     /// name
     $mform->addElement('text', 'name', get_string('name'), array('size' => '60'));
     $mform->setType('name', PARAM_TEXT);
     $mform->addRule('name', null, 'required', null, 'client');
     /// text (description)
     $mform->addElement('htmleditor', 'text', get_string('description'));
     $mform->setType('text', PARAM_RAW);
     //$mform->addRule('text', get_string('required'), 'required', null, 'client');
     $mform->setHelpButton('text', array('writing', 'richtext'), false, 'editorhelpbutton');
     /// introformat
     $mform->addElement('format', 'introformat', get_string('format'));
     //-- Stamp Collection------------------------------------------------------------
     $mform->addElement('header', 'stampcollection', get_string('modulename', 'stampcoll'));
     /// stampimage
     make_upload_directory("{$COURSE->id}");
     // Just in case
     $images = array();
     $coursefiles = get_directory_list("{$CFG->dataroot}/{$COURSE->id}", $CFG->moddata);
     foreach ($coursefiles as $filename) {
         if (mimeinfo("icon", $filename) == "image.gif") {
             $images["{$filename}"] = $filename;
         }
     }
     $mform->addElement('select', 'image', get_string('stampimage', 'stampcoll'), array_merge(array('' => get_string('default')), $images), 'a', 'b', 'c', 'd');
     $mform->addElement('static', 'stampimageinfo', '', get_string('stampimageinfo', 'stampcoll'));
     /// displayzero
     $mform->addElement('selectyesno', 'displayzero', get_string('displayzero', 'stampcoll'));
     $mform->setDefault('displayzero', 0);
     //-------------------------------------------------------------------------------
     // add standard elements, common to all modules
     $this->standard_coursemodule_elements();
     //-------------------------------------------------------------------------------
     // add standard buttons, common to all modules
     $this->add_action_buttons();
 }
 function print_student_answer($userid, $return = false)
 {
     global $CFG, $USER;
     $filearea = $this->file_area_name($userid);
     $output = '';
     if ($basedir = $this->file_area($userid)) {
         if ($files = get_directory_list($basedir)) {
             require_once $CFG->libdir . '/filelib.php';
             foreach ($files as $key => $file) {
                 $icon = mimeinfo('icon', $file);
                 $ffurl = get_file_url("{$filearea}/{$file}");
                 //died right here
                 //require_once($ffurl);
                 $output = '<img align="middle" src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . '<a href="' . $ffurl . '" >' . $file . '</a><br />';
             }
         }
     }
     $output = '<div class="files">' . $output . '</div>';
     return $output;
 }
 /**
  * Produces a list of links to the files uploaded by a user
  *
  * @param $userid int optional id of the user. If 0 then $USER->id is used.
  * @param $return boolean optional defaults to false. If true the list is returned rather than printed
  * @return string optional
  */
 function print_user_files($userid = 0, $return = false)
 {
     global $CFG, $USER;
     if (!$userid) {
         if (!isloggedin()) {
             return '';
         }
         $userid = $USER->id;
     }
     $filearea = $this->file_area_name($userid);
     $output = '';
     if ($basedir = $this->file_area($userid)) {
         if ($files = get_directory_list($basedir)) {
             require_once $CFG->libdir . '/filelib.php';
             foreach ($files as $key => $file) {
                 $icon = mimeinfo('icon', $file);
                 $ffurl = get_file_url("{$filearea}/{$file}", array('forcedownload' => 1));
                 // Syntax Highlighert source code
                 $viewlink = link_to_popup_window('/mod/assignment/type/onlinejudge/source.php?id=' . $this->cm->id . '&amp;userid=' . $userid . '&amp;file=' . $file, $file . 'sourcecode', get_string('preview'), 500, 740, $file, 'none', true, 'button' . $userid);
                 $output .= '<img src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . '<a href="' . $ffurl . '" >' . $file . '</a> (' . $viewlink . ')<br />';
             }
         }
     }
     $output = '<div class="files">' . $output . '</div>';
     if ($return) {
         return $output;
     }
     echo $output;
 }
Exemple #13
0
function photogallery_folder_view($folder)
{
    global $CFG, $metatags, $messages;
    require_once $CFG->dirroot . 'lib/filelib.php';
    $metatags .= file_get_contents($CFG->dirroot . "mod/photogallery/css");
    $metatags .= <<<END
        <script type="text/javascript">
            var elggWwwRoot = "{$CFG->wwwroot}";
        </script>
        <script type="text/javascript" src="{$CFG->wwwroot}mod/photogallery/lightbox/js/prototype.js"></script>
        <script type="text/javascript" src="{$CFG->wwwroot}mod/photogallery/lightbox/js/scriptaculous.js?load=effects"></script>
        <script type="text/javascript" src="{$CFG->wwwroot}mod/photogallery/lightbox/js/lightbox.js"></script>
        <link rel="stylesheet" href="{$CFG->wwwroot}mod/photogallery/lightbox/css/lightbox.css" type="text/css" media="screen" />

END;
    $file_html = "";
    $photo_html = "";
    $folder_html = "";
    // Get all the files in this folder
    if ($files = get_records_select('files', "folder = ? AND files_owner = ? ORDER BY time_uploaded desc", array($folder->ident, $folder->files_owner))) {
        foreach ($files as $file) {
            if (run("users:access_level_check", $file->access) == true) {
                $image = $CFG->wwwroot . "_files/icon.php?id=" . $file->ident . "&amp;w=200&amp;h=200";
                $filepath = $CFG->wwwroot . user_info("username", $file->files_owner) . "/files/{$folder->ident}/{$file->ident}/" . urlencode($file->originalname);
                $image = "<a href=\"{$CFG->wwwroot}_files/icon.php?id={$file->ident}&w=500&h=500\" rel=\"lightbox[folder]\"><img src=\"{$image}\" /></a>";
                $fileinfo = round($file->size / 1048576, 4) . "Mb";
                $filelinks = file_edit_links($file);
                $uploaded = sprintf(__gettext("Uploaded on %s"), strftime("%A, %d %B %Y", $file->time_uploaded));
                $keywords = display_output_field(array("", "keywords", "file", "file", $file->ident, $file->owner));
                $mimetype = mimeinfo('type', $file->originalname);
                if (empty($file->title)) {
                    $file->title = __gettext("No title");
                }
                if (substr_count($mimetype, "image") > 0) {
                    $photo_html .= <<<END

                            <div class="photogallery-photo-container">
                                <div class="photogallery-photo-image">
                                    {$image}
                                </div>
                                <div class="photogallery-photo-info">
                                    <h2 class="photogallery-photo-title"><a href="{$filepath}" >{$file->title}</a></h2>
                                    <p class="photogallery-photo-description">
                                        {$file->description}
                                    </p>
                                    <p class="photogallery-photo-keywords">
                                        {$keywords}
                                    </p>
                                    <p class="photogallery-photo-infobar">
                                        {$uploaded}<br />
                                        {$fileinfo} {$mimetype} {$filelinks}
                                    </p>
                                </div>
                            </div>

END;
                } else {
                    $file_html .= <<<END

                            <div class="photogallery-file-container">
                                <div class="photogallery-file-image">
                                    <a href="{$filepath}">{$image}</a>
                                </div>
                                <div class="photogallery-file-info">
                                    <h2 class="photogallery-file-title"><a href="{$filepath}">{$file->title}</a></h2>
                                    <p>{$file->description}</p>
                                    <p class="photogallery-file-keywords">
                                        {$keywords}
                                    </p>
                                    <p class="photogallery-file-infobar">
                                        {$uploaded}<br />
                                        {$fileinfo} {$mimetype} {$filelinks}
                                    </p>
                                </div>
                            </div>

END;
                }
            }
        }
    }
    if ($subfolders = get_records_select('file_folders', "parent = ? AND files_owner = ? ORDER BY name desc", array($folder->ident, $folder->owner))) {
        foreach ($subfolders as $subfolder) {
            $folderlinks = file_folder_edit_links($subfolder);
            $keywords = display_output_field(array("", "keywords", "folder", "folder", $subfolder->ident, $subfolder->owner));
            $filepath = $CFG->wwwroot . user_info("username", $folder->files_owner) . "/files/" . $subfolder->ident;
            $folder_html .= <<<END

                        <div class="photogallery-file-container">
                            <div class="photogallery-file-image">
                                <a href="{$filepath}"><img src="{$CFG->wwwroot}_files/folder.png" /></a>
                            </div>
                            <div class="photogallery-file-info">
                                <h2 class="photogallery-file-title"><a href="{$filepath}">{$subfolder->name}</a></h2>
                                <p class="photogallery-file-keywords">
                                    {$keywords}
                                </p>
                                <p class="photogallery-file-infobar">
                                    {$folderlinks}
                                </p>
                            </div>
                        </div>

END;
        }
    }
    if (!empty($file_html)) {
        $file_html = "<h2>" . __gettext("Non-photo files") . "</h2>" . $file_html;
    }
    if (!empty($folder_html)) {
        $folder_html = "<h2>" . __gettext("Subfolders") . "</h2>" . $folder_html;
    }
    $body = $photo_html . $file_html . $folder_html;
    if (empty($body)) {
        $body = "<p>" . __gettext("This folder is currently empty.") . "</p>";
    }
    return $body;
}
Exemple #14
0
require_once $CFG->libdir . '/filelib.php';
$id = required_param('id', PARAM_INT);
// Course Module ID
$printclose = optional_param('printclose', 0, PARAM_INT);
if (!($cm = get_coursemodule_from_id('lesson', $id))) {
    error('Course Module ID was incorrect');
}
if (!($course = get_record('course', 'id', $cm->course))) {
    error('Course is misconfigured');
}
if (!($lesson = get_record('lesson', 'id', $cm->instance))) {
    error('Course module is incorrect');
}
require_login($course->id, false, $cm);
// Get the mimetype
$mimetype = mimeinfo("type", $lesson->mediafile);
if (!is_url($lesson->mediafile) and !in_array($mimetype, array('text/plain', 'text/html'))) {
    print_header($course->shortname);
}
if ($printclose) {
    // this is for framesets
    if ($lesson->mediaclose) {
        print_header($course->shortname);
        echo '<div class="lessonmediafilecontrol">
                <form>
                <div>
                <input type="button" onclick="top.close();" value="' . get_string("closewindow") . '" />
                </div>
                </form>
                </div>';
        print_footer();
 public function add_file($section, $name, $path, $display = 0)
 {
     global $DB, $CFG, $USER;
     $section = (int) $section;
     $display = (int) $display;
     require_once $CFG->dirroot . '/course/lib.php';
     require_once $CFG->dirroot . '/mod/resource/lib.php';
     require_once $CFG->dirroot . '/mod/resource/locallib.php';
     $params = self::validate_parameters(self::add_file_parameters(), array('section' => $section, 'name' => $name, 'path' => $path, 'display' => $display));
     $section = $DB->get_record('course_sections', array('id' => $section), '*', MUST_EXIST);
     $course = $DB->get_record('course', array('id' => $section->course), '*', MUST_EXIST);
     self::require_access($course->id);
     // finally create the file item
     // first add course_module record because we need the context
     $newcm = new stdClass();
     $newcm->course = $course->id;
     $newcm->module = $DB->get_field('modules', 'id', array('name' => 'resource'));
     // not known yet, will be updated later (this is similar to restore code)
     $newcm->instance = 0;
     $newcm->section = $params['section'];
     $newcm->visible = 1;
     $newcm->groupmode = 0;
     $newcm->groupingid = 0;
     $newcm->groupmembersonly = 0;
     if (!($coursemodule = add_course_module($newcm))) {
         throw new invalid_parameter_exception('Error creating course module');
     }
     $config = get_config('resource');
     $module = new stdClass();
     $module->course = $course->id;
     $module->name = format_string($params['name']);
     $module->intro = '<p></p>';
     $module->introformat = 1;
     $module->coursemodule = $coursemodule;
     if (!$display) {
         $module->display = $config->display;
     } else {
         $module->display = $display;
     }
     $module->popupwidth = $config->popupwidth;
     $module->popupheight = $config->popupheight;
     $module->printheading = $config->printheading;
     $module->printintro = $config->printintro;
     // 'Show size' support only from Moodle 2.3 / OU moodle April 2012
     if (isset($config->showsize)) {
         $module->showsize = $config->showsize;
         $module->showtype = $config->showtype;
     }
     $module->filterfiles = $config->filterfiles;
     $module->section = $section->section;
     //check $params['path'] and create files based on that and attach to $module->files
     //now check $path and obtain $filename and $filepath
     $contextuser = get_context_instance(CONTEXT_USER, $USER->id);
     $fs = get_file_storage();
     $module->files = 0;
     file_prepare_draft_area($module->files, null, null, null, null);
     $fileinfo = array('contextid' => $contextuser->id, 'component' => 'user', 'filearea' => 'draft', 'itemid' => $module->files, 'filepath' => '/', 'filename' => basename($params['path']), 'timecreated' => time(), 'timemodified' => time(), 'mimetype' => mimeinfo('type', $path), 'userid' => $USER->id);
     if (strpos($params['path'], '://') === false) {
         //this is a path
         if (!file_exists($params['path'])) {
             throw new invalid_parameter_exception('Error accessing filepath - file may not exist.');
         }
         $fs->create_file_from_pathname($fileinfo, $params['path']);
     } else {
         //this is a URL - download the file first.
         $content = download_file_content($params['path']);
         if ($content === false) {
             throw new invalid_parameter_exception('Error accessing file - url may not exist.');
         }
         $fs->create_file_from_string($fileinfo, $content);
     }
     $module->instance = resource_add_instance($module, array());
     $DB->set_field('course_modules', 'instance', $module->instance, array('id' => $coursemodule));
     add_mod_to_section($module);
     rebuild_course_cache($course->id, true);
     return array('id' => $coursemodule);
 }
Exemple #16
0
 /** The string mime-type of the files that this plugin reads or writes. */
 public function mime_type() {
     return mimeinfo('type', $this->export_file_extension());
 }
Exemple #17
0
function file_folder_view($folder)
{
    global $CFG;
    /*
     *    View a specific folder
     *    (Access rights are presumed)
     */
    // Find out who's the owner
    global $page_owner;
    $owner_username = user_info('username', $page_owner);
    // If we're not in the parent folder, provide a link to return to the parent
    /*
    if ($folder->ident != -1) {
        $folder->name = stripslashes($folder->name);
    }
    */
    $body = "<h2>" . $folder->name . "</h2>";
    // Firstly, get a list of folders
    // Display folders we actually have access to
    if ($folder->idents = get_records_select('file_folders', "parent = {$folder->ident} AND (" . run("users:access_level_sql_where") . ") and files_owner = {$page_owner}")) {
        $subFolders = __gettext("Subfolders");
        // gettext variable
        $body .= <<<END

                            <h3>
                                {$subFolders}
                            </h3>

END;
        foreach ($folder->idents as $folder->ident_details) {
            if (run("users:access_level_check", $folder->ident_details->access) == true) {
                $username = $owner_username;
                $ident = (int) $folder->ident_details->ident;
                $name = get_access_description($folder->ident_details->access);
                $name .= stripslashes($folder->ident_details->name);
                $folder->identmenu = file_folder_edit_links($folder->ident_details);
                $keywords = display_output_field(array("", "keywords", "folder", "folder", $ident, $folder->ident_details->owner));
                if ($keywords) {
                    $keywords = __gettext("Keywords: ") . $keywords;
                }
                $body .= templates_draw(array('context' => 'folder', 'username' => $username, 'url' => $CFG->wwwroot . "{$username}/files/{$ident}", 'ident' => $ident, 'name' => $name, 'menu' => $folder->identmenu, 'icon' => $CFG->wwwroot . "mod/file/folder.png", 'keywords' => $keywords));
            }
        }
    }
    // Then get a list of files
    // View files we actually have access to
    if ($files = get_records_select('files', "folder = ? AND files_owner = ?", array($folder->ident, $page_owner))) {
        foreach ($files as $file) {
            if (run("users:access_level_check", $file->access) == true || $file->owner == $_SESSION['userid']) {
                $username = $owner_username;
                $ident = (int) $file->ident;
                $folder->ident = $file->folder;
                $title = get_access_description($file->access);
                $title .= stripslashes($file->title);
                $description = nl2br(stripslashes($file->description));
                $filetitle = urlencode($title);
                $originalname = stripslashes($file->originalname);
                $filemenu = round($file->size / 1048576, 4) . "MB ";
                $icon = $CFG->wwwroot . "_icon/file/" . $file->ident;
                $filepath = $CFG->wwwroot . "{$username}/files/{$folder->ident}/{$ident}/" . urlencode($originalname);
                $mimetype = mimeinfo('type', $file->originalname);
                if ($mimetype == "audio/mpeg" || $mimetype == "audio/mp3") {
                    $filemenu .= " <object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\"\n        codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\"\n        width=\"17\" height=\"17\" >\n            <param name=\"allowScriptAccess\" value=\"sameDomain\" />\n            <param name=\"movie\" value=\"" . $CFG->wwwroot . "mod/file/mp3player/musicplayer.swf?song_url={$filepath}&amp;song_title={$filetitle}\" />\n            <param name=\"quality\" value=\"high\" />\n            <embed src=\"" . $CFG->wwwroot . "mod/file/mp3player/musicplayer.swf?song_url={$filepath}&amp;song_title={$filetitle}\"\n            quality=\"high\" bgcolor=\"#E6E6E6\" name=\"xspf_player\" allowscriptaccess=\"sameDomain\"\n            type=\"application/x-shockwave-flash\"\n            pluginspage=\"http://www.macromedia.com/go/getflashplayer\"\n            align=\"center\" height=\"17\" width=\"17\" />\n        </object>";
                }
                $filemenu = file_edit_links($file);
                $keywords = display_output_field(array("", "keywords", "file", "file", $ident, $file->owner));
                if ($keywords) {
                    $keywords = __gettext("Keywords: ") . $keywords;
                }
                $body .= templates_draw(array('context' => 'file', 'username' => $username, 'title' => $title, 'ident' => $ident, 'folder' => $folder->ident, 'description' => $description, 'originalname' => $originalname, 'url' => $filepath, 'menu' => $filemenu, 'icon' => $icon, 'keywords' => $keywords));
                $body .= display_run_displayobjectannotations($file, "file::file");
            }
        }
    }
    // Deliver an apologetic message if there aren't any files or folders
    if (empty($files) && empty($folder->idents)) {
        $body .= "<p>" . __gettext("This folder is currently empty.") . "</p>";
    }
    return $body;
}
Exemple #18
0
 /**
  * Produces a list of links to the files uploaded by a user
  *
  * @param $userid int optional id of the user. If 0 then $USER->id is used.
  * @param $return boolean optional defaults to false. If true the list is returned rather than printed
  * @return string optional
  */
 function print_user_files($userid = 0, $return = false)
 {
     global $CFG, $USER;
     if (!$userid) {
         if (!isloggedin()) {
             return '';
         }
         $userid = $USER->id;
     }
     $filearea = $this->file_area_name($userid);
     $output = '';
     if ($basedir = $this->file_area($userid)) {
         if ($files = get_directory_list($basedir)) {
             require_once $CFG->libdir . '/filelib.php';
             foreach ($files as $key => $file) {
                 $icon = mimeinfo('icon', $file);
                 if ($CFG->slasharguments) {
                     $ffurl = "{$CFG->wwwroot}/file.php/{$filearea}/{$file}";
                 } else {
                     $ffurl = "{$CFG->wwwroot}/file.php?file=/{$filearea}/{$file}";
                 }
                 $output .= '<img align="middle" src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . '<a href="' . $ffurl . '" >' . $file . '</a><br />';
             }
         }
     }
     $output = '<div class="files">' . $output . '</div>';
     if ($return) {
         return $output;
     }
     echo $output;
 }
 /**
  * Display the file resource
  *
  * Displays a file resource embedded, in a frame, or in a popup.
  * Output depends on type of file resource.
  *
  * @param    CFG     global object
  */
 function display()
 {
     global $CFG, $THEME, $USER;
     /// Set up generic stuff first, including checking for access
     parent::display();
     /// Set up some shorthand variables
     $cm = $this->cm;
     $course = $this->course;
     $resource = $this->resource;
     $this->set_parameters();
     // set the parameters array
     ///////////////////////////////////////////////
     /// Possible display modes are:
     /// File displayed in a frame in a normal window
     /// File displayed embedded in a normal page
     /// File displayed in a popup window
     /// File displayed emebedded in a popup window
     /// First, find out what sort of file we are dealing with.
     require_once $CFG->libdir . '/filelib.php';
     $querystring = '';
     $resourcetype = '';
     $embedded = false;
     $mimetype = mimeinfo("type", $resource->reference);
     $pagetitle = strip_tags($course->shortname . ': ' . format_string($resource->name));
     $formatoptions = new object();
     $formatoptions->noclean = true;
     if ($resource->options != "bogusoption_usedtobe_frame") {
         // TODO nicolasconnault 14-03-07: This option should be renamed "embed"
         if (in_array($mimetype, array('image/gif', 'image/jpeg', 'image/png'))) {
             // It's an image
             $resourcetype = "image";
             $embedded = true;
         } else {
             if ($mimetype == "audio/mp3") {
                 // It's an MP3 audio file
                 $resourcetype = "mp3";
                 $embedded = true;
             } else {
                 if ($mimetype == "video/x-flv") {
                     // It's a Flash video file
                     $resourcetype = "flv";
                     $embedded = true;
                 } else {
                     if (substr($mimetype, 0, 10) == "video/x-ms") {
                         // It's a Media Player file
                         $resourcetype = "mediaplayer";
                         $embedded = true;
                     } else {
                         if ($mimetype == "video/quicktime") {
                             // It's a Quicktime file
                             $resourcetype = "quicktime";
                             $embedded = true;
                         } else {
                             if ($mimetype == "application/x-shockwave-flash") {
                                 // It's a Flash file
                                 $resourcetype = "flash";
                                 $embedded = true;
                             } else {
                                 if ($mimetype == "video/mpeg") {
                                     // It's a Mpeg file
                                     $resourcetype = "mpeg";
                                     $embedded = true;
                                 } else {
                                     if ($mimetype == "text/html") {
                                         // It's a web page
                                         $resourcetype = "html";
                                     } else {
                                         if ($mimetype == "application/zip") {
                                             // It's a zip archive
                                             $resourcetype = "zip";
                                             $embedded = true;
                                         } else {
                                             if ($mimetype == 'application/pdf' || $mimetype == 'application/x-pdf') {
                                                 $resourcetype = "pdf";
                                                 $embedded = true;
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     $isteamspeak = stripos($resource->reference, 'teamspeak://') === 0;
     /// Form the parse string
     if (!empty($resource->alltext)) {
         $querys = array();
         $parray = explode(',', $resource->alltext);
         foreach ($parray as $fieldstring) {
             $field = explode('=', $fieldstring);
             $querys[] = urlencode($field[1]) . '=' . urlencode($this->parameters[$field[0]]['value']);
         }
         if ($isteamspeak) {
             $querystring = implode('?', $querys);
         } else {
             $querystring = implode('&amp;', $querys);
         }
     }
     /// Set up some variables
     $inpopup = optional_param('inpopup', 0, PARAM_BOOL);
     if (resource_is_url($resource->reference)) {
         $fullurl = $resource->reference;
         if (!empty($querystring)) {
             $urlpieces = parse_url($resource->reference);
             if (empty($urlpieces['query']) or $isteamspeak) {
                 $fullurl .= '?' . $querystring;
             } else {
                 $fullurl .= '&amp;' . $querystring;
             }
         }
     } else {
         if ($CFG->resource_allowlocalfiles and strpos($resource->reference, RESOURCE_LOCALPATH) === 0) {
             // Localpath
             $localpath = get_user_preferences('resource_localpath', 'D:');
             $relativeurl = str_replace(RESOURCE_LOCALPATH, $localpath, $resource->reference);
             if ($querystring) {
                 $relativeurl .= '?' . $querystring;
             }
             $relativeurl = str_replace('\\', '/', $relativeurl);
             $relativeurl = str_replace(' ', '%20', $relativeurl);
             $fullurl = 'file:///' . htmlentities($relativeurl);
             $localpath = true;
         } else {
             // Normal uploaded file
             if ($CFG->slasharguments) {
                 $relativeurl = "/file.php/{$course->id}/{$resource->reference}";
                 if ($querystring) {
                     $relativeurl .= '?' . $querystring;
                 }
             } else {
                 $relativeurl = "/file.php?file=/{$course->id}/{$resource->reference}";
                 if ($querystring) {
                     $relativeurl .= '&amp;' . $querystring;
                 }
             }
             $fullurl = "{$CFG->wwwroot}{$relativeurl}";
         }
     }
     /// Print a notice and redirect if we are trying to access a file on a local file system
     /// and the config setting has been disabled
     if (!$CFG->resource_allowlocalfiles and strpos($resource->reference, RESOURCE_LOCALPATH) === 0) {
         if ($inpopup) {
             print_header($pagetitle, $course->fullname);
         } else {
             $this->navlinks[] = array('name' => format_string($resource->name), 'link' => null, 'type' => 'misc');
             $this->navigation = build_navigation($this->navlinks);
             print_header($pagetitle, $course->fullname, $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
         }
         notify(get_string('notallowedlocalfileaccess', 'resource', ''));
         if ($inpopup) {
             close_window_button();
         }
         print_footer('none');
         die;
     }
     /// Check whether this is supposed to be a popup, but was called directly
     if ($resource->popup and !$inpopup) {
         /// Make a page and a pop-up window
         $this->navlinks[] = array('name' => format_string($resource->name), 'link' => null, 'type' => 'misc');
         $this->navigation = build_navigation($this->navlinks);
         print_header($pagetitle, $course->fullname, $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm));
         echo "\n<script type=\"text/javascript\">";
         echo "\n<!--\n";
         echo "openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}','resource{$resource->id}','{$resource->popup}');\n";
         echo "\n-->\n";
         echo '</script>';
         if (trim(strip_tags($resource->summary))) {
             print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions), "center");
         }
         $link = "<a href=\"{$CFG->wwwroot}/mod/resource/view.php?inpopup=true&amp;id={$cm->id}\" " . "onclick=\"this.target='resource{$resource->id}'; return openpopup('/mod/resource/view.php?inpopup=true&amp;id={$cm->id}', " . "'resource{$resource->id}','{$resource->popup}');\">" . format_string($resource->name, true) . "</a>";
         echo '<div class="popupnotice">';
         print_string('popupresource', 'resource');
         echo '<br />';
         print_string('popupresourcelink', 'resource', $link);
         echo '</div>';
         print_footer($course);
         exit;
     }
     /// Now check whether we need to display a frameset
     $frameset = optional_param('frameset', '', PARAM_ALPHA);
     if (empty($frameset) and !$embedded and !$inpopup and $resource->options == "frame" and empty($USER->screenreader)) {
         @header('Content-Type: text/html; charset=utf-8');
         echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">\n";
         echo "<html dir=\"ltr\">\n";
         echo '<head>';
         echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
         echo "<title>" . format_string($course->shortname) . ": " . strip_tags(format_string($resource->name, true)) . "</title></head>\n";
         echo "<frameset rows=\"{$CFG->resource_framesize},*\">";
         echo "<frame src=\"view.php?id={$cm->id}&amp;type={$resource->type}&amp;frameset=top\" title=\"" . get_string('modulename', 'resource') . "\"/>";
         if (!empty($localpath)) {
             // Show it like this so we interpose some HTML
             echo "<frame src=\"view.php?id={$cm->id}&amp;type={$resource->type}&amp;inpopup=true\" title=\"" . get_string('modulename', 'resource') . "\"/>";
         } else {
             echo "<frame src=\"{$fullurl}\" title=\"" . get_string('modulename', 'resource') . "\"/>";
         }
         echo "</frameset>";
         echo "</html>";
         exit;
     }
     /// We can only get here once per resource, so add an entry to the log
     add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id);
     /// If we are in a frameset, just print the top of it
     if (!empty($frameset) and $frameset == "top") {
         $this->navlinks[] = array('name' => format_string($resource->name), 'link' => null, 'type' => 'misc');
         $this->navigation = build_navigation($this->navlinks);
         print_header($pagetitle, $course->fullname, $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "parent"));
         $options = new object();
         $options->para = false;
         echo '<div class="summary">' . format_text($resource->summary, FORMAT_HTML, $options) . '</div>';
         if (!empty($localpath)) {
             // Show some help
             echo '<div align="right" class="helplink">';
             link_to_popup_window('/mod/resource/type/file/localpath.php', get_string('localfile', 'resource'), get_string('localfilehelp', 'resource'), 400, 500, get_string('localfilehelp', 'resource'));
             echo '</div>';
         }
         echo '</div></div></body></html>';
         exit;
     }
     /// Display the actual resource
     if ($embedded) {
         // Display resource embedded in page
         $strdirectlink = get_string("directlink", "resource");
         if ($inpopup) {
             print_header($pagetitle);
         } else {
             $this->navlinks[] = array('name' => format_string($resource->name, true), 'link' => $fullurl, 'type' => 'misc');
             $this->navigation = build_navigation($this->navlinks);
             print_header_simple($pagetitle, '', $this->navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "self"));
         }
         if ($resourcetype == "image") {
             echo '<div class="resourcecontent resourceimg">';
             echo "<img title=\"" . strip_tags(format_string($resource->name, true)) . "\" class=\"resourceimage\" src=\"{$fullurl}\" alt=\"\" />";
             echo '</div>';
         } else {
             if ($resourcetype == "mp3") {
                 if (!empty($THEME->resource_mp3player_colors)) {
                     $c = $THEME->resource_mp3player_colors;
                     // You can set this up in your theme/xxx/config.php
                 } else {
                     $c = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&' . 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&' . 'font=Arial&fontColour=FF33FF&buffer=10&waitForPlay=no&autoPlay=yes';
                 }
                 $c .= '&volText=' . get_string('vol', 'resource') . '&panText=' . get_string('pan', 'resource');
                 $c = htmlentities($c);
                 $id = 'filter_mp3_' . time();
                 //we need something unique because it might be stored in text cache
                 $cleanurl = addslashes_js($fullurl);
                 // If we have Javascript, use UFO to embed the MP3 player, otherwise depend on plugins
                 echo '<div class="resourcecontent resourcemp3">';
                 echo '<span class="mediaplugin mediaplugin_mp3" id="' . $id . '"></span>' . '<script type="text/javascript">' . "\n" . '//<![CDATA[' . "\n" . 'var FO = { movie:"' . $CFG->wwwroot . '/lib/mp3player/mp3player.swf?src=' . $cleanurl . '",' . "\n" . 'width:"600", height:"70", majorversion:"6", build:"40", flashvars:"' . $c . '", quality: "high" };' . "\n" . 'UFO.create(FO, "' . $id . '");' . "\n" . '//]]>' . "\n" . '</script>' . "\n";
                 echo '<noscript>';
                 echo "<object type=\"audio/mpeg\" data=\"{$fullurl}\" width=\"600\" height=\"70\">";
                 echo "<param name=\"src\" value=\"{$fullurl}\" />";
                 echo '<param name="quality" value="high" />';
                 echo '<param name="autoplay" value="true" />';
                 echo '<param name="autostart" value="true" />';
                 echo '</object>';
                 echo '<p><a href="' . $fullurl . '">' . $fullurl . '</a></p>';
                 echo '</noscript>';
                 echo '</div>';
             } else {
                 if ($resourcetype == "flv") {
                     $id = 'filter_flv_' . time();
                     //we need something unique because it might be stored in text cache
                     $cleanurl = addslashes_js($fullurl);
                     // If we have Javascript, use UFO to embed the FLV player, otherwise depend on plugins
                     echo '<div class="resourcecontent resourceflv">';
                     echo '<span class="mediaplugin mediaplugin_flv" id="' . $id . '"></span>' . '<script type="text/javascript">' . "\n" . '//<![CDATA[' . "\n" . 'var FO = { movie:"' . $CFG->wwwroot . '/filter/mediaplugin/flvplayer.swf?file=' . $cleanurl . '",' . "\n" . 'width:"600", height:"400", majorversion:"6", build:"40", allowscriptaccess:"never", quality: "high" };' . "\n" . 'UFO.create(FO, "' . $id . '");' . "\n" . '//]]>' . "\n" . '</script>' . "\n";
                     echo '<noscript>';
                     echo "<object type=\"video/x-flv\" data=\"{$fullurl}\" width=\"600\" height=\"400\">";
                     echo "<param name=\"src\" value=\"{$fullurl}\" />";
                     echo '<param name="quality" value="high" />';
                     echo '<param name="autoplay" value="true" />';
                     echo '<param name="autostart" value="true" />';
                     echo '</object>';
                     echo '<p><a href="' . $fullurl . '">' . $fullurl . '</a></p>';
                     echo '</noscript>';
                     echo '</div>';
                 } else {
                     if ($resourcetype == "mediaplayer") {
                         echo '<div class="resourcecontent resourcewmv">';
                         echo '<object type="video/x-ms-wmv" data="' . $fullurl . '">';
                         echo '<param name="controller" value="true" />';
                         echo '<param name="autostart" value="true" />';
                         echo "<param name=\"src\" value=\"{$fullurl}\" />";
                         echo '<param name="scale" value="noScale" />';
                         echo "<a href=\"{$fullurl}\">{$fullurl}</a>";
                         echo '</object>';
                         echo '</div>';
                     } else {
                         if ($resourcetype == "mpeg") {
                             echo '<div class="resourcecontent resourcempeg">';
                             echo '<object classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"
                           codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsm p2inf.cab#Version=5,1,52,701"
                           type="application/x-oleobject">';
                             echo "<param name=\"fileName\" value=\"{$fullurl}\" />";
                             echo '<param name="autoStart" value="true" />';
                             echo '<param name="animationatStart" value="true" />';
                             echo '<param name="transparentatStart" value="true" />';
                             echo '<param name="showControls" value="true" />';
                             echo '<param name="Volume" value="-450" />';
                             echo '<!--[if !IE]>-->';
                             echo '<object type="video/mpeg" data="' . $fullurl . '">';
                             echo '<param name="controller" value="true" />';
                             echo '<param name="autostart" value="true" />';
                             echo "<param name=\"src\" value=\"{$fullurl}\" />";
                             echo "<a href=\"{$fullurl}\">{$fullurl}</a>";
                             echo '<!--<![endif]-->';
                             echo '<a href="' . $fullurl . '">' . $fullurl . '</a>';
                             echo '<!--[if !IE]>-->';
                             echo '</object>';
                             echo '<!--<![endif]-->';
                             echo '</object>';
                             echo '</div>';
                         } else {
                             if ($resourcetype == "quicktime") {
                                 echo '<style type="text/css">';
                                 echo '/* class to hide nested objects in IE */';
                                 echo '/* hides the second object from all versions of IE */';
                                 echo '* html object.hiddenObjectForIE { display: none; }';
                                 echo '/* display the second object only for IE5 Mac */';
                                 echo '/* IE Mac \\*//*/';
                                 echo '* html object.hiddenObjectForIE { display: inline; }';
                                 echo '/**/';
                                 echo '</style>';
                                 echo '<div class="resourcecontent resourceqt">';
                                 echo '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"';
                                 echo '        codebase="http://www.apple.com/qtactivex/qtplugin.cab">';
                                 echo "<param name=\"src\" value=\"{$fullurl}\" />";
                                 echo '<param name="autoplay" value="true" />';
                                 echo '<param name="loop" value="true" />';
                                 echo '<param name="controller" value="true" />';
                                 echo '<param name="scale" value="aspect" />';
                                 echo "<object class=\"hiddenObjectForIE\" type=\"video/quicktime\" data=\"{$fullurl}\">";
                                 echo '<param name="controller" value="true" />';
                                 echo '<param name="autoplay" value="true" />';
                                 echo '<param name="loop" value="true" />';
                                 echo '<param name="scale" value="aspect" />';
                                 echo '</object>';
                                 echo '<a href="' . $fullurl . '">' . $fullurl . '</a>';
                                 echo '</object>';
                                 echo '</div>';
                             } else {
                                 if ($resourcetype == "flash") {
                                     echo '<div class="resourcecontent resourceswf">';
                                     echo '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">';
                                     echo "<param name=\"movie\" value=\"{$fullurl}\" />";
                                     echo '<param name="autoplay" value="true" />';
                                     echo '<param name="loop" value="true" />';
                                     echo '<param name="controller" value="true" />';
                                     echo '<param name="scale" value="aspect" />';
                                     echo '<!--[if !IE]>-->';
                                     echo "<object type=\"application/x-shockwave-flash\" data=\"{$fullurl}\">";
                                     echo '<param name="controller" value="true" />';
                                     echo '<param name="autoplay" value="true" />';
                                     echo '<param name="loop" value="true" />';
                                     echo '<param name="scale" value="aspect" />';
                                     echo '<!--<![endif]-->';
                                     echo '<a href="' . $fullurl . '">' . $fullurl . '</a>';
                                     echo '<!--[if !IE]>-->';
                                     echo '</object>';
                                     echo '<!--<![endif]-->';
                                     echo '</object>';
                                     echo '</div>';
                                 } elseif ($resourcetype == 'zip') {
                                     echo '<div class="resourcepdf">';
                                     echo get_string('clicktoopen', 'resource') . '<a href="' . $fullurl . '">' . format_string($resource->name) . '</a>';
                                     echo '</div>';
                                 } elseif ($resourcetype == 'pdf') {
                                     echo '<div class="resourcepdf">';
                                     echo '<object data="' . $fullurl . '" type="application/pdf">';
                                     echo get_string('clicktoopen', 'resource') . '<a href="' . $fullurl . '">' . format_string($resource->name) . '</a>';
                                     echo '</object>';
                                     echo '</div>';
                                 }
                             }
                         }
                     }
                 }
             }
         }
         if (trim($resource->summary)) {
             print_simple_box(format_text($resource->summary, FORMAT_MOODLE, $formatoptions, $course->id), "center");
         }
         if ($inpopup) {
             echo "<div class=\"popupnotice\">(<a href=\"{$fullurl}\">{$strdirectlink}</a>)</div>";
         } else {
             print_spacer(20, 20);
             print_footer($course);
         }
     } else {
         // Display the resource on it's own
         if (!empty($localpath)) {
             // Show a link to help work around browser security
             echo '<div align="right" class="helplink">';
             link_to_popup_window('/mod/resource/type/file/localpath.php', get_string('localfile', 'resource'), get_string('localfilehelp', 'resource'), 400, 500, get_string('localfilehelp', 'resource'));
             echo '</div>';
             echo "<div class=\"popupnotice\">(<a href=\"{$fullurl}\">{$fullurl}</a>)</div>";
         }
         redirect($fullurl);
     }
 }
Exemple #20
0
 /**
  * Produces a list of links to the files uploaded by a user
  *
  * @param $userid int optional id of the user. If 0 then $USER->id is used.
  * @param $return boolean optional defaults to false. If true the list is returned rather than printed
  * @return string optional
  */
 function print_user_files($userid = 0, $return = false)
 {
     global $CFG, $USER;
     if (!$userid) {
         if (!isloggedin()) {
             return '';
         }
         $userid = $USER->id;
     }
     $filearea = $this->file_area_name($userid);
     $output = '';
     if ($basedir = $this->file_area($userid)) {
         if ($files = get_directory_list($basedir)) {
             require_once $CFG->libdir . '/filelib.php';
             foreach ($files as $key => $file) {
                 $icon = mimeinfo('icon', $file);
                 $ffurl = get_file_url("{$filearea}/{$file}", array('forcedownload' => 1));
                 $output .= '<img src="' . $CFG->pixpath . '/f/' . $icon . '" class="icon" alt="' . $icon . '" />' . '<a href="' . $ffurl . '" >' . $file . '</a><br />';
             }
         }
     }
     $output = '<div class="files">' . $output . '</div>';
     if ($return) {
         return $output;
     }
     echo $output;
 }
Exemple #21
0
function displaydir($wdir)
{
    //  $wdir == / or /a or /a/b/c/d  etc
    global $basedir;
    global $usecheckboxes;
    global $id;
    global $USER, $CFG;
    $fullpath = $basedir . $wdir;
    $directory = opendir($fullpath);
    // Find all files
    while (false !== ($file = readdir($directory))) {
        if ($file == "." || $file == "..") {
            continue;
        }
        if (is_dir($fullpath . "/" . $file)) {
            $dirlist[] = $file;
        } else {
            $filelist[] = $file;
        }
    }
    closedir($directory);
    $strfile = get_string("file");
    $strname = get_string("name");
    $strsize = get_string("size");
    $strmodified = get_string("modified");
    $straction = get_string("action");
    $strmakeafolder = get_string("makeafolder");
    $struploadafile = get_string("uploadafile");
    $strwithchosenfiles = get_string("withchosenfiles");
    $strmovetoanotherfolder = get_string("movetoanotherfolder");
    $strmovefilestohere = get_string("movefilestohere");
    $strdeletecompletely = get_string("deletecompletely");
    $strcreateziparchive = get_string("createziparchive");
    $strrename = get_string("rename");
    $stredit = get_string("edit");
    $strunzip = get_string("unzip");
    $strlist = get_string("list");
    $strchoose = get_string("choose");
    echo "<form action=\"coursefiles.php\" method=\"post\" name=\"dirform\">\n";
    echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"2\" width=\"100%\">\n";
    if ($wdir == "/") {
        $wdir = "";
    } else {
        $bdir = str_replace("/" . basename($wdir), "", $wdir);
        if ($bdir == "/") {
            $bdir = "";
        }
        print "<tr>\n<td colspan=\"5\">";
        print "<a href=\"coursefiles.php?id={$id}&amp;wdir={$bdir}&amp;usecheckboxes={$usecheckboxes}\" onclick=\"return reset_value();\">";
        print "<img src=\"{$CFG->wwwroot}/lib/editor/htmlarea/images/folderup.gif\" height=\"14\" width=\"24\" border=\"0\" alt=\"" . get_string('parentfolder') . "\" />";
        print "</a></td>\n</tr>\n";
    }
    $count = 0;
    if (!empty($dirlist)) {
        asort($dirlist);
        foreach ($dirlist as $dir) {
            $count++;
            $filename = $fullpath . "/" . $dir;
            $fileurl = $wdir . "/" . $dir;
            $filedate = userdate(filemtime($filename), "%d %b %Y, %I:%M %p");
            echo "<tr>";
            if ($usecheckboxes) {
                print_cell("center", "<input type=\"checkbox\" name=\"file{$count}\" value=\"{$fileurl}\" onclick=\"return set_rename('{$dir}');\" />");
            }
            print_cell("left", "<a href=\"coursefiles.php?id={$id}&amp;wdir={$fileurl}\" onclick=\"return reset_value();\"><img src=\"{$CFG->pixpath}/f/folder.gif\" class=\"icon\" alt=\"" . get_string('folder') . "\" /></a> <a href=\"coursefiles.php?id={$id}&amp;wdir={$fileurl}&amp;usecheckboxes={$usecheckboxes}\" onclick=\"return reset_value();\">" . htmlspecialchars($dir) . "</a>");
            print_cell("right", "&nbsp;");
            print_cell("right", $filedate);
            echo "</tr>";
        }
    }
    if (!empty($filelist)) {
        asort($filelist);
        foreach ($filelist as $file) {
            $icon = mimeinfo("icon", $file);
            $imgtype = mimeinfo("type", $file);
            $count++;
            $filename = $fullpath . "/" . $file;
            $fileurl = "{$wdir}/{$file}";
            $filedate = userdate(filemtime($filename), "%d %b %Y, %I:%M %p");
            $dimensions = get_image_size($filename);
            if ($dimensions) {
                $imgwidth = $dimensions[0];
                $imgheight = $dimensions[1];
            } else {
                $imgwidth = "Unknown";
                $imgheight = "Unknown";
            }
            unset($dimensions);
            echo "<tr>\n";
            if ($usecheckboxes) {
                print_cell("center", "<input type=\"checkbox\" name=\"file{$count}\" value=\"{$fileurl}\" onclick=\";return set_rename('{$file}');\" />");
            }
            echo "<td align=\"left\" nowrap=\"nowrap\">";
            $ffurl = get_file_url($id . $fileurl);
            link_to_popup_window($ffurl, "display", "<img src=\"{$CFG->pixpath}/f/{$icon}\" class=\"icon\" alt=\"{$strfile}\" />", 480, 640);
            $file_size = filesize($filename);
            echo "<a onclick=\"return set_value(info = {url: '" . $ffurl . "',";
            echo " isize: '" . $file_size . "', itype: '" . $imgtype . "', iwidth: '" . $imgwidth . "',";
            echo " iheight: '" . $imgheight . "', imodified: '" . $filedate . "' })\" href=\"#\">{$file}</a>";
            echo "</td>\n";
            if ($icon == "zip.gif") {
                $edittext = "<a href=\"coursefiles.php?id={$id}&amp;wdir={$wdir}&amp;file={$fileurl}&amp;action=unzip&amp;sesskey={$USER->sesskey}\">{$strunzip}</a>&nbsp;";
                $edittext .= "<a href=\"coursefiles.php?id={$id}&amp;wdir={$wdir}&amp;file={$fileurl}&amp;action=listzip&amp;sesskey={$USER->sesskey}\">{$strlist}</a> ";
            } else {
                $edittext = "&nbsp;";
            }
            print_cell("right", "{$edittext} ");
            print_cell("right", $filedate);
            echo "</tr>\n";
        }
    }
    echo "</table>\n";
    if (empty($wdir)) {
        $wdir = "/";
    }
    echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n";
    echo "<tr>\n<td>";
    echo "<input type=\"hidden\" name=\"id\" value=\"{$id}\" />\n";
    echo "<input type=\"hidden\" name=\"wdir\" value=\"{$wdir}\" />\n";
    echo "<input type=\"hidden\" name=\"sesskey\" value=\"{$USER->sesskey}\" />\n";
    $options = array("move" => "{$strmovetoanotherfolder}", "delete" => "{$strdeletecompletely}", "zip" => "{$strcreateziparchive}");
    if (!empty($count)) {
        choose_from_menu($options, "action", "", "{$strwithchosenfiles}...", "javascript:getElementById('dirform').submit()");
    }
    if (!empty($USER->fileop) and $USER->fileop == "move" and $USER->filesource != $wdir) {
        echo "<form action=\"coursefiles.php\" method=\"get\">\n";
        echo " <input type=\"hidden\" name=\"id\" value=\"{$id}\" />\n";
        echo " <input type=\"hidden\" name=\"wdir\" value=\"{$wdir}\" />\n";
        echo " <input type=\"hidden\" name=\"action\" value=\"paste\" />\n";
        echo " <input type=\"hidden\" name=\"sesskey\" value=\"{$USER->sesskey}\" />\n";
        echo " <input type=\"submit\" value=\"{$strmovefilestohere}\" />\n";
        echo "</form>";
    }
    echo "</td></tr>\n";
    echo "</table>\n";
    echo "</form>\n";
}
Exemple #22
0
/**
 * Checks if file with name $filename has one of the extensions in groups $groups
 *
 * @see get_mimetypes_array()
 * @param string $filename name of the file to check
 * @param string|array $groups one group or array of groups to check
 * @param bool $checktype if true and extension check fails, find the mimetype and check if
 * file mimetype is in mimetypes in groups $groups
 * @return bool
 */
function file_extension_in_typegroup($filename, $groups, $checktype = false)
{
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    if (!empty($extension) && in_array('.' . strtolower($extension), file_get_typegroup('extension', $groups))) {
        return true;
    }
    return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
}
function wiki_export_html(&$WS)
{
    global $CFG;
    check_dir_exists("{$CFG->dataroot}/temp", true);
    check_dir_exists("{$CFG->dataroot}/temp/html", true);
    check_dir_exists("{$CFG->dataroot}/temp/html/dfwiki{$WS->cm->id}", true);
    check_dir_exists("{$CFG->dataroot}/temp/html/dfwiki{$WS->cm->id}/atachments", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata/dfwiki{$WS->cm->id}", true);
    //export contents
    wiki_export_html_content($WS);
    //export attached files
    $flist = list_directories_and_files("{$CFG->dataroot}/{$WS->dfwiki->course}/moddata/dfwiki{$WS->cm->id}");
    if ($flist != null) {
        foreach ($flist as $fil) {
            $from_file = "{$CFG->dataroot}/{$WS->dfwiki->course}/moddata/dfwiki{$WS->cm->id}/{$fil}";
            $to_file = "{$CFG->dataroot}/temp/html/dfwiki{$WS->cm->id}/atachments/{$fil}";
            copy($from_file, $to_file);
        }
    }
    //zip file name
    $times = time();
    $name = $WS->dfwiki->name . '-' . $times . '.zip';
    $cleanzipname = clean_filename($name);
    //List of files and directories
    $filelist = list_directories_and_files("{$CFG->dataroot}/temp/html");
    //Convert them to full paths
    $files = array();
    if ($filelist != null) {
        foreach ($filelist as $file) {
            $files[] = "{$CFG->dataroot}/temp/html/{$file}";
        }
    }
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}", true);
    check_dir_exists("{$CFG->dataroot}/{$WS->dfwiki->course}/exportedhtml", true);
    $destination = "{$CFG->dataroot}/{$WS->dfwiki->course}/exportedhtml/{$cleanzipname}";
    $status = zip_files($files, $destination);
    //delete the folder created in temp
    $filelist2 = list_directories_and_files("{$CFG->dataroot}/temp/html");
    if ($filelist2 != null) {
        $del = delete_dir_contents("{$CFG->dataroot}/temp/html");
    }
    //show it all to be albe to download the file
    $prop = null;
    $prop->class = "textcenter";
    wiki_div_start($prop);
    wiki_size_text(get_string("exporthtmlcorrectly", "wiki"), 2);
    wiki_div_end();
    $prop = null;
    $prop->border = "0";
    $prop->class = "boxaligncenter";
    $prop->classtd = "nwikileftnow";
    wiki_table_start($prop);
    $wdir = '/exportedhtml';
    $fileurl = "{$wdir}/{$cleanzipname}";
    $ffurl = "/file.php?file=/{$WS->cm->course}{$fileurl}";
    $icon = mimeinfo("icon", $cleanzipname);
    link_to_popup_window($ffurl, "display", "<img src=\"{$CFG->pixpath}/f/{$icon}\" height=\"16\" width=\"16\" alt=\"File\" />", 480, 640);
    echo "\n" . '&nbsp;';
    link_to_popup_window($ffurl, "display", htmlspecialchars($cleanzipname), 480, 640);
    $prop = null;
    $prop->class = "nwikileftnow";
    wiki_change_row($prop);
    echo '&nbsp;';
    wiki_table_end();
    $prop = null;
    $prop->border = "0";
    $prop->class = "boxaligncenter";
    $prop->classtd = "nwikileftnow";
    wiki_table_start($prop);
    $prop = null;
    $prop->id = "form";
    $prop->method = "post";
    $prop->action = '../xml/index.php?id=' . $WS->dfwiki->course . '&amp;wdir=/exportedhtml';
    wiki_form_start($prop);
    wiki_div_start();
    $prop = null;
    $prop->name = "dfform[viewexported]";
    $prop->value = get_string('viewexported', 'wiki');
    wiki_input_submit($prop);
    wiki_div_end();
    wiki_form_end();
    wiki_change_column();
    print_continue("{$CFG->wwwroot}/mod/wiki/view.php?id={$WS->cm->id}");
    wiki_table_end();
}
Exemple #24
0
/**
 * Get mimetype of given url, useful for # alternative urls.
 *
 * @private
 * @param string $url
 * @return string $mimetype
 */
function filter_mediaplugin_get_mimetype($url)
{
    $matches = null;
    if (preg_match("|^(.*)/[a-z]*file.php(\\?file=)?(/[^&\\?#]*)|", $url, $matches)) {
        // remove the special moodle file serving hacks so that the *file.php is ignored
        $url = $matches[1] . $matches[3];
    } else {
        $url = preg_replace('/[#\\?].*$/', '', $url);
    }
    $mimetype = mimeinfo('type', $url);
    return $mimetype;
}
Exemple #25
0
 /**
  * Guesses MIME type for a moodle_url based on file extension.
  * @param moodle_url $url URL
  * @return string MIME type
  */
 public function get_mimetype(moodle_url $url)
 {
     return mimeinfo('type', $this->get_filename($url));
 }
/**
 * Optimised mimetype detection from general URL
 * @param $fullurl
 * @return string mimetype
 */
function mediaelementjs_guess_icon($fullurl)
{
    global $CFG;
    require_once "{$CFG->libdir}/filelib.php";
    if (substr_count($fullurl, '/') < 3 or substr($fullurl, -1) === '/') {
        // most probably default directory - index.php, index.html, etc.
        return 'f/web';
    }
    $icon = mimeinfo('icon', $fullurl);
    $icon = 'f/' . str_replace(array('.gif', '.png'), '', $icon);
    if ($icon === 'f/html' or $icon === 'f/unknown') {
        $icon = 'f/web';
    }
    return $icon;
}
Exemple #27
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);
 }
Exemple #28
0
/**
 * Send an email to a specified user
 *
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $PAGE, $SITE;
    if (empty($user) or empty($user->id)) {
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
        return false;
    }
    if (empty($user->email)) {
        debugging('Can not send email to user without email: ' . $user->id, DEBUG_DEVELOPER);
        return false;
    }
    if (!empty($user->deleted)) {
        debugging('Can not send email to deleted user: '******'BEHAT_SITE_RUNNING')) {
        // Fake email sending in behat.
        return true;
    }
    if (!empty($CFG->noemailever)) {
        // Hidden setting for development sites, set in config.php if needed.
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
        return true;
    }
    if (email_should_be_diverted($user->email)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // Skip mail to suspended users.
    if (isset($user->auth) && $user->auth == 'nologin' or isset($user->suspended) && $user->suspended) {
        return true;
    }
    if (!validate_email($user->email)) {
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email ({$user->email}) is invalid! Not sending.");
        return false;
    }
    if (over_bounce_threshold($user)) {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // TLD .invalid  is specifically reserved for invalid domain names.
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
    if (substr($user->email, -8) == '.invalid') {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email domain ({$user->email}) is invalid! Not sending.");
        return true;
        // This is not an error.
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself.
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    // Make sure that we fall back onto some reasonable no-reply address.
    $noreplyaddress = empty($CFG->noreplyaddress) ? 'noreply@' . get_host_from_url($CFG->wwwroot) : $CFG->noreplyaddress;
    // Make up an email address for handling bounces.
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $noreplyaddress;
    }
    $alloweddomains = null;
    if (!empty($CFG->allowedemaildomains)) {
        $alloweddomains = explode(PHP_EOL, $CFG->allowedemaildomains);
    }
    // Email will be sent using no reply address.
    if (empty($alloweddomains)) {
        $usetrueaddress = false;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need.
        $mail->From = $noreplyaddress;
        $mail->FromName = $from;
        // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
        // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
        // in a course with the sender.
    } else {
        if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
            $mail->From = $from->email;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($from->email, fullname($from));
            }
        } else {
            $mail->From = $noreplyaddress;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $temprecipients[] = array($user->email, fullname($user));
    // Set word wrap.
    $mail->WordWrap = $wordwrapwidth;
    if (!empty($from->customheaders)) {
        // Add custom headers.
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->addCustomHeader($customheader);
            }
        } else {
            $mail->addCustomHeader($from->customheaders);
        }
    }
    // If the X-PHP-Originating-Script email header is on then also add an additional
    // header with details of where exactly in moodle the email was triggered from,
    // either a call to message_send() or to email_to_user().
    if (ini_get('mail.add_x_header')) {
        $stack = debug_backtrace(false);
        $origin = $stack[0];
        foreach ($stack as $depth => $call) {
            if ($call['function'] == 'message_send') {
                $origin = $call;
            }
        }
        $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
        $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    $renderer = $PAGE->get_renderer('core');
    $context = array('sitefullname' => $SITE->fullname, 'siteshortname' => $SITE->shortname, 'sitewwwroot' => $CFG->wwwroot, 'subject' => $subject, 'to' => $user->email, 'toname' => fullname($user), 'from' => $mail->From, 'fromname' => $mail->FromName);
    if (!empty($tempreplyto[0])) {
        $context['replyto'] = $tempreplyto[0][0];
        $context['replytoname'] = $tempreplyto[0][1];
    }
    if ($user->id > 0) {
        $context['touserid'] = $user->id;
        $context['tousername'] = $user->username;
    }
    if (!empty($user->mailformat) && $user->mailformat == 1) {
        // Only process html templates if the user preferences allow html email.
        if ($messagehtml) {
            // If html has been given then pass it through the template.
            $context['body'] = $messagehtml;
            $messagehtml = $renderer->render_from_template('core/email_html', $context);
        } else {
            // If no html has been given, BUT there is an html wrapping template then
            // auto convert the text to html and then wrap it.
            $autohtml = trim(text_to_html($messagetext));
            $context['body'] = $autohtml;
            $temphtml = $renderer->render_from_template('core/email_html', $context);
            if ($autohtml != $temphtml) {
                $messagehtml = $temphtml;
            }
        }
    }
    $context['body'] = $messagetext;
    $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
    $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
    $messagetext = $renderer->render_from_template('core/email_text', $context);
    // Autogenerate a MessageID if it's missing.
    if (empty($mail->MessageID)) {
        $mail->MessageID = generate_email_messageid();
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it.
        $mail->isHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path.
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $attachmentpath = $attachment;
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
            $attachpath = str_replace('\\', '/', $attachmentpath);
            // Make sure both variables are normalised before comparing.
            $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
            // If the attachment is a full path to a file in the tempdir, use it as is,
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
            if (strpos($attachpath, $temppath) !== 0) {
                $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
            }
            $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8.
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // Use the defined site mail charset or eventually the one preferred by the recipient.
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // Convert all the necessary strings if the charset is supported.
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $mail->CharSet = $charset;
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->addAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->addReplyTo($values[0], $values[1]);
    }
    if ($mail->send()) {
        set_send_count($user);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        // Trigger event for failing to send email.
        $event = \core\event\email_failed::create(array('context' => context_system::instance(), 'userid' => $from->id, 'relateduserid' => $user->id, 'other' => array('subject' => $subject, 'message' => $messagetext, 'errorinfo' => $mail->ErrorInfo)));
        $event->trigger();
        if (CLI_SCRIPT) {
            mtrace('Error: lib/moodlelib.php email_to_user(): ' . $mail->ErrorInfo);
        }
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Exemple #29
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);
    }
 public function mime_type()
 {
     return mimeinfo('type', '.zip');
 }