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