3 * @file src/worker/CronJobs.php
5 namespace Friendica\Worker;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Core\Protocol;
11 use Friendica\Core\StorageManager;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBA;
14 use Friendica\Database\PostUpdate;
16 use Friendica\Model\Contact;
17 use Friendica\Model\GContact;
18 use Friendica\Model\GServer;
19 use Friendica\Model\Nodeinfo;
20 use Friendica\Model\Photo;
21 use Friendica\Model\User;
22 use Friendica\Network\Probe;
23 use Friendica\Util\Network;
24 use Friendica\Util\Proxy as ProxyUtils;
25 use Friendica\Util\Strings;
29 public static function execute($command = '')
33 // No parameter set? So return
38 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
46 Logger::info('cron_start');
48 // Now trying to register
49 $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHostname();
50 Logger::debug('Check registering url', ['url' => $url]);
51 $ret = Network::fetchUrl($url);
52 Logger::debug('Check registering answer', ['answer' => $ret]);
53 Logger::info('cron_end');
56 case 'expire_and_remove_users':
57 self::expireAndRemoveUsers();
60 case 'update_contact_birthdays':
61 Contact::updateBirthdays();
64 case 'update_photo_albums':
65 self::updatePhotoAlbums();
72 case 'repair_diaspora':
73 self::repairDiaspora($a);
76 case 'repair_database':
77 self::repairDatabase();
85 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
92 * @brief Update the cached values for the number of photo albums per user
94 private static function updatePhotoAlbums()
96 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
97 if (!DBA::isResult($r)) {
101 foreach ($r as $user) {
102 Photo::clearAlbumCache($user['uid']);
107 * @brief Expire and remove user entries
109 private static function expireAndRemoveUsers()
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);
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']);
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]);
130 DBA::delete('user', ['uid' => $user['uid']]);
135 * @brief Clear cache entries
138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
140 private static function clearCache(App $a)
142 $last = Config::get('system', 'cache_last_cleared');
145 $next = $last + (3600); // Once per hour
146 $clear_cache = ($next <= time());
156 DI::cache()->clear();
158 // clear old item cache files
161 // clear cache for photos
162 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
164 // clear smarty cache
165 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
167 // clear cache for image proxy
168 if (!Config::get("system", "proxy_disabled")) {
169 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
171 $cachetime = Config::get('system', 'proxy_cache_time');
174 $cachetime = ProxyUtils::DEFAULT_TIME;
177 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
178 Photo::delete($condition);
181 // Delete the cached OEmbed entries that are older than three month
182 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
184 // Delete the cached "parse_url" entries that are older than three month
185 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
187 // Maximum table size in megabyte
188 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
189 if ($max_tablesize == 0) {
190 $max_tablesize = 100 * 1000000; // Default are 100 MB
192 if ($max_tablesize > 0) {
193 // Minimum fragmentation level in percent
194 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
195 if ($fragmentation_level == 0) {
196 $fragmentation_level = 0.3; // Default value is 30%
199 // Optimize some tables that need to be optimized
200 $r = q("SHOW TABLE STATUS");
201 foreach ($r as $table) {
203 // Don't optimize tables that are too large
204 if ($table["Data_length"] > $max_tablesize) {
208 // Don't optimize empty tables
209 if ($table["Data_length"] == 0) {
213 // Calculate fragmentation
214 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
216 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
218 // Don't optimize tables that needn't to be optimized
219 if ($fragmentation < $fragmentation_level) {
224 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
225 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
229 Config::set('system', 'cache_last_cleared', time());
233 * @brief Repair missing values in Diaspora contacts
236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237 * @throws \ImagickException
239 private static function repairDiaspora(App $a)
243 $r = q("SELECT `id`, `url` FROM `contact`
244 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
245 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
246 if (!DBA::isResult($r)) {
250 foreach ($r as $contact) {
251 // Quit the loop after 3 minutes
252 if (time() > ($starttime + 180)) {
256 if (!GServer::reachable($contact["url"])) {
260 $data = Probe::uri($contact["url"]);
261 if ($data["network"] != Protocol::DIASPORA) {
265 Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
266 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
267 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
268 intval($contact["id"]));
273 * @brief Do some repairs in database entries
276 private static function repairDatabase()
278 // Sometimes there seem to be issues where the "self" contact vanishes.
279 // We haven't found the origin of the problem by now.
280 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
281 if (DBA::isResult($r)) {
282 foreach ($r AS $user) {
283 Logger::log('Create missing self contact for user ' . $user['uid']);
284 Contact::createSelfFromUserId($user['uid']);
288 // There was an issue where the nick vanishes from the contact table
289 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
291 // Update the global contacts for local users
292 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
293 if (DBA::isResult($r)) {
294 foreach ($r AS $user) {
295 GContact::updateForUser($user["uid"]);
300 /// - remove thread entries without item
301 /// - remove sign entries without item
302 /// - remove children when parent got lost
303 /// - set contact-id in item when not present
305 // Add intro entries for pending contacts
306 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
307 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
308 WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
309 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
310 0, Contact::FOLLOWER, Protocol::DFRN);
311 while ($contact = DBA::fetch($pending_contacts)) {
312 DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
313 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
315 DBA::close($pending_contacts);
319 * Moves up to 5000 attachments and photos to the current storage system.
320 * Self-replicates if legacy items have been found and moved.
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 private static function moveStorage()
326 $current = StorageManager::getBackend();
327 $moved = StorageManager::move($current);
330 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");