3 * @file src/worker/CronJobs.php
6 namespace Friendica\Worker;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Database\DBM;
12 use Friendica\Model\GlobalContact;
13 use Friendica\Network\Probe;
14 use Friendica\Protocol\PortableContact;
18 public static function execute($command = ''){
21 require_once 'include/datetime.php';
22 require_once 'include/post_update.php';
23 require_once 'mod/nodeinfo.php';
24 require_once 'include/photos.php';
25 require_once 'include/user.php';
27 // No parameter set? So return
32 logger("Starting cronjob ".$command, LOGGER_DEBUG);
34 // Call possible post update functions
35 // see include/post_update.php for more details
36 if ($command == 'post_update') {
41 // update nodeinfo data
42 if ($command == 'nodeinfo') {
47 // Expire and remove user entries
48 if ($command == 'expire_and_remove_users') {
49 self::expireAndRemoveUsers();
53 if ($command == 'update_contact_birthdays') {
54 update_contact_birthdays();
58 if ($command == 'update_photo_albums') {
59 self::updatePhotoAlbums();
63 // Clear cache entries
64 if ($command == 'clear_cache') {
69 // Repair missing Diaspora values in contacts
70 if ($command == 'repair_diaspora') {
71 self::repairDiaspora($a);
75 // Repair entries in the database
76 if ($command == 'repair_database') {
77 self::repairDatabase();
81 logger("Xronjob ".$command." is unknown.", LOGGER_DEBUG);
87 * @brief Update the cached values for the number of photo albums per user
89 private static function updatePhotoAlbums() {
90 $r = q("SELECT `uid` FROM `user` WHERE NOT `account_expired` AND NOT `account_removed`");
91 if (!DBM::is_result($r)) {
95 foreach ($r AS $user) {
96 photo_albums($user['uid'], true);
101 * @brief Expire and remove user entries
103 private static function expireAndRemoveUsers() {
104 // expire any expired accounts
105 q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
106 AND `account_expires_on` > '%s'
107 AND `account_expires_on` < UTC_TIMESTAMP()", dbesc(NULL_DATE));
109 // delete user records for recently removed accounts
110 $r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY");
111 if (DBM::is_result($r)) {
112 foreach ($r as $user) {
113 dba::delete('user', array('uid' => $user['uid']));
119 * @brief Clear cache entries
123 private static function clearCache(App $a) {
125 $last = Config::get('system','cache_last_cleared');
128 $next = $last + (3600); // Once per hour
129 $clear_cache = ($next <= time());
141 // clear old item cache files
144 // clear cache for photos
145 clear_cache($a->get_basepath(), $a->get_basepath()."/photo");
147 // clear smarty cache
148 clear_cache($a->get_basepath()."/view/smarty3/compiled", $a->get_basepath()."/view/smarty3/compiled");
150 // clear cache for image proxy
151 if (!Config::get("system", "proxy_disabled")) {
152 clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
154 $cachetime = Config::get('system','proxy_cache_time');
156 $cachetime = PROXY_DEFAULT_TIME;
158 $condition = array('`uid` = 0 AND `resource-id` LIKE "pic:%" AND `created` < NOW() - INTERVAL ? SECOND', $cachetime);
159 dba::delete('photo', $condition);
162 // Delete the cached OEmbed entries that are older than three month
163 dba::delete('oembed', array("`created` < NOW() - INTERVAL 3 MONTH"));
165 // Delete the cached "parse_url" entries that are older than three month
166 dba::delete('parsed_url', array("`created` < NOW() - INTERVAL 3 MONTH"));
168 // Maximum table size in megabyte
169 $max_tablesize = intval(Config::get('system','optimize_max_tablesize')) * 1000000;
170 if ($max_tablesize == 0) {
171 $max_tablesize = 100 * 1000000; // Default are 100 MB
173 if ($max_tablesize > 0) {
174 // Minimum fragmentation level in percent
175 $fragmentation_level = intval(Config::get('system','optimize_fragmentation')) / 100;
176 if ($fragmentation_level == 0) {
177 $fragmentation_level = 0.3; // Default value is 30%
180 // Optimize some tables that need to be optimized
181 $r = q("SHOW TABLE STATUS");
182 foreach ($r as $table) {
184 // Don't optimize tables that are too large
185 if ($table["Data_length"] > $max_tablesize) {
189 // Don't optimize empty tables
190 if ($table["Data_length"] == 0) {
194 // Calculate fragmentation
195 $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
197 logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
199 // Don't optimize tables that needn't to be optimized
200 if ($fragmentation < $fragmentation_level) {
205 logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
206 q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
210 Config::set('system','cache_last_cleared', time());
214 * @brief Repair missing values in Diaspora contacts
218 private static function repairDiaspora(App $a) {
222 $r = q("SELECT `id`, `url` FROM `contact`
223 WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
224 ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
225 if (!DBM::is_result($r)) {
229 foreach ($r AS $contact) {
230 // Quit the loop after 3 minutes
231 if (time() > ($starttime + 180)) {
235 if (!PortableContact::reachable($contact["url"])) {
239 $data = Probe::uri($contact["url"]);
240 if ($data["network"] != NETWORK_DIASPORA) {
244 logger("Repair contact ".$contact["id"]." ".$contact["url"], LOGGER_DEBUG);
245 q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
246 dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
247 intval($contact["id"]));
252 * @brief Do some repairs in database entries
255 private static function repairDatabase() {
257 // Sometimes there seem to be issues where the "self" contact vanishes.
258 // We haven't found the origin of the problem by now.
259 $r = q("SELECT `uid` FROM `user` WHERE NOT EXISTS (SELECT `uid` FROM `contact` WHERE `contact`.`uid` = `user`.`uid` AND `contact`.`self`)");
260 if (DBM::is_result($r)) {
261 foreach ($r AS $user) {
262 logger('Create missing self contact for user '.$user['uid']);
263 user_create_self_contact($user['uid']);
267 // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
268 // This call is very "cheap" so we can do it at any time without a problem
269 q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
271 // There was an issue where the nick vanishes from the contact table
272 q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
274 // Update the global contacts for local users
275 $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
276 if (DBM::is_result($r)) {
277 foreach ($r AS $user) {
278 GlobalContact::updateForUser($user["uid"]);
283 /// - remove thread entries without item
284 /// - remove sign entries without item
285 /// - remove children when parent got lost
286 /// - set contact-id in item when not present