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