3 * @file src/worker/CronJobs.php
5 namespace Friendica\Worker;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Database\DBM;
11 use Friendica\Database\PostUpdate;
12 use Friendica\Model\Contact;
13 use Friendica\Model\GContact;
14 use Friendica\Model\Photo;
15 use Friendica\Model\User;
16 use Friendica\Network\Probe;
17 use Friendica\Protocol\PortableContact;
20 require_once 'include/dba.php';
21 require_once 'mod/nodeinfo.php';
25 public static function execute($command = '')
29 // No parameter set? So return
34 logger("Starting cronjob " . $command, LOGGER_DEBUG);
36 // Call possible post update functions
37 // see src/Database/PostUpdate.php for more details
38 if ($command == 'post_update') {
43 // update nodeinfo data
44 if ($command == 'nodeinfo') {
49 // Expire and remove user entries
50 if ($command == 'expire_and_remove_users') {
51 self::expireAndRemoveUsers();
55 if ($command == 'update_contact_birthdays') {
56 Contact::updateBirthdays();
60 if ($command == 'update_photo_albums') {
61 self::updatePhotoAlbums();
65 // Clear cache entries
66 if ($command == 'clear_cache') {
71 // Repair missing Diaspora values in contacts
72 if ($command == 'repair_diaspora') {
73 self::repairDiaspora($a);
77 // Repair entries in the database
78 if ($command == 'repair_database') {
79 self::repairDatabase();
83 logger("Xronjob " . $command . " is unknown.", LOGGER_DEBUG);
89 * @brief Update the cached values for the number of photo albums per user
91 private static function updatePhotoAlbums()
93 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
94 if (!DBM::is_result($r)) {
98 foreach ($r as $user) {
99 Photo::clearAlbumCache($user['uid']);
104 * @brief Expire and remove user entries
106 private static function expireAndRemoveUsers()
108 // expire any expired regular accounts. Don't expire forums.
109 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", NULL_DATE];
110 dba::update('user', ['account_expired' => true], $condition);
112 // Remove any freshly expired account
113 $users = dba::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
114 while ($user = dba::fetch($users)) {
115 User::remove($user['uid']);
118 // delete user records for recently removed accounts
119 $users = dba::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY"]);
120 while ($user = dba::fetch($users)) {
121 dba::delete('user', ['uid' => $user['uid']]);
126 * @brief Clear cache entries
130 private static function clearCache(App $a)
132 $last = Config::get('system', 'cache_last_cleared');
135 $next = $last + (3600); // Once per hour
136 $clear_cache = ($next <= time());
148 // clear old item cache files
151 // clear cache for photos
152 clear_cache($a->get_basepath(), $a->get_basepath() . "/photo");
154 // clear smarty cache
155 clear_cache($a->get_basepath() . "/view/smarty3/compiled", $a->get_basepath() . "/view/smarty3/compiled");
157 // clear cache for image proxy
158 if (!Config::get("system", "proxy_disabled")) {
159 clear_cache($a->get_basepath(), $a->get_basepath() . "/proxy");
161 $cachetime = Config::get('system', 'proxy_cache_time');
163 $cachetime = PROXY_DEFAULT_TIME;
165 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
166 dba::delete('photo', $condition);
169 // Delete the cached OEmbed entries that are older than three month
170 dba::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
172 // Delete the cached "parse_url" entries that are older than three month
173 dba::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
175 // Maximum table size in megabyte
176 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
177 if ($max_tablesize == 0) {
178 $max_tablesize = 100 * 1000000; // Default are 100 MB
180 if ($max_tablesize > 0) {
181 // Minimum fragmentation level in percent
182 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
183 if ($fragmentation_level == 0) {
184 $fragmentation_level = 0.3; // Default value is 30%
187 // Optimize some tables that need to be optimized
188 $r = q("SHOW TABLE STATUS");
189 foreach ($r as $table) {
191 // Don't optimize tables that are too large
192 if ($table["Data_length"] > $max_tablesize) {
196 // Don't optimize empty tables
197 if ($table["Data_length"] == 0) {
201 // Calculate fragmentation
202 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
204 logger("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), LOGGER_DEBUG);
206 // Don't optimize tables that needn't to be optimized
207 if ($fragmentation < $fragmentation_level) {
212 logger("Optimize Table " . $table["Name"], LOGGER_DEBUG);
213 q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
217 Config::set('system', 'cache_last_cleared', time());
221 * @brief Repair missing values in Diaspora contacts
225 private static function repairDiaspora(App $a)
229 $r = q("SELECT `id`, `url` FROM `contact`
230 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
231 ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
232 if (!DBM::is_result($r)) {
236 foreach ($r AS $contact) {
237 // Quit the loop after 3 minutes
238 if (time() > ($starttime + 180)) {
242 if (!PortableContact::reachable($contact["url"])) {
246 $data = Probe::uri($contact["url"]);
247 if ($data["network"] != NETWORK_DIASPORA) {
251 logger("Repair contact " . $contact["id"] . " " . $contact["url"], LOGGER_DEBUG);
252 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
253 dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
254 intval($contact["id"]));
259 * @brief Do some repairs in database entries
262 private static function repairDatabase()
264 // Sometimes there seem to be issues where the "self" contact vanishes.
265 // We haven't found the origin of the problem by now.
266 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
267 if (DBM::is_result($r)) {
268 foreach ($r AS $user) {
269 logger('Create missing self contact for user ' . $user['uid']);
270 Contact::createSelfFromUserId($user['uid']);
274 // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
275 // This call is very "cheap" so we can do it at any time without a problem
276 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");
278 // There was an issue where the nick vanishes from the contact table
279 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
281 // Update the global contacts for local users
282 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
283 if (DBM::is_result($r)) {
284 foreach ($r AS $user) {
285 GContact::updateForUser($user["uid"]);
290 /// - remove thread entries without item
291 /// - remove sign entries without item
292 /// - remove children when parent got lost
293 /// - set contact-id in item when not present