]> git.mxchange.org Git - friendica.git/blob - src/Worker/Cron.php
Delivery of reshares
[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()
21         {
22                 $a = BaseObject::getApp();
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 discover global contacts in the background
42                 Worker::add(PRIORITY_LOW, "DiscoverPoCo");
43
44                 // run the process to update locally stored global contacts in the background
45                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "checkcontact");
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, "DiscoverPoCo", "update_server");
77
78                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "suggestions");
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                         Config::set('system', 'last_expire_day', $d2);
88                 }
89
90                 // Hourly cron calls
91                 if (Config::get('system', 'last_cron_hourly', 0) + 3600 < time()) {
92
93                         // Delete all done workerqueue entries
94                         DBA::delete('workerqueue', ['`done` AND `executed` < UTC_TIMESTAMP() - INTERVAL 1 HOUR']);
95
96                         // Optimizing this table only last seconds
97                         if (Config::get('system', 'optimize_workerqueue', false)) {
98                                 DBA::e("OPTIMIZE TABLE `workerqueue`");
99                         }
100
101                         Config::set('system', 'last_cron_hourly', time());
102                 }
103
104                 // Ensure to have a .htaccess file.
105                 // this is a precaution for systems that update automatically
106                 $basepath = $a->getBasePath();
107                 if (!file_exists($basepath . '/.htaccess') && is_writable($basepath)) {
108                         copy($basepath . '/.htaccess-dist', $basepath . '/.htaccess');
109                 }
110
111                 // Poll contacts
112                 self::pollContacts();
113
114                 // Update contact information
115                 self::updatePublicContacts();
116
117                 Logger::log('cron: end');
118
119                 Config::set('system', 'last_cron', time());
120
121                 return;
122         }
123
124         /**
125          * @brief Update public contacts
126          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127          */
128         private static function updatePublicContacts() {
129                 $count = 0;
130                 $last_updated = DateTimeFormat::utc('now - 1 week');
131                 $condition = ["`network` IN (?, ?, ?, ?) AND `uid` = ? AND NOT `self` AND `last-update` < ?",
132                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, 0, $last_updated];
133
134                 $total = DBA::count('contact', $condition);
135                 $oldest_date = '';
136                 $oldest_id = '';
137                 $contacts = DBA::select('contact', ['id', 'last-update'], $condition, ['limit' => 100, 'order' => ['last-update']]);
138                 while ($contact = DBA::fetch($contacts)) {
139                         if (empty($oldest_id)) {
140                                 $oldest_id = $contact['id'];
141                                 $oldest_date = $contact['last-update'];
142                         }
143                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], 'force');
144                         ++$count;
145                 }
146                 Logger::info('Initiated update for public contacts', ['interval' => $count, 'total' => $total, 'id' => $oldest_id, 'oldest' => $oldest_date]);
147                 DBA::close($contacts);
148         }
149
150         /**
151          * @brief Poll contacts for unreceived messages
152          *
153          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154          */
155         private static function pollContacts() {
156                 $min_poll_interval = Config::get('system', 'min_poll_interval', 1);
157
158                 Addon::reload();
159
160                 $sql = "SELECT `contact`.`id`, `contact`.`nick`, `contact`.`name`, `contact`.`network`, `contact`.`archive`,
161                                         `contact`.`last-update`, `contact`.`priority`, `contact`.`rel`, `contact`.`subhub`
162                                 FROM `user`
163                                 STRAIGHT_JOIN `contact`
164                                 ON `contact`.`uid` = `user`.`uid` AND `contact`.`poll` != ''
165                                         AND `contact`.`network` IN (?, ?, ?, ?)
166                                         AND NOT `contact`.`self` AND NOT `contact`.`blocked`
167                                         AND `contact`.`rel` != ?
168                                 WHERE NOT `user`.`account_expired` AND NOT `user`.`account_removed`";
169
170                 $parameters = [Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Contact::FOLLOWER];
171
172                 // Only poll from those with suitable relationships,
173                 // and which have a polling address and ignore Diaspora since
174                 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
175                 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
176                 if ($abandon_days < 1) {
177                         $abandon_days = 0;
178                 }
179
180                 if (!empty($abandon_days)) {
181                         $sql .= " AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL ? DAY";
182                         $parameters[] = $abandon_days;
183                 }
184
185                 $contacts = DBA::p($sql, $parameters);
186
187                 if (!DBA::isResult($contacts)) {
188                         return;
189                 }
190
191                 while ($contact = DBA::fetch($contacts)) {
192                         // Friendica and OStatus are checked once a day
193                         if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
194                                 $contact['priority'] = 3;
195                         }
196
197                         // Check archived contacts once a month
198                         if ($contact['archive']) {
199                                 $contact['priority'] = 5;
200                         }
201
202                         if ($contact['priority'] >= 0) {
203                                 $update = false;
204
205                                 $t = $contact['last-update'];
206
207                                 /*
208                                  * Based on $contact['priority'], should we poll this site now? Or later?
209                                  */
210                                 switch ($contact['priority']) {
211                                         case 5:
212                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 month")) {
213                                                         $update = true;
214                                                 }
215                                                 break;
216                                         case 4:
217                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 week")) {
218                                                         $update = true;
219                                                 }
220                                                 break;
221                                         case 3:
222                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
223                                                         $update = true;
224                                                 }
225                                                 break;
226                                         case 2:
227                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 12 hour")) {
228                                                         $update = true;
229                                                 }
230                                                 break;
231                                         case 1:
232                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 hour")) {
233                                                         $update = true;
234                                                 }
235                                                 break;
236                                         case 0:
237                                         default:
238                                                 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + " . $min_poll_interval . " minute")) {
239                                                         $update = true;
240                                                 }
241                                                 break;
242                                 }
243                                 if (!$update) {
244                                         continue;
245                                 }
246                         }
247
248                         if (($contact['network'] == Protocol::FEED) && ($contact['priority'] <= 3)) {
249                                 $priority = PRIORITY_MEDIUM;
250                         } elseif ($contact['archive']) {
251                                 $priority = PRIORITY_NEGLIGIBLE;
252                         } else {
253                                 $priority = PRIORITY_LOW;
254                         }
255
256                         Logger::log("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]);
257
258                         Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']);
259                 }
260                 DBA::close($contacts);
261         }
262 }