Updates site registration via cron

@throws moodle_exception
331660
public static function update_cron() {
        global $DB;

        if (!$registration = self::get_registration()) {
            mtrace(get_string('registrationwarning', 'admin'));
            return;
        }

        if (self::get_new_registration_fields()) {
            mtrace(get_string('pleaserefreshregistrationnewdata', 'admin'));
            return;
        }

        $siteinfo = self::get_site_info();
        api::update_registration($siteinfo);
        $DB->update_record('registration_hubs', ['id' => $registration->id, 'timemodified' => time()]);
        mtrace(get_string('siteregistrationupdated', 'hub'));
        self::$registration = null;
    }
730735
public function run(): void
    {
        foreach (self::SETTINGS as $setting_name => $setting_value) {
            DB::table('site_setting')->updateOrInsert([
                'setting_name'  => $setting_name,
            ], [
                'setting_value' => $setting_value,
            ]);
        }
    }
1287210
public function updateLogoutTime()
    {
        $loginId = $this->getLoginId();
        if ($loginId === null) {
            // Nemáme token, uživatel není přihlášen a není, co prodlužovat
            return $this;
        }

        $result = $this->wsdlManager->getWebService('UserManagement', $loginId)->LoginUpdateRefresh(["ID" => $loginId]);

        $logoutDate = preg_replace('/\.(\d*)$/', '', $result->DateLogout); //skautIS vrací sekundy včetně desetinné části
        $tz = new \DateTimeZone('Europe/Prague');
        $logoutDate = \DateTime::createFromFormat('Y-m-d\TH:i:s', $logoutDate, $tz);
        if ($logoutDate === false) {
            throw new UnexpectedValueException("Could not parse logout date '{$result->DateLogout}'.");
        }
        $this->loginData[self::LOGOUT_DATE] = $logoutDate;

        $this->saveToSession();

        return $this;
    }
1023023
public function Update() {
      
      try {
         // Check for permission or flood control.
         // These settings are loaded/saved to the database because we don't want the config file storing non/config information.
         $Now = time();
         $LastTime = Gdn::Get('Garden.Update.LastTimestamp', 0);

         if ($LastTime + (60 * 60 * 24) > $Now) {
            // Check for flood control.
            $Count = Gdn::Get('Garden.Update.Count', 0) + 1;
            if ($Count > 5) {
               if (!Gdn::Session()->CheckPermission('Garden.Settings.Manage')) {
                  // We are only allowing an update of 5 times every 24 hours.
                  throw PermissionException();
               }
            }
         } else {
            $Count = 1;
         }
         Gdn::Set('Garden.Update.LastTimestamp', $Now);
         Gdn::Set('Garden.Update.Count', $Count);
      } catch (PermissionException $Ex) {
         return;
      } catch (Exception $Ex) {}
      
      try {
         // Run the structure.
         $UpdateModel = new UpdateModel();
         $UpdateModel->RunStructure();
         $this->SetData('Success', TRUE);
      } catch (Exception $Ex) {
         $this->SetData('Success', FALSE);
      }
      
      if (Gdn::Session()->CheckPermission('Garden.Settings.Manage')) {
         SaveToConfig('Garden.Version', APPLICATION_VERSION);
      }
      
      if ($Target = $this->Request->Get('Target')) {
         Redirect($Target);
      }
      
      $this->FireEvent('AfterUpdate');

      $this->MasterView = 'empty';
      $this->CssClass = 'Home';
      $this->Render();
   }
1173182
public static function cron() {
        global $DB;

        // Only ever send a max of one days worth of updates.
        $yesterday = time() - (24 * 3600);
        $timenow   = time();
        $lastcron = $DB->get_field('modules', 'lastcron', array('name' => 'assign'));

        // Collect all submissions that require mailing.
        // Submissions are included if all are true:
        //   - The assignment is visible in the gradebook.
        //   - No previous notification has been sent.
        //   - The grader was a real user, not an automated process.
        //   - If marking workflow is not enabled, the grade was updated in the past 24 hours, or
        //     if marking workflow is enabled, the workflow state is at 'released'.
        $sql = "SELECT g.id as gradeid, a.course, a.name, a.blindmarking, a.revealidentities, a.hidegrader,
                       g.*, g.timemodified as lastmodified, cm.id as cmid, um.id as recordid
                 FROM {assign} a
                 JOIN {assign_grades} g ON g.assignment = a.id
            LEFT JOIN {assign_user_flags} uf ON uf.assignment = a.id AND uf.userid = g.userid
                 JOIN {course_modules} cm ON cm.course = a.course AND cm.instance = a.id
                 JOIN {modules} md ON md.id = cm.module AND md.name = 'assign'
                 JOIN {grade_items} gri ON gri.iteminstance = a.id AND gri.courseid = a.course AND gri.itemmodule = md.name
            LEFT JOIN {assign_user_mapping} um ON g.id = um.userid AND um.assignment = a.id
                 WHERE ((a.markingworkflow = 0 AND g.timemodified >= :yesterday AND g.timemodified <= :today) OR
                        (a.markingworkflow = 1 AND uf.workflowstate = :wfreleased)) AND
                       g.grader > 0 AND uf.mailed = 0 AND gri.hidden = 0
              ORDER BY a.course, cm.id";

        $params = array(
            'yesterday' => $yesterday,
            'today' => $timenow,
            'wfreleased' => ASSIGN_MARKING_WORKFLOW_STATE_RELEASED,
        );
        $submissions = $DB->get_records_sql($sql, $params);

        if (!empty($submissions)) {

            mtrace('Processing ' . count($submissions) . ' assignment submissions ...');

            // Preload courses we are going to need those.
            $courseids = array();
            foreach ($submissions as $submission) {
                $courseids[] = $submission->course;
            }

            // Filter out duplicates.
            $courseids = array_unique($courseids);
            $ctxselect = context_helper::get_preload_record_columns_sql('ctx');
            list($courseidsql, $params) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
            $sql = 'SELECT c.*, ' . $ctxselect .
                      ' FROM {course} c
                 LEFT JOIN {context} ctx ON ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel
                     WHERE c.id ' . $courseidsql;

            $params['contextlevel'] = CONTEXT_COURSE;
            $courses = $DB->get_records_sql($sql, $params);

            // Clean up... this could go on for a while.
            unset($courseids);
            unset($ctxselect);
            unset($courseidsql);
            unset($params);

            // Message students about new feedback.
            foreach ($submissions as $submission) {

                mtrace("Processing assignment submission $submission->id ...");

                // Do not cache user lookups - could be too many.
                if (!$user = $DB->get_record('user', array('id'=>$submission->userid))) {
                    mtrace('Could not find user ' . $submission->userid);
                    continue;
                }

                // Use a cache to prevent the same DB queries happening over and over.
                if (!array_key_exists($submission->course, $courses)) {
                    mtrace('Could not find course ' . $submission->course);
                    continue;
                }
                $course = $courses[$submission->course];
                if (isset($course->ctxid)) {
                    // Context has not yet been preloaded. Do so now.
                    context_helper::preload_from_record($course);
                }

                // Override the language and timezone of the "current" user, so that
                // mail is customised for the receiver.
                cron_setup_user($user, $course);

                // Context lookups are already cached.
                $coursecontext = context_course::instance($course->id);
                if (!is_enrolled($coursecontext, $user->id)) {
                    $courseshortname = format_string($course->shortname,
                                                     true,
                                                     array('context' => $coursecontext));
                    mtrace(fullname($user) . ' not an active participant in ' . $courseshortname);
                    continue;
                }

                if (!$grader = $DB->get_record('user', array('id'=>$submission->grader))) {
                    mtrace('Could not find grader ' . $submission->grader);
                    continue;
                }

                $modinfo = get_fast_modinfo($course, $user->id);
                $cm = $modinfo->get_cm($submission->cmid);
                // Context lookups are already cached.
                $contextmodule = context_module::instance($cm->id);

                if (!$cm->uservisible) {
                    // Hold mail notification for assignments the user cannot access until later.
                    continue;
                }

                // Notify the student. Default to the non-anon version.
                $messagetype = 'feedbackavailable';
                // Message type needs 'anon' if "hidden grading" is enabled and the student
                // doesn't have permission to see the grader.
                if ($submission->hidegrader && !has_capability('mod/assign:showhiddengrader', $contextmodule, $user)) {
                    $messagetype = 'feedbackavailableanon';
                    // There's no point in having an "anonymous grader" if the notification email
                    // comes from them. Send the email from the noreply user instead.
                    $grader = core_user::get_noreply_user();
                }

                $eventtype = 'assign_notification';
                $updatetime = $submission->lastmodified;
                $modulename = get_string('modulename', 'assign');

                $uniqueid = 0;
                if ($submission->blindmarking && !$submission->revealidentities) {
                    if (empty($submission->recordid)) {
                        $uniqueid = self::get_uniqueid_for_user_static($submission->assignment, $grader->id);
                    } else {
                        $uniqueid = $submission->recordid;
                    }
                }
                $showusers = $submission->blindmarking && !$submission->revealidentities;
                self::send_assignment_notification($grader,
                                                   $user,
                                                   $messagetype,
                                                   $eventtype,
                                                   $updatetime,
                                                   $cm,
                                                   $contextmodule,
                                                   $course,
                                                   $modulename,
                                                   $submission->name,
                                                   $showusers,
                                                   $uniqueid);

                $flags = $DB->get_record('assign_user_flags', array('userid'=>$user->id, 'assignment'=>$submission->assignment));
                if ($flags) {
                    $flags->mailed = 1;
                    $DB->update_record('assign_user_flags', $flags);
                } else {
                    $flags = new stdClass();
                    $flags->userid = $user->id;
                    $flags->assignment = $submission->assignment;
                    $flags->mailed = 1;
                    $DB->insert_record('assign_user_flags', $flags);
                }

                mtrace('Done');
            }
            mtrace('Done processing ' . count($submissions) . ' assignment submissions');

            cron_setup_user();

            // Free up memory just to be sure.
            unset($courses);
        }

        // Update calendar events to provide a description.
        $sql = 'SELECT id
                    FROM {assign}
                    WHERE
                        allowsubmissionsfromdate >= :lastcron AND
                        allowsubmissionsfromdate <= :timenow AND
                        alwaysshowdescription = 0';
        $params = array('lastcron' => $lastcron, 'timenow' => $timenow);
        $newlyavailable = $DB->get_records_sql($sql, $params);
        foreach ($newlyavailable as $record) {
            $cm = get_coursemodule_from_instance('assign', $record->id, 0, false, MUST_EXIST);
            $context = context_module::instance($cm->id);

            $assignment = new assign($context, null, null);
            $assignment->update_calendar($cm->id);
        }

        return true;
    }
1006790
protected function updateAssignment()
    {
        $uri = str_replace('{assignment}', $this->assignment, config('forge-publish.update_assignment_uri'));
        $url = config('forge-publish.url') . $uri;
        try {
            $response = $this->http->put($url, [
                'form_params' => [
                    'name' => $this->assignmentName,
                    'repository_uri' => $this->repository_uri,
                    'repository_type' => $this->repository_type,
                    'forge_site' => $this->forge_site,
                    'forge_server' => $this->forge_server
                ],
                'headers' => [
                    'X-Requested-With' => 'XMLHttpRequest',
                    'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
                ]
            ]);
        } catch (\Exception $e) {
            $this->error('And error occurs connecting to the api url: ' . $url);
            $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
            return [];
        }
        return json_decode((string) $response->getBody());
    }
252599
protected function loadCronModule(){
        //Consigo las variables globales para linea de comandos
        global $argv, $argc;
        //Analizo si se pasa por lo menos un parametros (nombre cron), el primer parametros es el nombre del archivo y el segundo en nombre de la clase
        //pregunta por >= 2
        if($argc >= 2){
            $this->cronCore= new Cron\CronCore($this, $argv);            
        }else{
            Error::general_error('Cron Controller', 'There isent define any cron controller name');
        }    
    }
502438
private function updateTime()
    {
        // Date string generation is (relatively) expensive. Since we only need HTTP
        // dates at a granularity of one second we're better off to generate this
        // information once per second and cache it.
        $this->currentTime = \time();
        $this->currentHttpDate = \gmdate("D, d M Y H:i:s", $this->currentTime) . " GMT";

        foreach ($this->callbacks as $callback) {
            $callback($this->currentTime, $this->currentHttpDate);
        }
    }
201964
protected static function process_curl_exception($token, $curloutput) {
        if (!isset($curloutput['exception'])) {
            return;
        }
        if ($token === registration::get_token()) {
            // Check if registration token was rejected or there are other problems with registration.
            if (($curloutput['exception'] === 'moodle_exception' && $curloutput['errorcode'] === 'invalidtoken')
                    || $curloutput['exception'] === 'registration_exception') {
                // Force admin to repeat site registration process.
                registration::reset_token();
                throw new moodle_exception('errorwstokenreset', 'hub', '', $curloutput['message']);
            }
        }
        throw new moodle_exception('errorws', 'hub', '', $curloutput['message']);
    }
1298904
protected function registerConsole()
    {
        /*
         * Allow plugins to use the scheduler
         */
        Event::listen('console.schedule', function ($schedule) {
            $plugins = PluginManager::instance()->getPlugins();
            foreach ($plugins as $plugin) {
                if (method_exists($plugin, 'registerSchedule')) {
                    $plugin->registerSchedule($schedule);
                }
            }
        });

        /*
         * Add CMS based cache clearing to native command
         */
        Event::listen('cache:cleared', function () {
            \System\Helpers\Cache::clearInternal();
        });

        /*
         * Register console commands
         */
        $this->registerConsoleCommand('october.up', 'System\Console\OctoberUp');
        $this->registerConsoleCommand('october.down', 'System\Console\OctoberDown');
        $this->registerConsoleCommand('october.update', 'System\Console\OctoberUpdate');
        $this->registerConsoleCommand('october.util', 'System\Console\OctoberUtil');
        $this->registerConsoleCommand('october.mirror', 'System\Console\OctoberMirror');
        $this->registerConsoleCommand('october.fresh', 'System\Console\OctoberFresh');
        $this->registerConsoleCommand('october.env', 'System\Console\OctoberEnv');
        $this->registerConsoleCommand('october.install', 'System\Console\OctoberInstall');

        $this->registerConsoleCommand('plugin.install', 'System\Console\PluginInstall');
        $this->registerConsoleCommand('plugin.remove', 'System\Console\PluginRemove');
        $this->registerConsoleCommand('plugin.refresh', 'System\Console\PluginRefresh');

        $this->registerConsoleCommand('theme.install', 'System\Console\ThemeInstall');
        $this->registerConsoleCommand('theme.remove', 'System\Console\ThemeRemove');
        $this->registerConsoleCommand('theme.list', 'System\Console\ThemeList');
        $this->registerConsoleCommand('theme.use', 'System\Console\ThemeUse');
    }
845256
private function update()
    {
        $errors = array();
        switch( State::get('action') )
        {
            case 'save':
                $errors = $this->save();
                Notifier::success('Settings saved.');
                break;
            case 'reset-section':
                $section = $this->config->get_section_by_slug(State::get('active_section'));
                $this->reset( $section );
                Notifier::success('<strong>'.$section->title.'</strong> section was reset to its default settings.');
                break;
            case 'reset-all':
                $this->reset();
                Notifier::success('All sections were reset to their default settings.');
                break;
            // No submission (simple request)
            default:
                $this->load();
        }
        
        $this->set_errors($errors);
    }
1360380
public static function register(){
		if( self::$registered ){
			return;
		}

		self::$libDir = dirname(__FILE__);

		if(false === spl_autoload_register(array('Less_Autoloader', 'loadClass'))){
			throw new Exception('Unable to register Less_Autoloader::loadClass as an autoloading method.');
		}

		self::$registered = true;
	}
336258
public function updateLastEntering(): bool
    {
        $this->last_entering_date = time();
        if (!$this->save()) {
            throw new Exception(\Yii::t('app', 'Ошибка обновления даты входа'));
        }
        return true;
    }
1221875
def update_site(sender, **kwargs):
    
    Site = apps.get_model('sites', 'Site')
    domain = settings.SITE_DOMAIN
    if settings.SITE_PORT:
        domain += ':%s' % settings.SITE_PORT
    Site.objects.update_or_create(
        pk=settings.SITE_ID,
        defaults=dict(
            domain=domain,
            name=settings.SITE_NAME))

    # We set an explicit pk instead of relying on auto-incrementation,
    # so we need to reset the database sequence.
    sequence_sql = connection.ops.sequence_reset_sql(no_style(), [Site])
    if sequence_sql:
        cursor = connection.cursor()
        for command in sequence_sql:
            cursor.execute(command)
882226
protected function cron_execute() {

        try {
            $this->restore_response();
            $previous = $this->recentresponse;
            $this->fetch();
            $this->restore_response(true);
            $current = $this->recentresponse;
            $changes = $this->compare_responses($previous, $current);
            $notifications = $this->cron_notifications($changes);
            $this->cron_notify($notifications);
            $this->cron_mtrace('done');
        } catch (checker_exception $e) {
            $this->cron_mtrace('FAILED!');
        }
    }
240194
public static function install_site() {
        global $DB, $CFG;
        require_once($CFG->dirroot.'/user/lib.php');
        if (!defined('BEHAT_UTIL')) {
            throw new coding_exception('This method can be only used by Behat CLI tool');
        }

        $tables = $DB->get_tables(false);
        if (!empty($tables)) {
            behat_error(BEHAT_EXITCODE_INSTALLED);
        }

        // New dataroot.
        self::reset_dataroot();

        $options = array();
        $options['adminuser'] = 'admin';
        $options['adminpass'] = 'admin';
        $options['fullname'] = self::BEHATSITENAME;
        $options['shortname'] = self::BEHATSITENAME;

        install_cli_database($options, false);

        // We need to keep the installed dataroot filedir files.
        // So each time we reset the dataroot before running a test, the default files are still installed.
        self::save_original_data_files();

        $frontpagesummary = new admin_setting_special_frontpagedesc();
        $frontpagesummary->write_setting(self::BEHATSITENAME);

        // Update admin user info.
        $user = $DB->get_record('user', array('username' => 'admin'));
        $user->email = 'moodle@example.com';
        $user->firstname = 'Admin';
        $user->lastname = 'User';
        $user->city = 'Perth';
        $user->country = 'AU';
        user_update_user($user, false);

        // Disable email message processor.
        $DB->set_field('message_processors', 'enabled', '0', array('name' => 'email'));

        // Sets maximum debug level.
        set_config('debug', DEBUG_DEVELOPER);
        set_config('debugdisplay', 1);

        // Disable some settings that are not wanted on test sites.
        set_config('noemailever', 1);

        // Enable web cron.
        set_config('cronclionly', 0);

        // Set editor autosave to high value, so as to avoid unwanted ajax.
        set_config('autosavefrequency', '604800', 'editor_atto');

        // Set noreplyaddress to an example domain, as it should be valid email address and test site can be a localhost.
        set_config('noreplyaddress', 'noreply@example.com');

        // Keeps the current version of database and dataroot.
        self::store_versions_hash();

        // Stores the database contents for fast reset.
        self::store_database_state();
    }
309874
public function register()
    {
        $configPath = __DIR__ . '/../config/sql-logging.php';
        $this->mergeConfigFrom($configPath, 'sql-logging');

        if (config('sql-logging.log', false)) {
            Event::listen('illuminate.query',
                function ($query, $bindings, $time) {
                    $data = compact('bindings', 'time');

                    // Format binding data for sql insertion
                    foreach ($bindings as $i => $binding) {
                        if ($binding instanceof \DateTime) {
                            $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                        } else if (is_string($binding)) {
                            $bindings[$i] = "'$binding'";
                        }
                    }

                    // Insert bindings into query
                    $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
                    $query = vsprintf($query, $bindings);

                    $log = new Logger('sql');
                    $log->pushHandler(new StreamHandler(storage_path() . '/logs/sql-' . date('Y-m-d') . '.log',
                        Logger::INFO));

                    // if log request data
                    if (config('sql-logging.log_request', false)) {
                        $data['request_path'] = Request::path();
                        $data['request_method'] = Request::method();
                        $data['request_data'] = Request::all();
                    }

                    // add records to the log
                    $log->addInfo($query, $data);
                });
        }
    }