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\GContact;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Nodeinfo;
35 use Friendica\Model\Photo;
36 use Friendica\Model\User;
37 use Friendica\Network\Probe;
38 use Friendica\Util\Network;
39 use Friendica\Util\Proxy as ProxyUtils;
40 use Friendica\Util\Strings;
44 public static function execute($command = '')
48 // No parameter set? So return
53 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
61 Logger::info('cron_start');
63 // Now trying to register
64 $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHostname();
65 Logger::debug('Check registering url', ['url' => $url]);
66 $ret = Network::fetchUrl($url);
67 Logger::debug('Check registering answer', ['answer' => $ret]);
68 Logger::info('cron_end');
71 case 'expire_and_remove_users':
72 self::expireAndRemoveUsers();
75 case 'update_contact_birthdays':
76 Contact::updateBirthdays();
79 case 'update_photo_albums':
80 self::updatePhotoAlbums();
87 case 'repair_database':
88 self::repairDatabase();
96 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
103 * Update the cached values for the number of photo albums per user
105 private static function updatePhotoAlbums()
107 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
108 if (!DBA::isResult($r)) {
112 foreach ($r as $user) {
113 Photo::clearAlbumCache($user['uid']);
118 * Expire and remove user entries
120 private static function expireAndRemoveUsers()
122 // expire any expired regular accounts. Don't expire forums.
123 $condition = ["NOT `account_expired` AND `account_expires_on` > ? AND `account_expires_on` < UTC_TIMESTAMP() AND `page-flags` = 0", DBA::NULL_DATETIME];
124 DBA::update('user', ['account_expired' => true], $condition);
126 // Remove any freshly expired account
127 $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]);
128 while ($user = DBA::fetch($users)) {
129 User::remove($user['uid']);
133 // delete user records for recently removed accounts
134 $users = DBA::select('user', ['uid'], ["`account_removed` AND `account_expires_on` < UTC_TIMESTAMP() "]);
135 while ($user = DBA::fetch($users)) {
136 // Delete the contacts of this user
137 $self = DBA::selectFirst('contact', ['nurl'], ['self' => true, 'uid' => $user['uid']]);
138 if (DBA::isResult($self)) {
139 DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]);
142 DBA::delete('user', ['uid' => $user['uid']]);
148 * Clear cache entries
151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 private static function clearCache(App $a)
155 $last = DI::config()->get('system', 'cache_last_cleared');
158 $next = $last + (3600); // Once per hour
159 $clear_cache = ($next <= time());
169 DI::cache()->clear();
171 // clear old item cache files
174 // clear cache for photos
175 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
177 // clear smarty cache
178 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
180 // clear cache for image proxy
181 if (!DI::config()->get("system", "proxy_disabled")) {
182 clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
184 $cachetime = DI::config()->get('system', 'proxy_cache_time');
187 $cachetime = ProxyUtils::DEFAULT_TIME;
190 $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
191 Photo::delete($condition);
194 // Delete the cached OEmbed entries that are older than three month
195 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
197 // Delete the cached "parse_url" entries that are older than three month
198 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
200 // Maximum table size in megabyte
201 $max_tablesize = intval(DI::config()->get('system', 'optimize_max_tablesize')) * 1000000;
202 if ($max_tablesize == 0) {
203 $max_tablesize = 100 * 1000000; // Default are 100 MB
205 if ($max_tablesize > 0) {
206 // Minimum fragmentation level in percent
207 $fragmentation_level = intval(DI::config()->get('system', 'optimize_fragmentation')) / 100;
208 if ($fragmentation_level == 0) {
209 $fragmentation_level = 0.3; // Default value is 30%
212 // Optimize some tables that need to be optimized
213 $r = q("SHOW TABLE STATUS");
214 foreach ($r as $table) {
216 // Don't optimize tables that are too large
217 if ($table["Data_length"] > $max_tablesize) {
221 // Don't optimize empty tables
222 if ($table["Data_length"] == 0) {
226 // Calculate fragmentation
227 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
229 Logger::log("Table " . $table["Name"] . " - Fragmentation level: " . round($fragmentation * 100, 2), Logger::DEBUG);
231 // Don't optimize tables that needn't to be optimized
232 if ($fragmentation < $fragmentation_level) {
237 Logger::log("Optimize Table " . $table["Name"], Logger::DEBUG);
238 q("OPTIMIZE TABLE `%s`", DBA::escape($table["Name"]));
242 DI::config()->set('system', 'cache_last_cleared', time());
246 * Do some repairs in database entries
249 private static function repairDatabase()
251 // Sometimes there seem to be issues where the "self" contact vanishes.
252 // We haven't found the origin of the problem by now.
253 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
254 if (DBA::isResult($r)) {
255 foreach ($r AS $user) {
256 Logger::log('Create missing self contact for user ' . $user['uid']);
257 Contact::createSelfFromUserId($user['uid']);
261 // There was an issue where the nick vanishes from the contact table
262 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
264 // Update the global contacts for local users
265 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
266 if (DBA::isResult($r)) {
267 foreach ($r AS $user) {
268 GContact::updateForUser($user["uid"]);
273 /// - remove thread entries without item
274 /// - remove sign entries without item
275 /// - remove children when parent got lost
276 /// - set contact-id in item when not present
278 // Add intro entries for pending contacts
279 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
280 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
281 WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
282 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
283 0, Contact::FOLLOWER, Protocol::DFRN);
284 while ($contact = DBA::fetch($pending_contacts)) {
285 DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
286 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
288 DBA::close($pending_contacts);
292 * Moves up to 5000 attachments and photos to the current storage system.
293 * Self-replicates if legacy items have been found and moved.
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 private static function moveStorage()
299 $current = DI::storage();
300 $moved = DI::storageManager()->move($current);
303 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");