]> git.mxchange.org Git - friendica.git/blob - src/Worker/CronJobs.php
Merge pull request #9017 from annando/issue-9015
[friendica.git] / src / Worker / CronJobs.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Worker;
23
24 use Friendica\App;
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;
30 use Friendica\DI;
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;
37
38 class CronJobs
39 {
40         public static function execute($command = '')
41         {
42                 $a = DI::app();
43
44                 // No parameter set? So return
45                 if ($command == '') {
46                         return;
47                 }
48
49                 Logger::log("Starting cronjob " . $command, Logger::DEBUG);
50
51                 switch($command) {
52                         case 'post_update':
53                                 PostUpdate::update();
54                                 break;
55
56                         case 'nodeinfo':
57                                 Logger::info('cron_start');
58                                 Nodeinfo::update();
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');
65                                 break;
66
67                         case 'expire_and_remove_users':
68                                 self::expireAndRemoveUsers();
69                                 break;
70
71                         case 'update_contact_birthdays':
72                                 Contact::updateBirthdays();
73                                 break;
74
75                         case 'update_photo_albums':
76                                 self::updatePhotoAlbums();
77                                 break;
78
79                         case 'clear_cache':
80                                 self::clearCache($a);
81                                 break;
82
83                         case 'repair_database':
84                                 self::repairDatabase();
85                                 break;
86
87                         case 'move_storage':
88                                 self::moveStorage();
89                                 break;
90
91                         default:
92                                 Logger::log("Cronjob " . $command . " is unknown.", Logger::DEBUG);
93                 }
94
95                 return;
96         }
97
98         /**
99          * Update the cached values for the number of photo albums per user
100          */
101         private static function updatePhotoAlbums()
102         {
103                 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
104                 if (!DBA::isResult($r)) {
105                         return;
106                 }
107
108                 foreach ($r as $user) {
109                         Photo::clearAlbumCache($user['uid']);
110                 }
111         }
112
113         /**
114          * Expire and remove user entries
115          */
116         private static function expireAndRemoveUsers()
117         {
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);
121
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']);
126                 }
127                 DBA::close($users);
128
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]);
136                         }
137
138                         DBA::delete('user', ['uid' => $user['uid']]);
139                 }
140                 DBA::close($users);
141         }
142
143         /**
144          * Clear cache entries
145          *
146          * @param App $a
147          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148          */
149         private static function clearCache(App $a)
150         {
151                 $last = DI::config()->get('system', 'cache_last_cleared');
152
153                 if ($last) {
154                         $next = $last + (3600); // Once per hour
155                         $clear_cache = ($next <= time());
156                 } else {
157                         $clear_cache = true;
158                 }
159
160                 if (!$clear_cache) {
161                         return;
162                 }
163
164                 // clear old cache
165                 DI::cache()->clear();
166
167                 // clear old item cache files
168                 clear_cache();
169
170                 // clear cache for photos
171                 clear_cache($a->getBasePath(), $a->getBasePath() . "/photo");
172
173                 // clear smarty cache
174                 clear_cache($a->getBasePath() . "/view/smarty3/compiled", $a->getBasePath() . "/view/smarty3/compiled");
175
176                 // clear cache for image proxy
177                 if (!DI::config()->get("system", "proxy_disabled")) {
178                         clear_cache($a->getBasePath(), $a->getBasePath() . "/proxy");
179
180                         $cachetime = DI::config()->get('system', 'proxy_cache_time');
181
182                         if (!$cachetime) {
183                                 $cachetime = ProxyUtils::DEFAULT_TIME;
184                         }
185
186                         $condition = ['`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime];
187                         Photo::delete($condition);
188                 }
189
190                 // Delete the cached OEmbed entries that are older than three month
191                 DBA::delete('oembed', ["`created` < NOW() - INTERVAL 3 MONTH"]);
192
193                 // Delete the cached "parse_url" entries that are older than three month
194                 DBA::delete('parsed_url', ["`created` < NOW() - INTERVAL 3 MONTH"]);
195
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');                      
208                 }
209
210                 DI::config()->set('system', 'cache_last_cleared', time());
211         }
212
213         /**
214          * Do some repairs in database entries
215          *
216          */
217         private static function repairDatabase()
218         {
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']);
226                         }
227                 }
228
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`=''");
231
232                 /// @todo
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
237
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']]);
247                 }
248                 DBA::close($pending_contacts);
249         }
250
251         /**
252          * Moves up to 5000 attachments and photos to the current storage system.
253          * Self-replicates if legacy items have been found and moved.
254          *
255          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256          */
257         private static function moveStorage()
258         {
259                 $current = DI::storage();
260                 $moved = DI::storageManager()->move($current);
261
262                 if ($moved) {
263                         Worker::add(PRIORITY_LOW, "CronJobs", "move_storage");
264                 }
265         }
266 }