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\Database\DBA;
14 use Friendica\Database\PostUpdate;
15 use Friendica\Model\Contact;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Photo;
18 use Friendica\Model\User;
19 use Friendica\Network\Probe;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Util\Proxy as ProxyUtils;
23 require_once 'mod/nodeinfo.php';
27 public static function execute($command = '')
29 $a = BaseObject::getApp();
31 // No parameter set? So return
36 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
47 case 'expire_and_remove_users':
48 self::expireAndRemoveUsers();
51 case 'update_contact_birthdays':
52 Contact::updateBirthdays();
55 case 'update_photo_albums':
56 self::updatePhotoAlbums();
63 case 'repair_diaspora':
64 self::repairDiaspora($a);
67 case 'repair_database':
68 self::repairDatabase();
72 Logger::log("Xronjob " . $command . " is unknown.", Logger::DEBUG);
79 * @brief Update the cached values for the number of photo albums per user
81 private static function updatePhotoAlbums()
83 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
84 if (!DBA::isResult($r)) {
88 foreach ($r as $user) {
89 Photo::clearAlbumCache($user['uid']);
94 * @brief Expire and remove user entries
96 private static function expireAndRemoveUsers()
98 // expire any expired regular accounts. Don't expire forums.
99 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
100 DBA::update('user', ['account_expired' => true], $condition);
102 // Remove any freshly expired account
103 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
104 while ($user = DBA::fetch($users)) {
105 User::remove($user['uid']);
108 // delete user records for recently removed accounts
109 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
110 while ($user = DBA::fetch($users)) {
111 // Delete the contacts of this user
112 $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
113 if (DBA::isResult($self)) {
114 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
117 DBA::delete('user', ['uid' => $user['uid']]);
122 * @brief Clear cache entries
125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127 private static function clearCache(App $a)
129 $last = Config::get('system', 'cache_last_cleared');
132 $next = $last + (3600); // Once per hour
133 $clear_cache = ($next <= time());
145 // clear old item cache files
148 // clear cache for photos
149 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
151 // clear smarty cache
152 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
154 // clear cache for image proxy
155 if (!Config::get("system", "proxy_disabled")) {
156 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
158 $cachetime = Config::get('system', 'proxy_cache_time');
161 $cachetime = ProxyUtils::DEFAULT_TIME;
164 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
165 Photo::delete($condition);
168 // Delete the cached OEmbed entries that are older than three month
169 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
171 // Delete the cached "parse_url" entries that are older than three month
172 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
174 // Maximum table size in megabyte
175 $max_tablesize = intval(Config::get('system', 'optimize_max_tablesize')) * 1000000;
176 if ($max_tablesize == 0) {
177 $max_tablesize = 100 * 1000000; // Default are 100 MB
179 if ($max_tablesize > 0) {
180 // Minimum fragmentation level in percent
181 $fragmentation_level = intval(Config::get('system', 'optimize_fragmentation')) / 100;
182 if ($fragmentation_level == 0) {
183 $fragmentation_level = 0.3; // Default value is 30%
186 // Optimize some tables that need to be optimized
187 $r = q("SHOW TABLE STATUS");
188 foreach ($r as $table) {
190 // Don't optimize tables that are too large
191 if ($table["Data_length"] > $max_tablesize) {
195 // Don't optimize empty tables
196 if ($table["Data_length"] == 0) {
200 // Calculate fragmentation
201 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
203 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
205 // Don't optimize tables that needn't to be optimized
206 if ($fragmentation < $fragmentation_level) {
211 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
212 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
216 Config::set('system', 'cache_last_cleared', time());
220 * @brief Repair missing values in Diaspora contacts
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @throws \ImagickException
226 private static function repairDiaspora(App $a)
230 $r = q("SELECT `id`, `url` FROM `contact`
231 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
232 ORDER BY RAND() LIMIT 50", DBA::escape(Protocol::DIASPORA));
233 if (!DBA::isResult($r)) {
237 foreach ($r as $contact) {
238 // Quit the loop after 3 minutes
239 if (time() > ($starttime + 180)) {
243 if (!PortableContact::reachable($contact["url"])) {
247 $data = Probe::uri($contact["url"]);
248 if ($data["network"] != Protocol::DIASPORA) {
252 Logger::log("Repair contact " . $contact["id"] . " " . $contact["url"], Logger::DEBUG);
253 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
254 DBA::escape($data["batch"]), DBA::escape($data["notify"]), DBA::escape($data["poll"]), DBA::escape($data["pubkey"]),
255 intval($contact["id"]));
260 * @brief Do some repairs in database entries
263 private static function repairDatabase()
265 // Sometimes there seem to be issues where the "self" contact vanishes.
266 // We haven't found the origin of the problem by now.
267 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
268 if (DBA::isResult($r)) {
269 foreach ($r AS $user) {
270 Logger::log('Create missing self contact for user ' . $user['uid']);
271 Contact::createSelfFromUserId($user['uid']);
275 // There was an issue where the nick vanishes from the contact table
276 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
278 // Update the global contacts for local users
279 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
280 if (DBA::isResult($r)) {
281 foreach ($r AS $user) {
282 GContact::updateForUser($user["uid"]);
287 /// - remove thread entries without item
288 /// - remove sign entries without item
289 /// - remove children when parent got lost
290 /// - set contact-id in item when not present