<commit_before><?php
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2016 Spring Signage Ltd
 * (MaintenanceDailyTask.php)
 */


namespace Xibo\XTR;
use Xibo\Exception\ConfigurationException;
use Xibo\Service\ConfigService;

/**
 * Class MaintenanceDailyTask
 * @package Xibo\XTR
 */
class MaintenanceDailyTask implements TaskInterface
{
    use TaskTrait;

    private $hasUpgradeRun = false;

    /** @inheritdoc */
    public function run()
    {
        $this->runMessage = '# ' . __('Daily Maintenance') . PHP_EOL . PHP_EOL;

        // Upgrade
        $this->upgrade();

        if ($this->hasUpgradeRun)
            return;

        // Long running task
        set_time_limit(0);

        // Import layouts
        $this->importLayouts();

        // Install module files
        $this->installModuleFiles();

        // Tidy logs
        $this->tidyLogs();

        // Tidy stats
        $this->tidyStats();

        // Tidy Cache
        $this->tidyCache();

        // API tokens
        $this->purgeExpiredApiTokens();
    }

    /**
     * Upgrade if required
     * @throws ConfigurationException
     */
    private function upgrade()
    {
        // Is there a pending upgrade (i.e. are there any pending upgrade steps).
        if ($this->config->isUpgradePending()) {
            // Flag to indicate we've run upgrade steps
            $this->hasUpgradeRun = true;

            $this->runMessage .= '#' . __('Upgrade') . PHP_EOL;
            $steps = $this->upgradeFactory->getIncomplete();

            if (count($steps) <= 0) {

                // Insert pending upgrade steps.
                $steps = $this->upgradeFactory->createSteps(DBVERSION, ConfigService::$WEBSITE_VERSION);

                foreach ($steps as $step) {
                    /* @var \Xibo\Entity\Upgrade $step */
                    $step->save();
                }
            }

            // Cycle through the steps until done
            set_time_limit(0);

            $previousStepSetsDbVersion = false;

            foreach ($steps as $upgradeStep) {
                /* @var \Xibo\Entity\Upgrade $upgradeStep */
                if ($previousStepSetsDbVersion) {
                    $this->log->notice('Pausing upgrade to reset version');
                    $this->runMessage .= '#' . __('Upgrade Paused') . PHP_EOL . PHP_EOL;
                    return;
                }

                // Assume success
                $stepFailed = false;

                try {
                    $upgradeStep->doStep();
                    $upgradeStep->complete = 1;

                    // Commit
                    $this->store->commitIfNecessary('upgrade');

                } catch (\Exception $e) {
                    // Failed to run upgrade step
                    $this->log->error('Unable to run upgrade stepId ' . $upgradeStep->stepId . '. Message = ' . $e->getMessage());
                    $this->log->error($e->getTraceAsString());

                    try {
                        $this->store->getConnection('upgrade')->rollBack();
                    } catch (\Exception $exception) {
                        $this->log->error('Unable to rollback. E = ' . $e->getMessage());
                    }

                    $stepFailed = true;
                }

                $upgradeStep->lastTryDate = $this->date->parse()->format('U');
                $upgradeStep->save();

                // if we are a step that updates the version table, then exit
                if ($upgradeStep->type == 'sql' && stripos($upgradeStep->action, 'SET `DBVersion`'))
                    $previousStepSetsDbVersion = true;

                if ($stepFailed)
                    throw new ConfigurationException('Unable to run upgrade step. Aborting Maintenance Task.');
            }

            $this->runMessage .= '#' . __('Upgrade Complete') . PHP_EOL . PHP_EOL;
        }
    }

    /**
     * Tidy the DB logs
     */
    private function tidyLogs()
    {
        $this->runMessage .= '## ' . __('Tidy Logs') . PHP_EOL;

        if ($this->config->GetSetting('MAINTENANCE_LOG_MAXAGE') != 0) {

            $maxage = date('Y-m-d H:i:s', time() - (86400 * intval($this->config->GetSetting('MAINTENANCE_LOG_MAXAGE'))));

            try {
                $this->store->update('DELETE FROM `log` WHERE logdate < :maxage', ['maxage' => $maxage]);

                $this->runMessage .= ' - ' . __('Done.') . PHP_EOL . PHP_EOL;
            }
            catch (\PDOException $e) {
                $this->runMessage .= ' - ' . __('Error.') . PHP_EOL . PHP_EOL;<commit_msg>Always commit the upgrade step status change.<commit_after><?php
/*
 * Spring Signage Ltd - http://www.springsignage.com
 * Copyright (C) 2016 Spring Signage Ltd
 * (MaintenanceDailyTask.php)
 */


namespace Xibo\XTR;
use Xibo\Exception\ConfigurationException;
use Xibo\Service\ConfigService;

/**
 * Class MaintenanceDailyTask
 * @package Xibo\XTR
 */
class MaintenanceDailyTask implements TaskInterface
{
    use TaskTrait;

    private $hasUpgradeRun = false;

    /** @inheritdoc */
    public function run()
    {
        $this->runMessage = '# ' . __('Daily Maintenance') . PHP_EOL . PHP_EOL;

        // Upgrade
        $this->upgrade();

        if ($this->hasUpgradeRun)
            return;

        // Long running task
        set_time_limit(0);

        // Import layouts
        $this->importLayouts();

        // Install module files
        $this->installModuleFiles();

        // Tidy logs
        $this->tidyLogs();

        // Tidy stats
        $this->tidyStats();

        // Tidy Cache
        $this->tidyCache();

        // API tokens
        $this->purgeExpiredApiTokens();
    }

    /**
     * Upgrade if required
     * @throws ConfigurationException
     */
    private function upgrade()
    {
        // Is there a pending upgrade (i.e. are there any pending upgrade steps).
        if ($this->config->isUpgradePending()) {
            // Flag to indicate we've run upgrade steps
            $this->hasUpgradeRun = true;

            $this->runMessage .= '#' . __('Upgrade') . PHP_EOL;
            $steps = $this->upgradeFactory->getIncomplete();

            if (count($steps) <= 0) {

                // Insert pending upgrade steps.
                $steps = $this->upgradeFactory->createSteps(DBVERSION, ConfigService::$WEBSITE_VERSION);

                foreach ($steps as $step) {
                    /* @var \Xibo\Entity\Upgrade $step */
                    $step->save();
                }
            }

            // Cycle through the steps until done
            set_time_limit(0);

            $previousStepSetsDbVersion = false;

            foreach ($steps as $upgradeStep) {
                /* @var \Xibo\Entity\Upgrade $upgradeStep */
                if ($previousStepSetsDbVersion) {
                    $this->log->notice('Pausing upgrade to reset version');
                    $this->runMessage .= '#' . __('Upgrade Paused') . PHP_EOL . PHP_EOL;
                    return;
                }

                // Assume success
                $stepFailed = false;

                try {
                    $upgradeStep->doStep();
                    $upgradeStep->complete = 1;

                    // Commit
                    $this->store->commitIfNecessary('upgrade');

                } catch (\Exception $e) {
                    // Failed to run upgrade step
                    $this->log->error('Unable to run upgrade stepId ' . $upgradeStep->stepId . '. Message = ' . $e->getMessage());
                    $this->log->error($e->getTraceAsString());

                    try {
                        $this->store->getConnection('upgrade')->rollBack();
                    } catch (\Exception $exception) {
                        $this->log->error('Unable to rollback. E = ' . $e->getMessage());
                    }

                    $stepFailed = true;
                }

                $upgradeStep->lastTryDate = $this->date->parse()->format('U');
                $upgradeStep->save();

                // Commit the default connection to ensure we persist this upgrade step status change.
                $this->store->commitIfNecessary();

                // if we are a step that updates the version table, then exit
                if ($upgradeStep->type == 'sql' && stripos($upgradeStep->action, 'SET `DBVersion`'))
                    $previousStepSetsDbVersion = true;

                if ($stepFailed)
                    throw new ConfigurationException('Unable to run upgrade step. Aborting Maintenance Task.');
            }

            $this->runMessage .= '#' . __('Upgrade Complete') . PHP_EOL . PHP_EOL;
        }
    }

    /**
     * Tidy the DB logs
     */
    private function tidyLogs()
    {
        $this->runMessage .= '## ' . __('Tidy Logs') . PHP_EOL;

        if ($this->config->GetSetting('MAINTENANCE_LOG_MAXAGE') != 0) {

            $maxage = date('Y-m-d H:i:s', time() - (86400 * intval($this->config->GetSetting('MAINTENANCE_LOG_MAXAGE'))));

            try {
                $this->store->update('DELETE FROM `log` WHERE logdate < :maxage', ['maxage' => $maxage]);

                $this->runMessage .= ' - ' . __('Done.') . PHP_EOL . PHP_EOL;
            }
            catch (\PDOException $e) {
                $this->runMessage .= ' - ' . __('Error.') . PHP_EOL . PHP_EOL;
{'fraction_non_alphanumeric': 0.13538002345165762, 'fraction_numerical': 0.0029847564225562308, 'mean_word_length': 1.552925170068027, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 117, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6416468', 'n_tokens_mistral': 2687, 'n_tokens_neox': 2455, 'n_words': 559}