3 * @file src/worker/CronJobs.php
5 namespace Friendica\Worker;
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\Nodeinfo;
20 use Friendica\Model\Photo;
21 use Friendica\Model\User;
22 use Friendica\Network\Probe;
23 use Friendica\Protocol\PortableContact;
24 use Friendica\Util\Network;
25 use Friendica\Util\Proxy as ProxyUtils;
27 require_once 'mod/nodeinfo.php';
31 public static function execute($command = '')
33 $a = BaseObject::getApp();
35 // No parameter set? So return
40 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
48 Logger::info('cron_start');
50 // Now trying to register
51 $url = 'http://the-federation.info/register/' . $a->getHostName();
52 Logger::debug('Check registering url', ['url' => $url]);
53 $ret = Network::fetchUrl($url);
54 Logger::debug('Check registering answer', ['answer' => $ret]);
55 Logger::info('cron_end');
58 case 'expire_and_remove_users':
59 self::expireAndRemoveUsers();
62 case 'update_contact_birthdays':
63 Contact::updateBirthdays();
66 case 'update_photo_albums':
67 self::updatePhotoAlbums();
74 case 'repair_diaspora':
75 self::repairDiaspora($a);
78 case 'repair_database':
79 self::repairDatabase();
87 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
94 * @brief Update the cached values for the number of photo albums per user
96 private static function updatePhotoAlbums()
98 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
99 if (!DBA::isResult($r)) {
103 foreach ($r as $user) {
104 Photo::clearAlbumCache($user['uid']);
109 * @brief Expire and remove user entries
111 private static function expireAndRemoveUsers()
113 // expire any expired regular accounts. Don't expire forums.
114 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
115 DBA::update('user', ['account_expired' => true], $condition);
117 // Remove any freshly expired account
118 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
119 while ($user = DBA::fetch($users)) {
120 User::remove($user['uid']);
123 // delete user records for recently removed accounts
124 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
125 while ($user = DBA::fetch($users)) {
126 // Delete the contacts of this user
127 $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
128 if (DBA::isResult($self)) {
129 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
132 DBA::delete('user', ['uid' => $user['uid']]);
137 * @brief Clear cache entries
140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
142 private static function clearCache(App $a)
144 $last = Config::get('system', 'cache_last_cleared');
147 $next = $last + (3600); // Once per hour
148 $clear_cache = ($next <= time());
160 // clear old item cache files
163 // clear cache for photos
164 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
166 // clear smarty cache
167 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
169 // clear cache for image proxy
170 if (!Config::get("system", "proxy_disabled")) {
171 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
173 $cachetime = Config::get('system', 'proxy_cache_time');
176 $cachetime = ProxyUtils::DEFAULT_TIME;
179 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
180 Photo::delete($condition);
183 // Delete the cached OEmbed entries that are older than three month
184 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
186 // Delete the cached "parse_url" entries that are older than three month
187 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
189 // Maximum table size in megabyte
190 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
191 if ($max_tablesize == 0) {
192 $max_tablesize = 100 * 1000000; // Default are 100 MB
194 if ($max_tablesize > 0) {
195 // Minimum fragmentation level in percent
196 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
197 if ($fragmentation_level == 0) {
198 $fragmentation_level = 0.3; // Default value is 30%
201 // Optimize some tables that need to be optimized
202 $r = q("SHOW TABLE STATUS");
203 foreach ($r as $table) {
205 // Don't optimize tables that are too large
206 if ($table["Data_length"] > $max_tablesize) {
210 // Don't optimize empty tables
211 if ($table["Data_length"] == 0) {
215 // Calculate fragmentation
216 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
218 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
220 // Don't optimize tables that needn't to be optimized
221 if ($fragmentation < $fragmentation_level) {
226 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
227 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
231 Config::set('system', 'cache_last_cleared', time());
235 * @brief Repair missing values in Diaspora contacts
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239 * @throws \ImagickException
241 private static function repairDiaspora(App $a)
245 $r = q("SELECT `id`, `url` FROM `contact`
246 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
247 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
248 if (!DBA::isResult($r)) {
252 foreach ($r as $contact) {
253 // Quit the loop after 3 minutes
254 if (time() > ($starttime + 180)) {
258 if (!PortableContact::reachable($contact["url"])) {
262 $data = Probe::uri($contact["url"]);
263 if ($data["network"] != Protocol::DIASPORA) {
267 Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
268 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
269 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
270 intval($contact["id"]));
275 * @brief Do some repairs in database entries
278 private static function repairDatabase()
280 // Sometimes there seem to be issues where the "self" contact vanishes.
281 // We haven't found the origin of the problem by now.
282 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
283 if (DBA::isResult($r)) {
284 foreach ($r AS $user) {
285 Logger::log('Create missing self contact for user ' . $user['uid']);
286 Contact::createSelfFromUserId($user['uid']);
290 // There was an issue where the nick vanishes from the contact table
291 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
293 // Update the global contacts for local users
294 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
295 if (DBA::isResult($r)) {
296 foreach ($r AS $user) {
297 GContact::updateForUser($user["uid"]);
302 /// - remove thread entries without item
303 /// - remove sign entries without item
304 /// - remove children when parent got lost
305 /// - set contact-id in item when not present
309 * Moves up to 5000 attachments and photos to the current storage system.
310 * Self-replicates if legacy items have been found and moved.
312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314 private static function moveStorage()
316 $current = StorageManager::getBackend();
317 $moved = StorageManager::move($current);
320 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");