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