3 * @file src/worker/CronJobs.php
5 namespace Friendica\Worker;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\StorageManager;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
15 use Friendica\Database\PostUpdate;
17 use Friendica\Model\Contact;
18 use Friendica\Model\GContact;
19 use Friendica\Model\GServer;
20 use Friendica\Model\Nodeinfo;
21 use Friendica\Model\Photo;
22 use Friendica\Model\User;
23 use Friendica\Network\Probe;
24 use Friendica\Util\Network;
25 use Friendica\Util\Proxy as ProxyUtils;
26 use Friendica\Util\Strings;
30 public static function execute($command = '')
34 // No parameter set? So return
39 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
47 Logger::info('cron_start');
49 // Now trying to register
50 $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHostname();
51 Logger::debug('Check registering url', ['url' => $url]);
52 $ret = Network::fetchUrl($url);
53 Logger::debug('Check registering answer', ['answer' => $ret]);
54 Logger::info('cron_end');
57 case 'expire_and_remove_users':
58 self::expireAndRemoveUsers();
61 case 'update_contact_birthdays':
62 Contact::updateBirthdays();
65 case 'update_photo_albums':
66 self::updatePhotoAlbums();
73 case 'repair_diaspora':
74 self::repairDiaspora($a);
77 case 'repair_database':
78 self::repairDatabase();
86 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
93 * @brief Update the cached values for the number of photo albums per user
95 private static function updatePhotoAlbums()
97 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
98 if (!DBA::isResult($r)) {
102 foreach ($r as $user) {
103 Photo::clearAlbumCache($user['uid']);
108 * @brief Expire and remove user entries
110 private static function expireAndRemoveUsers()
112 // expire any expired regular accounts. Don't expire forums.
113 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
114 DBA::update('user', ['account_expired' => true], $condition);
116 // Remove any freshly expired account
117 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
118 while ($user = DBA::fetch($users)) {
119 User::remove($user['uid']);
122 // delete user records for recently removed accounts
123 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
124 while ($user = DBA::fetch($users)) {
125 // Delete the contacts of this user
126 $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
127 if (DBA::isResult($self)) {
128 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
131 DBA::delete('user', ['uid' => $user['uid']]);
136 * @brief Clear cache entries
139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 private static function clearCache(App $a)
143 $last = Config::get('system', 'cache_last_cleared');
146 $next = $last + (3600); // Once per hour
147 $clear_cache = ($next <= time());
159 // clear old item cache files
162 // clear cache for photos
163 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
165 // clear smarty cache
166 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
168 // clear cache for image proxy
169 if (!Config::get("system", "proxy_disabled")) {
170 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
172 $cachetime = Config::get('system', 'proxy_cache_time');
175 $cachetime = ProxyUtils::DEFAULT_TIME;
178 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
179 Photo::delete($condition);
182 // Delete the cached OEmbed entries that are older than three month
183 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
185 // Delete the cached "parse_url" entries that are older than three month
186 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
188 // Maximum table size in megabyte
189 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
190 if ($max_tablesize == 0) {
191 $max_tablesize = 100 * 1000000; // Default are 100 MB
193 if ($max_tablesize > 0) {
194 // Minimum fragmentation level in percent
195 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
196 if ($fragmentation_level == 0) {
197 $fragmentation_level = 0.3; // Default value is 30%
200 // Optimize some tables that need to be optimized
201 $r = q("SHOW TABLE STATUS");
202 foreach ($r as $table) {
204 // Don't optimize tables that are too large
205 if ($table["Data_length"] > $max_tablesize) {
209 // Don't optimize empty tables
210 if ($table["Data_length"] == 0) {
214 // Calculate fragmentation
215 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
217 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
219 // Don't optimize tables that needn't to be optimized
220 if ($fragmentation < $fragmentation_level) {
225 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
226 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
230 Config::set('system', 'cache_last_cleared', time());
234 * @brief Repair missing values in Diaspora contacts
237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 * @throws \ImagickException
240 private static function repairDiaspora(App $a)
244 $r = q("SELECT `id`, `url` FROM `contact`
245 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
246 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
247 if (!DBA::isResult($r)) {
251 foreach ($r as $contact) {
252 // Quit the loop after 3 minutes
253 if (time() > ($starttime + 180)) {
257 if (!GServer::reachable($contact["url"])) {
261 $data = Probe::uri($contact["url"]);
262 if ($data["network"] != Protocol::DIASPORA) {
266 Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
267 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
268 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
269 intval($contact["id"]));
274 * @brief Do some repairs in database entries
277 private static function repairDatabase()
279 // Sometimes there seem to be issues where the "self" contact vanishes.
280 // We haven't found the origin of the problem by now.
281 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
282 if (DBA::isResult($r)) {
283 foreach ($r AS $user) {
284 Logger::log('Create missing self contact for user ' . $user['uid']);
285 Contact::createSelfFromUserId($user['uid']);
289 // There was an issue where the nick vanishes from the contact table
290 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
292 // Update the global contacts for local users
293 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
294 if (DBA::isResult($r)) {
295 foreach ($r AS $user) {
296 GContact::updateForUser($user["uid"]);
301 /// - remove thread entries without item
302 /// - remove sign entries without item
303 /// - remove children when parent got lost
304 /// - set contact-id in item when not present
306 // Add intro entries for pending contacts
307 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
308 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
309 WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
310 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
311 0, Contact::FOLLOWER, Protocol::DFRN);
312 while ($contact = DBA::fetch($pending_contacts)) {
313 DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
314 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
316 DBA::close($pending_contacts);
320 * Moves up to 5000 attachments and photos to the current storage system.
321 * Self-replicates if legacy items have been found and moved.
323 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325 private static function moveStorage()
327 $current = DI::storage();
328 $moved = DI::storageManager()->move($current);
331 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");