/**
  * Add question-type specific form fields.
  *
  * @param MoodleQuickForm $mform the form being built.
  */
 function definition_inner(&$mform)
 {
     global $COURSE, $CFG;
     // don't need these default elements :
     $mform->removeElement('defaultgrade');
     $mform->removeElement('penalty');
     $mform->addElement('html', '<a target="_new" href="' . $CFG->wwwroot . '/files/index.php?id=' . $COURSE->id . '">' . get_string("openinnewwindow", "qtype_imagedit") . '</a>');
     // this element will hold the URL of the HTML's IMG SRC value
     // of the altered image file that was uploaded by the user
     // to the current course's "users" folder
     //$mform->addElement('hidden', 'imgurl', '');
     // add feedback
     $mform->addElement('htmleditor', 'feedback', get_string("feedback", "quiz"));
     $mform->setType('feedback', PARAM_RAW);
     // add default elements
     $mform->addElement('hidden', 'defaultgrade', 0);
     $mform->addElement('hidden', 'fraction', 0);
     // add max upload limit menu
     $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
     $choices[0] = get_string('courseuploadlimit') . ' (' . display_size($COURSE->maxbytes) . ')';
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setDefault('maxbytes', $COURSE->maxbytes);
     // add essay area checkbox
     $mform->addElement('advcheckbox', 'essay', get_string('addessay', 'qtype_imagedit'), null, null, array(0, 1));
 }
Пример #2
0
 public function __construct($path = SEARCH_INDEX_PATH)
 {
     global $CFG, $db;
     $this->path = $path;
     //test to see if there is a valid index on disk, at the specified path
     try {
         $test_index = new Zend_Search_Lucene($this->path, false);
         $validindex = true;
     } catch (Exception $e) {
         $validindex = false;
     }
     //retrieve file system info about the index if it is valid
     if ($validindex) {
         $this->size = display_size(get_directory_size($this->path));
         $index_dir = get_directory_list($this->path, '', false, false);
         $this->filecount = count($index_dir);
         $this->indexcount = $test_index->count();
     } else {
         $this->size = 0;
         $this->filecount = 0;
         $this->indexcount = 0;
     }
     $db_exists = false;
     //for now
     //get all the current tables in moodle
     $admin_tables = $db->MetaTables();
     //TODO: use new IndexDBControl class for database checks?
     //check if our search table exists
     if (in_array($CFG->prefix . SEARCH_DATABASE_TABLE, $admin_tables)) {
         //retrieve database information if it does
         $db_exists = true;
         //total documents
         $this->dbcount = count_records(SEARCH_DATABASE_TABLE);
         //individual document types
         // $types = search_get_document_types();
         $types = search_collect_searchables(true, false);
         sort($types);
         foreach ($types as $type) {
             $c = count_records(SEARCH_DATABASE_TABLE, 'doctype', $type);
             $this->types[$type] = (int) $c;
         }
     } else {
         $this->dbcount = 0;
         $this->types = array();
     }
     //check if the busy flag is set
     if (isset($CFG->search_indexer_busy) && $CFG->search_indexer_busy == '1') {
         $this->complete = false;
     } else {
         $this->complete = true;
     }
     //get the last run date for the indexer
     if ($this->valid() && $CFG->search_indexer_run_date) {
         $this->time = $CFG->search_indexer_run_date;
     } else {
         $this->time = 0;
     }
 }
Пример #3
0
 /**
  * Override createElement event to add max files
  */
 function onQuickFormEvent($event, $arg, &$caller)
 {
     if ($event == 'createElement') {
         $className = get_class($this);
         $this->{$className}($arg[0], $arg[1] . ' (' . get_string('maxsize', '', display_size($caller->getMaxFileSize())) . ')', $arg[2]);
         return true;
     }
     return parent::onQuickFormEvent($event, $arg, $caller);
 }
Пример #4
0
 public function execute()
 {
     global $CFG, $DB;
     $options = $this->expandedOptions;
     $dataroot = run_external_command("du -s {$CFG->dataroot}", "Couldn't find dataroot directory");
     $pattern = '/\\d*/';
     preg_match($pattern, $dataroot[0], $matches);
     $filedir = run_external_command("du -s {$CFG->dataroot}/filedir", "Couldn't find filedir directory");
     preg_match($pattern, $filedir[0], $dir_matches);
     $sql_query = "SELECT SUM(filesize) AS total FROM {files}";
     $all_files = $DB->get_record_sql($sql_query);
     $sql_query = "SELECT DISTINCT contenthash, SUM(filesize) AS total FROM {files}";
     if (is_a($DB, 'pgsql_native_moodle_database')) {
         $sql_query .= " GROUP BY contenthash";
         $distinct_contenthash = $DB->get_records_sql($sql_query);
         $total = 0;
         foreach ($distinct_contenthash as $k => $v) {
             $total += $v->total;
         }
         $distinctfilestotal = $total;
     } else {
         $distinct_contenthash = $DB->get_record_sql($sql_query);
         $distinctfilestotal = $distinct_contenthash->total;
     }
     $filesbycourse = array();
     if ($courses = get_all_courses()) {
         foreach ($courses as $course) {
             $subcontexts = get_sub_context_ids($course->ctxpath);
             $filesbycourse[$course->id] = array('unique' => 0, 'all' => 0);
             foreach ($subcontexts as $subcontext) {
                 if ($files = get_files($subcontext->id)) {
                     foreach ($files as $file) {
                         $filesbycourse[$course->id]['unique'] += file_is_unique($file->contenthash, $subcontext->id) ? $file->filesize : 0;
                         $filesbycourse[$course->id]['all'] += $file->filesize;
                     }
                 }
             }
         }
     }
     $sortarray = higher_size($filesbycourse);
     $backups = backup_size();
     $data = array('dataroot' => $matches[0], 'filedir' => $dir_matches[0], 'files total' => $all_files->total, 'distinct files total' => $distinctfilestotal);
     foreach ($sortarray as $courseid => $values) {
         $data["Course {$courseid} files total"] = strval($values['all']);
         $data["Course {$courseid} files unique"] = strval($values['unique']);
     }
     foreach ($backups as $key => $values) {
         $data["Backup {$values->username}"] = strval($values->backupsize);
     }
     if ($options['json']) {
         echo json_encode($data);
     } else {
         foreach ($data as $k => $v) {
             echo "{$k}: " . display_size($v) . "\n";
         }
     }
 }
Пример #5
0
/**
 * get_performance_output() override get_peformance_info()
 *  in moodlelib.php. Returns a string
 * values ready for use.
 *
 * @return string
 */
function krystle2_performance_output($param) {
	
    $html = '<div class="performanceinfo"><ul>';
	if (isset($param['realtime'])) $html .= '<li><a class="red" href="#"><var>'.$param['realtime'].' secs</var><span>Load Time</span></a></li>';
	if (isset($param['memory_total'])) $html .= '<li><a class="orange" href="#"><var>'.display_size($param['memory_total']).'</var><span>Memory Used</span></a></li>';
    if (isset($param['includecount'])) $html .= '<li><a class="blue" href="#"><var>'.$param['includecount'].' Files </var><span>Included</span></a></li>';
    if (isset($param['dbqueries'])) $html .= '<li><a class="purple" href="#"><var>'.$param['dbqueries'].' </var><span>DB Read/Write</span></a></li>';
    $html .= '</ul></div>';

    return $html;
}
 function view_upload_form()
 {
     global $CFG;
     $struploadafile = get_string("uploadafile");
     $strmaxsize = get_string("maxsize", "", display_size($this->wqmaxbytes));
     echo '<center>';
     echo '<form enctype="multipart/form-data" method="post" ' . "action=\"{$CFG->wwwroot}/mod/webquestscorm/upload.php\">";
     echo "<p>{$struploadafile} ({$strmaxsize})</p>";
     echo '<input type="hidden" name="cmid" value="' . $this->cm->id . '" />';
     require_once $CFG->libdir . '/uploadlib.php';
     upload_print_form_fragment(1, array('newfile'), false, null, 0, $this->wqmaxbytes, false);
     echo '<input type="submit" name="save" value="' . get_string('uploadthisfile') . '" />';
     echo '</form>';
     echo '</center>';
 }
function print_table($data)
{
    $table = new html_table();
    $table->head = array(get_string('lastcrawledtime', 'local_linkchecker_robot'), get_string('linktext', 'local_linkchecker_robot'), get_string('idattr', 'local_linkchecker_robot'), get_string('response', 'local_linkchecker_robot'), get_string('size', 'local_linkchecker_robot'), get_string('url', 'local_linkchecker_robot'), get_string('mimetype', 'local_linkchecker_robot'));
    $table->data = array();
    foreach ($data as $row) {
        $text = trim($row->title);
        if (!$text || $text == "") {
            $text = get_string('unknown', 'local_linkchecker_robot');
        }
        $code = local_linkchecker_robot_http_code($row);
        $size = $row->filesize * 1;
        $data = array(userdate($row->lastcrawled, '%h %e,&nbsp;%H:%M:%S'), $row->text, str_replace(' #', '<br>#', $row->idattr), $code, display_size($size), local_linkchecker_robot_link($row->target, $text, $row->redirect), $row->mimetype);
        $table->data[] = $data;
    }
    echo html_writer::table($table);
}
 function view_upload_form()
 {
     global $CFG;
     $struploadafile = get_string("uploadafile");
     $maxbytes = $this->assignment->maxbytes == 0 ? $this->course->maxbytes : $this->assignment->maxbytes;
     $strmaxsize = get_string('maxsize', '', display_size($maxbytes));
     echo '<div style="text-align:center">';
     echo '<form enctype="multipart/form-data" method="post" ' . "action=\"{$CFG->wwwroot}/mod/assignment/upload-embedded.php\">";
     echo '<fieldset class="invisiblefieldset">';
     echo "<p>{$struploadafile} ({$strmaxsize})</p>";
     echo '<input type="hidden" name="id" value="' . $this->cm->id . '" />';
     require_once $CFG->libdir . '/uploadlib.php';
     upload_print_form_fragment(1, array('newfile'), false, null, 0, $this->assignment->maxbytes, false);
     echo '<input type="submit" name="save" value="' . get_string('uploadthisfile') . '" />';
     echo '</fieldset>';
     echo '</form>';
     echo '</div>';
 }
 /**
  * Add question-type specific form fields.
  *
  * @param MoodleQuickForm $mform the form being built.
  */
 function definition_inner(&$mform)
 {
     global $COURSE, $CFG;
     // don't need these default elements :
     $mform->removeElement('defaultgrade');
     $mform->removeElement('penalty');
     // add feedback
     $mform->addElement('htmleditor', 'feedback', get_string("feedback", "quiz"));
     $mform->setType('feedback', PARAM_RAW);
     // add default elements
     $mform->addElement('hidden', 'defaultgrade', 0);
     $mform->addElement('hidden', 'fraction', 0);
     // add max upload limit menu
     $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
     $choices[0] = get_string('courseuploadlimit') . ' (' . display_size($COURSE->maxbytes) . ')';
     $mform->addElement('select', 'maxbytes', get_string('maximumupload'), $choices);
     $mform->setDefault('maxbytes', $COURSE->maxbytes);
     // add essay area checkbox
     $mform->addElement('advcheckbox', 'essay', get_string('addessay', 'qtype_fileresponse'), null, null, array(0, 1));
 }
Пример #10
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     require_once get_config('docroot') . 'artefact/lib.php';
     $configdata = $instance->get('configdata');
     $result = '';
     if (isset($configdata['artefactids']) && is_array($configdata['artefactids'])) {
         foreach ($configdata['artefactids'] as $artefactid) {
             try {
                 $artefact = $instance->get_artefact_instance($artefactid);
             } catch (ArtefactNotFoundException $e) {
                 continue;
             }
             $icondata = array('id' => $artefactid, 'viewid' => $instance->get('view'));
             $detailsurl = get_config('wwwroot') . 'view/artefact.php?artefact=' . $artefactid . '&view=' . $instance->get('view');
             if ($artefact instanceof ArtefactTypeProfileIcon) {
                 require_once 'file.php';
                 $downloadurl = get_config('wwwroot') . 'thumb.php?type=profileiconbyid&id=' . $artefactid;
                 $size = filesize(get_dataroot_image_path('artefact/file/profileicons/', $artefactid));
             } else {
                 if ($artefact instanceof ArtefactTypeFile) {
                     $downloadurl = get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactid . '&view=' . $icondata['viewid'];
                     $size = $artefact->get('size');
                 }
             }
             $result .= '<div title="' . hsc($artefact->get('title')) . '">';
             $result .= '<div class="fl"><a href="' . hsc($downloadurl) . '">';
             $result .= '<img src="' . hsc(call_static_method(generate_artefact_class_name($artefact->get('artefacttype')), 'get_icon', $icondata)) . '" alt=""></a></div>';
             $result .= '<div style="margin-left: 30px;">';
             $result .= '<h4><a href="' . hsc($detailsurl) . '">' . str_shorten_text($artefact->get('title'), 20) . '</a></h4>';
             $description = $artefact->get('description');
             if ($description) {
                 $result .= '<p style="margin: 0;"><strong>' . hsc($description) . '</strong></p>';
             }
             $result .= '' . display_size($size) . ' | ' . strftime(get_string('strftimedaydate'), $artefact->get('ctime'));
             $result .= '</div>';
             $result .= '</div>';
         }
     }
     return $result;
 }
/**
 * Dwoo {mahara_performance_info} function plugin
 *
 * Type:     function<br>
 * Name:     mahara_performance_info<br>
 * Date:     June 22, 2006<br>
 * Purpose:  Fetch internationalized strings
 * @author   Catalyst IT Ltd
 * @version  1.0
 * @return html to display in the footer.
 */
function Dwoo_Plugin_mahara_performance_info(Dwoo $dwoo)
{
    if (!get_config('perftofoot') && !get_config('perftolog')) {
        return;
    }
    $info = get_performance_info();
    $dwoo = smarty_core();
    foreach ($info as $key => $value) {
        if ($key == 'realtime') {
            $value = round($value, 3);
        }
        $dwoo->assign('perf_' . $key, $value);
    }
    // extras
    $dwoo->assign('perf_memory_total_display', display_size($info['memory_total']));
    $dwoo->assign('perf_memory_growth_display', display_size($info['memory_growth']));
    if (get_config('perftolog')) {
        perf_to_log($info);
    }
    if (get_config('perftofoot')) {
        return $dwoo->fetch('performancefooter.tpl');
    }
}
Пример #12
0
function adduser_validate(Pieform $form, $values)
{
    global $USER, $TRANSPORTER;
    $authobj = AuthFactory::create($values['authinstance']);
    $institution = $authobj->institution;
    // Institutional admins can only set their own institutions' authinstances
    if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) {
        $form->set_error('authinstance', get_string('notadminforinstitution', 'admin'));
        return;
    }
    $institution = new Institution($authobj->institution);
    // Don't exceed max user accounts for the institution
    if ($institution->isFull()) {
        $institution->send_admin_institution_is_full_message();
        $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin'));
        return;
    }
    $username = $values['username'];
    $firstname = sanitize_firstname($values['firstname']);
    $lastname = sanitize_lastname($values['lastname']);
    $email = sanitize_email($values['email']);
    $password = $values['password'];
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
        }
    }
    if (method_exists($authobj, 'is_username_valid_admin')) {
        if (!$authobj->is_username_valid_admin($username)) {
            $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
        }
    } else {
        if (method_exists($authobj, 'is_username_valid')) {
            if (!$authobj->is_username_valid($username)) {
                $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
            }
        }
    }
    if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) {
        $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
    }
    if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) {
        $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type));
    }
    if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') {
        $form->set_error('firstname', null);
        $form->set_error('lastname', null);
        $form->set_error('email', null);
        if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) {
            $form->reply(PIEFORM_ERR, array('message' => get_string('uploadedfiletoobig'), 'goto' => '/admin/users/add.php'));
            $form->set_error('leap2afile', get_string('uploadedfiletoobig'));
            return;
        } else {
            if (!$values['leap2afile']) {
                $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required'));
                return;
            }
        }
        if ($values['leap2afile']['type'] == 'application/octet-stream') {
            require_once 'file.php';
            $mimetype = file_mime_type($values['leap2afile']['tmp_name']);
        } else {
            $mimetype = trim($values['leap2afile']['type'], '"');
        }
        $date = time();
        $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']);
        safe_require('import', 'leap');
        $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype));
        $TRANSPORTER = new LocalImporterTransport($fakeimportrecord);
        try {
            $TRANSPORTER->extract_file();
            PluginImportLeap::validate_transported_data($TRANSPORTER);
        } catch (Exception $e) {
            $form->set_error('leap2afile', $e->getMessage());
        }
    } else {
        if (!$form->get_error('firstname') && empty($firstname)) {
            $form->set_error('firstname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('lastname') && empty($lastname)) {
            $form->set_error('lastname', $form->i18n('rule', 'required', 'required'));
        }
        if (!$form->get_error('email')) {
            if (!$form->get_error('email') && empty($email)) {
                $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
            }
            if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) {
                $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
            }
        }
    }
}
Пример #13
0
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @return array
 */
function get_performance_info()
{
    global $CFG, $PERF, $DB, $PAGE;
    $info = array();
    $info['txt'] = me() . ' ';
    // Holds log-friendly representation.
    $info['html'] = '';
    if (!empty($CFG->themedesignermode)) {
        // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
        $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
    }
    $info['html'] .= '<ul class="list-unstyled m-l-1">';
    // Holds userfriendly HTML representation.
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    $info['html'] .= '<li class="timeused">' . $info['realtime'] . ' secs</li> ';
    $info['txt'] .= 'time: ' . $info['realtime'] . 's ';
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<li class="memoryused">RAM: ' . display_size($info['memory_total']) . '</li> ';
        $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') ';
    }
    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<li class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</li> ';
        $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') ';
    }
    $inc = get_included_files();
    $info['includecount'] = count($inc);
    $info['html'] .= '<li class="included">Included ' . $info['includecount'] . ' files</li> ';
    $info['txt'] .= 'includecount: ' . $info['includecount'] . ' ';
    if (!empty($CFG->early_install_lang) or empty($PAGE)) {
        // We can not track more performance before installation or before PAGE init, sorry.
        return $info;
    }
    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<li class="logwrites">Log DB writes ' . $info['logwrites'] . '</li> ';
        $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
    }
    $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<li class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</li> ';
    $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
    $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
    $info['html'] .= '<li class="dbtime">DB queries time: ' . $info['dbtime'] . ' secs</li> ';
    $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<li class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</li> ";
            $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
        }
    }
    // Grab the load average for the last minute.
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices.
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($serverload) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $serverload = $matches[1];
            } else {
                trigger_error('Could not parse uptime output!');
            }
        }
    }
    if (!empty($serverload)) {
        $info['serverload'] = $serverload;
        $info['html'] .= '<li class="serverload">Load average: ' . $info['serverload'] . '</li> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }
    // Display size of session if session started.
    if ($si = \core\session\manager::get_performance_info()) {
        $info['sessionsize'] = $si['size'];
        $info['html'] .= $si['html'];
        $info['txt'] .= $si['txt'];
    }
    if ($stats = cache_helper::get_stats()) {
        $html = '<ul class="cachesused list-unstyled m-l-1">';
        $html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>';
        $text = 'Caches used (hits/misses/sets): ';
        $hits = 0;
        $misses = 0;
        $sets = 0;
        foreach ($stats as $definition => $details) {
            switch ($details['mode']) {
                case cache_store::MODE_APPLICATION:
                    $modeclass = 'application';
                    $mode = ' <span title="application cache">[a]</span>';
                    break;
                case cache_store::MODE_SESSION:
                    $modeclass = 'session';
                    $mode = ' <span title="session cache">[s]</span>';
                    break;
                case cache_store::MODE_REQUEST:
                    $modeclass = 'request';
                    $mode = ' <span title="request cache">[r]</span>';
                    break;
            }
            $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-' . $modeclass . '">';
            $html .= '<li class="cache-definition-stats-heading p-t-1">' . $definition . $mode . '</li>';
            $text .= "{$definition} {";
            foreach ($details['stores'] as $store => $data) {
                $hits += $data['hits'];
                $misses += $data['misses'];
                $sets += $data['sets'];
                if ($data['hits'] == 0 and $data['misses'] > 0) {
                    $cachestoreclass = 'nohits text-danger';
                } else {
                    if ($data['hits'] < $data['misses']) {
                        $cachestoreclass = 'lowhits text-warning';
                    } else {
                        $cachestoreclass = 'hihits text-success';
                    }
                }
                $text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) ";
                $html .= "<li class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</li>";
            }
            $html .= '</ul>';
            $text .= '} ';
        }
        $html .= '</ul> ';
        $html .= "<div class='cache-total-stats row'>Total: {$hits} / {$misses} / {$sets}</div>";
        $info['cachesused'] = "{$hits} / {$misses} / {$sets}";
        $info['html'] .= $html;
        $info['txt'] .= $text . '. ';
    } else {
        $info['cachesused'] = '0 / 0 / 0';
        $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
    }
    $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
    return $info;
}
Пример #14
0
 *
 * @package    mahara
 * @subpackage core
 * @author     Catalyst IT Ltd
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
 *
 */
define('INTERNAL', 1);
define('JSON', 1);
define('INSTITUTIONALADMIN', 1);
require dirname(dirname(dirname(__FILE__))) . '/init.php';
require_once 'pieforms/pieform/elements/bytes.php';
$instid = param_integer('instid');
$disabled = param_boolean('disabled', false);
$definst = get_field('auth_instance', 'id', 'institution', 'mahara');
$record = get_record_sql('SELECT i.name, i.defaultquota FROM {institution} i JOIN {auth_instance} ai ON (i.name = ai.institution) WHERE ai.id = ?', array($instid));
if (!$USER->get('admin') && !$USER->is_institutional_admin($record->name)) {
    json_reply(true, 'You are not an administrator for institution ' . $record->name);
    return;
}
if ($definst && $instid == $definst) {
    $quota = get_config_plugin('artefact', 'file', 'defaultquota');
} else {
    $quota = $record->defaultquota;
    if (!$quota) {
        $quota = get_config_plugin('artefact', 'file', 'defaultquota');
    }
}
$data = array('data' => $disabled ? display_size($quota) : pieform_element_bytes_get_bytes_from_bytes($quota), 'error' => false, 'message' => null);
json_reply(false, $data);
Пример #15
0
/**
 * Listing all files (including folders) in current path (draft area)
 * used by file manager
 * @param int $draftitemid
 * @param string $filepath
 * @return stdClass
 */
function file_get_drafarea_files($draftitemid, $filepath = '/')
{
    global $USER, $OUTPUT, $CFG;
    $context = context_user::instance($USER->id);
    $fs = get_file_storage();
    $data = new stdClass();
    $data->path = array();
    $data->path[] = array('name' => get_string('files'), 'path' => '/');
    // will be used to build breadcrumb
    $trail = '/';
    if ($filepath !== '/') {
        $filepath = file_correct_filepath($filepath);
        $parts = explode('/', $filepath);
        foreach ($parts as $part) {
            if ($part != '' && $part != null) {
                $trail .= $part . '/';
                $data->path[] = array('name' => $part, 'path' => $trail);
            }
        }
    }
    $list = array();
    $maxlength = 12;
    if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
        foreach ($files as $file) {
            $item = new stdClass();
            $item->filename = $file->get_filename();
            $item->filepath = $file->get_filepath();
            $item->fullname = trim($item->filename, '/');
            $filesize = $file->get_filesize();
            $item->size = $filesize ? $filesize : null;
            $item->filesize = $filesize ? display_size($filesize) : '';
            $item->sortorder = $file->get_sortorder();
            $item->author = $file->get_author();
            $item->license = $file->get_license();
            $item->datemodified = $file->get_timemodified();
            $item->datecreated = $file->get_timecreated();
            $item->isref = $file->is_external_file();
            if ($item->isref && $file->get_status() == 666) {
                $item->originalmissing = true;
            }
            // find the file this draft file was created from and count all references in local
            // system pointing to that file
            $source = @unserialize($file->get_source());
            if (isset($source->original)) {
                $item->refcount = $fs->search_references_count($source->original);
            }
            if ($file->is_directory()) {
                $item->filesize = 0;
                $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
                $item->type = 'folder';
                $foldername = explode('/', trim($item->filepath, '/'));
                $item->fullname = trim(array_pop($foldername), '/');
                $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
            } else {
                // do NOT use file browser here!
                $item->mimetype = get_mimetype_description($file);
                if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
                    $item->type = 'zip';
                } else {
                    $item->type = 'file';
                }
                $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
                $item->url = $itemurl->out();
                $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
                $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
                if ($imageinfo = $file->get_imageinfo()) {
                    $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
                    $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
                    $item->image_width = $imageinfo['width'];
                    $item->image_height = $imageinfo['height'];
                }
            }
            $list[] = $item;
        }
    }
    $data->itemid = $draftitemid;
    $data->list = $list;
    return $data;
}
Пример #16
0
function pieform_element_filebrowser_delete(Pieform $form, $element, $artefact)
{
    global $USER;
    $institution = $form->get_property('institution');
    $group = $form->get_property('group');
    try {
        $artefact = artefact_instance_from_id($artefact);
    } catch (ArtefactNotFoundException $e) {
        $parentfolder = $element['folder'] ? $element['folder'] : null;
        $result = array('error' => true, 'message' => get_string('deletingfailed', 'artefact.file'), 'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder));
        return $result;
    }
    if (!$USER->can_edit_artefact($artefact)) {
        return array('error' => true, 'message' => get_string('nodeletepermission', 'mahara'));
    }
    if (!$artefact->can_be_deleted()) {
        return array('error' => true, 'message' => get_string('cantbedeleted', 'mahara'));
    }
    $parentfolder = $artefact->get('parent');
    // Remove the skin background and update the skin thumbs
    require_once get_config('libroot') . 'skin.php';
    Skin::remove_background($artefact->get('id'));
    $artefact->delete();
    $result = array('error' => false, 'deleted' => true, 'artefacttype' => $artefact->get('artefacttype'), 'message' => get_string('filethingdeleted', 'artefact.file', get_string($artefact->get('artefacttype'), 'artefact.file') . ' ' . $artefact->get('title')), 'maxuploadsize' => display_size(get_max_upload_size(!$institution && !$group)), 'newlist' => pieform_element_filebrowser_build_filelist($form, $element, $parentfolder));
    if (defined('GROUP')) {
        $group = group_current_group();
        $result['quota'] = $group->quota;
        $result['quotaused'] = $group->quotaused;
    } else {
        $result['quota'] = $USER->get('quota');
        $result['quotaused'] = $USER->get('quotaused');
    }
    return $result;
}
Пример #17
0
 $strok = get_string("ok");
 $strlistfiles = get_string("listfiles", "", $file);
 echo "<p align=\"center\">{$strlistfiles}:</p>";
 $file = basename($file);
 require_once $CFG->libdir . '/pclzip/pclzip.lib.php';
 $archive = new PclZip("{$basedir}/{$wdir}/{$file}");
 if (!($list = $archive->listContent("{$basedir}/{$wdir}"))) {
     notify($archive->errorInfo(true));
 } else {
     echo "<table cellpadding=\"4\" cellspacing=\"2\" border=\"0\">\n";
     echo "<tr>\n<th align=\"left\" scope=\"col\">{$strname}</th><th align=\"right\" scope=\"col\">{$strsize}</th><th align=\"right\" scope=\"col\">{$strmodified}</th></tr>";
     foreach ($list as $item) {
         echo "<tr>";
         print_cell("left", $item['filename']);
         if (!$item['folder']) {
             print_cell("right", display_size($item['size']));
         } else {
             echo "<td>&nbsp;</td>\n";
         }
         $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
         print_cell("right", $filedate);
         echo "</tr>\n";
     }
     echo "</table>\n";
 }
 echo "<br /><center><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=\"cancel\" />\n";
 echo " <input type=\"hidden\" name=\"sesskey\" value=\"{$USER->sesskey}\" />\n";
 echo " <input type=\"submit\" value=\"{$strok}\" />\n";
Пример #18
0
 /**
  * This function returns an
  * array of possible memory sizes in an array, translated to the
  * local language.
  *
  * @uses SORT_NUMERIC
  * @param int $sizebytes Moodle site $CGF->assignment_oj_max_mem
  * @return array
  */
 static function get_max_memory_usages($sitebytes = 0)
 {
     global $CFG;
     // Get max size
     $maxsize = $sitebytes;
     $memusage[$maxsize] = display_size($maxsize);
     $sizelist = array(4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912);
     // Allow maxbytes to be selected if it falls outside the above boundaries
     if (isset($CFG->assignment_oj_max_mem) && !in_array($CFG->assignment_oj_max_mem, $sizelist)) {
         $sizelist[] = $CFG->assignment_oj_max_mem;
     }
     foreach ($sizelist as $sizebytes) {
         if ($sizebytes < $maxsize) {
             $memusage[$sizebytes] = display_size($sizebytes);
         }
     }
     krsort($memusage, SORT_NUMERIC);
     return $memusage;
 }
Пример #19
0
 function definition()
 {
     global $CFG, $FORUM_TYPES, $COURSE;
     $mform =& $this->_form;
     //-------------------------------------------------------------------------------
     $mform->addElement('header', 'general', get_string('general', 'form'));
     $mform->addElement('text', 'name', get_string('forumname', 'forum'), array('size' => '64'));
     $mform->setType('name', PARAM_TEXT);
     $mform->addRule('name', null, 'required', null, 'client');
     $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');
     asort($FORUM_TYPES);
     $mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES);
     $mform->setHelpButton('type', array('forumtype', get_string('forumtype', 'forum'), 'forum'));
     $mform->setDefault('type', 'general');
     $mform->addElement('htmleditor', 'intro', get_string('forumintro', 'forum'));
     $mform->setType('intro', PARAM_RAW);
     $mform->addRule('intro', get_string('required'), 'required', null, 'client');
     $mform->setHelpButton('intro', array('writing', 'questions', 'richtext'), false, 'editorhelpbutton');
     $options = array();
     $options[0] = get_string('no');
     $options[1] = get_string('yesforever', 'forum');
     $options[FORUM_INITIALSUBSCRIBE] = get_string('yesinitially', 'forum');
     $options[FORUM_DISALLOWSUBSCRIBE] = get_string('disallowsubscribe', 'forum');
     $mform->addElement('select', 'forcesubscribe', get_string('forcesubscribeq', 'forum'), $options);
     $mform->setHelpButton('forcesubscribe', array('subscription2', get_string('forcesubscribeq', 'forum'), 'forum'));
     $options = array();
     $options[FORUM_TRACKING_OPTIONAL] = get_string('trackingoptional', 'forum');
     $options[FORUM_TRACKING_OFF] = get_string('trackingoff', 'forum');
     $options[FORUM_TRACKING_ON] = get_string('trackingon', 'forum');
     $mform->addElement('select', 'trackingtype', get_string('trackingtype', 'forum'), $options);
     $mform->setHelpButton('trackingtype', array('trackingtype', get_string('trackingtype', 'forum'), 'forum'));
     $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
     $choices[1] = get_string('uploadnotallowed');
     $choices[0] = get_string('courseuploadlimit') . ' (' . display_size($COURSE->maxbytes) . ')';
     $mform->addElement('select', 'maxbytes', get_string('maxattachmentsize', 'forum'), $choices);
     $mform->setHelpButton('maxbytes', array('maxattachmentsize', get_string('maxattachmentsize', 'forum'), 'forum'));
     $mform->setDefault('maxbytes', $CFG->forum_maxbytes);
     if ($CFG->enablerssfeeds && isset($CFG->forum_enablerssfeeds) && $CFG->forum_enablerssfeeds) {
         //-------------------------------------------------------------------------------
         $mform->addElement('header', '', get_string('rss'));
         $choices = array();
         $choices[0] = get_string('none');
         $choices[1] = get_string('discussions', 'forum');
         $choices[2] = get_string('posts', 'forum');
         $mform->addElement('select', 'rsstype', get_string('rsstype'), $choices);
         $mform->setHelpButton('rsstype', array('rsstype', get_string('rsstype'), 'forum'));
         $choices = array();
         $choices[0] = '0';
         $choices[1] = '1';
         $choices[2] = '2';
         $choices[3] = '3';
         $choices[4] = '4';
         $choices[5] = '5';
         $choices[10] = '10';
         $choices[15] = '15';
         $choices[20] = '20';
         $choices[25] = '25';
         $choices[30] = '30';
         $choices[40] = '40';
         $choices[50] = '50';
         $mform->addElement('select', 'rssarticles', get_string('rssarticles'), $choices);
         $mform->setHelpButton('rssarticles', array('rssarticles', get_string('rssarticles'), 'forum'));
     }
     //-------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('grade'));
     $mform->addElement('checkbox', 'assessed', get_string('allowratings', 'forum'), get_string('ratingsuse', 'forum'));
     $mform->addElement('modgrade', 'scale', get_string('grade'), false);
     $mform->disabledIf('scale', 'assessed');
     $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'forum'));
     $mform->disabledIf('ratingtime', 'assessed');
     $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));
     $mform->disabledIf('assesstimestart', 'assessed');
     $mform->disabledIf('assesstimestart', 'ratingtime');
     $mform->addElement('date_time_selector', 'assesstimefinish', get_string('to'));
     $mform->disabledIf('assesstimefinish', 'assessed');
     $mform->disabledIf('assesstimefinish', 'ratingtime');
     //-------------------------------------------------------------------------------
     $mform->addElement('header', '', get_string('blockafter', 'forum'));
     $options = array();
     $options[0] = get_string('blockperioddisabled', 'forum');
     $options[60 * 60 * 24] = '1 ' . get_string('day');
     $options[60 * 60 * 24 * 2] = '2 ' . get_string('days');
     $options[60 * 60 * 24 * 3] = '3 ' . get_string('days');
     $options[60 * 60 * 24 * 4] = '4 ' . get_string('days');
     $options[60 * 60 * 24 * 5] = '5 ' . get_string('days');
     $options[60 * 60 * 24 * 6] = '6 ' . get_string('days');
     $options[60 * 60 * 24 * 7] = '1 ' . get_string('week');
     $mform->addElement('select', 'blockperiod', get_string("blockperiod", "forum"), $options);
     $mform->setHelpButton('blockperiod', array('manageposts', get_string('blockperiod', 'forum'), 'forum'));
     $mform->addElement('text', 'blockafter', get_string('blockafter', 'forum'));
     $mform->setType('blockafter', PARAM_INT);
     $mform->setDefault('blockafter', '0');
     $mform->addRule('blockafter', null, 'numeric', null, 'client');
     $mform->setHelpButton('blockafter', array('manageposts', get_string('blockafter', 'forum'), 'forum'));
     $mform->disabledIf('blockafter', 'blockperiod', 'eq', 0);
     $mform->addElement('text', 'warnafter', get_string('warnafter', 'forum'));
     $mform->setType('warnafter', PARAM_INT);
     $mform->setDefault('warnafter', '0');
     $mform->addRule('warnafter', null, 'numeric', null, 'client');
     $mform->setHelpButton('warnafter', array('manageposts', get_string('warnafter', 'forum'), 'forum'));
     $mform->disabledIf('warnafter', 'blockperiod', 'eq', 0);
     //-------------------------------------------------------------------------------
     $this->standard_coursemodule_elements();
     //-------------------------------------------------------------------------------
     // buttons
     $this->add_action_buttons();
 }
Пример #20
0
    /**
     * Internal implementation of file picker rendering.
     *
     * @param file_picker $fp
     * @return string
     */
    public function render_file_picker(file_picker $fp) {
        global $CFG, $OUTPUT, $USER;
        $options = $fp->options;
        $client_id = $options->client_id;
        $strsaved = get_string('filesaved', 'repository');
        $straddfile = get_string('openpicker', 'repository');
        $strloading  = get_string('loading', 'repository');
        $strdndenabled = get_string('dndenabled_inbox', 'moodle');
        $strdroptoupload = get_string('droptoupload', 'moodle');
        $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading).'';

        $currentfile = $options->currentfile;
        if (empty($currentfile)) {
            $currentfile = '';
        } else {
            $currentfile .= ' - ';
        }
        if ($options->maxbytes) {
            $size = $options->maxbytes;
        } else {
            $size = get_max_upload_file_size();
        }
        if ($size == -1) {
            $maxsize = '';
        } else {
            $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
        }
        if ($options->buttonname) {
            $buttonname = ' name="' . $options->buttonname . '"';
        } else {
            $buttonname = '';
        }
        $html = <<<EOD
<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
$icon_progress
</div>
<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
    <div>
        <input type="button" class="fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
        <span> $maxsize </span>
    </div>
EOD;
        if ($options->env != 'url') {
            $html .= <<<EOD
    <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
    <div class="filepicker-filename">
        <div class="filepicker-container">$currentfile<div class="dndupload-message">$strdndenabled <br/><div class="dndupload-arrow"></div></div></div>
        <div class="dndupload-progressbars"></div>
    </div>
    <div><div class="dndupload-target">{$strdroptoupload}<br/><div class="dndupload-arrow"></div></div></div>
    </div>
EOD;
        }
        $html .= '</div>';
        return $html;
    }
Пример #21
0
    <div><strong><?php echo Dwoo_Plugin_str($this, 'groups', 'mahara', null, null, null, null, null);?>:</strong> <?php echo (is_string($tmp=$this->scope["sitedata"]["groups"]) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp);?></br />
    <?php echo (is_string($tmp=$this->scope["sitedata"]["strgroupmemberaverage"]) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp);?></div>
    <?php 
}?>

    <?php if ((is_string($tmp=(isset($this->scope["sitedata"]["views"]) ? $this->scope["sitedata"]["views"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)) {
?>
    <div><strong><?php echo Dwoo_Plugin_str($this, 'Views', 'view', null, null, null, null, null);?>:</strong> <?php echo (is_string($tmp=$this->scope["sitedata"]["views"]) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp);?><br />
    <?php echo (is_string($tmp=$this->scope["sitedata"]["strviewsperuser"]) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp);?></div>
    <?php 
}?>

    <div><strong><?php echo Dwoo_Plugin_str($this, 'databasesize', 'admin', null, null, null, null, null);?>:</strong> <?php echo display_size((is_string($tmp=(isset($this->scope["sitedata"]["dbsize"]) ? $this->scope["sitedata"]["dbsize"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp));?></div>
    <?php if ((is_string($tmp=(isset($this->scope["sitedata"]["diskusage"]) ? $this->scope["sitedata"]["diskusage"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)) {
?>
    <div><strong><?php echo Dwoo_Plugin_str($this, 'diskusage', 'admin', null, null, null, null, null);?>:</strong> <?php echo display_size((is_string($tmp=(isset($this->scope["sitedata"]["diskusage"]) ? $this->scope["sitedata"]["diskusage"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp));?></div>
    <?php 
}?>

    <div><strong><?php echo Dwoo_Plugin_str($this, 'maharaversion', 'admin', null, null, null, null, null);?>:</strong> <?php echo (is_string($tmp=$this->scope["sitedata"]["release"]) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp);
if ((is_string($tmp=(isset($this->scope["sitedata"]["strlatestversion"]) ? $this->scope["sitedata"]["strlatestversion"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)) {
?> (<?php echo clean_html((isset($this->scope["sitedata"]["strlatestversion"]) ? $this->scope["sitedata"]["strlatestversion"]:null));?>)<?php 
}?></div>
    <div><strong><?php echo Dwoo_Plugin_str($this, 'Cron', 'admin', null, null, null, null, null);?>:</strong> <?php if ((is_string($tmp=(isset($this->scope["sitedata"]["cronrunning"]) ? $this->scope["sitedata"]["cronrunning"]:null)) ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)) {

echo Dwoo_Plugin_str($this, 'runningnormally', 'admin', null, null, null, null, null);

}
else {

echo Dwoo_Plugin_str($this, 'cronnotrunning1', 'admin', null, null, null, null, null);
Пример #22
0
/**
 * Output some standard information during cron runs. Specifically current time
 * and memory usage. This method also does gc_collect_cycles() (before displaying
 * memory usage) to try to help PHP manage memory better.
 */
function cron_trace_time_and_memory()
{
    gc_collect_cycles();
    mtrace('... started ' . date('H:i:s') . '. Current memory use ' . display_size(memory_get_usage()) . '.');
}
Пример #23
0
 /**
  * Displays a backup files viewer
  *
  * @global stdClass $USER
  * @param backup_files_viewer $tree
  * @return string
  */
 public function render_backup_files_viewer(backup_files_viewer $viewer)
 {
     global $CFG;
     $files = $viewer->files;
     $table = new html_table();
     $table->attributes['class'] = 'backup-files-table generaltable';
     $table->head = array(get_string('filename', 'backup'), get_string('time'), get_string('size'), get_string('download'), get_string('restore'));
     $table->width = '100%';
     $table->data = array();
     foreach ($files as $file) {
         if ($file->is_directory()) {
             continue;
         }
         $fileurl = moodle_url::make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), null, $file->get_filepath(), $file->get_filename(), true);
         $params = array();
         $params['action'] = 'choosebackupfile';
         $params['filename'] = $file->get_filename();
         $params['filepath'] = $file->get_filepath();
         $params['component'] = $file->get_component();
         $params['filearea'] = $file->get_filearea();
         $params['filecontextid'] = $file->get_contextid();
         $params['contextid'] = $viewer->currentcontext->id;
         $params['itemid'] = $file->get_itemid();
         $restoreurl = new moodle_url('/backup/restorefile.php', $params);
         $table->data[] = array($file->get_filename(), userdate($file->get_timemodified()), display_size($file->get_filesize()), html_writer::link($fileurl, get_string('download')), html_writer::link($restoreurl, get_string('restore')));
     }
     $html = html_writer::table($table);
     $html .= $this->output->single_button(new moodle_url('/backup/backupfilesedit.php', array('currentcontext' => $viewer->currentcontext->id, 'contextid' => $viewer->filecontext->id, 'filearea' => $viewer->filearea, 'component' => $viewer->component, 'returnurl' => $this->page->url->out())), get_string('managefiles', 'backup'), 'post');
     return $html;
 }
Пример #24
0
    /**
     * Internal implementation of file picker rendering.
     * @param file_picker $fp
     * @return string
     */
    public function render_file_picker(file_picker $fp)
    {
        global $CFG, $OUTPUT, $USER;
        $options = $fp->options;
        $client_id = $options->client_id;
        $strsaved = get_string('filesaved', 'repository');
        $straddfile = get_string('openpicker', 'repository');
        $strloading = get_string('loading', 'repository');
        $icon_progress = $OUTPUT->pix_icon('i/loading_small', $strloading) . '';
        $currentfile = $options->currentfile;
        if (empty($currentfile)) {
            $currentfile = get_string('nofilesattached', 'repository');
        }
        if ($options->maxbytes) {
            $size = $options->maxbytes;
        } else {
            $size = get_max_upload_file_size();
        }
        if ($size == -1) {
            $maxsize = '';
        } else {
            $maxsize = get_string('maxfilesize', 'moodle', display_size($size));
        }
        if ($options->buttonname) {
            $buttonname = ' name="' . $options->buttonname . '"';
        } else {
            $buttonname = '';
        }
        $html = <<<EOD
<div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
{$icon_progress}
</div>
<div id="filepicker-wrapper-{$client_id}" class="mdl-left" style="display:none">
    <div>
        <input type="button" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
        <span> {$maxsize} </span>
    </div>
EOD;
        if ($options->env != 'url') {
            $html .= <<<EOD
    <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist">{$currentfile}</div>
EOD;
        }
        $html .= '</div>';
        return $html;
    }
Пример #25
0
 /**
  * Prepare the file/folder listing.
  *
  * @param array $list of files and folders.
  * @return array of files and folders.
  * @since Moodle 2.3.3
  */
 protected static function prepare_list($list)
 {
     global $OUTPUT;
     $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
     // Reset the array keys because non-numeric keys will create an object when converted to JSON.
     $list = array_values($list);
     $len = count($list);
     for ($i = 0; $i < $len; $i++) {
         if (is_object($list[$i])) {
             $file = (array) $list[$i];
             $converttoobject = true;
         } else {
             $file =& $list[$i];
             $converttoobject = false;
         }
         if (isset($file['size'])) {
             $file['size'] = (int) $file['size'];
             $file['size_f'] = display_size($file['size']);
         }
         if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
             $file['license_f'] = get_string($file['license'], 'license');
         }
         if (isset($file['image_width']) && isset($file['image_height'])) {
             $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
             $file['dimensions'] = get_string('imagesize', 'repository', (object) $a);
         }
         foreach (array('date', 'datemodified', 'datecreated') as $key) {
             if (!isset($file[$key]) && isset($file['date'])) {
                 $file[$key] = $file['date'];
             }
             if (isset($file[$key])) {
                 // must be UNIX timestamp
                 $file[$key] = (int) $file[$key];
                 if (!$file[$key]) {
                     unset($file[$key]);
                 } else {
                     $file[$key . '_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
                     $file[$key . '_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
                 }
             }
         }
         $isfolder = array_key_exists('children', $file) || isset($file['type']) && $file['type'] == 'folder';
         $filename = null;
         if (isset($file['title'])) {
             $filename = $file['title'];
         } else {
             if (isset($file['fullname'])) {
                 $filename = $file['fullname'];
             }
         }
         if (!isset($file['mimetype']) && !$isfolder && $filename) {
             $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
         }
         if (!isset($file['icon'])) {
             if ($isfolder) {
                 $file['icon'] = $foldericon;
             } else {
                 if ($filename) {
                     $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
                 }
             }
         }
         // Recursively loop over children.
         if (isset($file['children'])) {
             $file['children'] = self::prepare_list($file['children']);
         }
         // Convert the array back to an object.
         if ($converttoobject) {
             $list[$i] = (object) $file;
         }
     }
     return $list;
 }
Пример #26
0
function edituser_site_validate(Pieform $form, $values)
{
    global $USER, $SESSION;
    if (!($user = get_record('usr', 'id', $values['id']))) {
        return false;
    }
    if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) {
        $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled');
        $maxquota = get_config_plugin('artefact', 'file', 'maxquota');
        if ($maxquotaenabled && $values['quota'] > $maxquota) {
            $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota)));
            $SESSION->add_error_msg(get_string('maxquotaexceeded', 'artefact.file', display_size($maxquota)));
        }
    }
    $userobj = new User();
    $userobj = $userobj->find_by_id($user->id);
    if (isset($values['username']) && !empty($values['username']) && $values['username'] != $userobj->username) {
        if (!isset($values['authinstance'])) {
            $authobj = AuthFactory::create($userobj->authinstance);
        } else {
            $authobj = AuthFactory::create($values['authinstance']);
        }
        if (method_exists($authobj, 'change_username')) {
            if (method_exists($authobj, 'is_username_valid_admin')) {
                if (!$authobj->is_username_valid_admin($values['username'])) {
                    $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal'));
                }
            } else {
                if (method_exists($authobj, 'is_username_valid')) {
                    if (!$authobj->is_username_valid($values['username'])) {
                        $form->set_error('username', get_string('usernameinvalidform', 'auth.internal'));
                    }
                }
            }
            if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($values['username']))) {
                $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal'));
            }
        } else {
            $form->set_error('username', get_string('usernamechangenotallowed', 'admin'));
        }
    }
    // OVERWRITE 3: insert
    if (isset($values['email']) && !empty($values['email']) && $values['email'] != $userobj->email) {
        $email = sanitize_email($values['email']);
        if ($email == '') {
            $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal'));
        } else {
            $values['email'] = $email;
        }
        if (GcrInstitutionTable::isEmailAddressUsed($email)) {
            $form->set_error('email', get_string('emailalreadytaken', 'auth.internal'));
        }
    }
    // END OVERWITE 3
    // Check that the external username isn't already in use by someone else
    if (isset($values['authinstance']) && isset($values['remoteusername'])) {
        // there are 4 cases for changes on the page
        // 1) ai and remoteuser have changed
        // 2) just ai has changed
        // 3) just remoteuser has changed
        // 4) the ai changes and the remoteuser is wiped - this is a delete of the old ai-remoteuser
        // determine the current remoteuser
        $current_remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id);
        if (!$current_remotename) {
            $current_remotename = $user->username;
        }
        // what should the new remoteuser be
        $new_remoteuser = get_field('auth_remote_user', 'remoteusername', 'authinstance', $values['authinstance'], 'localusr', $user->id);
        if (!$new_remoteuser) {
            $new_remoteuser = $user->username;
        }
        if (strlen(trim($values['remoteusername'])) > 0) {
            // value changed on page - use it
            if ($values['remoteusername'] != $current_remotename) {
                $new_remoteuser = $values['remoteusername'];
            }
        }
        // what really counts is who owns the target remoteuser slot
        $target_owner = get_field('auth_remote_user', 'localusr', 'authinstance', $values['authinstance'], 'remoteusername', $new_remoteuser);
        // target remoteuser is owned by someone else
        if ($target_owner && $target_owner != $user->id) {
            $usedbyuser = get_field('usr', 'username', 'id', $target_owner);
            $SESSION->add_error_msg(get_string('duplicateremoteusername', 'auth', $usedbyuser));
            $form->set_error('remoteusername', get_string('duplicateremoteusernameformerror', 'auth'));
        }
    }
}
Пример #27
0
 /**
  * Helper to convert artefacts into smarty-friendly data
  *
  * @param int $parent   The ID of the parent folder for the artefact to 
  *                      convert
  * @param bool $folders True to get folders, false to get everything but 
  *                      folders
  */
 private function prepare_artefacts_for_smarty($parent, $folders)
 {
     $data = array();
     $equality = $folders ? '==' : '!=';
     $parent = is_null($parent) ? 'null' : intval($parent);
     $artefacts = array_filter($this->artefactdata, create_function('$a', 'return $a->get("parent") == ' . $parent . ' && $a->get("artefacttype") ' . $equality . ' "folder";'));
     foreach ($artefacts as $artefact) {
         $size = '';
         if ($artefact->get('artefacttype') != 'folder') {
             $size = $artefact->get('size');
             $size = $size ? display_size($size) : '';
         }
         $data[] = array('icon' => '', 'title' => $artefact->get('title'), 'path' => PluginExportHtml::sanitise_path($artefact->get('title')), 'description' => $artefact->get('description'), 'size' => $size, 'date' => strftime(get_string('strftimedaydatetime'), $artefact->get('ctime')));
     }
     return $data;
 }
Пример #28
0
/**
 * Listing all files (including folders) in current path (draft area)
 * used by file manager
 * @param int $draftitemid
 * @param string $filepath
 * @return mixed
 */
function file_get_drafarea_files($draftitemid, $filepath = '/')
{
    global $USER, $OUTPUT, $CFG;
    $context = get_context_instance(CONTEXT_USER, $USER->id);
    $fs = get_file_storage();
    $data = new stdClass();
    $data->path = array();
    $data->path[] = array('name' => get_string('files'), 'path' => '/');
    // will be used to build breadcrumb
    $trail = '';
    if ($filepath !== '/') {
        $filepath = file_correct_filepath($filepath);
        $parts = explode('/', $filepath);
        foreach ($parts as $part) {
            if ($part != '' && $part != null) {
                $trail .= '/' . $part . '/';
                $data->path[] = array('name' => $part, 'path' => $trail);
            }
        }
    }
    $list = array();
    $maxlength = 12;
    if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
        foreach ($files as $file) {
            $item = new stdClass();
            $item->filename = $file->get_filename();
            $item->filepath = $file->get_filepath();
            $item->fullname = trim($item->filename, '/');
            $filesize = $file->get_filesize();
            $item->filesize = $filesize ? display_size($filesize) : '';
            $icon = mimeinfo_from_type('icon', $file->get_mimetype());
            $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
            $item->sortorder = $file->get_sortorder();
            if ($icon == 'zip') {
                $item->type = 'zip';
            } else {
                $item->type = 'file';
            }
            if ($file->is_directory()) {
                $item->filesize = 0;
                $item->icon = $OUTPUT->pix_url('f/folder')->out();
                $item->type = 'folder';
                $foldername = explode('/', trim($item->filepath, '/'));
                $item->fullname = trim(array_pop($foldername), '/');
            } else {
                // do NOT use file browser here!
                $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
            }
            $list[] = $item;
        }
    }
    $data->itemid = $draftitemid;
    $data->list = $list;
    return $data;
}
Пример #29
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);
 }
Пример #30
0
 /**
  * Define this form - called by the parent constructor
  */
 public function definition()
 {
     global $DB, $CFG, $COURSE, $PAGE, $OUTPUT;
     $jsmodule = array('name' => 'mod_publication', 'fullpath' => '/mod/publication/publication.js', 'requires' => array('node-base', 'node-event-simulate'));
     $PAGE->requires->js_init_call('M.mod_publication.init_mod_form', array(), false, $jsmodule);
     $config = get_config('publication');
     $mform = $this->_form;
     $mform->addElement('header', 'general', get_string('general', 'form'));
     // Name.
     $mform->addElement('text', 'name', get_string('name', 'publication'));
     if (!empty($CFG->formatstringstriptags)) {
         $mform->setType('name', PARAM_TEXT);
     } else {
         $mform->setType('name', PARAM_CLEANHTML);
     }
     $mform->addRule('name', null, 'required', null, 'client');
     $requireintro = isset($config->requiremodintro) && $config->requiremodintro == 1 ? true : false;
     $this->add_intro_editor($requireintro);
     // Publication specific elements.
     $mform->addElement('header', 'publication', get_string('modulename', 'publication'));
     $mform->setExpanded('publication');
     if (isset($this->current->id) && $this->current->id != "") {
         $filecount = $DB->count_records('publication_file', array('publication' => $this->current->id));
     } else {
         $filecount = 0;
     }
     $disabled = array();
     if ($filecount > 0) {
         $disabled['disabled'] = 'disabled';
     }
     $modearray = array();
     $modearray[] =& $mform->createElement('radio', 'mode', '', get_string('modeupload', 'publication'), PUBLICATION_MODE_UPLOAD, $disabled);
     $modearray[] =& $mform->createElement('radio', 'mode', '', get_string('modeimport', 'publication'), PUBLICATION_MODE_IMPORT, $disabled);
     $mform->addGroup($modearray, 'modegrp', get_string('mode', 'publication'), array(' '), false);
     $mform->addHelpButton('modegrp', 'mode', 'publication');
     if (count($filecount) == 0) {
         $mform->addRule('modegrp', null, 'required', null, 'client');
     }
     // Publication mode import specific elements.
     $choices = array();
     $choices[-1] = get_string('choose', 'publication');
     $assigninstances = $DB->get_records('assign', array('course' => $COURSE->id));
     foreach ($assigninstances as $assigninstance) {
         $choices[$assigninstance->id] = $assigninstance->name;
     }
     $mform->addElement('select', 'importfrom', get_string('assignment', 'publication'), $choices, $disabled);
     if (count($disabled) == 0) {
         $mform->disabledif('importfrom', 'mode', 'neq', PUBLICATION_MODE_IMPORT);
     }
     $attributes = array();
     if (isset($this->current->id) && isset($this->current->obtainstudentapproval)) {
         if ($this->current->obtainstudentapproval) {
             $message = get_string('warning_changefromobtainstudentapproval', 'publication');
             $showwhen = "0";
         } else {
             $message = get_string('warning_changetoobtainstudentapproval', 'publication');
             $showwhen = "1";
         }
         $message = trim(preg_replace('/\\s+/', ' ', $message));
         $message = str_replace('\'', '\\\'', $message);
         $attributes['onChange'] = "if (this.value==" . $showwhen . ") {alert('" . $message . "')}";
     }
     $mform->addElement('selectyesno', 'obtainstudentapproval', get_string('obtainstudentapproval', 'publication'), $attributes);
     $mform->setDefault('obtainstudentapproval', get_config('publication', 'obtainstudentapproval'));
     $mform->addHelpButton('obtainstudentapproval', 'obtainstudentapproval', 'publication');
     $mform->disabledIf('obtainstudentapproval', 'mode', 'neq', PUBLICATION_MODE_IMPORT);
     // Publication mode upload specific elements.
     $maxfiles = array();
     for ($i = 1; $i <= 100 || $i <= get_config('publication', 'maxfiles'); $i++) {
         $maxfiles[$i] = $i;
     }
     $mform->addElement('select', 'maxfiles', get_string('maxfiles', 'publication'), $maxfiles);
     $mform->setDefault('maxfiles', get_config('publication', 'maxfiles'));
     $mform->disabledIf('maxfiles', 'mode', 'neq', PUBLICATION_MODE_UPLOAD);
     $choices = get_max_upload_sizes($CFG->maxbytes, $COURSE->maxbytes);
     $choices[0] = get_string('courseuploadlimit', 'publication') . ' (' . display_size($COURSE->maxbytes) . ')';
     $mform->addElement('select', 'maxbytes', get_string('maxbytes', 'publication'), $choices);
     $mform->setDefault('maxbytes', get_config('publication', 'maxbytes'));
     $mform->disabledIf('maxbytes', 'mode', 'neq', PUBLICATION_MODE_UPLOAD);
     $mform->addElement('text', 'allowedfiletypes', get_string('allowedfiletypes', 'publication'), array('size' => '45'));
     $mform->setType('allowedfiletypes', PARAM_RAW);
     $mform->addHelpButton('allowedfiletypes', 'allowedfiletypes', 'publication');
     $mform->addRule('allowedfiletypes', get_string('allowedfiletypes_err', 'publication'), 'regex', '/^([A-Za-z0-9]+([ ]*[,][ ]*[A-Za-z0-9]+)*)$/', 'client', false, false);
     $mform->disabledIf('allowedfiletypes', 'mode', 'neq', PUBLICATION_MODE_UPLOAD);
     $attributes = array();
     if (isset($this->current->id) && isset($this->current->obtainteacherapproval)) {
         if (!$this->current->obtainteacherapproval) {
             $message = get_string('warning_changefromobtainteacherapproval', 'publication');
             $showwhen = "1";
         } else {
             $message = get_string('warning_changetoobtainteacherapproval', 'publication');
             $showwhen = "0";
         }
         $message = trim(preg_replace('/\\s+/', ' ', $message));
         $attributes['onChange'] = "if (this.value==" . $showwhen . ") {alert('" . $message . "')}";
     }
     $mform->addElement('selectyesno', 'obtainteacherapproval', get_string('obtainteacherapproval', 'publication'), $attributes);
     $mform->setDefault('obtainteacherapproval', get_config('publication', 'obtainteacherapproval'));
     $mform->addHelpButton('obtainteacherapproval', 'obtainteacherapproval', 'publication');
     $mform->disabledIf('obtainteacherapproval', 'mode', 'neq', PUBLICATION_MODE_UPLOAD);
     // Availability.
     $mform->addElement('header', 'availability', get_string('availability', 'publication'));
     $mform->setExpanded('availability', true);
     $name = get_string('allowsubmissionsfromdate', 'publication');
     $options = array('optional' => true);
     $mform->addElement('date_time_selector', 'allowsubmissionsfromdate', $name, $options);
     $mform->addHelpButton('allowsubmissionsfromdate', 'allowsubmissionsfromdateh', 'publication');
     $mform->setDefault('allowsubmissionsfromdate', time());
     $name = get_string('duedate', 'publication');
     $mform->addElement('date_time_selector', 'duedate', $name, array('optional' => true));
     $mform->setDefault('duedate', time() + 7 * 24 * 3600);
     $mform->addElement('hidden', 'cutoffdate', false);
     $mform->setType('cutoffdate', PARAM_BOOL);
     $mform->addElement('hidden', 'alwaysshowdescription', true);
     $mform->setType('alwaysshowdescription', PARAM_BOOL);
     // Standard coursemodule elements.
     $this->standard_coursemodule_elements();
     // Buttons.
     $this->add_action_buttons();
 }