]> git.mxchange.org Git - friendica.git/blob - src/Worker/CronJobs.php
Improved dba calls
[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                         $condition = array('`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime);
159                         dba::delete('photo', $condition);
160                 }
161
162                 // Delete the cached OEmbed entries that are older than three month
163                 dba::delete('oembed', array("`created` < NOW() - INTERVAL 3 MONTH"));
164
165                 // Delete the cached "parse_url" entries that are older than three month
166                 dba::delete('parsed_url', array("`created` < NOW() - INTERVAL 3 MONTH"));
167
168                 // Maximum table size in megabyte
169                 $max_tablesize = intval(Config::get('system','optimize_max_tablesize')) * 1000000;
170                 if ($max_tablesize == 0) {
171                         $max_tablesize = 100 * 1000000; // Default are 100 MB
172                 }
173                 if ($max_tablesize > 0) {
174                         // Minimum fragmentation level in percent
175                         $fragmentation_level = intval(Config::get('system','optimize_fragmentation')) / 100;
176                         if ($fragmentation_level == 0) {
177                                 $fragmentation_level = 0.3; // Default value is 30%
178                         }
179
180                         // Optimize some tables that need to be optimized
181                         $r = q("SHOW TABLE STATUS");
182                         foreach ($r as $table) {
183
184                                 // Don't optimize tables that are too large
185                                 if ($table["Data_length"] > $max_tablesize) {
186                                         continue;
187                                 }
188
189                                 // Don't optimize empty tables
190                                 if ($table["Data_length"] == 0) {
191                                         continue;
192                                 }
193
194                                 // Calculate fragmentation
195                                 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
196
197                                 logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
198
199                                 // Don't optimize tables that needn't to be optimized
200                                 if ($fragmentation < $fragmentation_level) {
201                                         continue;
202                                 }
203
204                                 // So optimize it
205                                 logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
206                                 q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
207                         }
208                 }
209
210                 Config::set('system','cache_last_cleared', time());
211         }
212
213         /**
214          * @brief Repair missing values in Diaspora contacts
215          *
216          * @param App $a
217          */
218         private static function repairDiaspora(App $a) {
219
220                 $starttime = time();
221
222                 $r = q("SELECT `id`, `url` FROM `contact`
223                         WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
224                                 ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
225                 if (!DBM::is_result($r)) {
226                         return;
227                 }
228
229                 foreach ($r AS $contact) {
230                         // Quit the loop after 3 minutes
231                         if (time() > ($starttime + 180)) {
232                                 return;
233                         }
234
235                         if (!PortableContact::reachable($contact["url"])) {
236                                 continue;
237                         }
238
239                         $data = Probe::uri($contact["url"]);
240                         if ($data["network"] != NETWORK_DIASPORA) {
241                                 continue;
242                         }
243
244                         logger("Repair contact ".$contact["id"]." ".$contact["url"], LOGGER_DEBUG);
245                         q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
246                                 dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
247                                 intval($contact["id"]));
248                 }
249         }
250
251         /**
252          * @brief Do some repairs in database entries
253          *
254          */
255         private static function repairDatabase() {
256
257                 // Sometimes there seem to be issues where the "self" contact vanishes.
258                 // We haven't found the origin of the problem by now.
259                 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
260                 if (DBM::is_result($r)) {
261                         foreach ($r AS $user) {
262                                 logger('Create missing self contact for user '.$user['uid']);
263                                 user_create_self_contact($user['uid']);
264                         }
265                 }
266
267                 // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
268                 // This call is very "cheap" so we can do it at any time without a problem
269                 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");
270
271                 // There was an issue where the nick vanishes from the contact table
272                 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
273
274                 // Update the global contacts for local users
275                 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
276                 if (DBM::is_result($r)) {
277                         foreach ($r AS $user) {
278                                 GlobalContact::updateForUser($user["uid"]);
279                         }
280                 }
281
282                 /// @todo
283                 /// - remove thread entries without item
284                 /// - remove sign entries without item
285                 /// - remove children when parent got lost
286                 /// - set contact-id in item when not present
287         }
288 }