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