AutoCron.php 8.26 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 8/18/17
 * Time: 8:49 AM
 */

namespace qfq;

use qfq;

require_once(__DIR__ . '/../qfq/store/Store.php');
require_once(__DIR__ . '/../qfq/Constants.php');
require_once(__DIR__ . '/../qfq/database/Database.php');
require_once(__DIR__ . '/../qfq/exceptions/ShellException.php');
17
18
require_once(__DIR__ . '/../qfq/Evaluate.php');
require_once(__DIR__ . '/../qfq/report/Sendmail.php');
19
20
21
22
23
24
25
26
27
28
29
30
31

class AutoCron {

    /**
     * @var Database instantiated class
     */
    protected $db = null;

    /**
     * @var Store
     */
    protected $store = null;

32
33
34
35
36
    /**
     * @var Evaluate
     */
    protected $evaluate = null;

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    /**
     * @var bool
     */
    private $phpUnit = false;

    public function __construct($phpUnit = false) {

        $this->phpUnit = $phpUnit;

        mb_internal_encoding("UTF-8");

//        set_error_handler("\\qfq\\ErrorHandler::exception_error_handler");

        $this->store = Store::getInstance();
        $this->db = new Database();
52
        $this->evaluate = new Evaluate($this->store, $this->db);
53
54
55
56
57
58
    }

    /**
     * Check if there started cronJobs, older than $ageMaxMinutes
     *
     * @param int $ageMaxMinutes
Carsten  Rose's avatar
Carsten Rose committed
59
     *
60
61
62
63
64
65
66
67
68
69
     * @throws CodeException
     * @throws DbException
     */
    private function checkForOldJobs($ageMaxMinutes) {
        $sql = "SELECT c.id, ' Started at: ', c.inProgress FROM Cron AS c WHERE DATE_ADD(c.inProgress, INTERVAL $ageMaxMinutes MINUTE)<NOW()";
        $this->db->sql($sql, ROW_EXPECT_0);
    }

    /**
     * @param array $job
Carsten  Rose's avatar
Carsten Rose committed
70
     *
71
72
73
74
75
76
77
78
79
80
81
82
83
84
     * @return array
     * @throws CodeException
     * @throws DbException
     */
    private function calcNextRun(array $job) {

        // If nextRun is already in the future, do nothing.
        if (date('Y-m-d H:i:s') < $job[AUTOCRON_NEXT_RUN]) {
            return $job;
        }

        // With no frequency: stop future repeating by setting nextRun=0
        if ($job[AUTOCRON_FREQUENCY] == '') {
            $job[AUTOCRON_NEXT_RUN] = 0;
Carsten  Rose's avatar
Carsten Rose committed
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
            return $job;
        }

        // '1 DAY', '15 MINUTE', '6 MONTH', or empty
        $job[AUTOCRON_FREQUENCY] = trim($job[AUTOCRON_FREQUENCY]);

        $arr = explode(' ', $job[AUTOCRON_FREQUENCY]);
        $count = empty($arr[0]) ? '1' : $arr[0];
        $unit = empty($arr[1]) ? 'DAY' : $arr[1];

        // Regular: nextRun is in the past and +frequency is in the future
        // Late:   nextRun is so much behind that +frequency is still in the past. Calculate nextRun for the future with respect to the given shedule/frequency (skip lost past actions)
        // Do the calculation with MySQL to stay in the MySQL date/time calculation world.
        $sql = "SELECT DATE_ADD('" . $job[AUTOCRON_NEXT_RUN] . "', INTERVAL CEILING( ( 1 + TIMESTAMPDIFF($unit, '" .
            $job[AUTOCRON_NEXT_RUN] . "', NOW() ) ) / $count ) * " . $job[AUTOCRON_FREQUENCY] . ") AS " . AUTOCRON_NEXT_RUN;
101
        $row = $this->db->sql($sql, ROW_EXPECT_1);  // frequency, nextRun, unit, count
102
103
104
105
106
107
108

        $job[AUTOCRON_NEXT_RUN] = $row[AUTOCRON_NEXT_RUN];

        return $job;
    }

    /**
109
110
     * Calls the Webpage given in $job[AUTOCRON_CONTENT].
     *
111
     * @param array $job
Carsten  Rose's avatar
Carsten Rose committed
112
     *
113
     * @return array $job, updated with AUTOCRON_LAST_STATUS
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
     */
    private function doJobWebsite(array $job) {

        $job[AUTOCRON_LAST_STATUS] = 'nothing done';
        $job[AUTOCRON_CONTENT] = trim($job[AUTOCRON_CONTENT]);
        if (!empty($job[AUTOCRON_CONTENT])) {
            if (substr($job[AUTOCRON_CONTENT], 0, 4) != 'http') {
                // We need to prefix
                $baseUrl = $this->store->getVar(SYSTEM_BASE_URL_PRINT, STORE_SYSTEM);
                $job[AUTOCRON_CONTENT] = $baseUrl . $job[AUTOCRON_CONTENT];
            }

            // Download page
            $page = file_get_contents($job[AUTOCRON_CONTENT]);
            if ($page === false) {
                $job[AUTOCRON_LAST_STATUS] = 'Error: failed to fetch ' . $job[AUTOCRON_CONTENT];
            } else {
                $job[AUTOCRON_LAST_STATUS] = 'OK: ' . substr($page, 0, 30);
            }
        }

        return $job;
    }

    /**
139
     * @param array $mailEntry
Carsten  Rose's avatar
Carsten Rose committed
140
     *
141
142
143
144
     * @return array
     */
    private function mailEntryFill(array $mailEntry) {
        foreach ([FE_SENDMAIL_TO, FE_SENDMAIL_CC, FE_SENDMAIL_BCC, FE_SENDMAIL_FROM, FE_SENDMAIL_SUBJECT,
145
146
                     FE_SENDMAIL_REPLY_TO, FE_SENDMAIL_FLAG_AUTO_SUBMIT, FE_SENDMAIL_GR_ID, FE_SENDMAIL_X_ID,
                     FE_SENDMAIL_X_ID2, FE_SENDMAIL_X_ID3] as $key) {
147
148
149
150
            if (!isset($mailEntry[$key])) {
                $mailEntry[$key] = '';
            }
        }
Carsten  Rose's avatar
Carsten Rose committed
151

152
153
154
155
156
157
158
159
        return $mailEntry;
    }

    /**
     * Send as many emails as $job[AUTOCRON_SQL1] has records.
     * Do not send mails if: no record OR no receiver OR empty body
     *
     * @param array $job
Carsten  Rose's avatar
Carsten Rose committed
160
     *
161
162
163
164
165
166
167
168
169
     * @return array $job, updated with AUTOCRON_LAST_STATUS
     */
    private function doJobMail(array $job) {

        $mailArr = $this->evaluate->parse($job[AUTOCRON_SQL1]);

        $mailsSent = 0;
        foreach ($mailArr as $mailEntry) {

170
171
            $this->store->setStore($mailEntry, STORE_PARENT_RECORD, true);

172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
            $mailEntry = $this->mailEntryFill($mailEntry);

            $content = $this->evaluate->parse($job[AUTOCRON_CONTENT]);
            if ($content == '' OR ($mailEntry[FE_SENDMAIL_TO] == '' AND $mailEntry[FE_SENDMAIL_CC] == '' AND $mailEntry[FE_SENDMAIL_BCC] == '')) {
                continue; // no receiver: skip
            }
            $mail[SENDMAIL_IDX_RECEIVER] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_TO]);
            $mail[SENDMAIL_IDX_SENDER] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_FROM]);
            $mail[SENDMAIL_IDX_SUBJECT] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_SUBJECT]);
            $mail[SENDMAIL_IDX_BODY] = $content;
            $mail[SENDMAIL_IDX_REPLY_TO] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_REPLY_TO]);
            $mail[SENDMAIL_IDX_FLAG_AUTO_SUBMIT] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_FLAG_AUTO_SUBMIT]) === 'off' ? 'off' : 'on';
            $mail[SENDMAIL_IDX_GR_ID] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_GR_ID]);
            $mail[SENDMAIL_IDX_X_ID] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID]);
            $mail[SENDMAIL_IDX_RECEIVER_CC] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_CC]);
            $mail[SENDMAIL_IDX_RECEIVER_BCC] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_BCC]);
188
189
190
            $mail[SENDMAIL_IDX_X_ID2] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID2]);
            $mail[SENDMAIL_IDX_X_ID3] = $this->evaluate->parse($mailEntry[FE_SENDMAIL_X_ID3]);

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            $mail[SENDMAIL_IDX_SRC] = "AutoCron: Cron.id=" . $job[COLUMN_ID];

            // Mail: send
            new Sendmail($mail);
            $mailsSent++;
        }

        $job[AUTOCRON_LAST_STATUS] = "OK: $mailsSent mails sent";

        return $job;
    }

    /**
     * Iterates over all AutoCron jobs and fire pending.
     *
206
207
208
209
     * @throws CodeException
     * @throws DbException
     */
    public function process() {
210
211

        // Select pending jobs
212
        $sql = "SELECT * FROM Cron AS c WHERE c.status='enable' AND c.nextRun < NOW() AND c.nextRun!=0 AND c.inProgress=0";
213
214
215
216
217
        $jobs = $this->db->sql($sql);

        // Iterate over all AutoCron Jobs
        foreach ($jobs as $job) {

218
219
            $this->store->setStore($job, STORE_PARENT_RECORD, true);

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
            // Start progress counter
            $this->db->sql("UPDATE Cron SET inProgress=NOW() WHERE id=? LIMIT 1", ROW_REGULAR, [$job[COLUMN_ID]]);

            switch ($job[AUTOCRON_TYPE]) {
                case AUTOCRON_TYPE_WEBSITE:
                    $job = $this->doJobWebsite($job);
                    break;
                case AUTOCRON_TYPE_MAIL:
                    $job = $this->doJobMail($job);
                    break;
                default:
                    throw new ShellException('Unknown cron.type value: ' . $job[AUTOCRON_TYPE], ERROR_UNKNOWN_MODE);
            }

            // Finish Job
            $job = $this->calcNextRun($job);
            $sql = "UPDATE Cron SET lastRun=NOW(), lastStatus=?, nextRun=?, inProgress=0 WHERE id=? LIMIT 1";
            $this->db->sql($sql, ROW_REGULAR, [$job[AUTOCRON_LAST_STATUS], $job[AUTOCRON_NEXT_RUN], $job[COLUMN_ID]]);
        }

        $this->checkForOldJobs(AUTOCRON_MAX_AGE_MINUTES);
    }
}