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 if (DI::config()->get('system', 'optimize_tables')) {
197 Logger::info('Optimize start');
198 DBA::e("OPTIMIZE TABLE `auth_codes`");
199 DBA::e("OPTIMIZE TABLE `cache`");
200 DBA::e("OPTIMIZE TABLE `challenge`");
201 DBA::e("OPTIMIZE TABLE `locks`");
202 DBA::e("OPTIMIZE TABLE `oembed`");
203 DBA::e("OPTIMIZE TABLE `parsed_url`");
204 DBA::e("OPTIMIZE TABLE `profile_check`");
205 DBA::e("OPTIMIZE TABLE `session`");
206 DBA::e("OPTIMIZE TABLE `tokens`");
207 Logger::info('Optimize finished');
210 DI::config()->set('system', 'cache_last_cleared', time());
214 * Do some repairs in database entries
217 private static function repairDatabase()
219 // Sometimes there seem to be issues where the "self" contact vanishes.
220 // We haven't found the origin of the problem by now.
221 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
222 if (DBA::isResult($r)) {
223 foreach ($r AS $user) {
224 Logger::log('Create missing self contact for user ' . $user['uid']);
225 Contact::createSelfFromUserId($user['uid']);
229 // There was an issue where the nick vanishes from the contact table
230 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
233 /// - remove thread entries without item
234 /// - remove sign entries without item
235 /// - remove children when parent got lost
236 /// - set contact-id in item when not present
238 // Add intro entries for pending contacts
239 // We don't do this for DFRN entries since such revived contact requests seem to mostly fail.
240 $pending_contacts = DBA::p("SELECT `uid`, `id`, `url`, `network`, `created` FROM `contact`
241 WHERE `pending` AND `rel` IN (?, ?) AND `network` != ?
242 AND NOT EXISTS (SELECT `id` FROM `intro` WHERE `contact-id` = `contact`.`id`)",
243 0, Contact::FOLLOWER, Protocol::DFRN);
244 while ($contact = DBA::fetch($pending_contacts)) {
245 DBA::insert('intro', ['uid' => $contact['uid'], 'contact-id' => $contact['id'], 'blocked' => false,
246 'hash' => Strings::getRandomHex(), 'datetime' => $contact['created']]);
248 DBA::close($pending_contacts);
252 * Moves up to 5000 attachments and photos to the current storage system.
253 * Self-replicates if legacy items have been found and moved.
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 private static function moveStorage()
259 $current = DI::storage();
260 $moved = DI::storageManager()->move($current);
263 Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");