Maintenance::execute

@throws \Exception
160545
public function execute()
    {
        $options = input()->get();

        if (empty($options)) {
            $_GET[ 'switch' ] = 'ON';
            $_GET[ 'mode' ] = 'default';
            $_GET[ 'lifetime' ] = 300;
            $_GET[ 'title' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_TITLE'));
            $_GET[ 'message' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_MESSAGE'));
        } else {
            $_GET[ 'mode' ] = 'default';
            $_GET[ 'lifetime' ] = 300;
            $_GET[ 'title' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_TITLE'));
            $_GET[ 'message' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_MESSAGE'));
        }

        parent::execute();

        if ($this->optionSwitch === 'ON') {
            if (cache()->hasItem('maintenance')) {

                $maintenanceInfo = cache()->getItem('maintenance')->get();
                output()->write(
                    (new Format())
                        ->setContextualClass(Format::DANGER)
                        ->setString(language()->getLine('CLI_MAINTENANCE_ALREADY_STARTED', [
                            $maintenanceInfo[ 'mode' ],
                            $maintenanceInfo[ 'datetime' ],
                            date('r', strtotime($maintenanceInfo[ 'datetime' ]) + $maintenanceInfo[ 'lifetime' ]),
                            $maintenanceInfo[ 'title' ],
                            $maintenanceInfo[ 'message' ],
                        ]))
                        ->setNewLinesAfter(1)
                );
            } else {
                output()->write(
                    (new Format())
                        ->setContextualClass(Format::WARNING)
                        ->setString(language()->getLine('CLI_MAINTENANCE_STARTED', [
                            $datetime = date('r'),
                            $this->optionLifetime,
                            $this->optionMode,
                            $this->optionTitle,
                            $this->optionMessage,
                        ]))
                        ->setNewLinesAfter(1)
                );

                cache()->save(new Item('maintenance', [
                    'datetime' => $datetime,
                    'lifetime' => $this->optionLifetime,
                    'mode'     => $this->optionMode,
                    'title'    => $this->optionTitle,
                    'message'  => $this->optionMessage,
                ], $this->optionLifetime));
            }

        } elseif ($this->optionSwitch === 'OFF') {
            if (cache()->hasItem('maintenance')) {
                output()->write(
                    (new Format())
                        ->setContextualClass(Format::DANGER)
                        ->setString(language()->getLine('CLI_MAINTENANCE_STOPPED', [
                            $this->optionMode,
                            date('r'),
                        ]))
                        ->setNewLinesAfter(1)
                );

                cache()->deleteItem('maintenance');
            } else {
                output()->write(
                    (new Format())
                        ->setContextualClass(Format::DANGER)
                        ->setString(language()->getLine('CLI_MAINTENANCE_INACTIVE'))
                        ->setNewLinesAfter(1)
                );
            }
        }
    }
643373
public function execute()
    {
        $batch  = $this->getBatch();
        $import = $batch->getVariable('import');

        if (! (isset($import['trackId']) && $import['trackId'])) {
            // Do nothing
            return;
        }

        $tracker     = $this->loader->getTracker();
        $trackEngine = $tracker->getTrackEngine($import['trackId']);
        $trackEngine->updateRoundCount($this->currentUser->getUserLoginId());
        
        // Now cleanup the cache
        $this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('tracks'));
    }
1153274
public function execute() {
        if (!is_enabled_auth('db')) {
            mtrace('auth_db plugin is disabled, synchronisation stopped', 2);
            return;
        }

        $dbauth = get_auth_plugin('db');
        $config = get_config('auth_db');
        $trace = new \text_progress_trace();
        $update = !empty($config->updateusers);
        $dbauth->sync_users($trace, $update);
    }
271678
public function run()
    {
        if (is_callable($this->closure)) {
            // Set the error handler for the spec
            set_error_handler([$this, 'handleError'], E_ALL);

            // Invoke the closure while catching exceptions
            try {
                $this->closure->__invoke();
            } catch (ExpectationException $exception) {
                $this->exception = $exception;
            } catch (\Exception $exception) {
                $this->handleException($exception);
            }

            restore_error_handler();
        }
    }
1358632
public function execute(): void
    {
        $path = '';
        
        try {
            $path = $this->getPath();
            
            if ($this->config->cache) {
                try {
                    $this->setCache();
                } catch (StorageNotSupportedException $e) {
                    $this->cache = null;
                } catch (StorageConnectException $e) {
                    $this->cache = null;
                }
            }
            
            if (null !== $this->cache 
            && !$this->cache->expired($path, $this->config->cacheTtlWholePage)) {
                $result = $this->getCacheResult($this->cache->get($path, ''));
            } else {
                $result = $this->compose($this->parse($path));
            }
            
        } catch (BadPathException $e) {
            $result = $this->getError(500, 'Bad path');
            
        } catch (RouteStorageNotSetException $e) {
            $result = $this->getError(500, 'Route storage not set');
            
        } catch (RouteStorageEmptyException $e) {
            $result = $this->getError(500, 'Route storage empty');
            
        } catch (DbConnectException $e) {
            if (null !== $this->cache && $this->cache->has($path)) {
                // @codeCoverageIgnoreStart
                // passed in local tests, but skipped in travis
                $result = $this->getCacheResult($this->cache->get($path, ''));
                // @codeCoverageIgnoreEnd
            } else {
                $result = $this->getError(500, 'DataBase connection error');
            }
            
        } catch (SectionNotExistsException $e) {
            $result = $this->getError(404, 'Section not exists');
            
        } catch (SectionDisabledException $e) {
            $result = $this->getError(403, 'Section disabled');
            
        } catch (ModuleDisabledException $e) {
            $result = $this->getError(403, 'Section module disabled');
            
        } catch (ModuleParameterConflictException $e) {
            $result = $this->getError(404, 'Module parameter conflict with another');
            
        } catch (ModuleParameterFormatException $e) {
            $result = $this->getError(404, 'Module parameter bad format');
            
        } catch (ModuleParameterUnknownException $e) {
            $result = $this->getError(404, 'Module parameter unknown');
            
        } catch (\Throwable $e) {
            $result = $this->getError(500, 'Unexpected exception: ' . $e->getMessage());
            
        }
        
        $this->sendHeaders($result->getHeaders());
        
        $this->render($result->getView());
    }
981254
public function execute() {
        $accessrecords = access::get_records();
        $expires = new DateTime();
        $expires->sub(new DateInterval("P7D"));
        $timestamp = $expires->getTimestamp();

        $issuerid = get_config('onedrive', 'issuerid');
        $issuer = \core\oauth2\api::get_issuer($issuerid);

        // Add the current user as an OAuth writer.
        $systemauth = \core\oauth2\api::get_system_oauth_client($issuer);

        if ($systemauth === false) {
            $details = 'Cannot connect as system user';
            throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
        }
        $systemservice = new \repository_onedrive\rest($systemauth);

        foreach ($accessrecords as $access) {
            if ($access->get('timemodified') < $timestamp) {
                $params = ['permissionid' => $access->get('permissionid'), 'itemid' => $access->get('itemid')];
                try {
                    $systemservice->call('delete_permission', $params);
                } catch (rest_exception $re) {
                    // We log and give up here or we will always fail for eternity.
                    mtrace('Failed to remove access from file: ' . $access->get('itemid'));
                }
                $access->delete();
            }
        }
    }
802592
public function execute() {
        global $DB;
        $started = time();

        $restoreid = $this->get_custom_data()->backupid;
        $restorerecordid = $DB->get_field('backup_controllers', 'id', array('backupid' => $restoreid), MUST_EXIST);
        mtrace('Processing asynchronous restore for id: ' . $restoreid);

        // Get the restore controller by backup id.
        $rc = \restore_controller::load_controller($restoreid);
        $rc->set_progress(new \core\progress\db_updater($restorerecordid, 'backup_controllers', 'progress'));

        // Do some preflight checks on the restore.
        $status = $rc->get_status();
        $execution = $rc->get_execution();

        // Check that the restore is in the correct status and
        // that is set for asynchronous execution.
        if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
            // Execute the restore.
            $rc->execute_plan();

            // Send message to user if enabled.
            $messageenabled = (bool)get_config('backup', 'backup_async_message_users');
            if ($messageenabled && $rc->get_status() == \backup::STATUS_FINISHED_OK) {
                $asynchelper = new async_helper('restore', $restoreid);
                $asynchelper->send_message();
            }

        } else {
            // If status isn't 700, it means the process has failed.
            // Retrying isn't going to fix it, so marked operation as failed.
            $rc->set_status(\backup::STATUS_FINISHED_ERR);
            mtrace('Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');

        }

        // Cleanup.
        $rc->destroy();

        $duration = time() - $started;
        mtrace('Restore completed in: ' . $duration . ' seconds');
    }
691554
public function execute()
    {
        if (!defined('ENABLE_SHELL_PLUGIN') || !ENABLE_SHELL_PLUGIN) {
            throw new \Exception(Lang::get('shell_not_enabled'));
        }

        $success = true;

        foreach ($this->commands as $command) {
            $command = $this->phpci->interpolate($command);

            if (!$this->phpci->executeCommand($command)) {
                $success = false;
            }
        }

        return $success;
    }
181644
public function execute()
    {
        // clean up
        $cleanUpResult = $this->cleanUpIndex();

        // initialize for re-indexing
            /** @var Queue $indexQueue */
        $indexQueue = GeneralUtility::makeInstance(Queue::class);
        $indexQueueInitializationResults = $indexQueue->getInitializationService()
            ->initializeBySiteAndIndexConfigurations($this->getSite(), $this->indexingConfigurationsToReIndex);

        return ($cleanUpResult && !in_array(false, $indexQueueInitializationResults));
    }
1331237
@Override
    public Object execute() throws Exception 
    {
        Object ret = executeChange();
        if (changesManager != null)
            changesManager.modelChanged();
        return ret;
    }
490304
public function execute()
    {
        $ch = curl_init();
        $this->setAuth($ch);
        try {
            switch (strtoupper($this->verb)) {
                case 'GET':
                    $this->executeGet($ch);
                    break;
                case 'POST':
                    $this->executePost($ch);
                    break;
                case 'PUT':
                    $this->executePut($ch);
                    break;
                case 'DELETE':
                    $this->executeDelete($ch);
                    break;
                default:
                    throw new \InvalidArgumentException(
                        'Current verb (' . $this->verb
                        . ') is an invalid REST verb.'
                    );
            }
        } catch (\InvalidArgumentException $e) {
            curl_close($ch);
            throw $e;
        } catch (\Exception $e) {
            curl_close($ch);
            throw $e;
        }

        /*
         * check and debug api request total time
         */
        $this->processDebugApi();

        return $this->responseBody;
    }
450826
public function execute()
    {
        $packages = ['updates' => [], 'installs' => []];

        // Get known installed packages
        $rootPackage = $this->app['extend.action']['show']->execute('installed');

        /** @var \Bolt\Filesystem\Handler\JsonFile $jsonFile */
        $jsonFile = $this->getOptions()->composerJson();

        // Get the packages that a set as "required" in the JSON file
        $json = $jsonFile->parse();
        $jsonRequires = isset($json['require']) ? (array) $json['require'] : [];

        /** @var string $packageName */
        /** @var string $versionConstraint */
        foreach ($jsonRequires as $packageName => $versionConstraint) {
            try {
                $remote = $this->findBestVersionForPackage($packageName, $versionConstraint, true);
            } catch (\Exception $e) {
                $msg = sprintf('%s received an error from Composer: %s in %s::%s', __METHOD__, $e->getMessage(), $e->getFile(), $e->getLine());
                $this->app['logger.system']->critical($msg, ['event' => 'exception', 'exception' => $e]);

                throw new PackageManagerException($e->getMessage(), $e->getCode(), $e);
            }
            if (!is_array($remote)) {
                continue;
            }

            if (array_key_exists($packageName, $rootPackage)) {
                $rootVer = isset($rootPackage[$packageName]['versions']) ? $rootPackage[$packageName]['versions'] : false;
                if ($rootVer && $rootVer !== $remote['package']->getVersion()) {
                    $packages['updates'][] = $remote;
                }
            } else {
                $packages['installs'][] = $remote;
                unset($jsonRequires[$packageName]);
            }
        }

        return $packages;
    }
60101
public function handle()
    {
        $exportPath = $this->option('path');

        if($exportPath) {
            if(!file_exists($exportPath)) {
                throw new \Exception('Path '.$exportPath. ' does not exists!');
            }
        }else{
            $exportPath = storage_path('app/dumper');

            // create dumper directory
            if(!file_exists($exportPath)) {
                File::makeDirectory($exportPath, 0755);
            }
        }

        $filePath = $exportPath.'/'.date("Ymdhisi").'.sql';
      
        $this->comment("Starting database dump...");

        switch (config('database.default')){
        case 'mysql':
            MySql::create()
                ->setDbName(config('database.connections.mysql.database'))
                ->setHost(config('database.connections.mysql.host'))
                ->setUserName(config('database.connections.mysql.username'))
                ->setPassword(config('database.connections.mysql.password'))
                ->dumpToFile($filePath);
            break;

        case 'pgsql':
            PostgreSql::create()
                ->setDbName(config('database.connections.pgsql.database'))
                ->setUserName(config('database.connections.pgsql.username'))
                ->setPassword(config('database.connections.pgsql.password'))
                ->dumpToFile($filePath);
            break;

        case 'sqlite':
            Sqlite::create()
                ->setDbName(config('database.connections.sqlite.database'))
                ->dumpToFile($filePath);
            break;

        case 'mongodb':
            MongoDb::create()
                ->setDbName(config('database.connections.mongodb.database'))
                ->setUserName(config('database.connections.mongodb.username'))
                ->setPassword(config('database.connections.mongodb.password'))
                ->dumpToFile($filePath);
            break;
        }

        $this->info("Database successfully dumped to ".$filePath);
    }
941129
public function execute() {
        if(is_null($this->client)) {
            $this->client = $this->getConnection();
        }
        if(is_null($this->query)) {
            throw new Exception('No query');
        }

        list($query_data, $meta) = $this->constructQuery($this->source, $this->query, $this->aggs, $this->post_query, $this->settings);

        $results_set = $this->query($query_data, $meta);
        $results = $this->processResults($results_set, $meta);
        $results = $this->postProcessResults($this->post_query, $results, $meta);

        return $results;
    }
412112
public function execute() {
        global $CFG;

        if (!empty($CFG->enableplagiarism)) {
            require_once($CFG->libdir.'/plagiarismlib.php');
            $plagiarismplugins = plagiarism_load_available_plugins();
            foreach ($plagiarismplugins as $plugin => $dir) {
                require_once($dir . '/lib.php');
                $plagiarismclass = "plagiarism_plugin_$plugin";
                $plagiarismplugin = new $plagiarismclass;
                if (method_exists($plagiarismplugin, 'cron')) {
                    mtrace('Processing cron function for plagiarism_plugin_' . $plugin . '...', '');
                    cron_trace_time_and_memory();
                    mtrace('It has been detected the class ' . $plagiarismclass . ' has a legacy cron method
                            implemented. Plagiarism plugins should implement their own schedule tasks.', '');
                    $plagiarismplugin->cron();
                }
            }
        }
    }
274924
public function execute()
    {
        $this->cleanHistory();
        $this->log();
        $this->instanceManager->update($this->instance);
    }
486692
public function execute()
    {
        $command = new \ReflectionClass($this);
        $options = input()->get();

        if (empty($options)) {
            $this->optionHelp();
        } else {

            foreach ($options as $method => $arguments) {

                if (array_key_exists('-' . $method, $this->commandOptionsShortcuts)) {
                    $method = $this->commandOptionsShortcuts[ '-' . $method ];
                }

                $optionMethod = camelcase('option-' . $method);

                if ($command->hasMethod($optionMethod)) {

                    $commandMethod = $command->getMethod($optionMethod);

                    if ($commandMethod->getNumberOfRequiredParameters() == 0) {
                        call_user_func([&$this, $optionMethod]);
                    } elseif ($commandMethod->getNumberOfRequiredParameters() > 0 and empty($arguments)) {
                        if (isset($this->commandOptions[ $method ][ 'help' ])) {
                            output()->write(
                                (new Format())
                                    ->setContextualClass(Format::INFO)
                                    ->setString(language()->getLine('CLI_USAGE') . ':')
                                    ->setNewLinesBefore(1)
                                    ->setNewLinesAfter(1)
                            );

                            output()->write(
                                (new Format())
                                    ->setContextualClass(Format::INFO)
                                    ->setString(language()->getLine($this->commandOptions[ $method ][ 'help' ]))
                                    ->setNewLinesAfter(2)
                            );
                        }
                    } else {
                        $optionArguments = is_array($arguments)
                            ? $arguments
                            : [$arguments];

                        call_user_func_array([&$this, $optionMethod], $optionArguments);
                    }
                }
            }
        }
    }