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