]> git.mxchange.org Git - friendica.git/blob - src/Worker/Cron.php
Merge pull request #8099 from annando/statistics
[friendica.git] / src / Worker / Cron.php
1 <?php
2 /**
3  * @file src/Worker/Cron.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\Core\Addon;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBA;
14 use Friendica\DI;
15 use Friendica\Model\Contact;
16 use Friendica\Util\DateTimeFormat;
17
18 class Cron
19 {
20         public static function execute()
21         {
22                 $a = DI::app();
23
24                 $last = Config::get('system', 'last_cron');
25
26                 $poll_interval = intval(Config::get('system', 'cron_interval'));
27
28                 if ($last) {
29                         $next = $last + ($poll_interval * 60);
30                         if ($next > time()) {
31                                 Logger::log('cron intervall not reached');
32                                 return;
33                         }
34                 }
35
36                 Logger::log('cron: start');
37
38                 // Fork the cron jobs in separate parts to avoid problems when one of them is crashing
39                 Hook::fork($a->queue['priority'], "cron");
40
41                 // run the process to update server directories in the background
42                 Worker::add(PRIORITY_LOW, 'UpdateServerDirectories');
43
44                 // run the process to update locally stored global contacts in the background
45                 Worker::add(PRIORITY_LOW, 'UpdateGContacts');
46
47                 // Expire and remove user entries
48                 Worker::add(PRIORITY_MEDIUM, "CronJobs", "expire_and_remove_users");
49
50                 // Call possible post update functions
51                 Worker::add(PRIORITY_LOW, "CronJobs", "post_update");
52
53                 // Clear cache entries
54                 Worker::add(PRIORITY_LOW, "CronJobs", "clear_cache");
55
56                 // Repair missing Diaspora values in contacts
57                 Worker::add(PRIORITY_LOW, "CronJobs", "repair_diaspora");
58
59                 // Repair entries in the database
60                 Worker::add(PRIORITY_LOW, "CronJobs", "repair_database");
61
62                 // once daily run birthday_updates and then expire in background
63                 $d1 = Config::get('system', 'last_expire_day');
64                 $d2 = intval(DateTimeFormat::utcNow('d'));
65
66                 // Daily cron calls
67                 if ($d2 != intval($d1)) {
68
69                         Worker::add(PRIORITY_LOW, "CronJobs", "update_contact_birthdays");
70
71                         Worker::add(PRIORITY_LOW, "CronJobs", "update_photo_albums");
72
73                         // update nodeinfo data
74                         Worker::add(PRIORITY_LOW, "CronJobs", "nodeinfo");
75
76                         Worker::add(PRIORITY_LOW, 'UpdateGServers');
77
78                         Worker::add(PRIORITY_LOW, 'UpdateSuggestions');
79
80                         Worker::add(PRIORITY_LOW, 'Expire');
81
82                         Worker::add(PRIORITY_MEDIUM, 'DBClean');
83
84                         // check upstream version?
85                         Worker::add(PRIORITY_LOW, 'CheckVersion');
86
87                         self::checkdeletedContacts();
88
89                         Config::set('system', 'last_expire_day', $d2);
90                 }
91
92                 // Hourly cron calls
93                 if (Config::get('system', 'last_cron_hourly', 0) + 3600 < time()) {
94
95                         // Delete all done workerqueue entries
96                         DBA::delete('workerqueue', ['`done` AND `executed` < UTC_TIMESTAMP() - INTERVAL 1 HOUR']);
97
98                         // Optimizing this table only last seconds
99                         if (Config::get('system', 'optimize_workerqueue', false)) {
100                                 DBA::e("OPTIMIZE TABLE `workerqueue`");
101                         }
102
103                         Config::set('system', 'last_cron_hourly', time());
104                 }
105
106                 // Ensure to have a .htaccess file.
107                 // this is a precaution for systems that update automatically
108                 $basepath = $a->getBasePath();
109                 if (!file_exists($basepath . '/.htaccess') && is_writable($basepath)) {
110                         copy($basepath . '/.htaccess-dist', $basepath . '/.htaccess');
111                 }
112
113                 // Poll contacts
114                 self::pollContacts();
115
116                 // Update contact information
117                 self::updatePublicContacts();
118
119                 Logger::log('cron: end');
120
121                 Config::set('system', 'last_cron', time());
122
123                 return;
124         }
125
126         /**
127          * Checks for contacts that are about to be deleted and ensures that they are removed.
128          * This should be done automatically in the "remove" function. This here is a cleanup job.
129          */
130         private static function checkdeletedContacts()
131         {
132                 $contacts = DBA::select('contact', ['id'], ['deleted' => true]);
133                 while ($contact = DBA::fetch($contacts)) {
134                         Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $contact['id']);
135                 }
136                 DBA::close($contacts);
137         }
138
139         /**
140          * @brief Update public contacts
141          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
142          */
143         private static function updatePublicContacts() {
144                 $count = 0;
145                 $last_updated = DateTimeFormat::utc('now - 1 week');
146                 $condition = ["`network` IN (?, ?, ?, ?) AND `uid` = ? AND NOT `self` AND `last-update` < ?",
147                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, 0, $last_updated];
148
149                 $total = DBA::count('contact', $condition);
150                 $oldest_date = '';
151                 $oldest_id = '';
152                 $contacts = DBA::select('contact', ['id', 'last-update'], $condition, ['limit' => 100, 'order' => ['last-update']]);
153                 while ($contact = DBA::fetch($contacts)) {
154                         if (empty($oldest_id)) {
155                                 $oldest_id = $contact['id'];
156                                 $oldest_date = $contact['last-update'];
157                         }
158                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], 'force');
159                         ++$count;
160                 }
161                 Logger::info('Initiated update for public contacts', ['interval' => $count, 'total' => $total, 'id' => $oldest_id, 'oldest' => $oldest_date]);
162                 DBA::close($contacts);
163         }
164
165         /**
166          * @brief Poll contacts for unreceived messages
167          *
168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169          */
170         private static function pollContacts() {
171                 $min_poll_interval = Config::get('system', 'min_poll_interval', 1);
172
173                 Addon::reload();
174
175                 $sql = "SELECT `contact`.`id`, `contact`.`nick`, `contact`.`name`, `contact`.`network`, `contact`.`archive`,
176                                         `contact`.`last-update`, `contact`.`priority`, `contact`.`rel`, `contact`.`subhub`
177                                 FROM `user`
178                                 STRAIGHT_JOIN `contact`
179                                 ON `contact`.`uid` = `user`.`uid` AND `contact`.`poll` != ''
180                                         AND `contact`.`network` IN (?, ?, ?, ?)
181                                         AND NOT `contact`.`self` AND NOT `contact`.`blocked`
182                                         AND `contact`.`rel` != ?
183                                 WHERE NOT `user`.`account_expired` AND NOT `user`.`account_removed`";
184
185                 $parameters = [Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Contact::FOLLOWER];
186
187                 // Only poll from those with suitable relationships,
188                 // and which have a polling address and ignore Diaspora since
189                 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
190                 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
191                 if ($abandon_days < 1) {
192                         $abandon_days = 0;
193                 }
194
195                 if (!empty($abandon_days)) {
196                         $sql .= " AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL ? DAY";
197                         $parameters[] = $abandon_days;
198                 }
199
200                 $contacts = DBA::p($sql, $parameters);
201
202                 if (!DBA::isResult($contacts)) {
203                         return;
204                 }
205
206                 while ($contact = DBA::fetch($contacts)) {
207                         // Friendica and OStatus are checked once a day
208                         if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
209                                 $contact['priority'] = 3;
210                         }
211
212                         // Check archived contacts once a month
213                         if ($contact['archive']) {
214                                 $contact['priority'] = 5;
215                         }
216
217                         if ($contact['priority'] >= 0) {
218                                 $update = false;
219
220                                 $t = $contact['last-update'];
221
222                                 /*
223                                  * Based on $contact['priority'], should we poll this site now? Or later?
224                                  */
225                                 switch ($contact['priority']) {
226                                         case 5:
227                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 month")) {
228                                                         $update = true;
229                                                 }
230                                                 break;
231                                         case 4:
232                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 week")) {
233                                                         $update = true;
234                                                 }
235                                                 break;
236                                         case 3:
237                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
238                                                         $update = true;
239                                                 }
240                                                 break;
241                                         case 2:
242                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 12 hour")) {
243                                                         $update = true;
244                                                 }
245                                                 break;
246                                         case 1:
247                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 hour")) {
248                                                         $update = true;
249                                                 }
250                                                 break;
251                                         case 0:
252                                         default:
253                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + " . $min_poll_interval . " minute")) {
254                                                         $update = true;
255                                                 }
256                                                 break;
257                                 }
258                                 if (!$update) {
259                                         continue;
260                                 }
261                         }
262
263                         if (($contact['network'] == Protocol::FEED) && ($contact['priority'] <= 3)) {
264                                 $priority = PRIORITY_MEDIUM;
265                         } elseif ($contact['archive']) {
266                                 $priority = PRIORITY_NEGLIGIBLE;
267                         } else {
268                                 $priority = PRIORITY_LOW;
269                         }
270
271                         Logger::log("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]);
272
273                         Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']);
274                 }
275                 DBA::close($contacts);
276         }
277 }