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