]> git.mxchange.org Git - friendica.git/blob - src/Worker/CronJobs.php
New page for remote follow requests
[friendica.git] / src / Worker / CronJobs.php
1 <?php
2 /**
3  * @file src/worker/CronJobs.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\App;
8 use Friendica\Core\Logger;
9 use Friendica\Core\Protocol;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBA;
12 use Friendica\Database\PostUpdate;
13 use Friendica\DI;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\GServer;
17 use Friendica\Model\Nodeinfo;
18 use Friendica\Model\Photo;
19 use Friendica\Model\User;
20 use Friendica\Network\Probe;
21 use Friendica\Util\Network;
22 use Friendica\Util\Proxy as ProxyUtils;
23 use Friendica\Util\Strings;
24
25 class CronJobs
26 {
27         public static function execute($command = '')
28         {
29                 $a = DI::app();
30
31                 // No parameter set? So return
32                 if ($command == '') {
33                         return;
34                 }
35
36                 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
37
38                 switch($command) {
39                         case 'post_update':
40                                 PostUpdate::update();
41                                 break;
42
43                         case 'nodeinfo':
44                                 Logger::info('cron_start');
45                                 Nodeinfo::update();
46                                 // Now trying to register
47                                 $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHostname();
48                                 Logger::debug('Check registering url', ['url' => $url]);
49                                 $ret = Network::fetchUrl($url);
50                                 Logger::debug('Check registering answer', ['answer' => $ret]);
51                                 Logger::info('cron_end');
52                                 break;
53
54                         case 'expire_and_remove_users':
55                                 self::expireAndRemoveUsers();
56                                 break;
57
58                         case 'update_contact_birthdays':
59                                 Contact::updateBirthdays();
60                                 break;
61
62                         case 'update_photo_albums':
63                                 self::updatePhotoAlbums();
64                                 break;
65
66                         case 'clear_cache':
67                                 self::clearCache($a);
68                                 break;
69
70                         case 'repair_diaspora':
71                                 self::repairDiaspora($a);
72                                 break;
73
74                         case 'repair_database':
75                                 self::repairDatabase();
76                                 break;
77
78                         case 'move_storage':
79                                 self::moveStorage();
80                                 break;
81
82                         default:
83                                 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
84                 }
85
86                 return;
87         }
88
89         /**
90          * Update the cached values for the number of photo albums per user
91          */
92         private static function updatePhotoAlbums()
93         {
94                 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
95                 if (!DBA::isResult($r)) {
96                         return;
97                 }
98
99                 foreach ($r as $user) {
100                         Photo::clearAlbumCache($user['uid']);
101                 }
102         }
103
104         /**
105          * Expire and remove user entries
106          */
107         private static function expireAndRemoveUsers()
108         {
109                 // expire any expired regular accounts. Don't expire forums.
110                 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
111                 DBA::update('user', ['account_expired' => true], $condition);
112
113                 // Remove any freshly expired account
114                 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
115                 while ($user = DBA::fetch($users)) {
116                         User::remove($user['uid']);
117                 }
118
119                 // delete user records for recently removed accounts
120                 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
121                 while ($user = DBA::fetch($users)) {
122                         // Delete the contacts of this user
123                         $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
124                         if (DBA::isResult($self)) {
125                                 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
126                         }
127
128                         DBA::delete('user', ['uid' => $user['uid']]);
129                 }
130         }
131
132         /**
133          * Clear cache entries
134          *
135          * @param App $a
136          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
137          */
138         private static function clearCache(App $a)
139         {
140                 $last = DI::config()->get('system', 'cache_last_cleared');
141
142                 if ($last) {
143                         $next = $last + (3600); // Once per hour
144                         $clear_cache = ($next <= time());
145                 } else {
146                         $clear_cache = true;
147                 }
148
149                 if (!$clear_cache) {
150                         return;
151                 }
152
153                 // clear old cache
154                 DI::cache()->clear();
155
156                 // clear old item cache files
157                 clear_cache();
158
159                 // clear cache for photos
160                 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
161
162                 // clear smarty cache
163                 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
164
165                 // clear cache for image proxy
166                 if (!DI::config()->get("system", "proxy_disabled")) {
167                         clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
168
169                         $cachetime = DI::config()->get('system', 'proxy_cache_time');
170
171                         if (!$cachetime) {
172                                 $cachetime = ProxyUtils::DEFAULT_TIME;
173                         }
174
175                         $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
176                         Photo::delete($condition);
177                 }
178
179                 // Delete the cached OEmbed entries that are older than three month
180                 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
181
182                 // Delete the cached "parse_url" entries that are older than three month
183                 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
184
185                 // Maximum table size in megabyte
186                 $max_tablesize = intval(DI::config()->get('system', 'optimize_max_tablesize')) * 1000000;
187                 if ($max_tablesize == 0) {
188                         $max_tablesize = 100 * 1000000; // Default are 100 MB
189                 }
190                 if ($max_tablesize > 0) {
191                         // Minimum fragmentation level in percent
192                         $fragmentation_level = intval(DI::config()->get('system', 'optimize_fragmentation')) / 100;
193                         if ($fragmentation_level == 0) {
194                                 $fragmentation_level = 0.3; // Default value is 30%
195                         }
196
197                         // Optimize some tables that need to be optimized
198                         $r = q("SHOW TABLE STATUS");
199                         foreach ($r as $table) {
200
201                                 // Don't optimize tables that are too large
202                                 if ($table["Data_length"] > $max_tablesize) {
203                                         continue;
204                                 }
205
206                                 // Don't optimize empty tables
207                                 if ($table["Data_length"] == 0) {
208                                         continue;
209                                 }
210
211                                 // Calculate fragmentation
212                                 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
213
214                                 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
215
216                                 // Don't optimize tables that needn't to be optimized
217                                 if ($fragmentation < $fragmentation_level) {
218                                         continue;
219                                 }
220
221                                 // So optimize it
222                                 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
223                                 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
224                         }
225                 }
226
227                 DI::config()->set('system', 'cache_last_cleared', time());
228         }
229
230         /**
231          * Repair missing values in Diaspora contacts
232          *
233          * @param App $a
234          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235          * @throws \ImagickException
236          */
237         private static function repairDiaspora(App $a)
238         {
239                 $starttime = time();
240
241                 $r = q("SELECT `id`, `url` FROM `contact`
242                         WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
243                                 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
244                 if (!DBA::isResult($r)) {
245                         return;
246                 }
247
248                 foreach ($r as $contact) {
249                         // Quit the loop after 3 minutes
250                         if (time() > ($starttime + 180)) {
251                                 return;
252                         }
253
254                         if (!GServer::reachable($contact["url"])) {
255                                 continue;
256                         }
257
258                         $data = Probe::uri($contact["url"]);
259                         if ($data["network"] != Protocol::DIASPORA) {
260                                 continue;
261                         }
262
263                         Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
264                         q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
265                                 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
266                                 intval($contact["id"]));
267                 }
268         }
269
270         /**
271          * Do some repairs in database entries
272          *
273          */
274         private static function repairDatabase()
275         {
276                 // Sometimes there seem to be issues where the "self" contact vanishes.
277                 // We haven't found the origin of the problem by now.
278                 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
279                 if (DBA::isResult($r)) {
280                         foreach ($r AS $user) {
281                                 Logger::log('Create missing self contact for user ' . $user['uid']);
282                                 Contact::createSelfFromUserId($user['uid']);
283                         }
284                 }
285
286                 // There was an issue where the nick vanishes from the contact table
287                 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
288
289                 // Update the global contacts for local users
290                 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
291                 if (DBA::isResult($r)) {
292                         foreach ($r AS $user) {
293                                 GContact::updateForUser($user["uid"]);
294                         }
295                 }
296
297                 /// @todo
298                 /// - remove thread entries without item
299                 /// - remove sign entries without item
300                 /// - remove children when parent got lost
301                 /// - set contact-id in item when not present
302
303                 // Add intro entries for pending contacts
304                 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
305                 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
306                         WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
307                                 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
308                         0, Contact::FOLLOWER, Protocol::DFRN);
309                 while ($contact = DBA::fetch($pending_contacts)) {
310                         DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
311                                 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
312                 }
313                 DBA::close($pending_contacts);
314         }
315
316         /**
317          * Moves up to 5000 attachments and photos to the current storage system.
318          * Self-replicates if legacy items have been found and moved.
319          *
320          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321          */
322         private static function moveStorage()
323         {
324                 $current = DI::storage();
325                 $moved = DI::storageManager()->move($current);
326
327                 if ($moved) {
328                         Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");
329                 }
330         }
331 }