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