예제 #1
0
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG;
     require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
     $registrationmanager = new \registration_manager();
     $registrationmanager->cron();
 }
예제 #2
0
/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: context_helper::build_all_paths(true);
        mtrace(' Built context paths');
        // Remove expired cache flags
        gc_cache_flags();
        mtrace(' Cleaned cache flags');
        // Cleanup messaging
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace(' Cleaned up read notifications');
        }
        mtrace(' Deleting temporary files...');
        cron_delete_from_temp();
        // Cleanup user password reset records
        // Delete any reset request records which are expired by more than a day.
        // (We keep recently expired requests around so we can give a different error msg to users who
        // are trying to user a recently expired reset attempt).
        $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
        $earliestvalid = time() - $pwresettime - DAYSECS;
        $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
        mtrace(' Cleaned up old password reset records');
        mtrace("...finished clean-up tasks");
    }
    // End of occasional clean-up tasks
    // Send login failures notification - brute force protection in moodle is weak,
    // we should at least send notices early in each cron execution
    if (notify_login_failures()) {
        mtrace(' Notified login failures');
    }
    // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
    context_helper::create_instances();
    mtrace(' Created missing context instances');
    // Session gc.
    mtrace("Running session gc tasks...");
    \core\session\manager::gc();
    mtrace("...finished stale session cleanup");
    // Run the auth cron, if any before enrolments
    // because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    cron_trace_time_and_memory();
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    // Generate new password emails for users - ppl expect these generated asap
    if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
        mtrace('Creating passwords for new users...');
        $usernamefields = get_all_user_name_fields(true, 'u');
        $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n                                                 {$usernamefields}, u.username, u.lang,\n                                                 p.id as prefid\n                                            FROM {user} u\n                                            JOIN {user_preferences} p ON u.id=p.userid\n                                           WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
        // note: we can not send emails to suspended accounts
        foreach ($newusers as $newuser) {
            // Use a low cost factor when generating bcrypt hash otherwise
            // hashing would be slow when emailing lots of users. Hashes
            // will be automatically updated to a higher cost factor the first
            // time the user logs in.
            if (setnew_password_and_mail($newuser, true)) {
                unset_user_preference('create_password', $newuser);
                set_user_preference('auth_forcepasswordchange', 1, $newuser);
            } else {
                trigger_error("Could not create and mail new user password!");
            }
        }
        $newusers->close();
    }
    // It is very important to run enrol early
    // because other plugins depend on correct enrolment info.
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        cron_trace_time_and_memory();
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    // Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    cron_trace_time_and_memory();
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    // Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // We will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    cron_trace_time_and_memory();
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    // Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    mtrace('Starting admin reports');
    cron_execute_plugin_type('report');
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job...');
    cron_trace_time_and_memory();
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    cron_trace_time_and_memory();
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        cron_trace_time_and_memory();
        require_once $CFG->dirroot . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        cron_trace_time_and_memory();
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace('Starting course reports');
    cron_execute_plugin_type('coursereport');
    mtrace('Finished course reports');
    // run gradebook import/export/report cron
    mtrace('Starting gradebook plugins');
    cron_execute_plugin_type('gradeimport');
    cron_execute_plugin_type('gradeexport');
    cron_execute_plugin_type('gradereport');
    mtrace('Finished gradebook plugins');
    // run calendar cron
    require_once "{$CFG->dirroot}/calendar/lib.php";
    calendar_cron();
    // Run external blog cron if needed
    if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        cron_trace_time_and_memory();
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
        mtrace('done.');
    }
    // Run blog associations cleanup
    if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        cron_trace_time_and_memory();
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
        mtrace('done.');
    }
    // Run question bank clean-up.
    mtrace("Starting the question bank cron...", '');
    cron_trace_time_and_memory();
    require_once $CFG->libdir . '/questionlib.php';
    question_bank::cron();
    mtrace('done.');
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    cron_trace_time_and_memory();
    require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // If enabled, fetch information about available updates and eventually notify site admins
    if (empty($CFG->disableupdatenotifications)) {
        $updateschecker = \core\update\checker::instance();
        $updateschecker->cron();
    }
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    cron_trace_time_and_memory();
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // all other plugins
    cron_execute_plugin_type('message', 'message plugins');
    cron_execute_plugin_type('filter', 'filters');
    cron_execute_plugin_type('editor', 'editors');
    cron_execute_plugin_type('format', 'course formats');
    cron_execute_plugin_type('profilefield', 'profile fields');
    cron_execute_plugin_type('webservice', 'webservices');
    cron_execute_plugin_type('repository', 'repository plugins');
    cron_execute_plugin_type('qbehaviour', 'question behaviours');
    cron_execute_plugin_type('qformat', 'question import/export formats');
    cron_execute_plugin_type('qtype', 'question types');
    cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
    cron_execute_plugin_type('theme', 'themes');
    cron_execute_plugin_type('tool', 'admin tools');
    // and finally run any local cronjobs, if any
    if ($locals = core_component::get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        // new cron functions in lib.php first
        cron_execute_plugin_type('local');
        // legacy cron files are executed directly
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace('Running cache cron routines');
    cache_helper::cron();
    mtrace('done.');
    // Run automated backups if required - these may take a long time to execute
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    // Run stats as at the end because they are known to take very long time on large sites
    if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
        require_once $CFG->dirroot . '/lib/statslib.php';
        // check we're not before our runtime
        $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
        if (time() > $timetocheck) {
            // process configured number of days as max (defaulting to 31)
            $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
            if (stats_cron_daily($maxdays)) {
                if (stats_cron_weekly()) {
                    if (stats_cron_monthly()) {
                        stats_clean_old();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // Run badges review cron.
    mtrace("Starting badges cron...");
    require_once $CFG->dirroot . '/badges/cron.php';
    badge_cron();
    mtrace('done.');
    // cleanup file trash - not very important
    $fs = get_file_storage();
    $fs->cron();
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
예제 #3
0
파일: index.php 프로젝트: vuchannguyen/web
             $publication = $publicationmanager->get_publication($sitecourse['id'], $hub->huburl);
             if (!empty($publication)) {
                 $publication->status = $sitecourse['privacy'];
                 $publication->timechecked = time();
                 $publicationmanager->update_publication($publication);
             } else {
                 $msgparams = new stdClass();
                 $msgparams->id = $sitecourse['id'];
                 $msgparams->hubname = html_writer::tag('a', $hub->hubname, array('href' => $hub->huburl));
                 $confirmmessage .= $OUTPUT->notification(get_string('detectednotexistingpublication', 'hub', $msgparams));
             }
         }
     }
 }
 //if the site os registered on no hub display an error page
 $registrationmanager = new registration_manager();
 $registeredhubs = $registrationmanager->get_registered_on_hubs();
 if (empty($registeredhubs)) {
     echo $OUTPUT->header();
     echo $OUTPUT->heading(get_string('publishon', 'hub'), 3, 'main');
     echo $OUTPUT->box(get_string('notregisteredonhub', 'hub'));
     echo $OUTPUT->footer();
     die;
 }
 $renderer = $PAGE->get_renderer('core', 'publish');
 /// UNPUBLISH
 $cancel = optional_param('cancel', 0, PARAM_BOOL);
 if (!empty($cancel) and confirm_sesskey()) {
     $confirm = optional_param('confirm', 0, PARAM_BOOL);
     $hubcourseid = optional_param('hubcourseid', 0, PARAM_INT);
     $publicationid = optional_param('publicationid', 0, PARAM_INT);
 * directory later by web service.
 */
require '../../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
$newtoken = optional_param('newtoken', '', PARAM_ALPHANUM);
$url = optional_param('url', '', PARAM_URL);
$hubname = optional_param('hubname', '', PARAM_TEXT);
$token = optional_param('token', '', PARAM_TEXT);
$error = optional_param('error', '', PARAM_ALPHANUM);
admin_externalpage_setup('registrationhubs');
if (!empty($error) and $error == 'urlalreadyexist') {
    throw new moodle_exception('urlalreadyregistered', 'hub', $CFG->wwwroot . '/' . $CFG->admin . '/registration/index.php');
}
//check that we are waiting a confirmation from this hub, and check that the token is correct
$registrationmanager = new registration_manager();
$registeredhub = $registrationmanager->get_unconfirmedhub($url);
if (!empty($registeredhub) and $registeredhub->token == $token) {
    echo $OUTPUT->header();
    echo $OUTPUT->heading(get_string('registrationconfirmed', 'hub'), 3, 'main');
    $hublink = html_writer::tag('a', $hubname, array('href' => $url));
    $registeredhub->token = $newtoken;
    $registeredhub->confirmed = 1;
    $registeredhub->hubname = $hubname;
    $registrationmanager->update_registeredhub($registeredhub);
    //display notficiation message
    $notificationmessage = $OUTPUT->notification(get_string('registrationconfirmedon', 'hub', $hublink), 'notifysuccess');
    echo $notificationmessage;
    //display continue button
    $registrationpage = new moodle_url('/admin/registration/index.php');
    $continuebutton = $OUTPUT->render(new single_button($registrationpage, get_string('continue', 'hub')));
예제 #5
0
파일: backup.php 프로젝트: nmicha/moodle
    echo $OUTPUT->header();
    echo $OUTPUT->heading(get_string('publishcourseon', 'hub', !empty($hubname) ? $hubname : $huburl), 3, 'main');
    if ($backup->enforce_changed_dependencies()) {
        echo $renderer->dependency_notification(get_string('dependenciesenforced', 'backup'));
    }
    echo $renderer->progress_bar($backup->get_progress_bar());
    echo $backup->display();
    echo $OUTPUT->footer();
    die;
}
//$backupfile = $backup->get_stage_results();
$backupfile = $bc->get_results();
$backupfile = $backupfile['backup_destination'];
//END backup processing
//retrieve the token to call the hub
$registrationmanager = new registration_manager();
$registeredhub = $registrationmanager->get_registeredhub($huburl);
//display the sending file page
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('sendingcourse', 'hub'), 3, 'main');
$renderer = $PAGE->get_renderer('core', 'publish');
echo $renderer->sendingbackupinfo($backupfile);
if (ob_get_level()) {
    ob_flush();
}
flush();
//send backup file to the hub
$curl = new curl();
$params = array();
$params['filetype'] = HUB_BACKUP_FILE_TYPE;
$params['courseid'] = $hubcourseid;
예제 #6
0
 /**
  * Download the community course backup and save it in file API
  * @param integer $courseid
  * @param string $huburl
  * @return array 'privatefile' the file name saved in private area
  *               'tmpfile' the file name saved in the moodledata temp dir (for restore)
  */
 public function block_community_download_course_backup($course)
 {
     global $CFG, $USER;
     require_once $CFG->libdir . "/filelib.php";
     require_once $CFG->dirroot . "/course/publish/lib.php";
     $params['courseid'] = $course->id;
     $params['filetype'] = HUB_BACKUP_FILE_TYPE;
     make_upload_directory('temp/backup');
     $filename = md5(time() . '-' . $course->id . '-' . $USER->id . '-' . random_string(20));
     $url = new moodle_url($course->huburl . '/local/hub/webservice/download.php', $params);
     $path = $CFG->dataroot . '/temp/backup/' . $filename . ".mbz";
     $fp = fopen($path, 'w');
     $curlurl = $course->huburl . '/local/hub/webservice/download.php?filetype=' . HUB_BACKUP_FILE_TYPE . '&courseid=' . $course->id;
     //send an identification token if the site is registered on the hub
     require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
     $registrationmanager = new registration_manager();
     $registeredhub = $registrationmanager->get_registeredhub($course->huburl);
     if (!empty($registeredhub)) {
         $token = $registeredhub->token;
         $curlurl .= '&token=' . $token;
     }
     $ch = curl_init($curlurl);
     curl_setopt($ch, CURLOPT_FILE, $fp);
     $data = curl_exec($ch);
     curl_close($ch);
     fclose($fp);
     $fs = get_file_storage();
     $record = new stdClass();
     $record->contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
     $record->component = 'user';
     $record->filearea = 'private';
     $record->itemid = 0;
     $record->filename = urlencode($course->fullname) . "_" . time() . ".mbz";
     $record->filepath = '/downloaded_backup/';
     if (!$fs->file_exists($record->contextid, $record->component, $record->filearea, 0, $record->filepath, $record->filename)) {
         $fs->create_file_from_pathname($record, $CFG->dataroot . '/temp/backup/' . $filename . ".mbz");
     }
     $filenames = array();
     $filenames['privatefile'] = $record->filename;
     $filenames['tmpfile'] = $filename;
     return $filenames;
 }
 }
 if ($fromformdata['audience'] != 'all') {
     $options->audience = $fromformdata['audience'];
 }
 if ($fromformdata['educationallevel'] != 'all') {
     $options->educationallevel = $fromformdata['educationallevel'];
 }
 if ($fromformdata['language'] != 'all') {
     $options->language = $fromformdata['language'];
 }
 $options->orderby = $fromformdata['orderby'];
 //the range of course requested
 $options->givememore = optional_param('givememore', 0, PARAM_INT);
 //check if the selected hub is from the registered list (in this case we use the private token)
 $token = 'publichub';
 $registrationmanager = new registration_manager();
 $registeredhubs = $registrationmanager->get_registered_on_hubs();
 foreach ($registeredhubs as $registeredhub) {
     if ($huburl == $registeredhub->huburl) {
         $token = $registeredhub->token;
     }
 }
 $function = 'hub_get_courses';
 $params = array('search' => $search, 'downloadable' => $downloadable, 'enrollable' => !$downloadable, 'options' => $options);
 $serverurl = $huburl . "/local/hub/webservice/webservices.php";
 require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
 $xmlrpcclient = new webservice_xmlrpc_client($serverurl, $token);
 try {
     $result = $xmlrpcclient->call($function, $params);
     $courses = $result['courses'];
     $coursetotal = $result['coursetotal'];
예제 #8
0
 public function definition()
 {
     global $CFG, $USER, $OUTPUT;
     $strrequired = get_string('required');
     $mform =& $this->_form;
     //set default value
     $search = $this->_customdata['search'];
     if (isset($this->_customdata['coverage'])) {
         $coverage = $this->_customdata['coverage'];
     } else {
         $coverage = 'all';
     }
     if (isset($this->_customdata['licence'])) {
         $licence = $this->_customdata['licence'];
     } else {
         $licence = 'all';
     }
     if (isset($this->_customdata['subject'])) {
         $subject = $this->_customdata['subject'];
     } else {
         $subject = 'all';
     }
     if (isset($this->_customdata['audience'])) {
         $audience = $this->_customdata['audience'];
     } else {
         $audience = 'all';
     }
     if (isset($this->_customdata['language'])) {
         $language = $this->_customdata['language'];
     } else {
         $language = current_language();
     }
     if (isset($this->_customdata['educationallevel'])) {
         $educationallevel = $this->_customdata['educationallevel'];
     } else {
         $educationallevel = 'all';
     }
     if (isset($this->_customdata['downloadable'])) {
         $downloadable = $this->_customdata['downloadable'];
     } else {
         $downloadable = 1;
     }
     if (isset($this->_customdata['orderby'])) {
         $orderby = $this->_customdata['orderby'];
     } else {
         $orderby = 'newest';
     }
     if (isset($this->_customdata['huburl'])) {
         $huburl = $this->_customdata['huburl'];
     } else {
         $huburl = HUB_MOODLEORGHUBURL;
     }
     $mform->addElement('header', 'site', get_string('search', 'block_community'));
     //add the course id (of the context)
     $mform->addElement('hidden', 'courseid', $this->_customdata['courseid']);
     $mform->setType('courseid', PARAM_INT);
     $mform->addElement('hidden', 'executesearch', 1);
     $mform->setType('executesearch', PARAM_INT);
     //retrieve the hub list on the hub directory by web service
     $function = 'hubdirectory_get_hubs';
     $params = array();
     $serverurl = HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/webservices.php";
     require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
     $xmlrpcclient = new webservice_xmlrpc_client($serverurl, 'publichubdirectory');
     try {
         $hubs = $xmlrpcclient->call($function, $params);
     } catch (Exception $e) {
         $hubs = array();
         $error = $OUTPUT->notification(get_string('errorhublisting', 'block_community', $e->getMessage()));
         $mform->addElement('static', 'errorhub', '', $error);
     }
     //display list of registered on hub
     $registrationmanager = new registration_manager();
     $registeredhubs = $registrationmanager->get_registered_on_hubs();
     //retrieve some additional hubs that we will add to
     //the hub list got from the hub directory
     $additionalhubs = array();
     foreach ($registeredhubs as $registeredhub) {
         $inthepubliclist = false;
         foreach ($hubs as $hub) {
             if ($hub['url'] == $registeredhub->huburl) {
                 $inthepubliclist = true;
                 $hub['registeredon'] = true;
             }
         }
         if (!$inthepubliclist) {
             $additionalhub = array();
             $additionalhub['name'] = $registeredhub->hubname;
             $additionalhub['url'] = $registeredhub->huburl;
             $additionalhubs[] = $additionalhub;
         }
     }
     if (!empty($additionalhubs)) {
         $hubs = array_merge($hubs, $additionalhubs);
     }
     if (!empty($hubs)) {
         $htmlhubs = array();
         foreach ($hubs as $hub) {
             // Name can come from hub directory - need some cleaning.
             $hubname = clean_text($hub['name'], PARAM_TEXT);
             $smalllogohtml = '';
             if (array_key_exists('id', $hub)) {
                 // Retrieve hub logo + generate small logo.
                 $params = array('hubid' => $hub['id'], 'filetype' => HUB_HUBSCREENSHOT_FILE_TYPE);
                 $imgurl = new moodle_url(HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/download.php", $params);
                 $imgsize = getimagesize($imgurl->out(false));
                 if ($imgsize[0] > 1) {
                     $ascreenshothtml = html_writer::empty_tag('img', array('src' => $imgurl, 'alt' => $hubname));
                     $smalllogohtml = html_writer::empty_tag('img', array('src' => $imgurl, 'alt' => $hubname, 'height' => 30, 'width' => 40));
                 } else {
                     $ascreenshothtml = '';
                 }
                 $hubimage = html_writer::tag('div', $ascreenshothtml, array('class' => 'hubimage'));
                 // Statistics + trusted info.
                 $hubstats = '';
                 if (isset($hub['enrollablecourses'])) {
                     //check needed to avoid warnings for Moodle version < 2011081700
                     $additionaldesc = get_string('enrollablecourses', 'block_community') . ': ' . $hub['enrollablecourses'] . ' - ' . get_string('downloadablecourses', 'block_community') . ': ' . $hub['downloadablecourses'];
                     $hubstats .= html_writer::tag('div', $additionaldesc);
                 }
                 if ($hub['trusted']) {
                     $hubtrusted = get_string('hubtrusted', 'block_community');
                     $hubstats .= $OUTPUT->doc_link('trusted_hubs') . html_writer::tag('div', $hubtrusted);
                 }
                 $hubstats = html_writer::tag('div', $hubstats, array('class' => 'hubstats'));
                 // hub name link + hub description.
                 $hubnamelink = html_writer::link($hub['url'], html_writer::tag('h2', $hubname), array('class' => 'hubtitlelink'));
                 // The description can come from the hub directory - need to clean.
                 $hubdescription = clean_param($hub['description'], PARAM_TEXT);
                 $hubdescriptiontext = html_writer::tag('div', format_text($hubdescription, FORMAT_PLAIN), array('class' => 'hubdescription'));
                 $hubtext = html_writer::tag('div', $hubdescriptiontext . $hubstats, array('class' => 'hubtext'));
                 $hubimgandtext = html_writer::tag('div', $hubimage . $hubtext, array('class' => 'hubimgandtext'));
                 $hubfulldesc = html_writer::tag('div', $hubnamelink . $hubimgandtext, array('class' => 'hubmainhmtl'));
             } else {
                 $hubfulldesc = html_writer::link($hub['url'], $hubname);
             }
             // Add hub to the hub items.
             $hubinfo = new stdClass();
             $hubinfo->mainhtml = $hubfulldesc;
             $hubinfo->rowhtml = html_writer::tag('div', $smalllogohtml, array('class' => 'hubsmalllogo')) . $hubname;
             $hubitems[$hub['url']] = $hubinfo;
         }
         // Hub listing form element.
         $mform->addElement('listing', 'huburl', '', '', array('items' => $hubitems, 'showall' => get_string('showall', 'block_community'), 'hideall' => get_string('hideall', 'block_community')));
         $mform->setDefault('huburl', $huburl);
         //display enrol/download select box if the USER has the download capability on the course
         if (has_capability('moodle/community:download', context_course::instance($this->_customdata['courseid']))) {
             $options = array(0 => get_string('enrollable', 'block_community'), 1 => get_string('downloadable', 'block_community'));
             $mform->addElement('select', 'downloadable', get_string('enroldownload', 'block_community'), $options);
             $mform->addHelpButton('downloadable', 'enroldownload', 'block_community');
             $mform->setDefault('downloadable', $downloadable);
         } else {
             $mform->addElement('hidden', 'downloadable', 0);
         }
         $mform->setType('downloadable', PARAM_INT);
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_AUDIENCE_EDUCATORS] = get_string('audienceeducators', 'hub');
         $options[HUB_AUDIENCE_STUDENTS] = get_string('audiencestudents', 'hub');
         $options[HUB_AUDIENCE_ADMINS] = get_string('audienceadmins', 'hub');
         $mform->addElement('select', 'audience', get_string('audience', 'block_community'), $options);
         $mform->setDefault('audience', $audience);
         unset($options);
         $mform->addHelpButton('audience', 'audience', 'block_community');
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_EDULEVEL_PRIMARY] = get_string('edulevelprimary', 'hub');
         $options[HUB_EDULEVEL_SECONDARY] = get_string('edulevelsecondary', 'hub');
         $options[HUB_EDULEVEL_TERTIARY] = get_string('eduleveltertiary', 'hub');
         $options[HUB_EDULEVEL_GOVERNMENT] = get_string('edulevelgovernment', 'hub');
         $options[HUB_EDULEVEL_ASSOCIATION] = get_string('edulevelassociation', 'hub');
         $options[HUB_EDULEVEL_CORPORATE] = get_string('edulevelcorporate', 'hub');
         $options[HUB_EDULEVEL_OTHER] = get_string('edulevelother', 'hub');
         $mform->addElement('select', 'educationallevel', get_string('educationallevel', 'block_community'), $options);
         $mform->setDefault('educationallevel', $educationallevel);
         unset($options);
         $mform->addHelpButton('educationallevel', 'educationallevel', 'block_community');
         $publicationmanager = new course_publish_manager();
         $options = $publicationmanager->get_sorted_subjects();
         $mform->addElement('searchableselector', 'subject', get_string('subject', 'block_community'), $options, array('id' => 'communitysubject'));
         $mform->setDefault('subject', $subject);
         unset($options);
         $mform->addHelpButton('subject', 'subject', 'block_community');
         require_once $CFG->libdir . "/licenselib.php";
         $licensemanager = new license_manager();
         $licences = $licensemanager->get_licenses();
         $options = array();
         $options['all'] = get_string('any');
         foreach ($licences as $license) {
             $options[$license->shortname] = get_string($license->shortname, 'license');
         }
         $mform->addElement('select', 'licence', get_string('licence', 'block_community'), $options);
         unset($options);
         $mform->addHelpButton('licence', 'licence', 'block_community');
         $mform->setDefault('licence', $licence);
         $languages = get_string_manager()->get_list_of_languages();
         core_collator::asort($languages);
         $languages = array_merge(array('all' => get_string('any')), $languages);
         $mform->addElement('select', 'language', get_string('language'), $languages);
         $mform->setDefault('language', $language);
         $mform->addHelpButton('language', 'language', 'block_community');
         $mform->addElement('select', 'orderby', get_string('orderby', 'block_community'), array('newest' => get_string('orderbynewest', 'block_community'), 'eldest' => get_string('orderbyeldest', 'block_community'), 'fullname' => get_string('orderbyname', 'block_community'), 'publisher' => get_string('orderbypublisher', 'block_community'), 'ratingaverage' => get_string('orderbyratingaverage', 'block_community')));
         $mform->setDefault('orderby', $orderby);
         $mform->addHelpButton('orderby', 'orderby', 'block_community');
         $mform->setType('orderby', PARAM_ALPHA);
         $mform->setAdvanced('audience');
         $mform->setAdvanced('educationallevel');
         $mform->setAdvanced('subject');
         $mform->setAdvanced('licence');
         $mform->setAdvanced('language');
         $mform->setAdvanced('orderby');
         $mform->addElement('text', 'search', get_string('keywords', 'block_community'), array('size' => 30));
         $mform->addHelpButton('search', 'keywords', 'block_community');
         $mform->setType('search', PARAM_NOTAGS);
         $mform->addElement('submit', 'submitbutton', get_string('search', 'block_community'));
     }
 }
 * a specific hub
 */
require '../../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/forms.php';
require_once $CFG->dirroot . '/course/publish/lib.php';
require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
admin_externalpage_setup('registrationindex');
$renderer = $PAGE->get_renderer('core', 'register');
$unregistration = optional_param('unregistration', 0, PARAM_INT);
$cleanregdata = optional_param('cleanregdata', 0, PARAM_BOOL);
$confirm = optional_param('confirm', 0, PARAM_INT);
$huburl = optional_param('huburl', '', PARAM_URL);
$cancel = optional_param('cancel', null, PARAM_ALPHA);
$registrationmanager = new registration_manager();
$publicationmanager = new course_publish_manager();
$errormessage = '';
if (empty($cancel) and $unregistration and $confirm and confirm_sesskey()) {
    $hub = $registrationmanager->get_registeredhub($huburl);
    //unpublish course and unregister the site by web service
    if (!$cleanregdata) {
        //check if we need to unpublish courses
        //enrollable courses
        $unpublishalladvertisedcourses = optional_param('unpublishalladvertisedcourses', 0, PARAM_INT);
        $hubcourseids = array();
        if ($unpublishalladvertisedcourses) {
            $enrollablecourses = $publicationmanager->get_publications($huburl, null, 1);
            if (!empty($enrollablecourses)) {
                foreach ($enrollablecourses as $enrollablecourse) {
                    $hubcourseids[] = $enrollablecourse->hubcourseid;
예제 #10
0
파일: forms.php 프로젝트: vuchannguyen/web
 public function definition()
 {
     global $CFG, $DB, $USER, $OUTPUT;
     $strrequired = get_string('required');
     $mform =& $this->_form;
     $huburl = $this->_customdata['huburl'];
     $hubname = $this->_customdata['hubname'];
     $course = $this->_customdata['course'];
     $advertise = $this->_customdata['advertise'];
     $share = $this->_customdata['share'];
     $page = $this->_customdata['page'];
     $site = get_site();
     //hidden parameters
     $mform->addElement('hidden', 'huburl', $huburl);
     $mform->addElement('hidden', 'hubname', $hubname);
     //check on the hub if the course has already been published
     $registrationmanager = new registration_manager();
     $registeredhub = $registrationmanager->get_registeredhub($huburl);
     $publicationmanager = new course_publish_manager();
     $publications = $publicationmanager->get_publications($registeredhub->huburl, $course->id, $advertise);
     if (!empty($publications)) {
         //get the last publication of this course
         $publication = array_pop($publications);
         $function = 'hub_get_courses';
         $options = new stdClass();
         $options->ids = array($publication->hubcourseid);
         $options->allsitecourses = 1;
         $params = array('search' => '', 'downloadable' => $share, 'enrollable' => !$share, 'options' => $options);
         $serverurl = $huburl . "/local/hub/webservice/webservices.php";
         require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
         $xmlrpcclient = new webservice_xmlrpc_client($serverurl, $registeredhub->token);
         try {
             $result = $xmlrpcclient->call($function, $params);
             $publishedcourses = $result['courses'];
         } catch (Exception $e) {
             $error = $OUTPUT->notification(get_string('errorcourseinfo', 'hub', $e->getMessage()));
             $mform->addElement('static', 'errorhub', '', $error);
         }
     }
     if (!empty($publishedcourses)) {
         $publishedcourse = $publishedcourses[0];
         $hubcourseid = $publishedcourse['id'];
         $defaultfullname = $publishedcourse['fullname'];
         $defaultshortname = $publishedcourse['shortname'];
         $defaultsummary = $publishedcourse['description'];
         $defaultlanguage = $publishedcourse['language'];
         $defaultpublishername = $publishedcourse['publishername'];
         $defaultpublisheremail = $publishedcourse['publisheremail'];
         $defaultcontributornames = $publishedcourse['contributornames'];
         $defaultcoverage = $publishedcourse['coverage'];
         $defaultcreatorname = $publishedcourse['creatorname'];
         $defaultlicenceshortname = $publishedcourse['licenceshortname'];
         $defaultsubject = $publishedcourse['subject'];
         $defaultaudience = $publishedcourse['audience'];
         $defaulteducationallevel = $publishedcourse['educationallevel'];
         $defaultcreatornotes = $publishedcourse['creatornotes'];
         $defaultcreatornotesformat = $publishedcourse['creatornotesformat'];
         $screenshotsnumber = $publishedcourse['screenshots'];
         $privacy = $publishedcourse['privacy'];
         if ($screenshotsnumber > 0 and !empty($privacy)) {
             $page->requires->yui_module('moodle-block_community-imagegallery', 'M.blocks_community.init_imagegallery', array(array('imageids' => array($hubcourseid), 'imagenumbers' => array($screenshotsnumber), 'huburl' => $huburl)));
         }
     } else {
         $defaultfullname = $course->fullname;
         $defaultshortname = $course->shortname;
         $defaultsummary = clean_param($course->summary, PARAM_TEXT);
         if (empty($course->lang)) {
             $language = get_site()->lang;
             if (empty($language)) {
                 $defaultlanguage = current_language();
             } else {
                 $defaultlanguage = $language;
             }
         } else {
             $defaultlanguage = $course->lang;
         }
         $defaultpublishername = $USER->firstname . ' ' . $USER->lastname;
         $defaultpublisheremail = $USER->email;
         $defaultcontributornames = '';
         $defaultcoverage = '';
         $defaultcreatorname = $USER->firstname . ' ' . $USER->lastname;
         $defaultlicenceshortname = 'cc';
         $defaultsubject = 'none';
         $defaultaudience = HUB_AUDIENCE_STUDENTS;
         $defaulteducationallevel = HUB_EDULEVEL_TERTIARY;
         $defaultcreatornotes = '';
         $defaultcreatornotesformat = FORMAT_HTML;
         $screenshotsnumber = 0;
     }
     //the input parameters
     $mform->addElement('header', 'moodle', get_string('publicationinfo', 'hub'));
     $mform->addElement('text', 'name', get_string('coursename', 'hub'), array('class' => 'metadatatext'));
     $mform->addRule('name', $strrequired, 'required', null, 'client');
     $mform->setType('name', PARAM_TEXT);
     $mform->setDefault('name', $defaultfullname);
     $mform->addHelpButton('name', 'name', 'hub');
     $mform->addElement('hidden', 'id', $this->_customdata['id']);
     if ($share) {
         $buttonlabel = get_string('shareon', 'hub', !empty($hubname) ? $hubname : $huburl);
         $mform->addElement('hidden', 'share', $share);
         $mform->addElement('text', 'demourl', get_string('demourl', 'hub'), array('class' => 'metadatatext'));
         $mform->setType('demourl', PARAM_URL);
         $mform->setDefault('demourl', new moodle_url("/course/view.php?id=" . $course->id));
         $mform->addHelpButton('demourl', 'demourl', 'hub');
     }
     if ($advertise) {
         if (empty($publishedcourses)) {
             $buttonlabel = get_string('advertiseon', 'hub', !empty($hubname) ? $hubname : $huburl);
         } else {
             $buttonlabel = get_string('readvertiseon', 'hub', !empty($hubname) ? $hubname : $huburl);
         }
         $mform->addElement('hidden', 'advertise', $advertise);
         $mform->addElement('hidden', 'courseurl', $CFG->wwwroot . "/course/view.php?id=" . $course->id);
         $mform->addElement('static', 'courseurlstring', get_string('courseurl', 'hub'));
         $mform->setDefault('courseurlstring', new moodle_url("/course/view.php?id=" . $course->id));
         $mform->addHelpButton('courseurlstring', 'courseurl', 'hub');
     }
     $mform->addElement('text', 'courseshortname', get_string('courseshortname', 'hub'), array('class' => 'metadatatext'));
     $mform->setDefault('courseshortname', $defaultshortname);
     $mform->addHelpButton('courseshortname', 'courseshortname', 'hub');
     $mform->addElement('textarea', 'description', get_string('description'), array('rows' => 10, 'cols' => 57));
     $mform->addRule('description', $strrequired, 'required', null, 'client');
     $mform->setDefault('description', $defaultsummary);
     $mform->setType('description', PARAM_TEXT);
     $mform->addHelpButton('description', 'description', 'hub');
     $languages = get_string_manager()->get_list_of_languages();
     textlib_get_instance()->asort($languages);
     $mform->addElement('select', 'language', get_string('language'), $languages);
     $mform->setDefault('language', $defaultlanguage);
     $mform->addHelpButton('language', 'language', 'hub');
     $mform->addElement('text', 'publishername', get_string('publishername', 'hub'), array('class' => 'metadatatext'));
     $mform->setDefault('publishername', $defaultpublishername);
     $mform->addRule('publishername', $strrequired, 'required', null, 'client');
     $mform->addHelpButton('publishername', 'publishername', 'hub');
     $mform->addElement('text', 'publisheremail', get_string('publisheremail', 'hub'), array('class' => 'metadatatext'));
     $mform->setDefault('publisheremail', $defaultpublisheremail);
     $mform->addRule('publisheremail', $strrequired, 'required', null, 'client');
     $mform->addHelpButton('publisheremail', 'publisheremail', 'hub');
     $mform->addElement('text', 'creatorname', get_string('creatorname', 'hub'), array('class' => 'metadatatext'));
     $mform->addRule('creatorname', $strrequired, 'required', null, 'client');
     $mform->setType('creatorname', PARAM_TEXT);
     $mform->setDefault('creatorname', $defaultcreatorname);
     $mform->addHelpButton('creatorname', 'creatorname', 'hub');
     $mform->addElement('text', 'contributornames', get_string('contributornames', 'hub'), array('class' => 'metadatatext'));
     $mform->setDefault('contributornames', $defaultcontributornames);
     $mform->addHelpButton('contributornames', 'contributornames', 'hub');
     $mform->addElement('text', 'coverage', get_string('tags', 'hub'), array('class' => 'metadatatext'));
     $mform->setType('coverage', PARAM_TEXT);
     $mform->setDefault('coverage', $defaultcoverage);
     $mform->addHelpButton('coverage', 'tags', 'hub');
     require_once $CFG->libdir . "/licenselib.php";
     $licensemanager = new license_manager();
     $licences = $licensemanager->get_licenses();
     $options = array();
     foreach ($licences as $license) {
         $options[$license->shortname] = get_string($license->shortname, 'license');
     }
     $mform->addElement('select', 'licence', get_string('license'), $options);
     $mform->setDefault('licence', $defaultlicenceshortname);
     unset($options);
     $mform->addHelpButton('licence', 'licence', 'hub');
     $options = $publicationmanager->get_sorted_subjects();
     //prepare data for the smartselect
     foreach ($options as $key => &$option) {
         $keylength = strlen($key);
         if ($keylength == 10) {
             $option = "&nbsp;&nbsp;" . $option;
         } else {
             if ($keylength == 12) {
                 $option = "&nbsp;&nbsp;&nbsp;&nbsp;" . $option;
             }
         }
     }
     $options = array('none' => get_string('none', 'hub')) + $options;
     $mform->addElement('select', 'subject', get_string('subject', 'hub'), $options);
     unset($options);
     $mform->addHelpButton('subject', 'subject', 'hub');
     $mform->setDefault('subject', $defaultsubject);
     $mform->addRule('subject', $strrequired, 'required', null, 'client');
     $this->init_javascript_enhancement('subject', 'smartselect', array('selectablecategories' => false, 'mode' => 'compact'));
     $options = array();
     $options[HUB_AUDIENCE_EDUCATORS] = get_string('audienceeducators', 'hub');
     $options[HUB_AUDIENCE_STUDENTS] = get_string('audiencestudents', 'hub');
     $options[HUB_AUDIENCE_ADMINS] = get_string('audienceadmins', 'hub');
     $mform->addElement('select', 'audience', get_string('audience', 'hub'), $options);
     $mform->setDefault('audience', $defaultaudience);
     unset($options);
     $mform->addHelpButton('audience', 'audience', 'hub');
     $options = array();
     $options[HUB_EDULEVEL_PRIMARY] = get_string('edulevelprimary', 'hub');
     $options[HUB_EDULEVEL_SECONDARY] = get_string('edulevelsecondary', 'hub');
     $options[HUB_EDULEVEL_TERTIARY] = get_string('eduleveltertiary', 'hub');
     $options[HUB_EDULEVEL_GOVERNMENT] = get_string('edulevelgovernment', 'hub');
     $options[HUB_EDULEVEL_ASSOCIATION] = get_string('edulevelassociation', 'hub');
     $options[HUB_EDULEVEL_CORPORATE] = get_string('edulevelcorporate', 'hub');
     $options[HUB_EDULEVEL_OTHER] = get_string('edulevelother', 'hub');
     $mform->addElement('select', 'educationallevel', get_string('educationallevel', 'hub'), $options);
     $mform->setDefault('educationallevel', $defaulteducationallevel);
     unset($options);
     $mform->addHelpButton('educationallevel', 'educationallevel', 'hub');
     $editoroptions = array('maxfiles' => 0, 'maxbytes' => 0, 'trusttext' => false, 'forcehttps' => false);
     $mform->addElement('editor', 'creatornotes', get_string('creatornotes', 'hub'), '', $editoroptions);
     $mform->addRule('creatornotes', $strrequired, 'required', null, 'client');
     $mform->setType('creatornotes', PARAM_CLEANHTML);
     $mform->addHelpButton('creatornotes', 'creatornotes', 'hub');
     if ($advertise) {
         if (!empty($screenshotsnumber)) {
             if (!empty($privacy)) {
                 $baseurl = new moodle_url($huburl . '/local/hub/webservice/download.php', array('courseid' => $hubcourseid, 'filetype' => HUB_SCREENSHOT_FILE_TYPE));
                 $screenshothtml = html_writer::empty_tag('img', array('src' => $baseurl, 'alt' => $defaultfullname));
                 $screenshothtml = html_writer::tag('div', $screenshothtml, array('class' => 'coursescreenshot', 'id' => 'image-' . $hubcourseid));
             } else {
                 $screenshothtml = get_string('existingscreenshotnumber', 'hub', $screenshotsnumber);
             }
             $mform->addElement('static', 'existingscreenshots', get_string('existingscreenshots', 'hub'), $screenshothtml);
             $mform->addHelpButton('existingscreenshots', 'deletescreenshots', 'hub');
             $mform->addElement('checkbox', 'deletescreenshots', '', ' ' . get_string('deletescreenshots', 'hub'));
         }
         $mform->addElement('hidden', 'existingscreenshotnumber', $screenshotsnumber);
     }
     $mform->addElement('filemanager', 'screenshots', get_string('addscreenshots', 'hub'), null, array('subdirs' => 0, 'maxbytes' => 1000000, 'maxfiles' => 3));
     $mform->addHelpButton('screenshots', 'screenshots', 'hub');
     $this->add_action_buttons(false, $buttonlabel);
     //set default value for creatornotes editor
     $data = new stdClass();
     $data->creatornotes = array();
     $data->creatornotes['text'] = $defaultcreatornotes;
     $data->creatornotes['format'] = $defaultcreatornotesformat;
     $this->set_data($data);
 }
예제 #11
0
 public function definition()
 {
     global $CFG, $DB;
     $strrequired = get_string('required');
     $mform =& $this->_form;
     $huburl = $this->_customdata['huburl'];
     $hubname = $this->_customdata['hubname'];
     $password = $this->_customdata['password'];
     $admin = get_admin();
     $site = get_site();
     //retrieve config for this hub and set default if they don't exist
     $cleanhuburl = clean_param($huburl, PARAM_ALPHANUMEXT);
     $sitename = get_config('hub', 'site_name_' . $cleanhuburl);
     if ($sitename === false) {
         $sitename = format_string($site->fullname, true, array('context' => context_course::instance(SITEID)));
     }
     $sitedescription = get_config('hub', 'site_description_' . $cleanhuburl);
     if ($sitedescription === false) {
         $sitedescription = $site->summary;
     }
     $contactname = get_config('hub', 'site_contactname_' . $cleanhuburl);
     if ($contactname === false) {
         $contactname = fullname($admin, true);
     }
     $contactemail = get_config('hub', 'site_contactemail_' . $cleanhuburl);
     if ($contactemail === false) {
         $contactemail = $admin->email;
     }
     $contactphone = get_config('hub', 'site_contactphone_' . $cleanhuburl);
     if ($contactphone === false) {
         $contactphone = $admin->phone1;
     }
     $imageurl = get_config('hub', 'site_imageurl_' . $cleanhuburl);
     $privacy = get_config('hub', 'site_privacy_' . $cleanhuburl);
     $address = get_config('hub', 'site_address_' . $cleanhuburl);
     $region = get_config('hub', 'site_region_' . $cleanhuburl);
     $country = get_config('hub', 'site_country_' . $cleanhuburl);
     if ($country === false) {
         $country = $admin->country;
     }
     $language = get_config('hub', 'site_language_' . $cleanhuburl);
     if ($language === false) {
         $language = current_language();
     }
     $geolocation = get_config('hub', 'site_geolocation_' . $cleanhuburl);
     $contactable = get_config('hub', 'site_contactable_' . $cleanhuburl);
     $emailalert = get_config('hub', 'site_emailalert_' . $cleanhuburl);
     $emailalert = $emailalert === 0 ? 0 : 1;
     $coursesnumber = get_config('hub', 'site_coursesnumber_' . $cleanhuburl);
     $usersnumber = get_config('hub', 'site_usersnumber_' . $cleanhuburl);
     $roleassignmentsnumber = get_config('hub', 'site_roleassignmentsnumber_' . $cleanhuburl);
     $postsnumber = get_config('hub', 'site_postsnumber_' . $cleanhuburl);
     $questionsnumber = get_config('hub', 'site_questionsnumber_' . $cleanhuburl);
     $resourcesnumber = get_config('hub', 'site_resourcesnumber_' . $cleanhuburl);
     $badgesnumber = get_config('hub', 'site_badges_' . $cleanhuburl);
     $issuedbadgesnumber = get_config('hub', 'site_issuedbadges_' . $cleanhuburl);
     $mediancoursesize = get_config('hub', 'site_mediancoursesize_' . $cleanhuburl);
     $participantnumberaveragecfg = get_config('hub', 'site_participantnumberaverage_' . $cleanhuburl);
     $modulenumberaveragecfg = get_config('hub', 'site_modulenumberaverage_' . $cleanhuburl);
     //hidden parameters
     $mform->addElement('hidden', 'huburl', $huburl);
     $mform->setType('huburl', PARAM_URL);
     $mform->addElement('hidden', 'hubname', $hubname);
     $mform->setType('hubname', PARAM_TEXT);
     $mform->addElement('hidden', 'password', $password);
     $mform->setType('password', PARAM_RAW);
     //the input parameters
     $mform->addElement('header', 'moodle', get_string('registrationinfo', 'hub'));
     $mform->addElement('text', 'name', get_string('sitename', 'hub'), array('class' => 'registration_textfield'));
     $mform->addRule('name', $strrequired, 'required', null, 'client');
     $mform->setType('name', PARAM_TEXT);
     $mform->setDefault('name', $sitename);
     $mform->addHelpButton('name', 'sitename', 'hub');
     $options = array();
     $registrationmanager = new registration_manager();
     $options[HUB_SITENOTPUBLISHED] = $registrationmanager->get_site_privacy_string(HUB_SITENOTPUBLISHED);
     $options[HUB_SITENAMEPUBLISHED] = $registrationmanager->get_site_privacy_string(HUB_SITENAMEPUBLISHED);
     $options[HUB_SITELINKPUBLISHED] = $registrationmanager->get_site_privacy_string(HUB_SITELINKPUBLISHED);
     $mform->addElement('select', 'privacy', get_string('siteprivacy', 'hub'), $options);
     $mform->setDefault('privacy', $privacy);
     $mform->setType('privacy', PARAM_ALPHA);
     $mform->addHelpButton('privacy', 'privacy', 'hub');
     unset($options);
     $mform->addElement('textarea', 'description', get_string('sitedesc', 'hub'), array('rows' => 8, 'cols' => 41));
     $mform->addRule('description', $strrequired, 'required', null, 'client');
     $mform->setDefault('description', $sitedescription);
     $mform->setType('description', PARAM_TEXT);
     $mform->addHelpButton('description', 'sitedesc', 'hub');
     $languages = get_string_manager()->get_list_of_languages();
     collatorlib::asort($languages);
     $mform->addElement('select', 'language', get_string('sitelang', 'hub'), $languages);
     $mform->setType('language', PARAM_ALPHANUMEXT);
     $mform->addHelpButton('language', 'sitelang', 'hub');
     $mform->setDefault('language', $language);
     $mform->addElement('textarea', 'address', get_string('postaladdress', 'hub'), array('rows' => 4, 'cols' => 41));
     $mform->setType('address', PARAM_TEXT);
     $mform->setDefault('address', $address);
     $mform->addHelpButton('address', 'postaladdress', 'hub');
     //TODO: use the region array I generated
     //        $mform->addElement('select', 'region', get_string('selectaregion'), array('-' => '-'));
     //        $mform->setDefault('region', $region);
     $mform->addElement('hidden', 'regioncode', '-');
     $mform->setType('regioncode', PARAM_ALPHANUMEXT);
     $countries = get_string_manager()->get_list_of_countries();
     $mform->addElement('select', 'countrycode', get_string('sitecountry', 'hub'), $countries);
     $mform->setDefault('countrycode', $country);
     $mform->setType('countrycode', PARAM_ALPHANUMEXT);
     $mform->addHelpButton('countrycode', 'sitecountry', 'hub');
     $mform->addElement('text', 'geolocation', get_string('sitegeolocation', 'hub'), array('class' => 'registration_textfield'));
     $mform->setDefault('geolocation', $geolocation);
     $mform->setType('geolocation', PARAM_RAW);
     $mform->addHelpButton('geolocation', 'sitegeolocation', 'hub');
     $mform->addElement('text', 'contactname', get_string('siteadmin', 'hub'), array('class' => 'registration_textfield'));
     $mform->addRule('contactname', $strrequired, 'required', null, 'client');
     $mform->setType('contactname', PARAM_TEXT);
     $mform->setDefault('contactname', $contactname);
     $mform->addHelpButton('contactname', 'siteadmin', 'hub');
     $mform->addElement('text', 'contactphone', get_string('sitephone', 'hub'), array('class' => 'registration_textfield'));
     $mform->setType('contactphone', PARAM_TEXT);
     $mform->addHelpButton('contactphone', 'sitephone', 'hub');
     $mform->addElement('text', 'contactemail', get_string('siteemail', 'hub'), array('class' => 'registration_textfield'));
     $mform->addRule('contactemail', $strrequired, 'required', null, 'client');
     $mform->setType('contactemail', PARAM_EMAIL);
     $mform->setDefault('contactemail', $contactemail);
     $mform->addHelpButton('contactemail', 'siteemail', 'hub');
     $options = array();
     $options[0] = get_string("registrationcontactno");
     $options[1] = get_string("registrationcontactyes");
     $mform->addElement('select', 'contactable', get_string('siteregistrationcontact', 'hub'), $options);
     $mform->setDefault('contactable', $contactable);
     $mform->setType('contactable', PARAM_INT);
     $mform->addHelpButton('contactable', 'siteregistrationcontact', 'hub');
     unset($options);
     $options = array();
     $options[0] = get_string("registrationno");
     $options[1] = get_string("registrationyes");
     $mform->addElement('select', 'emailalert', get_string('siteregistrationemail', 'hub'), $options);
     $mform->setDefault('emailalert', $emailalert);
     $mform->setType('emailalert', PARAM_INT);
     $mform->addHelpButton('emailalert', 'siteregistrationemail', 'hub');
     unset($options);
     //TODO site logo
     $mform->addElement('hidden', 'imageurl', '');
     //TODO: temporary
     $mform->setType('imageurl', PARAM_URL);
     $mform->addElement('static', 'urlstring', get_string('siteurl', 'hub'), $CFG->wwwroot);
     $mform->addHelpButton('urlstring', 'siteurl', 'hub');
     $mform->addElement('static', 'versionstring', get_string('siteversion', 'hub'), $CFG->version);
     $mform->addElement('hidden', 'moodleversion', $CFG->version);
     $mform->setType('moodleversion', PARAM_INT);
     $mform->addHelpButton('versionstring', 'siteversion', 'hub');
     $mform->addElement('static', 'releasestring', get_string('siterelease', 'hub'), $CFG->release);
     $mform->addElement('hidden', 'moodlerelease', $CFG->release);
     $mform->setType('moodlerelease', PARAM_TEXT);
     $mform->addHelpButton('releasestring', 'siterelease', 'hub');
     /// Display statistic that are going to be retrieve by the hub
     $coursecount = $DB->count_records('course') - 1;
     $usercount = $DB->count_records('user', array('deleted' => 0));
     $roleassigncount = $DB->count_records('role_assignments');
     $postcount = $DB->count_records('forum_posts');
     $questioncount = $DB->count_records('question');
     $resourcecount = $DB->count_records('resource');
     require_once $CFG->dirroot . "/course/lib.php";
     $participantnumberaverage = number_format(average_number_of_participants(), 2);
     $modulenumberaverage = number_format(average_number_of_courses_modules(), 2);
     require_once $CFG->libdir . '/badgeslib.php';
     $badges = $DB->count_records_select('badge', 'status <> ' . BADGE_STATUS_ARCHIVED);
     $issuedbadges = $DB->count_records('badge_issued');
     if (HUB_MOODLEORGHUBURL != $huburl) {
         $mform->addElement('checkbox', 'courses', get_string('sendfollowinginfo', 'hub'), " " . get_string('coursesnumber', 'hub', $coursecount));
         $mform->setDefault('courses', $coursesnumber != -1);
         $mform->setType('courses', PARAM_INT);
         $mform->addHelpButton('courses', 'sendfollowinginfo', 'hub');
         $mform->addElement('checkbox', 'users', '', " " . get_string('usersnumber', 'hub', $usercount));
         $mform->setDefault('users', $usersnumber != -1);
         $mform->setType('users', PARAM_INT);
         $mform->addElement('checkbox', 'roleassignments', '', " " . get_string('roleassignmentsnumber', 'hub', $roleassigncount));
         $mform->setDefault('roleassignments', $roleassignmentsnumber != -1);
         $mform->setType('roleassignments', PARAM_INT);
         $mform->addElement('checkbox', 'posts', '', " " . get_string('postsnumber', 'hub', $postcount));
         $mform->setDefault('posts', $postsnumber != -1);
         $mform->setType('posts', PARAM_INT);
         $mform->addElement('checkbox', 'questions', '', " " . get_string('questionsnumber', 'hub', $questioncount));
         $mform->setDefault('questions', $questionsnumber != -1);
         $mform->setType('questions', PARAM_INT);
         $mform->addElement('checkbox', 'resources', '', " " . get_string('resourcesnumber', 'hub', $resourcecount));
         $mform->setDefault('resources', $resourcesnumber != -1);
         $mform->setType('resources', PARAM_INT);
         $mform->addElement('checkbox', 'badges', '', " " . get_string('badgesnumber', 'hub', $badges));
         $mform->setDefault('badges', $badgesnumber != -1);
         $mform->setType('resources', PARAM_INT);
         $mform->addElement('checkbox', 'issuedbadges', '', " " . get_string('issuedbadgesnumber', 'hub', $issuedbadges));
         $mform->setDefault('issuedbadges', $issuedbadgesnumber != -1);
         $mform->setType('resources', PARAM_INT);
         $mform->addElement('checkbox', 'participantnumberaverage', '', " " . get_string('participantnumberaverage', 'hub', $participantnumberaverage));
         $mform->setDefault('participantnumberaverage', $participantnumberaveragecfg != -1);
         $mform->setType('participantnumberaverage', PARAM_FLOAT);
         $mform->addElement('checkbox', 'modulenumberaverage', '', " " . get_string('modulenumberaverage', 'hub', $modulenumberaverage));
         $mform->setDefault('modulenumberaverage', $modulenumberaveragecfg != -1);
         $mform->setType('modulenumberaverage', PARAM_FLOAT);
     } else {
         $mform->addElement('static', 'courseslabel', get_string('sendfollowinginfo', 'hub'), " " . get_string('coursesnumber', 'hub', $coursecount));
         $mform->addElement('hidden', 'courses', 1);
         $mform->setType('courses', PARAM_INT);
         $mform->addHelpButton('courseslabel', 'sendfollowinginfo', 'hub');
         $mform->addElement('static', 'userslabel', '', " " . get_string('usersnumber', 'hub', $usercount));
         $mform->addElement('hidden', 'users', 1);
         $mform->setType('users', PARAM_INT);
         $mform->addElement('static', 'roleassignmentslabel', '', " " . get_string('roleassignmentsnumber', 'hub', $roleassigncount));
         $mform->addElement('hidden', 'roleassignments', 1);
         $mform->setType('roleassignments', PARAM_INT);
         $mform->addElement('static', 'postslabel', '', " " . get_string('postsnumber', 'hub', $postcount));
         $mform->addElement('hidden', 'posts', 1);
         $mform->setType('posts', PARAM_INT);
         $mform->addElement('static', 'questionslabel', '', " " . get_string('questionsnumber', 'hub', $questioncount));
         $mform->addElement('hidden', 'questions', 1);
         $mform->setType('questions', PARAM_INT);
         $mform->addElement('static', 'resourceslabel', '', " " . get_string('resourcesnumber', 'hub', $resourcecount));
         $mform->addElement('hidden', 'resources', 1);
         $mform->setType('resources', PARAM_INT);
         $mform->addElement('static', 'badgeslabel', '', " " . get_string('badgesnumber', 'hub', $badges));
         $mform->addElement('hidden', 'badges', 1);
         $mform->setType('badges', PARAM_INT);
         $mform->addElement('static', 'issuedbadgeslabel', '', " " . get_string('issuedbadgesnumber', 'hub', $issuedbadges));
         $mform->addElement('hidden', 'issuedbadges', true);
         $mform->setType('issuedbadges', PARAM_INT);
         $mform->addElement('static', 'participantnumberaveragelabel', '', " " . get_string('participantnumberaverage', 'hub', $participantnumberaverage));
         $mform->addElement('hidden', 'participantnumberaverage', 1);
         $mform->setType('participantnumberaverage', PARAM_FLOAT);
         $mform->addElement('static', 'modulenumberaveragelabel', '', " " . get_string('modulenumberaverage', 'hub', $modulenumberaverage));
         $mform->addElement('hidden', 'modulenumberaverage', 1);
         $mform->setType('modulenumberaverage', PARAM_FLOAT);
     }
     //check if it's a first registration or update
     $hubregistered = $registrationmanager->get_registeredhub($huburl);
     if (!empty($hubregistered)) {
         $buttonlabel = get_string('updatesite', 'hub', !empty($hubname) ? $hubname : $huburl);
         $mform->addElement('hidden', 'update', true);
         $mform->setType('update', PARAM_BOOL);
     } else {
         $buttonlabel = get_string('registersite', 'hub', !empty($hubname) ? $hubname : $huburl);
     }
     $this->add_action_buttons(false, $buttonlabel);
 }
 * @author     Jerome Mouneyrac <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 1999 onwards Martin Dougiamas  http://dougiamas.com
 *
 * The administrator is redirect to this page from the hub to renew a registration
 * process because
 */
require '../../config.php';
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
$url = optional_param('url', '', PARAM_URL);
$hubname = optional_param('hubname', '', PARAM_TEXT);
$token = optional_param('token', '', PARAM_TEXT);
admin_externalpage_setup('registrationindex');
//check that we are waiting a confirmation from this hub, and check that the token is correct
$registrationmanager = new registration_manager();
$registeredhub = $registrationmanager->get_unconfirmedhub($url);
if (!empty($registeredhub) and $registeredhub->token == $token) {
    echo $OUTPUT->header();
    echo $OUTPUT->heading(get_string('renewregistration', 'hub'), 3, 'main');
    $hublink = html_writer::tag('a', $hubname, array('href' => $url));
    $registrationmanager->delete_registeredhub($url);
    //Mooch case, need to recreate the siteidentifier
    if ($url == HUB_MOODLEORGHUBURL) {
        $CFG->siteidentifier = null;
        get_site_identifier();
    }
    $deletedregmsg = get_string('previousregistrationdeleted', 'hub', $hublink);
    $button = new single_button(new moodle_url('/admin/registration/index.php'), get_string('restartregistration', 'hub'));
    $button->class = 'restartregbutton';
    echo html_writer::tag('div', $deletedregmsg . $OUTPUT->render($button), array('class' => 'mdl-align'));
예제 #13
0
require_sesskey();
require_capability('moodle/site:config', context_system::instance());
$strheading = get_string('requestaccesskey', 'message_airnotifier');
$PAGE->navbar->add(get_string('administrationsite'));
$PAGE->navbar->add(get_string('plugins', 'admin'));
$PAGE->navbar->add(get_string('messageoutputs', 'message'));
$returl = new moodle_url('/admin/settings.php', array('section' => 'messagesettingairnotifier'));
$PAGE->navbar->add(get_string('pluginname', 'message_airnotifier'), $returl);
$PAGE->navbar->add($strheading);
$PAGE->set_heading($strheading);
$PAGE->set_title($strheading);
$msg = "";
// If we are requesting a key to the official message system, verify first that this site is registered.
// This check is also done in Airnotifier.
if (strpos($CFG->airnotifierurl, AIRNOTIFIER_PUBLICURL) !== false) {
    $registrationmanager = new registration_manager();
    if (!$registrationmanager->get_registeredhub(HUB_MOODLEORGHUBURL)) {
        $msg = get_string('sitemustberegistered', 'message_airnotifier');
        $msg .= $OUTPUT->continue_button($returl);
        echo $OUTPUT->header();
        echo $OUTPUT->box($msg, 'generalbox');
        echo $OUTPUT->footer();
        die;
    }
}
$manager = new message_airnotifier_manager();
if ($key = $manager->request_accesskey()) {
    set_config('airnotifieraccesskey', $key);
    $msg = get_string('keyretrievedsuccessfully', 'message_airnotifier');
} else {
    $msg = get_string('errorretrievingkey', 'message_airnotifier');
예제 #14
0
 public function definition()
 {
     global $CFG, $USER, $OUTPUT;
     $strrequired = get_string('required');
     $mform =& $this->_form;
     //set default value
     $search = $this->_customdata['search'];
     if (isset($this->_customdata['coverage'])) {
         $coverage = $this->_customdata['coverage'];
     } else {
         $coverage = 'all';
     }
     if (isset($this->_customdata['licence'])) {
         $licence = $this->_customdata['licence'];
     } else {
         $licence = 'all';
     }
     if (isset($this->_customdata['subject'])) {
         $subject = $this->_customdata['subject'];
     } else {
         $subject = 'all';
     }
     if (isset($this->_customdata['audience'])) {
         $audience = $this->_customdata['audience'];
     } else {
         $audience = 'all';
     }
     if (isset($this->_customdata['language'])) {
         $language = $this->_customdata['language'];
     } else {
         $language = current_language();
     }
     if (isset($this->_customdata['educationallevel'])) {
         $educationallevel = $this->_customdata['educationallevel'];
     } else {
         $educationallevel = 'all';
     }
     if (isset($this->_customdata['downloadable'])) {
         $downloadable = $this->_customdata['downloadable'];
     } else {
         $downloadable = 0;
     }
     if (isset($this->_customdata['orderby'])) {
         $orderby = $this->_customdata['orderby'];
     } else {
         $orderby = 'newest';
     }
     if (isset($this->_customdata['huburl'])) {
         $huburl = $this->_customdata['huburl'];
     } else {
         $huburl = HUB_MOODLEORGHUBURL;
     }
     $mform->addElement('header', 'site', get_string('search', 'block_community'));
     //add the course id (of the context)
     $mform->addElement('hidden', 'courseid', $this->_customdata['courseid']);
     $mform->addElement('hidden', 'executesearch', 1);
     //retrieve the hub list on the hub directory by web service
     $function = 'hubdirectory_get_hubs';
     $params = array();
     $serverurl = HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/webservices.php";
     require_once $CFG->dirroot . "/webservice/xmlrpc/lib.php";
     $xmlrpcclient = new webservice_xmlrpc_client($serverurl, 'publichubdirectory');
     try {
         $hubs = $xmlrpcclient->call($function, $params);
     } catch (Exception $e) {
         $hubs = array();
         $error = $OUTPUT->notification(get_string('errorhublisting', 'block_community', $e->getMessage()));
         $mform->addElement('static', 'errorhub', '', $error);
     }
     //display list of registered on hub
     $registrationmanager = new registration_manager();
     $registeredhubs = $registrationmanager->get_registered_on_hubs();
     //retrieve some additional hubs that we will add to
     //the hub list got from the hub directory
     $additionalhubs = array();
     foreach ($registeredhubs as $registeredhub) {
         $inthepubliclist = false;
         foreach ($hubs as $hub) {
             if ($hub['url'] == $registeredhub->huburl) {
                 $inthepubliclist = true;
                 $hub['registeredon'] = true;
             }
         }
         if (!$inthepubliclist) {
             $additionalhub = array();
             $additionalhub['name'] = $registeredhub->hubname;
             $additionalhub['url'] = $registeredhub->huburl;
             $additionalhubs[] = $additionalhub;
         }
     }
     if (!empty($additionalhubs)) {
         $hubs = array_merge($hubs, $additionalhubs);
     }
     if (!empty($hubs)) {
         //TODO: sort hubs by trusted/prioritize
         //Public hub list
         $options = array();
         $firsthub = false;
         foreach ($hubs as $hub) {
             if (array_key_exists('id', $hub)) {
                 $params = array('hubid' => $hub['id'], 'filetype' => HUB_HUBSCREENSHOT_FILE_TYPE);
                 $imgurl = new moodle_url(HUB_HUBDIRECTORYURL . "/local/hubdirectory/webservice/download.php", $params);
                 $ascreenshothtml = html_writer::empty_tag('img', array('src' => $imgurl, 'alt' => $hub['name']));
                 $hubdescription = html_writer::tag('a', $hub['name'], array('class' => 'hublink clearfix', 'href' => $hub['url'], 'onclick' => 'this.target="_blank"'));
                 $hubdescription .= html_writer::tag('span', $ascreenshothtml, array('class' => 'hubscreenshot'));
                 $hubdescriptiontext = html_writer::tag('span', format_text($hub['description'], FORMAT_PLAIN), array('class' => 'hubdescription'));
                 if (isset($hub['enrollablecourses'])) {
                     //check needed to avoid warnings for Moodle version < 2011081700
                     $additionaldesc = get_string('enrollablecourses', 'block_community') . ': ' . $hub['enrollablecourses'] . ' - ' . get_string('downloadablecourses', 'block_community') . ': ' . $hub['downloadablecourses'];
                     $hubdescriptiontext .= html_writer::tag('span', $additionaldesc, array('class' => 'hubadditionaldesc'));
                 }
                 if ($hub['trusted']) {
                     $hubtrusted = get_string('hubtrusted', 'block_community');
                     $hubdescriptiontext .= html_writer::tag('span', $hubtrusted . ' ' . $OUTPUT->doc_link('trusted_hubs'), array('class' => 'trusted'));
                 }
                 $hubdescriptiontext = html_writer::tag('span', $hubdescriptiontext, array('class' => 'hubdescriptiontext'));
                 $hubdescription = html_writer::tag('span', $hubdescription . $hubdescriptiontext, array('class' => $hub['trusted'] ? 'hubtrusted' : 'hubnottrusted'));
             } else {
                 $hubdescription = html_writer::tag('a', $hub['name'], array('class' => 'hublink hubtrusted', 'href' => $hub['url']));
             }
             if (empty($firsthub)) {
                 $mform->addElement('radio', 'huburl', get_string('selecthub', 'block_community'), $hubdescription, $hub['url']);
                 $mform->setDefault('huburl', $huburl);
                 $firsthub = true;
             } else {
                 $mform->addElement('radio', 'huburl', '', $hubdescription, $hub['url']);
             }
         }
         //display enrol/download select box if the USER has the download capability on the course
         if (has_capability('moodle/community:download', context_course::instance($this->_customdata['courseid']))) {
             $options = array(0 => get_string('enrollable', 'block_community'), 1 => get_string('downloadable', 'block_community'));
             $mform->addElement('select', 'downloadable', get_string('enroldownload', 'block_community'), $options);
             $mform->addHelpButton('downloadable', 'enroldownload', 'block_community');
         } else {
             $mform->addElement('hidden', 'downloadable', 0);
         }
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_AUDIENCE_EDUCATORS] = get_string('audienceeducators', 'hub');
         $options[HUB_AUDIENCE_STUDENTS] = get_string('audiencestudents', 'hub');
         $options[HUB_AUDIENCE_ADMINS] = get_string('audienceadmins', 'hub');
         $mform->addElement('select', 'audience', get_string('audience', 'block_community'), $options);
         $mform->setDefault('audience', $audience);
         unset($options);
         $mform->addHelpButton('audience', 'audience', 'block_community');
         $options = array();
         $options['all'] = get_string('any');
         $options[HUB_EDULEVEL_PRIMARY] = get_string('edulevelprimary', 'hub');
         $options[HUB_EDULEVEL_SECONDARY] = get_string('edulevelsecondary', 'hub');
         $options[HUB_EDULEVEL_TERTIARY] = get_string('eduleveltertiary', 'hub');
         $options[HUB_EDULEVEL_GOVERNMENT] = get_string('edulevelgovernment', 'hub');
         $options[HUB_EDULEVEL_ASSOCIATION] = get_string('edulevelassociation', 'hub');
         $options[HUB_EDULEVEL_CORPORATE] = get_string('edulevelcorporate', 'hub');
         $options[HUB_EDULEVEL_OTHER] = get_string('edulevelother', 'hub');
         $mform->addElement('select', 'educationallevel', get_string('educationallevel', 'block_community'), $options);
         $mform->setDefault('educationallevel', $educationallevel);
         unset($options);
         $mform->addHelpButton('educationallevel', 'educationallevel', 'block_community');
         $publicationmanager = new course_publish_manager();
         $options = $publicationmanager->get_sorted_subjects();
         foreach ($options as $key => &$option) {
             $keylength = strlen($key);
             if ($keylength == 10) {
                 $option = "&nbsp;&nbsp;" . $option;
             } else {
                 if ($keylength == 12) {
                     $option = "&nbsp;&nbsp;&nbsp;&nbsp;" . $option;
                 }
             }
         }
         $options = array_merge(array('all' => get_string('any')), $options);
         $mform->addElement('select', 'subject', get_string('subject', 'block_community'), $options, array('id' => 'communitysubject'));
         $mform->setDefault('subject', $subject);
         unset($options);
         $mform->addHelpButton('subject', 'subject', 'block_community');
         $this->init_javascript_enhancement('subject', 'smartselect', array('selectablecategories' => true, 'mode' => 'compact'));
         require_once $CFG->libdir . "/licenselib.php";
         $licensemanager = new license_manager();
         $licences = $licensemanager->get_licenses();
         $options = array();
         $options['all'] = get_string('any');
         foreach ($licences as $license) {
             $options[$license->shortname] = get_string($license->shortname, 'license');
         }
         $mform->addElement('select', 'licence', get_string('licence', 'block_community'), $options);
         unset($options);
         $mform->addHelpButton('licence', 'licence', 'block_community');
         $mform->setDefault('licence', $licence);
         $languages = get_string_manager()->get_list_of_languages();
         collatorlib::asort($languages);
         $languages = array_merge(array('all' => get_string('any')), $languages);
         $mform->addElement('select', 'language', get_string('language'), $languages);
         $mform->setDefault('language', $language);
         $mform->addHelpButton('language', 'language', 'block_community');
         $mform->addElement('radio', 'orderby', get_string('orderby', 'block_community'), get_string('orderbynewest', 'block_community'), 'newest');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyeldest', 'block_community'), 'eldest');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyname', 'block_community'), 'fullname');
         $mform->addElement('radio', 'orderby', null, get_string('orderbypublisher', 'block_community'), 'publisher');
         $mform->addElement('radio', 'orderby', null, get_string('orderbyratingaverage', 'block_community'), 'ratingaverage');
         $mform->setDefault('orderby', $orderby);
         $mform->setType('orderby', PARAM_ALPHA);
         $mform->addElement('text', 'search', get_string('keywords', 'block_community'));
         $mform->addHelpButton('search', 'keywords', 'block_community');
         $mform->addElement('submit', 'submitbutton', get_string('search', 'block_community'));
     }
 }
예제 #15
0
/**
 * Cron functions.
 *
 * @package    core
 * @subpackage admin
 * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        $CFG->debug = DEBUG_DEVELOPER;
        $CFG->debugdisplay = true;
    }
    set_time_limit(0);
    $starttime = microtime();
    /// increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    /// emulate normal session
    cron_setup_user();
    /// Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    /// Session gc
    mtrace("Cleaning up stale sessions");
    session_gc();
    /// Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    /// Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // we will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    /// Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace("Starting quiz reports");
    if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) {
        foreach ($reports as $report) {
            $cronfile = "{$CFG->dirroot}/mod/quiz/report/{$report->name}/cron.php";
            if (file_exists($cronfile)) {
                include_once $cronfile;
                $cron_function = 'quiz_report_' . $report->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing quiz report cron function {$cron_function} ...", '');
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field('quiz_report', "lastcron", $timenow, array("id" => $report->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    mtrace("done.");
                }
            }
        }
    }
    mtrace("Finished quiz reports");
    mtrace('Starting admin reports');
    // Admin reports do not have a database table that lists them. Instead a
    // report includes cron.php with function report_reportname_cron() if it wishes
    // to be cronned. It is up to cron.php to handle e.g. if it only needs to
    // actually do anything occasionally.
    $reports = get_plugin_list('report');
    foreach ($reports as $report => $reportdir) {
        $cronfile = $reportdir . '/cron.php';
        if (file_exists($cronfile)) {
            require_once $cronfile;
            $cronfunction = 'report_' . $report . '_cron';
            mtrace('Processing cron function for ' . $report . '...', '');
            $pre_dbqueries = null;
            $pre_dbqueries = $DB->perf_get_queries();
            $pre_time = microtime(true);
            $cronfunction();
            if (isset($pre_dbqueries)) {
                mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                mtrace("... used " . round(microtime(true) - $pre_time, 2) . " seconds");
            }
            mtrace('done.');
        }
    }
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job ...');
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        require_once $CFG->libdir . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    /// Run all core cron jobs, but not every time since they aren't too important.
    /// These don't have a timer to reduce load, so we'll use a random number
    /// to randomly choose the percentage of times we should run these jobs.
    srand((double) microtime() * 10000000);
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        /// Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT id, firstname, lastname\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                if ($DB->delete_records('user', array('id' => $user->id))) {
                    mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
                }
            }
            $rs->close();
        }
        flush();
        /// Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT id, username\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (delete_user($user)) {
                    mtrace("Deleted not fully setup user {$user->username} ({$user->id})");
                }
            }
            $rs->close();
        }
        flush();
        /// Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) {
                mtrace("Deleted old log records");
            }
        }
        flush();
        // Delete old backup_controllers and logs
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            // Delete child records from backup_logs
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace("Deleted old backup records");
        }
        flush();
        /// Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) {
                mtrace("Deleted old cache_text records");
            }
        }
        flush();
        if (!empty($CFG->notifyloginfailures)) {
            notify_login_failures();
            mtrace('Notified login failured');
        }
        flush();
        //
        // generate new password emails for users
        //
        mtrace('checking for create_password');
        if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
            mtrace('creating passwords for new users');
            $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,\n                                                     u.lastname, u.username,\n                                                     p.id as prefid\n                                                FROM {user} u\n                                                JOIN {user_preferences} p ON u.id=p.userid\n                                               WHERE p.name='create_password' AND p.value='1' AND u.email !='' ");
            foreach ($newusers as $newuserid => $newuser) {
                // email user
                if (setnew_password_and_mail($newuser)) {
                    // remove user pref
                    $DB->delete_records('user_preferences', array('id' => $newuser->prefid));
                } else {
                    trigger_error("Could not create and mail new user password!");
                }
            }
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace('Executed tag cron');
        }
        // Accesslib stuff
        cleanup_contexts();
        mtrace('Cleaned up contexts');
        gc_cache_flags();
        mtrace('Cleaned cache flags');
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: build_context_path(true);
        build_context_path();
        mtrace('Built context paths');
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace('Cleaned up read notifications');
        }
        mtrace("Finished clean-up tasks...");
    }
    // End of occasional clean-up tasks
    // Run automated backups if required.
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    /// Run the auth cron, if any
    /// before enrolments because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
        require_once $CFG->dirroot . '/lib/statslib.php';
        // check we're not before our runtime
        $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
        if (time() > $timetocheck) {
            // process configured number of days as max (defaulting to 31)
            $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
            if (stats_cron_daily($maxdays)) {
                if (stats_cron_weekly()) {
                    if (stats_cron_monthly()) {
                        stats_clean_old();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // run gradebook import/export/report cron
    if ($gradeimports = get_plugin_list('gradeimport')) {
        foreach ($gradeimports as $gradeimport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_import_' . $gradeimport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook import function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    if ($gradeexports = get_plugin_list('gradeexport')) {
        foreach ($gradeexports as $gradeexport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_export_' . $gradeexport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook export function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    if ($gradereports = get_plugin_list('gradereport')) {
        foreach ($gradereports as $gradereport => $plugindir) {
            if (file_exists($plugindir . '/lib.php')) {
                require_once $plugindir . '/lib.php';
                $cron_function = 'grade_report_' . $gradereport . '_cron';
                if (function_exists($cron_function)) {
                    mtrace("Processing gradebook report function {$cron_function} ...", '');
                    $cron_function();
                }
            }
        }
    }
    // Run external blog cron if needed
    if ($CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
    }
    // Run blog associations cleanup
    if ($CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
    }
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    require_once $CFG->dirroot . '/admin/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // cleanup file trash
    $fs = get_file_storage();
    $fs->cron();
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // run any customized cronjobs, if any
    if ($locals = get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace("Cron script completed correctly");
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
예제 #16
0
파일: register.php 프로젝트: JP-Git/moodle
require_once $CFG->libdir . '/adminlib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/forms.php';
require_once $CFG->dirroot . '/webservice/lib.php';
require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
$huburl = required_param('huburl', PARAM_URL);
$huburl = rtrim($huburl, "/");
if ($huburl == HUB_MOODLEORGHUBURL) {
    // register to Moodle.org
    admin_externalpage_setup('registrationmoodleorg');
} else {
    //register to a hub
    admin_externalpage_setup('registrationhub');
}
$password = optional_param('password', '', PARAM_TEXT);
$hubname = optional_param('hubname', '', PARAM_TEXT);
$registrationmanager = new registration_manager();
$registeredhub = $registrationmanager->get_registeredhub($huburl);
$siteregistrationform = new site_registration_form('', array('alreadyregistered' => !empty($registeredhub->token), 'huburl' => $huburl, 'hubname' => $hubname, 'password' => $password));
$fromform = $siteregistrationform->get_data();
if (!empty($fromform) and confirm_sesskey()) {
    //save the settings
    $cleanhuburl = clean_param($huburl, PARAM_ALPHANUMEXT);
    set_config('site_name_' . $cleanhuburl, $fromform->name, 'hub');
    set_config('site_description_' . $cleanhuburl, $fromform->description, 'hub');
    set_config('site_contactname_' . $cleanhuburl, $fromform->contactname, 'hub');
    set_config('site_contactemail_' . $cleanhuburl, $fromform->contactemail, 'hub');
    set_config('site_contactphone_' . $cleanhuburl, $fromform->contactphone, 'hub');
    set_config('site_imageurl_' . $cleanhuburl, $fromform->imageurl, 'hub');
    set_config('site_privacy_' . $cleanhuburl, $fromform->privacy, 'hub');
    set_config('site_address_' . $cleanhuburl, $fromform->address, 'hub');
    set_config('site_region_' . $cleanhuburl, $fromform->regioncode, 'hub');
예제 #17
0
 /**
  * Display a list of sites
  * If $withwriteaccess = true, we display visible field,
  * trust/prioritise button, and timecreated/modified information.
  * @param array $sites
  * @param boolean $withwriteaccess
  * @return string
  */
 public function site_list($sites, $withwriteaccess = false, $displaysecret = false)
 {
     global $CFG;
     $renderedhtml = '';
     $brtag = html_writer::empty_tag('br');
     $table = new html_table();
     if ($withwriteaccess) {
         $table->head = array('', get_string('sitename', 'local_hub'), get_string('sitedesc', 'local_hub'), get_string('sitelang', 'local_hub'), get_string('siteadmin', 'local_hub'), get_string('operation', 'local_hub'), '');
         $table->align = array('center', 'left', 'left', 'center', 'center', 'center', 'center', 'center');
         $table->size = array('1%', '25%', '40%', '5%', '5%');
     } else {
         $table->head = array('', get_string('sitename', 'local_hub'), get_string('sitedesc', 'local_hub'), get_string('sitelang', 'local_hub'));
         $table->align = array('center', 'left', 'left', 'center');
         $table->size = array('10%', '25%', '60%', '5%');
     }
     if (empty($sites)) {
         if (isset($sites)) {
             $renderedhtml .= get_string('nosite', 'local_hub');
         }
     } else {
         $table->width = '100%';
         $table->data = array();
         $table->attributes['class'] = 'sitedirectory';
         // iterate through sites and add to the display table
         foreach ($sites as $site) {
             //create site name with link
             $siteurl = new moodle_url($site->url);
             $siteatag = html_writer::tag('a', $site->name, array('href' => $siteurl));
             $sitenamespan = html_writer::span($siteatag);
             $siteurlspan = html_writer::span($siteurl, 'additionaldesc');
             $sitenamehtml = $sitenamespan . '<br>' . $siteurlspan;
             //create image tag
             if (!empty($site->imageurl)) {
                 $imageurl = new moodle_url($site->imageurl);
                 $imagehtml = html_writer::empty_tag('img', array('src' => $imageurl, 'alt' => $site->name));
             } else {
                 $imagehtml = '';
             }
             //create description to display
             $deschtml = $site->description;
             //the description
             /// courses and sites number display under the description, in smaller
             $deschtml .= $brtag;
             $site->participantnumberavg = number_format($site->participantnumberaverage, 2);
             $site->modulenumberavg = number_format($site->modulenumberaverage, 2);
             $additionaldesc = get_string('additionaldesc', 'local_hub', $site);
             $deschtml .= html_writer::tag('span', $additionaldesc, array('class' => 'additionaldesc'));
             /// time registered and time modified only display for administrator
             if ($withwriteaccess) {
                 $admindisplayedinfo = new stdClass();
                 $admindisplayedinfo->timeregistered = userdate($site->timeregistered);
                 if (!empty($site->timemodified)) {
                     $admindisplayedinfo->timemodified = userdate($site->timemodified);
                 } else {
                     $admindisplayedinfo->timemodified = '-';
                 }
                 $registrationmanager = new registration_manager();
                 $admindisplayedinfo->privacy = $registrationmanager->get_site_privacy_string($site->privacy);
                 $admindisplayedinfo->contactable = $site->contactable ? get_string('yes') : get_string('no');
                 $admindisplayedinfo->emailalert = $site->emailalert ? get_string('yes') : get_string('no');
                 $additionaladmindesc = $brtag;
                 $additionaladmindesc .= get_string('additionaladmindesc', 'local_hub', $admindisplayedinfo);
                 $deschtml .= html_writer::tag('span', $additionaladmindesc, array('class' => 'additionaladmindesc'));
                 if ($displaysecret) {
                     $markstolen = new moodle_url('/local/hub/admin/stolensecret.php', array('stolen' => $site->id, 'sesskey' => sesskey()));
                     $deschtml .= html_writer::tag('span', get_string('secretvalue', 'local_hub', $site->secret) . ' ' . html_writer::tag('a', get_string('markstolen', 'local_hub'), array('href' => $markstolen, 'class' => 'markstolen')), array('class' => 'sitesecret'));
                 }
             }
             //retrieve language string
             //construct languages array
             if (!empty($site->language)) {
                 $languages = get_string_manager()->get_list_of_languages();
                 $langcode = str_replace('_utf8', '', $site->language);
                 $language = isset($languages[$langcode]) ? $languages[$langcode] : '';
             } else {
                 $language = '';
             }
             //retrieve country string
             if (!empty($site->countrycode)) {
                 $country = get_string_manager()->get_list_of_countries();
                 $language .= ' (' . $country[$site->countrycode] . ')';
             }
             if ($withwriteaccess) {
                 //create site administrator name with email link
                 $adminnamehtml = html_writer::tag('a', $site->contactname, array('href' => 'mailto:' . $site->contactemail));
                 //create trust button
                 if ($site->trusted) {
                     $trustmsg = get_string('untrustme', 'local_hub');
                     $trust = false;
                 } else {
                     $trustmsg = get_string('trustme', 'local_hub');
                     $trust = true;
                 }
                 $trusturl = new moodle_url("/local/hub/admin/managesites.php", array('sesskey' => sesskey(), 'trust' => $trust, 'id' => $site->id));
                 $trustedbutton = new single_button($trusturl, $trustmsg);
                 $trustbuttonhtml = $this->output->render($trustedbutton);
                 //create prioritise button TODO: MDL-25422
                 //                    if ($site->prioritise) {
                 //                        $prioritisemsg = get_string('unprioritise', 'local_hub');
                 //                        $makeprioritise = false;
                 //                        $trustbuttonhtml = '';
                 //                    } else {
                 //                        $prioritisemsg = get_string('prioritise', 'local_hub');
                 //                        $makeprioritise = true;
                 //                    }
                 //                    $prioritiseurl = new moodle_url("/local/hub/admin/managesites.php",
                 //                                    array('sesskey' => sesskey(), 'prioritise' => $makeprioritise,
                 //                                        'id' => $site->id));
                 //                    $prioritisebutton = new single_button($prioritiseurl, $prioritisemsg);
                 //                    $prioritisebuttonhtml = $this->output->render($prioritisebutton);
                 //visible TODO: MDL-25422
                 //                    if ($site->visible) {
                 //                        $hideimgtag = html_writer::empty_tag('img',
                 //                                        array('src' => $this->output->pix_url('i/hide'),
                 //                                            'class' => 'siteimage', 'alt' => get_string('disable')));
                 //                        $makevisible = false;
                 //                    } else {
                 //                        $hideimgtag = html_writer::empty_tag('img',
                 //                                        array('src' => $this->output->pix_url('i/show'),
                 //                                            'class' => 'siteimage', 'alt' => get_string('enable')));
                 //                        $makevisible = true;
                 //                    }
                 //                    if ($site->privacy != HUB_SITENOTPUBLISHED) {
                 //                        $visibleurl = new moodle_url("/local/hub/admin/managesites.php",
                 //                                        array('sesskey' => sesskey(), 'visible' => $makevisible,
                 //                                            'id' => $site->id));
                 //                        $visiblehtml = html_writer::tag('a', $hideimgtag,
                 //                                        array('href' => $visibleurl));
                 //                    } else {
                 //                        $visiblehtml = get_string('private', 'local_hub');
                 //                    }
                 //delete link
                 $deleteurl = new moodle_url("/local/hub/admin/managesites.php", array('sesskey' => sesskey(), 'delete' => $site->id));
                 $deletelinkhtml = html_writer::tag('a', get_string('delete'), array('href' => $deleteurl));
                 //settings link
                 $settingsurl = new moodle_url("/local/hub/admin/sitesettings.php", array('sesskey' => sesskey(), 'id' => $site->id));
                 $settingslinkhtml = html_writer::tag('a', get_string('settings'), array('href' => $settingsurl));
                 // add a row to the table
                 $cells = array($imagehtml, $sitenamehtml, $deschtml, $language, $adminnamehtml, $deletelinkhtml . $brtag . $trustbuttonhtml, $settingslinkhtml);
             } else {
                 // add a row to the table
                 $cells = array($imagehtml, $sitenamehtml, $deschtml, $languages[$site->language]);
             }
             $row = new html_table_row($cells);
             if ($site->prioritise) {
                 $row->attributes['class'] = 'prioritisetr';
             } else {
                 if ($site->trusted) {
                     $row->attributes['class'] = 'trustedtr';
                 }
             }
             $table->data[] = $row;
         }
         $renderedhtml .= html_writer::table($table);
     }
     return $renderedhtml;
 }