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\Photo;
20 use Friendica\Model\User;
21 use Friendica\Network\Probe;
22 use Friendica\Protocol\PortableContact;
23 use Friendica\Util\Proxy as ProxyUtils;
25 require_once 'mod/nodeinfo.php';
29 public static function execute($command = '')
31 $a = BaseObject::getApp();
33 // No parameter set? So return
38 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
49 case 'expire_and_remove_users':
50 self::expireAndRemoveUsers();
53 case 'update_contact_birthdays':
54 Contact::updateBirthdays();
57 case 'update_photo_albums':
58 self::updatePhotoAlbums();
65 case 'repair_diaspora':
66 self::repairDiaspora($a);
69 case 'repair_database':
70 self::repairDatabase();
78 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
85 * @brief Update the cached values for the number of photo albums per user
87 private static function updatePhotoAlbums()
89 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
90 if (!DBA::isResult($r)) {
94 foreach ($r as $user) {
95 Photo::clearAlbumCache($user['uid']);
100 * @brief Expire and remove user entries
102 private static function expireAndRemoveUsers()
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);
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']);
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]);
123 DBA::delete('user', ['uid' => $user['uid']]);
128 * @brief Clear cache entries
131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133 private static function clearCache(App $a)
135 $last = Config::get('system', 'cache_last_cleared');
138 $next = $last + (3600); // Once per hour
139 $clear_cache = ($next <= time());
151 // clear old item cache files
154 // clear cache for photos
155 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
157 // clear smarty cache
158 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
160 // clear cache for image proxy
161 if (!Config::get("system", "proxy_disabled")) {
162 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
164 $cachetime = Config::get('system', 'proxy_cache_time');
167 $cachetime = ProxyUtils::DEFAULT_TIME;
170 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
171 Photo::delete($condition);
174 // Delete the cached OEmbed entries that are older than three month
175 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
177 // Delete the cached "parse_url" entries that are older than three month
178 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
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
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%
192 // Optimize some tables that need to be optimized
193 $r = q("SHOW TABLE STATUS");
194 foreach ($r as $table) {
196 // Don't optimize tables that are too large
197 if ($table["Data_length"] > $max_tablesize) {
201 // Don't optimize empty tables
202 if ($table["Data_length"] == 0) {
206 // Calculate fragmentation
207 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
209 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
211 // Don't optimize tables that needn't to be optimized
212 if ($fragmentation < $fragmentation_level) {
217 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
218 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
222 Config::set('system', 'cache_last_cleared', time());
226 * @brief Repair missing values in Diaspora contacts
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 private static function repairDiaspora(App $a)
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)) {
243 foreach ($r as $contact) {
244 // Quit the loop after 3 minutes
245 if (time() > ($starttime + 180)) {
249 if (!PortableContact::reachable($contact["url"])) {
253 $data = Probe::uri($contact["url"]);
254 if ($data["network"] != Protocol::DIASPORA) {
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"]));
266 * @brief Do some repairs in database entries
269 private static function repairDatabase()
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']);
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`=''");
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"]);
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
300 * Moves up to 5000 attachments and photos to the current storage system.
301 * Self-replicates if legacy items have been found and moved.
303 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 private static function moveStorage()
307 $current = StorageManager::getBackend();
308 $moved = StorageManager::move($current);
311 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");