]> git.mxchange.org Git - friendica.git/blob - src/Worker/CronJobs.php
Merge pull request #6209 from MrPetovan/task/move-config-to-php-array
[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\Database\DBA;
14 use Friendica\Database\PostUpdate;
15 use Friendica\Model\Contact;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Photo;
18 use Friendica\Model\User;
19 use Friendica\Network\Probe;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Util\Proxy as ProxyUtils;
22
23 require_once 'mod/nodeinfo.php';
24
25 class CronJobs
26 {
27         public static function execute($command = '')
28         {
29                 $a = BaseObject::getApp();
30
31                 // No parameter set? So return
32                 if ($command == '') {
33                         return;
34                 }
35
36                 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
37
38                 // Call possible post update functions
39                 // see src/Database/PostUpdate.php for more details
40                 if ($command == 'post_update') {
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::log("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 (!DBA::isResult($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", DBA::NULL_DATETIME];
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() "]);
122                 while ($user = DBA::fetch($users)) {
123                         // Delete the contacts of this user
124                         $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
125                         if (DBA::isResult($self)) {
126                                 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
127                         }
128
129                         DBA::delete('user', ['uid' => $user['uid']]);
130                 }
131         }
132
133         /**
134          * @brief Clear cache entries
135          *
136          * @param App $a
137          */
138         private static function clearCache(App $a)
139         {
140                 $last = Config::get('system', 'cache_last_cleared');
141
142                 if ($last) {
143                         $next = $last + (3600); // Once per hour
144                         $clear_cache = ($next <= time());
145                 } else {
146                         $clear_cache = true;
147                 }
148
149                 if (!$clear_cache) {
150                         return;
151                 }
152
153                 // clear old cache
154                 Cache::clear();
155
156                 // clear old item cache files
157                 clear_cache();
158
159                 // clear cache for photos
160                 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
161
162                 // clear smarty cache
163                 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
164
165                 // clear cache for image proxy
166                 if (!Config::get("system", "proxy_disabled")) {
167                         clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
168
169                         $cachetime = Config::get('system', 'proxy_cache_time');
170
171                         if (!$cachetime) {
172                                 $cachetime = ProxyUtils::DEFAULT_TIME;
173                         }
174
175                         $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
176                         DBA::delete('photo', $condition);
177                 }
178
179                 // Delete the cached OEmbed entries that are older than three month
180                 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
181
182                 // Delete the cached "parse_url" entries that are older than three month
183                 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
184
185                 // Maximum table size in megabyte
186                 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
187                 if ($max_tablesize == 0) {
188                         $max_tablesize = 100 * 1000000; // Default are 100 MB
189                 }
190                 if ($max_tablesize > 0) {
191                         // Minimum fragmentation level in percent
192                         $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
193                         if ($fragmentation_level == 0) {
194                                 $fragmentation_level = 0.3; // Default value is 30%
195                         }
196
197                         // Optimize some tables that need to be optimized
198                         $r = q("SHOW TABLE STATUS");
199                         foreach ($r as $table) {
200
201                                 // Don't optimize tables that are too large
202                                 if ($table["Data_length"] > $max_tablesize) {
203                                         continue;
204                                 }
205
206                                 // Don't optimize empty tables
207                                 if ($table["Data_length"] == 0) {
208                                         continue;
209                                 }
210
211                                 // Calculate fragmentation
212                                 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
213
214                                 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
215
216                                 // Don't optimize tables that needn't to be optimized
217                                 if ($fragmentation < $fragmentation_level) {
218                                         continue;
219                                 }
220
221                                 // So optimize it
222                                 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
223                                 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
224                         }
225                 }
226
227                 Config::set('system', 'cache_last_cleared', time());
228         }
229
230         /**
231          * @brief Repair missing values in Diaspora contacts
232          *
233          * @param App $a
234          */
235         private static function repairDiaspora(App $a)
236         {
237                 $starttime = time();
238
239                 $r = q("SELECT `id`, `url` FROM `contact`
240                         WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
241                                 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
242                 if (!DBA::isResult($r)) {
243                         return;
244                 }
245
246                 foreach ($r as $contact) {
247                         // Quit the loop after 3 minutes
248                         if (time() > ($starttime + 180)) {
249                                 return;
250                         }
251
252                         if (!PortableContact::reachable($contact["url"])) {
253                                 continue;
254                         }
255
256                         $data = Probe::uri($contact["url"]);
257                         if ($data["network"] != Protocol::DIASPORA) {
258                                 continue;
259                         }
260
261                         Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
262                         q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
263                                 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
264                                 intval($contact["id"]));
265                 }
266         }
267
268         /**
269          * @brief Do some repairs in database entries
270          *
271          */
272         private static function repairDatabase()
273         {
274                 // Sometimes there seem to be issues where the "self" contact vanishes.
275                 // We haven't found the origin of the problem by now.
276                 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
277                 if (DBA::isResult($r)) {
278                         foreach ($r AS $user) {
279                                 Logger::log('Create missing self contact for user ' . $user['uid']);
280                                 Contact::createSelfFromUserId($user['uid']);
281                         }
282                 }
283
284                 // There was an issue where the nick vanishes from the contact table
285                 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
286
287                 // Update the global contacts for local users
288                 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
289                 if (DBA::isResult($r)) {
290                         foreach ($r AS $user) {
291                                 GContact::updateForUser($user["uid"]);
292                         }
293                 }
294
295                 /// @todo
296                 /// - remove thread entries without item
297                 /// - remove sign entries without item
298                 /// - remove children when parent got lost
299                 /// - set contact-id in item when not present
300         }
301 }