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