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