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\Protocol;
12 use Friendica\Database\DBA;
13 use Friendica\Database\PostUpdate;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Photo;
17 use Friendica\Model\User;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Util\Proxy as ProxyUtils;
22 require_once 'include/dba.php';
23 require_once 'mod/nodeinfo.php';
27 public static function execute($command = '')
29 $a = BaseObject::getApp();
31 // No parameter set? So return
36 logger("Starting cronjob " . $command, LOGGER_DEBUG);
38 // Call possible post update functions
39 // see src/Database/PostUpdate.php for more details
40 if ($command == 'post_update') {
45 // update nodeinfo data
46 if ($command == 'nodeinfo') {
51 // Expire and remove user entries
52 if ($command == 'expire_and_remove_users') {
53 self::expireAndRemoveUsers();
57 if ($command == 'update_contact_birthdays') {
58 Contact::updateBirthdays();
62 if ($command == 'update_photo_albums') {
63 self::updatePhotoAlbums();
67 // Clear cache entries
68 if ($command == 'clear_cache') {
73 // Repair missing Diaspora values in contacts
74 if ($command == 'repair_diaspora') {
75 self::repairDiaspora($a);
79 // Repair entries in the database
80 if ($command == 'repair_database') {
81 self::repairDatabase();
85 logger("Xronjob " . $command . " is unknown.", LOGGER_DEBUG);
91 * @brief Update the cached values for the number of photo albums per user
93 private static function updatePhotoAlbums()
95 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
96 if (!DBA::isResult($r)) {
100 foreach ($r as $user) {
101 Photo::clearAlbumCache($user['uid']);
106 * @brief Expire and remove user entries
108 private static function expireAndRemoveUsers()
110 // expire any expired regular accounts. Don't expire forums.
111 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", NULL_DATE];
112 DBA::update('user', ['account_expired' => true], $condition);
114 // Remove any freshly expired account
115 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
116 while ($user = DBA::fetch($users)) {
117 User::remove($user['uid']);
120 // delete user records for recently removed accounts
121 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY"]);
122 while ($user = DBA::fetch($users)) {
123 DBA::delete('user', ['uid' => $user['uid']]);
128 * @brief Clear cache entries
132 private static function clearCache(App $a)
134 $last = Config::get('system', 'cache_last_cleared');
137 $next = $last + (3600); // Once per hour
138 $clear_cache = ($next <= time());
150 // clear old item cache files
153 // clear cache for photos
154 clear_cache($a->get_basepath(), $a->get_basepath() . "/photo");
156 // clear smarty cache
157 clear_cache($a->get_basepath() . "/view/smarty3/compiled", $a->get_basepath() . "/view/smarty3/compiled");
159 // clear cache for image proxy
160 if (!Config::get("system", "proxy_disabled")) {
161 clear_cache($a->get_basepath(), $a->get_basepath() . "/proxy");
163 $cachetime = Config::get('system', 'proxy_cache_time');
166 $cachetime = ProxyUtils::DEFAULT_TIME;
169 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
170 DBA::delete('photo', $condition);
173 // Delete the cached OEmbed entries that are older than three month
174 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
176 // Delete the cached "parse_url" entries that are older than three month
177 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
179 // Maximum table size in megabyte
180 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
181 if ($max_tablesize == 0) {
182 $max_tablesize = 100 * 1000000; // Default are 100 MB
184 if ($max_tablesize > 0) {
185 // Minimum fragmentation level in percent
186 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
187 if ($fragmentation_level == 0) {
188 $fragmentation_level = 0.3; // Default value is 30%
191 // Optimize some tables that need to be optimized
192 $r = q("SHOW TABLE STATUS");
193 foreach ($r as $table) {
195 // Don't optimize tables that are too large
196 if ($table["Data_length"] > $max_tablesize) {
200 // Don't optimize empty tables
201 if ($table["Data_length"] == 0) {
205 // Calculate fragmentation
206 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
208 logger("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), LOGGER_DEBUG);
210 // Don't optimize tables that needn't to be optimized
211 if ($fragmentation < $fragmentation_level) {
216 logger("Optimize Table " . $table["Name"], LOGGER_DEBUG);
217 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
221 Config::set('system', 'cache_last_cleared', time());
225 * @brief Repair missing values in Diaspora contacts
229 private static function repairDiaspora(App $a)
233 $r = q("SELECT `id`, `url` FROM `contact`
234 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
235 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
236 if (!DBA::isResult($r)) {
240 foreach ($r as $contact) {
241 // Quit the loop after 3 minutes
242 if (time() > ($starttime + 180)) {
246 if (!PortableContact::reachable($contact["url"])) {
250 $data = Probe::uri($contact["url"]);
251 if ($data["network"] != Protocol::DIASPORA) {
255 logger("Repair contact " . $contact["id"] . " " . $contact["url"], LOGGER_DEBUG);
256 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
257 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
258 intval($contact["id"]));
263 * @brief Do some repairs in database entries
266 private static function repairDatabase()
268 // Sometimes there seem to be issues where the "self" contact vanishes.
269 // We haven't found the origin of the problem by now.
270 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
271 if (DBA::isResult($r)) {
272 foreach ($r AS $user) {
273 logger('Create missing self contact for user ' . $user['uid']);
274 Contact::createSelfFromUserId($user['uid']);
278 // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
279 // This call is very "cheap" so we can do it at any time without a problem
280 q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
282 // There was an issue where the nick vanishes from the contact table
283 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
285 // Update the global contacts for local users
286 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
287 if (DBA::isResult($r)) {
288 foreach ($r AS $user) {
289 GContact::updateForUser($user["uid"]);
294 /// - remove thread entries without item
295 /// - remove sign entries without item
296 /// - remove children when parent got lost
297 /// - set contact-id in item when not present