]> git.mxchange.org Git - friendica.git/blob - src/Database/PostUpdate.php
Merge pull request #8272 from MrPetovan/bug/8254-regex-url-img
[friendica.git] / src / Database / PostUpdate.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\Database;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Item;
29 use Friendica\Model\ItemURI;
30 use Friendica\Model\PermissionSet;
31 use Friendica\Model\UserItem;
32
33 /**
34  * These database-intensive post update routines are meant to be executed in the background by the cronjob.
35  *
36  * If there is a need for a intensive migration after a database structure change, update this file
37  * by adding a new method at the end with the number of the new DB_UPDATE_VERSION.
38  */
39 class PostUpdate
40 {
41         /**
42          * Calls the post update functions
43          */
44         public static function update()
45         {
46                 if (!self::update1194()) {
47                         return false;
48                 }
49                 if (!self::update1206()) {
50                         return false;
51                 }
52                 if (!self::update1279()) {
53                         return false;
54                 }
55                 if (!self::update1281()) {
56                         return false;
57                 }
58                 if (!self::update1297()) {
59                         return false;
60                 }
61                 if (!self::update1322()) {
62                         return false;
63                 }
64                 if (!self::update1329()) {
65                         return false;
66                 }
67
68                 return true;
69         }
70
71         /**
72          * Updates the "global" field in the item table
73          *
74          * @return bool "true" when the job is done
75          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76          */
77         private static function update1194()
78         {
79                 // Was the script completed?
80                 if (DI::config()->get("system", "post_update_version") >= 1194) {
81                         return true;
82                 }
83
84                 Logger::log("Start", Logger::DEBUG);
85
86                 $end_id = DI::config()->get("system", "post_update_1194_end");
87                 if (!$end_id) {
88                         $r = q("SELECT `id` FROM `item` WHERE `uid` != 0 ORDER BY `id` DESC LIMIT 1");
89                         if ($r) {
90                                 DI::config()->set("system", "post_update_1194_end", $r[0]["id"]);
91                                 $end_id = DI::config()->get("system", "post_update_1194_end");
92                         }
93                 }
94
95                 Logger::log("End ID: ".$end_id, Logger::DEBUG);
96
97                 $start_id = DI::config()->get("system", "post_update_1194_start");
98
99                 $query1 = "SELECT `item`.`id` FROM `item` ";
100
101                 $query2 = "INNER JOIN `item` AS `shadow` ON `item`.`uri` = `shadow`.`uri` AND `shadow`.`uid` = 0 ";
102
103                 $query3 = "WHERE `item`.`uid` != 0 AND `item`.`id` >= %d AND `item`.`id` <= %d
104                                 AND `item`.`visible` AND NOT `item`.`private`
105                                 AND NOT `item`.`deleted` AND NOT `item`.`moderated`
106                                 AND `item`.`network` IN ('%s', '%s', '%s', '')
107                                 AND NOT `item`.`global`";
108
109                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1",
110                         intval($start_id), intval($end_id),
111                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
112                 if (!$r) {
113                         DI::config()->set("system", "post_update_version", 1194);
114                         Logger::log("Update is done", Logger::DEBUG);
115                         return true;
116                 } else {
117                         DI::config()->set("system", "post_update_1194_start", $r[0]["id"]);
118                         $start_id = DI::config()->get("system", "post_update_1194_start");
119                 }
120
121                 Logger::log("Start ID: ".$start_id, Logger::DEBUG);
122
123                 $r = q($query1.$query2.$query3."  ORDER BY `item`.`id` LIMIT 1000,1",
124                         intval($start_id), intval($end_id),
125                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
126                 if ($r) {
127                         $pos_id = $r[0]["id"];
128                 } else {
129                         $pos_id = $end_id;
130                 }
131                 Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
132
133                 q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
134                         intval($start_id), intval($pos_id),
135                         DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
136
137                 Logger::log("Done", Logger::DEBUG);
138         }
139
140         /**
141          * update the "last-item" field in the "self" contact
142          *
143          * This field avoids cost intensive calls in the admin panel and in "nodeinfo"
144          *
145          * @return bool "true" when the job is done
146          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147          */
148         private static function update1206()
149         {
150                 // Was the script completed?
151                 if (DI::config()->get("system", "post_update_version") >= 1206) {
152                         return true;
153                 }
154
155                 Logger::log("Start", Logger::DEBUG);
156                 $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
157                         (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
158                         FROM `user`
159                         INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self`");
160
161                 if (!DBA::isResult($r)) {
162                         return false;
163                 }
164                 foreach ($r as $user) {
165                         if (!empty($user["lastitem_date"]) && ($user["lastitem_date"] > $user["last-item"])) {
166                                 DBA::update('contact', ['last-item' => $user['lastitem_date']], ['id' => $user['id']]);
167                         }
168                 }
169
170                 DI::config()->set("system", "post_update_version", 1206);
171                 Logger::log("Done", Logger::DEBUG);
172                 return true;
173         }
174
175         /**
176          * update the item related tables
177          *
178          * @return bool "true" when the job is done
179          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180          * @throws \ImagickException
181          */
182         private static function update1279()
183         {
184                 // Was the script completed?
185                 if (DI::config()->get("system", "post_update_version") >= 1279) {
186                         return true;
187                 }
188
189                 $id = DI::config()->get("system", "post_update_version_1279_id", 0);
190
191                 Logger::log("Start from item " . $id, Logger::DEBUG);
192
193                 $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
194                         'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
195                         'uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid', 'post-type', 'bookmark', 'type',
196                         'inform', 'postopts', 'icid']);
197
198                 $start_id = $id;
199                 $rows = 0;
200                 $condition = ["`id` > ?", $id];
201                 $params = ['order' => ['id'], 'limit' => 10000];
202                 $items = Item::select($fields, $condition, $params);
203
204                 if (DBA::errorNo() != 0) {
205                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
206                         return false;
207                 }
208
209                 while ($item = Item::fetch($items)) {
210                         $id = $item['id'];
211
212                         if (empty($item['author-id'])) {
213                                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
214                                         'photo' => $item['author-avatar'], 'network' => $item['network']];
215
216                                 $item['author-id'] = Contact::getIdForURL($item["author-link"], 0, false, $default);
217                         }
218
219                         if (empty($item['owner-id'])) {
220                                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
221                                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
222
223                                 $item['owner-id'] = Contact::getIdForURL($item["owner-link"], 0, false, $default);
224                         }
225
226                         if (empty($item['psid'])) {
227                                 $item['psid'] = PermissionSet::getIdFromACL(
228                                         $item['uid'],
229                                         $item['allow_cid'],
230                                         $item['allow_gid'],
231                                         $item['deny_cid'],
232                                         $item['deny_gid']
233                                 );
234                         }
235
236                         $item['allow_cid'] = null;
237                         $item['allow_gid'] = null;
238                         $item['deny_cid'] = null;
239                         $item['deny_gid'] = null;
240
241                         if ($item['post-type'] == 0) {
242                                 if (!empty($item['type']) && ($item['type'] == 'note')) {
243                                         $item['post-type'] = Item::PT_PERSONAL_NOTE;
244                                 } elseif (!empty($item['type']) && ($item['type'] == 'photo')) {
245                                         $item['post-type'] = Item::PT_IMAGE;
246                                 } elseif (!empty($item['bookmark']) && $item['bookmark']) {
247                                         $item['post-type'] = Item::PT_PAGE;
248                                 }
249                         }
250
251                         self::createLanguage($item);
252
253                         if (!empty($item['icid']) && !empty($item['language'])) {
254                                 DBA::update('item-content', ['language' => $item['language']], ['id' => $item['icid']]);
255                         }
256                         unset($item['language']);
257
258                         Item::update($item, ['id' => $id]);
259
260                         ++$rows;
261                 }
262                 DBA::close($items);
263
264                 DI::config()->set("system", "post_update_version_1279_id", $id);
265
266                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
267
268                 if ($start_id == $id) {
269                         // Set all deprecated fields to "null" if they contain an empty string
270                         $nullfields = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'postopts', 'inform', 'type',
271                                 'bookmark', 'file', 'location', 'coord', 'tag', 'plink', 'title', 'content-warning',
272                                 'body', 'app', 'verb', 'object-type', 'object', 'target-type', 'target',
273                                 'author-name', 'author-link', 'author-avatar', 'owner-name', 'owner-link', 'owner-avatar',
274                                 'rendered-hash', 'rendered-html'];
275                         foreach ($nullfields as $field) {
276                                 $fields = [$field => null];
277                                 $condition = [$field => ''];
278                                 Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
279                                 // Important: This has to be a "DBA::update", not a "Item::update"
280                                 DBA::update('item', $fields, $condition);
281                         }
282
283                         DI::config()->set("system", "post_update_version", 1279);
284                         Logger::log("Done", Logger::DEBUG);
285                         return true;
286                 }
287
288                 return false;
289         }
290
291         private static function createLanguage(&$item)
292         {
293                 if (empty($item['postopts'])) {
294                         return;
295                 }
296
297                 $opts = explode(',', $item['postopts']);
298
299                 $postopts = [];
300
301                 foreach ($opts as $opt) {
302                         if (strstr($opt, 'lang=')) {
303                                 $language = substr($opt, 5);
304                         } else {
305                                 $postopts[] = $opt;
306                         }
307                 }
308
309                 if (empty($language)) {
310                         return;
311                 }
312
313                 if (!empty($postopts)) {
314                         $item['postopts'] = implode(',', $postopts);
315                 } else {
316                         $item['postopts'] = null;
317                 }
318
319                 $lang_pairs = explode(':', $language);
320
321                 $lang_arr = [];
322
323                 foreach ($lang_pairs as $pair) {
324                         $lang_pair_arr = explode(';', $pair);
325                         if (count($lang_pair_arr) == 2) {
326                                 $lang_arr[$lang_pair_arr[0]] = $lang_pair_arr[1];
327                         }
328                 }
329
330                 $item['language'] = json_encode($lang_arr);
331         }
332
333         /**
334          * update item-uri data. Prerequisite for the next item structure update.
335          *
336          * @return bool "true" when the job is done
337          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
338          */
339         private static function update1281()
340         {
341                 // Was the script completed?
342                 if (DI::config()->get("system", "post_update_version") >= 1281) {
343                         return true;
344                 }
345
346                 $id = DI::config()->get("system", "post_update_version_1281_id", 0);
347
348                 Logger::log("Start from item " . $id, Logger::DEBUG);
349
350                 $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
351
352                 $start_id = $id;
353                 $rows = 0;
354                 $condition = ["`id` > ?", $id];
355                 $params = ['order' => ['id'], 'limit' => 10000];
356                 $items = DBA::select('item', $fields, $condition, $params);
357
358                 if (DBA::errorNo() != 0) {
359                         Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
360                         return false;
361                 }
362
363                 while ($item = DBA::fetch($items)) {
364                         $id = $item['id'];
365
366                         if (empty($item['uri'])) {
367                                 // Should not happen
368                                 continue;
369                         } elseif (empty($item['uri-id'])) {
370                                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
371                         }
372
373                         if (empty($item['parent-uri'])) {
374                                 $item['parent-uri-id'] = $item['uri-id'];
375                         } elseif (empty($item['parent-uri-id'])) {
376                                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
377                         }
378
379                         // Very old items don't have this field
380                         if (empty($item['thr-parent'])) {
381                                 $item['thr-parent-id'] = $item['parent-uri-id'];
382                         } elseif (empty($item['thr-parent-id'])) {
383                                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
384                         }
385
386                         unset($item['id']);
387                         unset($item['guid']);
388                         unset($item['uri']);
389                         unset($item['parent-uri']);
390                         unset($item['thr-parent']);
391
392                         DBA::update('item', $item, ['id' => $id]);
393
394                         ++$rows;
395                 }
396                 DBA::close($items);
397
398                 DI::config()->set("system", "post_update_version_1281_id", $id);
399
400                 Logger::log("Processed rows: " . $rows . " - last processed item:  " . $id, Logger::DEBUG);
401
402                 if ($start_id == $id) {
403                         Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
404                         DBA::e("UPDATE `item-activity` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-activity`.`uri` SET `item-activity`.`uri-id` = `item-uri`.`id` WHERE `item-activity`.`uri-id` IS NULL");
405
406                         Logger::log("Updating item-uri in item-content", Logger::DEBUG);
407                         DBA::e("UPDATE `item-content` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-content`.`uri` SET `item-content`.`uri-id` = `item-uri`.`id` WHERE `item-content`.`uri-id` IS NULL");
408
409                         DI::config()->set("system", "post_update_version", 1281);
410                         Logger::log("Done", Logger::DEBUG);
411                         return true;
412                 }
413
414                 return false;
415         }
416
417         /**
418          * Set the delivery queue count to a negative value for all items preceding the feature.
419          *
420          * @return bool "true" when the job is done
421          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422          */
423         private static function update1297()
424         {
425                 // Was the script completed?
426                 if (DI::config()->get('system', 'post_update_version') >= 1297) {
427                         return true;
428                 }
429
430                 $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
431                 $max_iid = $max_item_delivery_data['iid'];
432
433                 Logger::info('Start update1297 with max iid: ' . $max_iid);
434
435                 $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
436
437                 DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
438
439                 if (DBA::errorNo() != 0) {
440                         Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
441                         return false;
442                 }
443
444                 Logger::info('Processed rows: ' . DBA::affectedRows());
445
446                 DI::config()->set('system', 'post_update_version', 1297);
447
448                 Logger::info('Done');
449
450                 return true;
451         }
452         /**
453          * Remove contact duplicates
454          *
455          * @return bool "true" when the job is done
456          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457          */
458         private static function update1322()
459         {
460                 // Was the script completed?
461                 if (DI::config()->get('system', 'post_update_version') >= 1322) {
462                         return true;
463                 }
464
465                 Logger::info('Start');
466
467                 $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
468                         WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
469                                 WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
470                         AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
471                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB,
472                         Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0);
473
474                 while ($contact = DBA::fetch($contacts)) {
475                         Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
476                         Contact::removeDuplicates($contact['nurl'], $contact['uid']);
477                 }
478
479                 DBA::close($contact);
480                 DI::config()->set('system', 'post_update_version', 1322);
481
482                 Logger::info('Done');
483
484                 return true;
485         }
486
487         /**
488          * update user-item data with notifications
489          *
490          * @return bool "true" when the job is done
491          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
492          */
493         private static function update1329()
494         {
495                 // Was the script completed?
496                 if (DI::config()->get('system', 'post_update_version') >= 1329) {
497                         return true;
498                 }
499
500                 $id = DI::config()->get('system', 'post_update_version_1329_id', 0);
501
502                 Logger::info('Start', ['item' => $id]);
503
504                 $start_id = $id;
505                 $rows = 0;
506                 $condition = ["`id` > ?", $id];
507                 $params = ['order' => ['id'], 'limit' => 10000];
508                 $items = DBA::select('item', ['id'], $condition, $params);
509
510                 if (DBA::errorNo() != 0) {
511                         Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
512                         return false;
513                 }
514
515                 while ($item = DBA::fetch($items)) {
516                         $id = $item['id'];
517
518                         UserItem::setNotification($item['id']);
519
520                         ++$rows;
521                 }
522                 DBA::close($items);
523
524                 DI::config()->set('system', 'post_update_version_1329_id', $id);
525
526                 Logger::info('Processed', ['rows' => $rows, 'last' => $id]);
527
528                 if ($start_id == $id) {
529                         DI::config()->set('system', 'post_update_version', 1329);
530                         Logger::info('Done');
531                         return true;
532                 }
533
534                 return false;
535         }
536 }