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