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