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