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