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