3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Worker;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
29 use Friendica\Database\PostUpdate;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Nodeinfo;
33 use Friendica\Model\Photo;
34 use Friendica\Model\User;
35 use Friendica\Util\Proxy as ProxyUtils;
36 use Friendica\Util\Strings;
40 public static function execute($command = '')
44 // No parameter set? So return
49 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
57 Logger::info('cron_start');
59 // Now trying to register
60 $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHostname();
61 Logger::debug('Check registering url', ['url' => $url]);
62 $ret = DI::httpRequest()->fetch($url);
63 Logger::debug('Check registering answer', ['answer' => $ret]);
64 Logger::info('cron_end');
67 case 'expire_and_remove_users':
68 self::expireAndRemoveUsers();
71 case 'update_contact_birthdays':
72 Contact::updateBirthdays();
75 case 'update_photo_albums':
76 self::updatePhotoAlbums();
83 case 'repair_database':
84 self::repairDatabase();
92 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
99 * Update the cached values for the number of photo albums per user
101 private static function updatePhotoAlbums()
103 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
104 if (!DBA::isResult($r)) {
108 foreach ($r as $user) {
109 Photo::clearAlbumCache($user['uid']);
114 * Expire and remove user entries
116 private static function expireAndRemoveUsers()
118 // expire any expired regular accounts. Don't expire forums.
119 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
120 DBA::update('user', ['account_expired' => true], $condition);
122 // Remove any freshly expired account
123 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
124 while ($user = DBA::fetch($users)) {
125 User::remove($user['uid']);
129 // delete user records for recently removed accounts
130 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
131 while ($user = DBA::fetch($users)) {
132 // Delete the contacts of this user
133 $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
134 if (DBA::isResult($self)) {
135 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
138 DBA::delete('user', ['uid' => $user['uid']]);
144 * Clear cache entries
147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149 private static function clearCache(App $a)
151 $last = DI::config()->get('system', 'cache_last_cleared');
154 $next = $last + (3600); // Once per hour
155 $clear_cache = ($next <= time());
165 DI::cache()->clear();
167 // clear old item cache files
170 // clear cache for photos
171 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
173 // clear smarty cache
174 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
176 // clear cache for image proxy
177 if (!DI::config()->get("system", "proxy_disabled")) {
178 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
180 $cachetime = DI::config()->get('system', 'proxy_cache_time');
183 $cachetime = ProxyUtils::DEFAULT_TIME;
186 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
187 Photo::delete($condition);
190 // Delete the cached OEmbed entries that are older than three month
191 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
193 // Delete the cached "parse_url" entries that are older than three month
194 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
196 // Maximum table size in megabyte
197 $max_tablesize = intval(DI::config()->get('system', 'optimize_max_tablesize')) * 1000000;
198 if ($max_tablesize == 0) {
199 $max_tablesize = 100 * 1000000; // Default are 100 MB
201 if ($max_tablesize > 0) {
202 // Minimum fragmentation level in percent
203 $fragmentation_level = intval(DI::config()->get('system', 'optimize_fragmentation')) / 100;
204 if ($fragmentation_level == 0) {
205 $fragmentation_level = 0.3; // Default value is 30%
208 // Optimize some tables that need to be optimized
209 $r = q("SHOW TABLE STATUS");
210 foreach ($r as $table) {
212 // Don't optimize tables that are too large
213 if ($table["Data_length"] > $max_tablesize) {
217 // Don't optimize empty tables
218 if ($table["Data_length"] == 0) {
222 // Calculate fragmentation
223 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
225 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
227 // Don't optimize tables that needn't to be optimized
228 if ($fragmentation < $fragmentation_level) {
233 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
234 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
238 DI::config()->set('system', 'cache_last_cleared', time());
242 * Do some repairs in database entries
245 private static function repairDatabase()
247 // Sometimes there seem to be issues where the "self" contact vanishes.
248 // We haven't found the origin of the problem by now.
249 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
250 if (DBA::isResult($r)) {
251 foreach ($r AS $user) {
252 Logger::log('Create missing self contact for user ' . $user['uid']);
253 Contact::createSelfFromUserId($user['uid']);
257 // There was an issue where the nick vanishes from the contact table
258 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
261 /// - remove thread entries without item
262 /// - remove sign entries without item
263 /// - remove children when parent got lost
264 /// - set contact-id in item when not present
266 // Add intro entries for pending contacts
267 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
268 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
269 WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
270 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
271 0, Contact::FOLLOWER, Protocol::DFRN);
272 while ($contact = DBA::fetch($pending_contacts)) {
273 DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
274 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
276 DBA::close($pending_contacts);
280 * Moves up to 5000 attachments and photos to the current storage system.
281 * Self-replicates if legacy items have been found and moved.
283 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
285 private static function moveStorage()
287 $current = DI::storage();
288 $moved = DI::storageManager()->move($current);
291 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");