]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Insert a `user-contact` for every contact
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\Model;
23
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\OStatus;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
49
50 /**
51  * functions for interacting with a contact
52  */
53 class Contact
54 {
55         const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
56         const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
57         const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
58
59         /**
60          * @deprecated since version 2019.03
61          * @see User::PAGE_FLAGS_NORMAL
62          */
63         const PAGE_NORMAL    = User::PAGE_FLAGS_NORMAL;
64         /**
65          * @deprecated since version 2019.03
66          * @see User::PAGE_FLAGS_SOAPBOX
67          */
68         const PAGE_SOAPBOX   = User::PAGE_FLAGS_SOAPBOX;
69         /**
70          * @deprecated since version 2019.03
71          * @see User::PAGE_FLAGS_COMMUNITY
72          */
73         const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
74         /**
75          * @deprecated since version 2019.03
76          * @see User::PAGE_FLAGS_FREELOVE
77          */
78         const PAGE_FREELOVE  = User::PAGE_FLAGS_FREELOVE;
79         /**
80          * @deprecated since version 2019.03
81          * @see User::PAGE_FLAGS_BLOG
82          */
83         const PAGE_BLOG      = User::PAGE_FLAGS_BLOG;
84         /**
85          * @deprecated since version 2019.03
86          * @see User::PAGE_FLAGS_PRVGROUP
87          */
88         const PAGE_PRVGROUP  = User::PAGE_FLAGS_PRVGROUP;
89         /**
90          * @}
91          */
92
93         const LOCK_INSERT = 'contact-insert';
94
95         /**
96          * Account types
97          *
98          * TYPE_UNKNOWN - unknown type
99          *
100          * TYPE_PERSON - the account belongs to a person
101          *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
102          *
103          * TYPE_ORGANISATION - the account belongs to an organisation
104          *      Associated page type: PAGE_SOAPBOX
105          *
106          * TYPE_NEWS - the account is a news reflector
107          *      Associated page type: PAGE_SOAPBOX
108          *
109          * TYPE_COMMUNITY - the account is community forum
110          *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
111          *
112          * TYPE_RELAY - the account is a relay
113          *      This will only be assigned to contacts, not to user accounts
114          * @{
115          */
116         const TYPE_UNKNOWN =     -1;
117         const TYPE_PERSON =       User::ACCOUNT_TYPE_PERSON;
118         const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
119         const TYPE_NEWS =         User::ACCOUNT_TYPE_NEWS;
120         const TYPE_COMMUNITY =    User::ACCOUNT_TYPE_COMMUNITY;
121         const TYPE_RELAY =        User::ACCOUNT_TYPE_RELAY;
122         /**
123          * @}
124          */
125
126         /**
127          * Contact_is
128          *
129          * Relationship types
130          * @{
131          */
132         const NOTHING  = 0;
133         const FOLLOWER = 1;
134         const SHARING  = 2;
135         const FRIEND   = 3;
136         /**
137          * @}
138          */
139
140          const MIRROR_DEACTIVATED = 0;
141          const MIRROR_FORWARDED = 1;
142          const MIRROR_OWN_POST = 2;
143          const MIRROR_NATIVE_RESHARE = 3;
144
145          /**
146          * @param array $fields    Array of selected fields, empty for all
147          * @param array $condition Array of fields for condition
148          * @param array $params    Array of several parameters
149          * @return array
150          * @throws \Exception
151          */
152         public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
153         {
154                 return DBA::selectToArray('contact', $fields, $condition, $params);
155         }
156
157         /**
158          * @param array $fields    Array of selected fields, empty for all
159          * @param array $condition Array of fields for condition
160          * @param array $params    Array of several parameters
161          * @return array
162          * @throws \Exception
163          */
164         public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
165         {
166                 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
167
168                 return $contact;
169         }
170
171         /**
172          * Insert a row into the contact table
173          * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
174          *
175          * @param array $fields         field array
176          * @param int   $duplicate_mode Do an update on a duplicate entry
177          *
178          * @return int  id of the created contact
179          * @throws \Exception
180          */
181         public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
182         {
183                 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
184                         $fields['gsid'] = GServer::getID($fields['baseurl'], true);
185                 }
186
187                 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
188
189                 if (empty($fields['created'])) {
190                         $fields['created'] = DateTimeFormat::utcNow();
191                 }
192
193                 DBA::insert('contact', $fields, $duplicate_mode);
194                 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
195                 if (!DBA::isResult($contact)) {
196                         // Shouldn't happen
197                         Logger::warning('Created contact could not be found', ['fields' => $fields]);
198                         return 0;
199                 }
200
201                 Contact\User::insertForContactArray($contact);
202
203                 // Search for duplicated contacts and get rid of them
204                 if (!$contact['self']) {
205                         self::removeDuplicates($contact['nurl'], $contact['uid']);
206                 }
207
208                 return $contact['id'];
209         }
210
211         /**
212          * @param integer $id     Contact ID
213          * @param array   $fields Array of selected fields, empty for all
214          * @return array|boolean Contact record if it exists, false otherwise
215          * @throws \Exception
216          */
217         public static function getById($id, $fields = [])
218         {
219                 return DBA::selectFirst('contact', $fields, ['id' => $id]);
220         }
221
222         /**
223          * Fetches a contact by a given url
224          *
225          * @param string  $url    profile url
226          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
227          * @param array   $fields Field list
228          * @param integer $uid    User ID of the contact
229          * @return array contact array
230          */
231         public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
232         {
233                 if ($update || is_null($update)) {
234                         $cid = self::getIdForURL($url, $uid, $update);
235                         if (empty($cid)) {
236                                 return [];
237                         }
238
239                         $contact = self::getById($cid, $fields);
240                         if (empty($contact)) {
241                                 return [];
242                         }
243                         return $contact;
244                 }
245
246                 // Add internal fields
247                 $removal = [];
248                 if (!empty($fields)) {
249                         foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
250                                 if (!in_array($internal, $fields)) {
251                                         $fields[] = $internal;
252                                         $removal[] = $internal;
253                                 }
254                         }
255                 }
256
257                 // We first try the nurl (http://server.tld/nick), most common case
258                 $options = ['order' => ['id']];
259                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
260
261                 // Then the addr (nick@server.tld)
262                 if (!DBA::isResult($contact)) {
263                         $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
264                 }
265
266                 // Then the alias (which could be anything)
267                 if (!DBA::isResult($contact)) {
268                         // The link could be provided as http although we stored it as https
269                         $ssl_url = str_replace('http://', 'https://', $url);
270                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
271                         $contact = DBA::selectFirst('contact', $fields, $condition, $options);
272                 }
273
274                 if (!DBA::isResult($contact)) {
275                         return [];
276                 }
277
278                 // Update the contact in the background if needed
279                 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
280                 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
281                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
282                 }
283
284                 // Remove the internal fields
285                 foreach ($removal as $internal) {
286                         unset($contact[$internal]);
287                 }
288
289                 return $contact;
290         }
291
292         /**
293          * Fetches a contact for a given user by a given url.
294          * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
295          *
296          * @param string  $url    profile url
297          * @param integer $uid    User ID of the contact
298          * @param boolean $update true = always update, false = never update, null = update when not found or outdated
299          * @param array   $fields Field list
300          * @return array contact array
301          */
302         public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
303         {
304                 if ($uid != 0) {
305                         $contact = self::getByURL($url, $update, $fields, $uid);
306                         if (!empty($contact)) {
307                                 if (!empty($contact['id'])) {
308                                         $contact['cid'] = $contact['id'];
309                                         $contact['zid'] = 0;
310                                 }
311                                 return $contact;
312                         }
313                 }
314
315                 $contact = self::getByURL($url, $update, $fields);
316                 if (!empty($contact['id'])) {
317                         $contact['cid'] = 0;
318                         $contact['zid'] = $contact['id'];
319                 }
320                 return $contact;
321         }
322
323         /**
324          * Tests if the given contact is a follower
325          *
326          * @param int $cid Either public contact id or user's contact id
327          * @param int $uid User ID
328          *
329          * @return boolean is the contact id a follower?
330          * @throws HTTPException\InternalServerErrorException
331          * @throws \ImagickException
332          */
333         public static function isFollower($cid, $uid)
334         {
335                 if (Contact\User::isBlocked($cid, $uid)) {
336                         return false;
337                 }
338
339                 $cdata = self::getPublicAndUserContactID($cid, $uid);
340                 if (empty($cdata['user'])) {
341                         return false;
342                 }
343
344                 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
345                 return DBA::exists('contact', $condition);
346         }
347
348         /**
349          * Tests if the given contact url is a follower
350          *
351          * @param string $url Contact URL
352          * @param int    $uid User ID
353          *
354          * @return boolean is the contact id a follower?
355          * @throws HTTPException\InternalServerErrorException
356          * @throws \ImagickException
357          */
358         public static function isFollowerByURL($url, $uid)
359         {
360                 $cid = self::getIdForURL($url, $uid);
361
362                 if (empty($cid)) {
363                         return false;
364                 }
365
366                 return self::isFollower($cid, $uid);
367         }
368
369         /**
370          * Tests if the given user follow the given contact
371          *
372          * @param int $cid Either public contact id or user's contact id
373          * @param int $uid User ID
374          *
375          * @return boolean is the contact url being followed?
376          * @throws HTTPException\InternalServerErrorException
377          * @throws \ImagickException
378          */
379         public static function isSharing($cid, $uid)
380         {
381                 if (Contact\User::isBlocked($cid, $uid)) {
382                         return false;
383                 }
384
385                 $cdata = self::getPublicAndUserContactID($cid, $uid);
386                 if (empty($cdata['user'])) {
387                         return false;
388                 }
389
390                 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
391                 return DBA::exists('contact', $condition);
392         }
393
394         /**
395          * Tests if the given user follow the given contact url
396          *
397          * @param string $url Contact URL
398          * @param int    $uid User ID
399          *
400          * @return boolean is the contact url being followed?
401          * @throws HTTPException\InternalServerErrorException
402          * @throws \ImagickException
403          */
404         public static function isSharingByURL($url, $uid)
405         {
406                 $cid = self::getIdForURL($url, $uid);
407
408                 if (empty($cid)) {
409                         return false;
410                 }
411
412                 return self::isSharing($cid, $uid);
413         }
414
415         /**
416          * Get the basepath for a given contact link
417          *
418          * @param string $url The contact link
419          * @param boolean $dont_update Don't update the contact
420          *
421          * @return string basepath
422          * @throws HTTPException\InternalServerErrorException
423          * @throws \ImagickException
424          */
425         public static function getBasepath($url, $dont_update = false)
426         {
427                 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
428                 if (!DBA::isResult($contact)) {
429                         return '';
430                 }
431
432                 if (!empty($contact['baseurl'])) {
433                         return $contact['baseurl'];
434                 } elseif ($dont_update) {
435                         return '';
436                 }
437
438                 // Update the existing contact
439                 self::updateFromProbe($contact['id']);
440
441                 // And fetch the result
442                 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
443                 if (empty($contact['baseurl'])) {
444                         Logger::info('No baseurl for contact', ['url' => $url]);
445                         return '';
446                 }
447
448                 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
449                 return $contact['baseurl'];
450         }
451
452         /**
453          * Check if the given contact url is on the same server
454          *
455          * @param string $url The contact link
456          *
457          * @return boolean Is it the same server?
458          */
459         public static function isLocal($url)
460         {
461                 if (!parse_url($url, PHP_URL_SCHEME)) {
462                         $addr_parts = explode('@', $url);
463                         return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
464                 }
465
466                 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
467         }
468
469         /**
470          * Check if the given contact ID is on the same server
471          *
472          * @param string $url The contact link
473          *
474          * @return boolean Is it the same server?
475          */
476         public static function isLocalById(int $cid)
477         {
478                 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
479                 if (!DBA::isResult($contact)) {
480                         return false;
481                 }
482
483                 if (empty($contact['baseurl'])) {
484                         $baseurl = self::getBasepath($contact['url'], true);
485                 } else {
486                         $baseurl = $contact['baseurl'];
487                 }
488
489                 return Strings::compareLink($baseurl, DI::baseUrl());
490         }
491
492         /**
493          * Returns the public contact id of the given user id
494          *
495          * @param  integer $uid User ID
496          *
497          * @return integer|boolean Public contact id for given user id
498          * @throws \Exception
499          */
500         public static function getPublicIdByUserId($uid)
501         {
502                 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
503                 if (!DBA::isResult($self)) {
504                         return false;
505                 }
506                 return self::getIdForURL($self['url']);
507         }
508
509         /**
510          * Returns the contact id for the user and the public contact id for a given contact id
511          *
512          * @param int $cid Either public contact id or user's contact id
513          * @param int $uid User ID
514          *
515          * @return array with public and user's contact id
516          * @throws HTTPException\InternalServerErrorException
517          * @throws \ImagickException
518          */
519         public static function getPublicAndUserContactID($cid, $uid)
520         {
521                 // We have to use the legacy function as long as the post update hasn't finished
522                 if (DI::config()->get('system', 'post_update_version') < 1427) {
523                         return self::legacyGetPublicAndUserContactID($cid, $uid);
524                 }
525
526                 if (empty($uid) || empty($cid)) {
527                         return [];
528                 }
529
530                 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
531                 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
532                         return [];
533                 }
534
535                 $pcid = $contact['pid'];
536                 if ($contact['uid'] == $uid) {
537                         $ucid = $contact['id'];
538                 } else {
539                         $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
540                         if (DBA::isResult($contact)) {
541                                 $ucid = $contact['id'];
542                         } else {
543                                 $ucid = 0;
544                         }
545                 }
546
547                 return ['public' => $pcid, 'user' => $ucid];
548         }
549
550         /**
551          * Helper function for "getPublicAndUserContactID"
552          *
553          * @param int $cid Either public contact id or user's contact id
554          * @param int $uid User ID
555          *
556          * @return array with public and user's contact id
557          * @throws HTTPException\InternalServerErrorException
558          * @throws \ImagickException
559          */
560         private static function legacyGetPublicAndUserContactID($cid, $uid)
561         {
562                 if (empty($uid) || empty($cid)) {
563                         return [];
564                 }
565
566                 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
567                 if (!DBA::isResult($contact)) {
568                         return [];
569                 }
570
571                 // We quit when the user id don't match the user id of the provided contact
572                 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
573                         return [];
574                 }
575
576                 if ($contact['uid'] != 0) {
577                         $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
578                         if (empty($pcid)) {
579                                 return [];
580                         }
581                         $ucid = $contact['id'];
582                 } else {
583                         $pcid = $contact['id'];
584                         $ucid = self::getIdForURL($contact['url'], $uid);
585                 }
586
587                 return ['public' => $pcid, 'user' => $ucid];
588         }
589
590         /**
591          * Returns contact details for a given contact id in combination with a user id
592          *
593          * @param int $cid A contact ID
594          * @param int $uid The User ID
595          * @param array $fields The selected fields for the contact
596          *
597          * @return array The contact details
598          *
599          * @throws \Exception
600          */
601         public static function getContactForUser($cid, $uid, array $fields = [])
602         {
603                 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
604
605                 if (!DBA::isResult($contact)) {
606                         return [];
607                 } else {
608                         return $contact;
609                 }
610         }
611
612         /**
613          * Creates the self-contact for the provided user id
614          *
615          * @param int $uid
616          * @return bool Operation success
617          * @throws HTTPException\InternalServerErrorException
618          */
619         public static function createSelfFromUserId($uid)
620         {
621                 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
622                         ['uid' => $uid, 'account_expired' => false]);
623                 if (!DBA::isResult($user)) {
624                         return false;
625                 }
626
627                 $contact = [
628                         'uid'         => $user['uid'],
629                         'created'     => DateTimeFormat::utcNow(),
630                         'self'        => 1,
631                         'name'        => $user['username'],
632                         'nick'        => $user['nickname'],
633                         'pubkey'      => $user['pubkey'],
634                         'prvkey'      => $user['prvkey'],
635                         'photo'       => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
636                         'thumb'       => DI::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
637                         'micro'       => DI::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
638                         'blocked'     => 0,
639                         'pending'     => 0,
640                         'url'         => DI::baseUrl() . '/profile/' . $user['nickname'],
641                         'nurl'        => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
642                         'addr'        => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
643                         'request'     => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
644                         'notify'      => DI::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
645                         'poll'        => DI::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
646                         'confirm'     => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
647                         'poco'        => DI::baseUrl() . '/poco/'         . $user['nickname'],
648                         'name-date'   => DateTimeFormat::utcNow(),
649                         'uri-date'    => DateTimeFormat::utcNow(),
650                         'avatar-date' => DateTimeFormat::utcNow(),
651                         'closeness'   => 0
652                 ];
653
654                 $return = true;
655
656                 // Only create the entry if it doesn't exist yet
657                 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
658                         $return = (bool)self::insert($contact);
659                 }
660
661                 // Create the public contact
662                 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
663                         $contact['self']   = false;
664                         $contact['uid']    = 0;
665                         $contact['prvkey'] = null;
666
667                         self::insert($contact, Database::INSERT_IGNORE);
668                 }
669
670                 return $return;
671         }
672
673         /**
674          * Updates the self-contact for the provided user id
675          *
676          * @param int     $uid
677          * @param boolean $update_avatar Force the avatar update
678          * @return bool   "true" if updated
679          * @throws HTTPException\InternalServerErrorException
680          */
681         public static function updateSelfFromUserID($uid, $update_avatar = false)
682         {
683                 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
684                         'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
685                         'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
686                 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
687                 if (!DBA::isResult($self)) {
688                         return false;
689                 }
690
691                 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
692                 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
693                 if (!DBA::isResult($user)) {
694                         return false;
695                 }
696
697                 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
698                         'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
699                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
700                 if (!DBA::isResult($profile)) {
701                         return false;
702                 }
703
704                 $file_suffix = 'jpg';
705
706                 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
707                         'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
708                         'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
709                         'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
710                         'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
711
712                 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
713                 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
714                 $fields['nurl'] = Strings::normaliseLink($fields['url']);
715                 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
716                 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
717                 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
718                 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
719                 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
720                 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
721
722                 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
723                 if (DBA::isResult($avatar)) {
724                         if ($update_avatar) {
725                                 $fields['avatar-date'] = DateTimeFormat::utcNow();
726                         }
727
728                         // Creating the path to the avatar, beginning with the file suffix
729                         $types = Images::supportedTypes();
730                         if (isset($types[$avatar['type']])) {
731                                 $file_suffix = $types[$avatar['type']];
732                         }
733
734                         // We are adding a timestamp value so that other systems won't use cached content
735                         $timestamp = strtotime($fields['avatar-date']);
736
737                         $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
738                         $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
739
740                         $fields['photo'] = $prefix . '4' . $suffix;
741                         $fields['thumb'] = $prefix . '5' . $suffix;
742                         $fields['micro'] = $prefix . '6' . $suffix;
743                 } else {
744                         // We hadn't found a photo entry, so we use the default avatar
745                         $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
746                         $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
747                         $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
748                 }
749
750                 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
751                 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
752                 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
753                 $fields['unsearchable'] = !$profile['net-publish'];
754
755                 $update = false;
756
757                 foreach ($fields as $field => $content) {
758                         if ($self[$field] != $content) {
759                                 $update = true;
760                         }
761                 }
762
763                 if ($update) {
764                         if ($fields['name'] != $self['name']) {
765                                 $fields['name-date'] = DateTimeFormat::utcNow();
766                         }
767                         $fields['updated'] = DateTimeFormat::utcNow();
768                         DBA::update('contact', $fields, ['id' => $self['id']]);
769
770                         // Update the public contact as well
771                         $fields['prvkey'] = null;
772                         $fields['self']   = false;
773                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
774
775                         // Update the profile
776                         $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
777                                 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
778                         DBA::update('profile', $fields, ['uid' => $uid]);
779                 }
780
781                 return $update;
782         }
783
784         /**
785          * Marks a contact for removal
786          *
787          * @param int $id contact id
788          * @return null
789          * @throws HTTPException\InternalServerErrorException
790          */
791         public static function remove($id)
792         {
793                 // We want just to make sure that we don't delete our "self" contact
794                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
795                 if (!DBA::isResult($contact)) {
796                         return;
797                 }
798
799                 // Archive the contact
800                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
801
802                 // Delete it in the background
803                 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
804         }
805
806         /**
807          * Sends an unfriend message. Does not remove the contact
808          *
809          * @param array   $user     User unfriending
810          * @param array   $contact  Contact unfriended
811          * @param boolean $dissolve Remove the contact on the remote side
812          * @return void
813          * @throws HTTPException\InternalServerErrorException
814          * @throws \ImagickException
815          */
816         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
817         {
818                 if (empty($contact['network'])) {
819                         return;
820                 }
821
822                 $protocol = $contact['network'];
823                 if (($protocol == Protocol::DFRN) && !empty($contact['protocol'])) {
824                         $protocol = $contact['protocol'];
825                 }
826
827                 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
828                         // create an unfollow slap
829                         $item = [];
830                         $item['verb'] = Activity::O_UNFOLLOW;
831                         $item['gravity'] = GRAVITY_ACTIVITY;
832                         $item['follow'] = $contact["url"];
833                         $item['body'] = '';
834                         $item['title'] = '';
835                         $item['guid'] = '';
836                         $item['uri-id'] = 0;
837                         $slap = OStatus::salmon($item, $user);
838
839                         if (!empty($contact['notify'])) {
840                                 Salmon::slapper($user, $contact['notify'], $slap);
841                         }
842                 } elseif ($protocol == Protocol::DIASPORA) {
843                         Diaspora::sendUnshare($user, $contact);
844                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
845                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
846
847                         if ($dissolve) {
848                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
849                         }
850                 }
851         }
852
853         /**
854          * Marks a contact for archival after a communication issue delay
855          *
856          * Contact has refused to recognise us as a friend. We will start a countdown.
857          * If they still don't recognise us in 32 days, the relationship is over,
858          * and we won't waste any more time trying to communicate with them.
859          * This provides for the possibility that their database is temporarily messed
860          * up or some other transient event and that there's a possibility we could recover from it.
861          *
862          * @param array $contact contact to mark for archival
863          * @return null
864          * @throws HTTPException\InternalServerErrorException
865          */
866         public static function markForArchival(array $contact)
867         {
868                 if (!isset($contact['url']) && !empty($contact['id'])) {
869                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
870                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
871                         if (!DBA::isResult($contact)) {
872                                 return;
873                         }
874                 } elseif (!isset($contact['url'])) {
875                         Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
876                 }
877
878                 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
879
880                 // Contact already archived or "self" contact? => nothing to do
881                 if ($contact['archive'] || $contact['self']) {
882                         return;
883                 }
884
885                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
886                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
887                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
888                 } else {
889                         /* @todo
890                          * We really should send a notification to the owner after 2-3 weeks
891                          * so they won't be surprised when the contact vanishes and can take
892                          * remedial action if this was a serious mistake or glitch
893                          */
894
895                         /// @todo Check for contact vitality via probing
896                         $archival_days = DI::config()->get('system', 'archival_days', 32);
897
898                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
899                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
900                                 /* Relationship is really truly dead. archive them rather than
901                                  * delete, though if the owner tries to unarchive them we'll start
902                                  * the whole process over again.
903                                  */
904                                 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
905                                 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
906                         }
907                 }
908         }
909
910         /**
911          * Cancels the archival countdown
912          *
913          * @see   Contact::markForArchival()
914          *
915          * @param array $contact contact to be unmarked for archival
916          * @return null
917          * @throws \Exception
918          */
919         public static function unmarkForArchival(array $contact)
920         {
921                 // Always unarchive the relay contact entry
922                 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
923                         $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
924                         $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
925                         if (!DBA::exists('contact', array_merge($condition, $fields))) {
926                                 DBA::update('contact', $fields, $condition);
927                         }
928                 }
929
930                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
931                 $exists = DBA::exists('contact', $condition);
932
933                 // We don't need to update, we never marked this contact for archival
934                 if (!$exists) {
935                         return;
936                 }
937
938                 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
939
940                 if (!isset($contact['url']) && !empty($contact['id'])) {
941                         $fields = ['id', 'url', 'batch'];
942                         $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
943                         if (!DBA::isResult($contact)) {
944                                 return;
945                         }
946                 }
947
948                 // It's a miracle. Our dead contact has inexplicably come back to life.
949                 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
950                 DBA::update('contact', $fields, ['id' => $contact['id']]);
951                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
952         }
953
954         /**
955          * Returns the data array for the photo menu of a given contact
956          *
957          * @param array $contact contact
958          * @param int   $uid     optional, default 0
959          * @return array
960          * @throws HTTPException\InternalServerErrorException
961          * @throws \ImagickException
962          */
963         public static function photoMenu(array $contact, $uid = 0)
964         {
965                 $pm_url = '';
966                 $status_link = '';
967                 $photos_link = '';
968                 $contact_drop_link = '';
969                 $poke_link = '';
970
971                 if ($uid == 0) {
972                         $uid = local_user();
973                 }
974
975                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
976                         if ($uid == 0) {
977                                 $profile_link = self::magicLinkByContact($contact);
978                                 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
979
980                                 return $menu;
981                         }
982
983                         // Look for our own contact if the uid doesn't match and isn't public
984                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
985                         if (DBA::isResult($contact_own)) {
986                                 return self::photoMenu($contact_own, $uid);
987                         }
988                 }
989
990                 $sparkle = false;
991                 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
992                         $sparkle = true;
993                         $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
994                 } else {
995                         $profile_link = $contact['url'];
996                 }
997
998                 if ($profile_link === 'mailbox') {
999                         $profile_link = '';
1000                 }
1001
1002                 if ($sparkle) {
1003                         $status_link = $profile_link . '/status';
1004                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1005                         $profile_link = $profile_link . '/profile';
1006                 }
1007
1008                 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1009                         $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1010                 }
1011
1012                 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1013                         $poke_link = 'contact/' . $contact['id'] . '/poke';
1014                 }
1015
1016                 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1017
1018                 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1019
1020                 if (!$contact['self']) {
1021                         $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1022                 }
1023
1024                 $follow_link = '';
1025                 $unfollow_link = '';
1026                 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1027                         if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1028                                 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1029                         } elseif(!$contact['pending']) {
1030                                 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1031                         }
1032                 }
1033
1034                 if (!empty($follow_link) || !empty($unfollow_link)) {
1035                         $contact_drop_link = '';
1036                 }
1037
1038                 /**
1039                  * Menu array:
1040                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1041                  */
1042                 if (empty($contact['uid'])) {
1043                         $menu = [
1044                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link , true],
1045                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link   , false],
1046                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url  , false],
1047                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link  , true],
1048                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link, true],
1049                         ];
1050                 } else {
1051                         $menu = [
1052                                 'status'  => [DI::l10n()->t('View Status')   , $status_link      , true],
1053                                 'profile' => [DI::l10n()->t('View Profile')  , $profile_link     , true],
1054                                 'photos'  => [DI::l10n()->t('View Photos')   , $photos_link      , true],
1055                                 'network' => [DI::l10n()->t('Network Posts') , $posts_link       , false],
1056                                 'edit'    => [DI::l10n()->t('View Contact')  , $contact_url      , false],
1057                                 'drop'    => [DI::l10n()->t('Drop Contact')  , $contact_drop_link, false],
1058                                 'pm'      => [DI::l10n()->t('Send PM')       , $pm_url           , false],
1059                                 'poke'    => [DI::l10n()->t('Poke')          , $poke_link        , false],
1060                                 'follow'  => [DI::l10n()->t('Connect/Follow'), $follow_link      , true],
1061                                 'unfollow'=> [DI::l10n()->t('UnFollow')      , $unfollow_link    , true],
1062                         ];
1063
1064                         if (!empty($contact['pending'])) {
1065                                 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1066                                 if (DBA::isResult($intro)) {
1067                                         $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1068                                 }
1069                         }
1070                 }
1071
1072                 $args = ['contact' => $contact, 'menu' => &$menu];
1073
1074                 Hook::callAll('contact_photo_menu', $args);
1075
1076                 $menucondensed = [];
1077
1078                 foreach ($menu as $menuname => $menuitem) {
1079                         if ($menuitem[1] != '') {
1080                                 $menucondensed[$menuname] = $menuitem;
1081                         }
1082                 }
1083
1084                 return $menucondensed;
1085         }
1086
1087         /**
1088          * Fetch the contact id for a given URL and user
1089          *
1090          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1091          * `addr` or `alias`.
1092          *
1093          * If there's no record and we aren't looking for a public contact, we quit.
1094          * If there's one, we check that it isn't time to update the picture else we
1095          * directly return the found contact id.
1096          *
1097          * Second, we probe the provided $url whether it's http://server.tld/profile or
1098          * nick@server.tld. We quit if we can't get any info back.
1099          *
1100          * Third, we create the contact record if it doesn't exist
1101          *
1102          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1103          * if there's any updates
1104          *
1105          * @param string  $url       Contact URL
1106          * @param integer $uid       The user id for the contact (0 = public contact)
1107          * @param boolean $update    true = always update, false = never update, null = update when not found
1108          * @param array   $default   Default value for creating the contact when everything else fails
1109          *
1110          * @return integer Contact ID
1111          * @throws HTTPException\InternalServerErrorException
1112          * @throws \ImagickException
1113          */
1114         public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1115         {
1116                 $contact_id = 0;
1117
1118                 if ($url == '') {
1119                         Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1120                         return 0;
1121                 }
1122
1123                 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1124
1125                 if (!empty($contact)) {
1126                         $contact_id = $contact["id"];
1127
1128                         if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1129                                 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1130                                 return $contact_id;
1131                         }
1132                 } elseif ($uid != 0) {
1133                         Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1134                         return 0;
1135                 } elseif (empty($default) && !is_null($update) && !$update) {
1136                         Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1137                         return 0;
1138                 }
1139
1140                 $data = [];
1141
1142                 if (empty($default['network']) || $update) {
1143                         $data = Probe::uri($url, "", $uid);
1144
1145                         // Take the default values when probing failed
1146                         if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1147                                 $data = array_merge($data, $default);
1148                         }
1149                 } elseif (!empty($default['network'])) {
1150                         $data = $default;
1151                 }
1152
1153                 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1154                         // Fetch data for the public contact via the first found personal contact
1155                         /// @todo Check if this case can happen at all (possibly with mail accounts?)
1156                         $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1157                                 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1158                                 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1159
1160                         $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1161                         if (!DBA::isResult($personal_contact)) {
1162                                 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1163                         }
1164
1165                         if (DBA::isResult($personal_contact)) {
1166                                 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1167                                 $data = $personal_contact;
1168                                 $data['photo'] = $personal_contact['avatar'];
1169                                 $data['account-type'] = $personal_contact['contact-type'];
1170                                 $data['hide'] = $personal_contact['unsearchable'];
1171                                 unset($data['avatar']);
1172                                 unset($data['contact-type']);
1173                                 unset($data['unsearchable']);
1174                         }
1175                 }
1176
1177                 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1178                         Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1179                         return 0;
1180                 }
1181
1182                 if (!$contact_id) {
1183                         $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1184                         if (!empty($data['alias'])) {
1185                                 $urls[] = Strings::normaliseLink($data['alias']);
1186                         }
1187                         $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1188                         if (!empty($contact['id'])) {
1189                                 $contact_id = $contact['id'];
1190                                 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1191                         }
1192                 }
1193
1194                 if (!$contact_id) {
1195                         // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1196                         $fields = [
1197                                 'uid'       => $uid,
1198                                 'url'       => $data['url'],
1199                                 'nurl'      => Strings::normaliseLink($data['url']),
1200                                 'network'   => $data['network'],
1201                                 'created'   => DateTimeFormat::utcNow(),
1202                                 'rel'       => self::SHARING,
1203                                 'writable'  => 1,
1204                                 'blocked'   => 0,
1205                                 'readonly'  => 0,
1206                                 'pending'   => 0];
1207
1208                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1209
1210                         // Before inserting we do check if the entry does exist now.
1211                         if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1212                                 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1213                                 if (DBA::isResult($contact)) {
1214                                         $contact_id = $contact['id'];
1215                                         Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1216                                 } else {
1217                                         $contact_id = self::insert($fields);
1218                                         if ($contact_id) {
1219                                                 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1220                                         }
1221                                 }
1222                                 DI::lock()->release(self::LOCK_INSERT);
1223                         } else {
1224                                 Logger::warning('Contact lock had not been acquired');
1225                         }
1226
1227                         if (!$contact_id) {
1228                                 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1229                                 return 0;
1230                         }
1231                 } else {
1232                         Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1233                 }
1234
1235                 self::updateFromProbeArray($contact_id, $data);
1236
1237                 // Don't return a number for a deleted account
1238                 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1239                         Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1240                         return 0;
1241                 }
1242
1243                 return $contact_id;
1244         }
1245
1246         /**
1247          * Checks if the contact is archived
1248          *
1249          * @param int $cid contact id
1250          *
1251          * @return boolean Is the contact archived?
1252          * @throws HTTPException\InternalServerErrorException
1253          */
1254         public static function isArchived(int $cid)
1255         {
1256                 if ($cid == 0) {
1257                         return false;
1258                 }
1259
1260                 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1261                 if (!DBA::isResult($contact)) {
1262                         return false;
1263                 }
1264
1265                 if ($contact['archive']) {
1266                         return true;
1267                 }
1268
1269                 // Check status of ActivityPub endpoints
1270                 $apcontact = APContact::getByURL($contact['url'], false);
1271                 if (!empty($apcontact)) {
1272                         if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1273                                 return true;
1274                         }
1275
1276                         if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1277                                 return true;
1278                         }
1279                 }
1280
1281                 // Check status of Diaspora endpoints
1282                 if (!empty($contact['batch'])) {
1283                         $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1284                         return DBA::exists('contact', $condition);
1285                 }
1286
1287                 return false;
1288         }
1289
1290         /**
1291          * Checks if the contact is blocked
1292          *
1293          * @param int $cid contact id
1294          *
1295          * @return boolean Is the contact blocked?
1296          * @throws HTTPException\InternalServerErrorException
1297          */
1298         public static function isBlocked($cid)
1299         {
1300                 if ($cid == 0) {
1301                         return false;
1302                 }
1303
1304                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1305                 if (!DBA::isResult($blocked)) {
1306                         return false;
1307                 }
1308
1309                 if (Network::isUrlBlocked($blocked['url'])) {
1310                         return true;
1311                 }
1312
1313                 return (bool) $blocked['blocked'];
1314         }
1315
1316         /**
1317          * Checks if the contact is hidden
1318          *
1319          * @param int $cid contact id
1320          *
1321          * @return boolean Is the contact hidden?
1322          * @throws \Exception
1323          */
1324         public static function isHidden($cid)
1325         {
1326                 if ($cid == 0) {
1327                         return false;
1328                 }
1329
1330                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1331                 if (!DBA::isResult($hidden)) {
1332                         return false;
1333                 }
1334                 return (bool) $hidden['hidden'];
1335         }
1336
1337         /**
1338          * Returns posts from a given contact url
1339          *
1340          * @param string $contact_url Contact URL
1341          * @param bool   $thread_mode
1342          * @param int    $update      Update mode
1343          * @param int    $parent      Item parent ID for the update mode
1344          * @return string posts in HTML
1345          * @throws \Exception
1346          */
1347         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1348         {
1349                 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1350         }
1351
1352         /**
1353          * Returns posts from a given contact id
1354          *
1355          * @param int  $cid         Contact ID
1356          * @param bool $thread_mode
1357          * @param int  $update      Update mode
1358          * @param int  $parent     Item parent ID for the update mode
1359          * @return string posts in HTML
1360          * @throws \Exception
1361          */
1362         public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1363         {
1364                 $a = DI::app();
1365
1366                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1367                 if (!DBA::isResult($contact)) {
1368                         return '';
1369                 }
1370
1371                 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1372                         $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1373                 } else {
1374                         $sql = "`uid` = ?";
1375                 }
1376
1377                 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1378
1379                 if ($thread_mode) {
1380                         $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1381                                 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1382                 } else {
1383                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1384                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1385                 }
1386
1387                 if (!empty($parent)) {
1388                         $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1389                 } else {
1390                         $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1391                         if (!empty($last_received)) {
1392                                 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1393                         }
1394                 }
1395
1396                 if (DI::mode()->isMobile()) {
1397                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1398                                 DI::config()->get('system', 'itemspage_network_mobile'));
1399                 } else {
1400                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1401                                 DI::config()->get('system', 'itemspage_network'));
1402                 }
1403
1404                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1405
1406                 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1407
1408                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1409                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1410                         $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1411                 } else {
1412                         $o = '';
1413                 }
1414
1415                 if ($thread_mode) {
1416                         $items = Post::toArray(Post::selectForUser(local_user(), ['uri-id', 'gravity', 'parent-uri-id', 'thr-parent-id', 'author-id'], $condition, $params));
1417
1418                         $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1419                 } else {
1420                         $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1421
1422                         $o .= conversation($a, $items, 'contact-posts', $update);
1423                 }
1424
1425                 if (!$update) {
1426                         if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1427                                 $o .= HTML::scrollLoader();
1428                         } else {
1429                                 $o .= $pager->renderMinimal(count($items));
1430                         }
1431                 }
1432
1433                 return $o;
1434         }
1435
1436         /**
1437          * Returns the account type name
1438          *
1439          * The function can be called with either the user or the contact array
1440          *
1441          * @param array $contact contact or user array
1442          * @return string
1443          */
1444         public static function getAccountType(array $contact)
1445         {
1446                 // There are several fields that indicate that the contact or user is a forum
1447                 // "page-flags" is a field in the user table,
1448                 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1449                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1450                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1451                         || (isset($contact['forum']) && intval($contact['forum']))
1452                         || (isset($contact['prv']) && intval($contact['prv']))
1453                         || (isset($contact['community']) && intval($contact['community']))
1454                 ) {
1455                         $type = self::TYPE_COMMUNITY;
1456                 } else {
1457                         $type = self::TYPE_PERSON;
1458                 }
1459
1460                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1461                 if (isset($contact["contact-type"])) {
1462                         $type = $contact["contact-type"];
1463                 }
1464
1465                 if (isset($contact["account-type"])) {
1466                         $type = $contact["account-type"];
1467                 }
1468
1469                 switch ($type) {
1470                         case self::TYPE_ORGANISATION:
1471                                 $account_type = DI::l10n()->t("Organisation");
1472                                 break;
1473
1474                         case self::TYPE_NEWS:
1475                                 $account_type = DI::l10n()->t('News');
1476                                 break;
1477
1478                         case self::TYPE_COMMUNITY:
1479                                 $account_type = DI::l10n()->t("Forum");
1480                                 break;
1481
1482                         default:
1483                                 $account_type = "";
1484                                 break;
1485                 }
1486
1487                 return $account_type;
1488         }
1489
1490         /**
1491          * Blocks a contact
1492          *
1493          * @param int $cid
1494          * @return bool
1495          * @throws \Exception
1496          */
1497         public static function block($cid, $reason = null)
1498         {
1499                 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1500
1501                 return $return;
1502         }
1503
1504         /**
1505          * Unblocks a contact
1506          *
1507          * @param int $cid
1508          * @return bool
1509          * @throws \Exception
1510          */
1511         public static function unblock($cid)
1512         {
1513                 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1514
1515                 return $return;
1516         }
1517
1518         /**
1519          * Ensure that cached avatar exist
1520          *
1521          * @param integer $cid
1522          */
1523         public static function checkAvatarCache(int $cid)
1524         {
1525                 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1526                 if (!DBA::isResult($contact)) {
1527                         return;
1528                 }
1529
1530                 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1531                         return;
1532                 }
1533
1534                 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1535
1536                 self::updateAvatar($cid, $contact['avatar'], true);
1537         }
1538
1539         /**
1540          * Return the photo path for a given contact array in the given size
1541          *
1542          * @param array $contact    contact array
1543          * @param string $field     Fieldname of the photo in the contact array
1544          * @param string $size      Size of the avatar picture
1545          * @param string $avatar    Avatar path that is displayed when no photo had been found
1546          * @param bool  $no_update Don't perfom an update if no cached avatar was found
1547          * @return string photo path
1548          */
1549         private static function getAvatarPath(array $contact, string $size, $no_update = false)
1550         {
1551                 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1552                 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1553         }
1554
1555         /**
1556          * Return the photo path for a given contact array
1557          *
1558          * @param array  $contact   Contact array
1559          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1560          * @return string photo path
1561          */
1562         public static function getPhoto(array $contact, bool $no_update = false)
1563         {
1564                 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1565         }
1566
1567         /**
1568          * Return the photo path (thumb size) for a given contact array
1569          *
1570          * @param array  $contact   Contact array
1571          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1572          * @return string photo path
1573          */
1574         public static function getThumb(array $contact, bool $no_update = false)
1575         {
1576                 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1577         }
1578
1579         /**
1580          * Return the photo path (micro size) for a given contact array
1581          *
1582          * @param array  $contact   Contact array
1583          * @param bool   $no_update Don't perfom an update if no cached avatar was found
1584          * @return string photo path
1585          */
1586         public static function getMicro(array $contact, bool $no_update = false)
1587         {
1588                 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1589         }
1590
1591         /**
1592          * Check the given contact array for avatar cache fields
1593          *
1594          * @param array $contact
1595          * @param bool  $no_update Don't perfom an update if no cached avatar was found
1596          * @return array contact array with avatar cache fields
1597          */
1598         private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1599         {
1600                 $update = false;
1601                 $contact_fields = [];
1602                 $fields = ['photo', 'thumb', 'micro'];
1603                 foreach ($fields as $field) {
1604                         if (isset($contact[$field])) {
1605                                 $contact_fields[] = $field;
1606                         }
1607                         if (isset($contact[$field]) && empty($contact[$field])) {
1608                                 $update = true;
1609                         }
1610                 }
1611
1612                 if (!$update || $no_update) {
1613                         return $contact;
1614                 }
1615
1616                 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1617                         self::updateAvatar($contact['id'], $contact['avatar'], true);
1618
1619                         $new_contact = self::getById($contact['id'], $contact_fields);
1620                         if (DBA::isResult($new_contact)) {
1621                                 // We only update the cache fields
1622                                 $contact = array_merge($contact, $new_contact);
1623                         }
1624                 }
1625
1626                 /// add the default avatars if the fields aren't filled
1627                 if (isset($contact['photo']) && empty($contact['photo'])) {
1628                         $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1629                 }
1630                 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1631                         $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1632                 }
1633                 if (isset($contact['micro']) && empty($contact['micro'])) {
1634                         $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1635                 }
1636
1637                 return $contact;
1638         }
1639
1640         /**
1641          * Fetch the default avatar for the given contact and size
1642          *
1643          * @param array $contact  contact array
1644          * @param string $size    Size of the avatar picture
1645          * @return string avatar URL
1646          */
1647         public static function getDefaultAvatar(array $contact, string $size)
1648         {
1649                 switch ($size) {
1650                         case Proxy::SIZE_MICRO:
1651                                 $avatar['size'] = 48;
1652                                 $default = self::DEFAULT_AVATAR_MICRO;
1653                                 break;
1654
1655                         case Proxy::SIZE_THUMB:
1656                                 $avatar['size'] = 80;
1657                                 $default = self::DEFAULT_AVATAR_THUMB;
1658                                 break;
1659
1660                         case Proxy::SIZE_SMALL:
1661                         default:
1662                                 $avatar['size'] = 300;
1663                                 $default = self::DEFAULT_AVATAR_PHOTO;
1664                                 break;
1665                 }
1666
1667                 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1668                         return DI::baseUrl() . $default;
1669                 }
1670
1671                 if (!empty($contact['xmpp'])) {
1672                         $avatar['email'] = $contact['xmpp'];
1673                 } elseif (!empty($contact['addr'])) {
1674                         $avatar['email'] = $contact['addr'];
1675                 } elseif (!empty($contact['url'])) {
1676                         $avatar['email'] = $contact['url'];
1677                 } else {
1678                         return DI::baseUrl() . $default;
1679                 }
1680
1681                 $avatar['url'] = '';
1682                 $avatar['success'] = false;
1683
1684                 Hook::callAll('avatar_lookup', $avatar);
1685
1686                 if ($avatar['success'] && !empty($avatar['url'])) {
1687                         return $avatar['url'];
1688                 }
1689
1690                 return DI::baseUrl() . $default;
1691         }
1692
1693         /**
1694          * Get avatar link for given contact id
1695          *
1696          * @param integer $cid     contact id
1697          * @param string  $size    One of the ProxyUtils::SIZE_* constants
1698          * @param string  $updated Contact update date
1699          * @return string avatar link
1700          */
1701         public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = ''):string
1702         {
1703                 // We have to fetch the "updated" variable when it wasn't provided
1704                 // The parameter can be provided to improve performance
1705                 if (empty($updated)) {
1706                         $contact = self::getById($cid, ['updated']);
1707                         $updated = $contact['updated'] ?? '';
1708                 }
1709
1710                 $url = DI::baseUrl() . '/photo/contact/';
1711                 switch ($size) {
1712                         case Proxy::SIZE_MICRO:
1713                                 $url .= Proxy::PIXEL_MICRO . '/';
1714                                 break;
1715                         case Proxy::SIZE_THUMB:
1716                                 $url .= Proxy::PIXEL_THUMB . '/';
1717                                 break;
1718                         case Proxy::SIZE_SMALL:
1719                                 $url .= Proxy::PIXEL_SMALL . '/';
1720                                 break;
1721                         case Proxy::SIZE_MEDIUM:
1722                                 $url .= Proxy::PIXEL_MEDIUM . '/';
1723                                 break;
1724                         case Proxy::SIZE_LARGE:
1725                                 $url .= Proxy::PIXEL_LARGE . '/';
1726                                 break;
1727                 }
1728                 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1729         }
1730
1731         /**
1732          * Get avatar link for given contact URL
1733          *
1734          * @param string  $url  contact url
1735          * @param integer $uid  user id
1736          * @param string  $size One of the ProxyUtils::SIZE_* constants
1737          * @return string avatar link
1738          */
1739         public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1740         {
1741                 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1742                         Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1743                 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1744                 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1745         }
1746
1747         /**
1748          * Get header link for given contact id
1749          *
1750          * @param integer $cid     contact id
1751          * @param string  $size    One of the ProxyUtils::SIZE_* constants
1752          * @param string  $updated Contact update date
1753          * @return string header link
1754          */
1755         public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = ''):string
1756         {
1757                 // We have to fetch the "updated" variable when it wasn't provided
1758                 // The parameter can be provided to improve performance
1759                 if (empty($updated)) {
1760                         $contact = self::getById($cid, ['updated']);
1761                         $updated = $contact['updated'] ?? '';
1762                 }
1763
1764                 $url = DI::baseUrl() . '/photo/header/';
1765                 switch ($size) {
1766                         case Proxy::SIZE_MICRO:
1767                                 $url .= Proxy::PIXEL_MICRO . '/';
1768                                 break;
1769                         case Proxy::SIZE_THUMB:
1770                                 $url .= Proxy::PIXEL_THUMB . '/';
1771                                 break;
1772                         case Proxy::SIZE_SMALL:
1773                                 $url .= Proxy::PIXEL_SMALL . '/';
1774                                 break;
1775                         case Proxy::SIZE_MEDIUM:
1776                                 $url .= Proxy::PIXEL_MEDIUM . '/';
1777                                 break;
1778                         case Proxy::SIZE_LARGE:
1779                                 $url .= Proxy::PIXEL_LARGE . '/';
1780                                 break;
1781                 }
1782
1783                 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1784         }
1785
1786         /**
1787          * Updates the avatar links in a contact only if needed
1788          *
1789          * @param int    $cid          Contact id
1790          * @param string $avatar       Link to avatar picture
1791          * @param bool   $force        force picture update
1792          * @param bool   $create_cache Enforces the creation of cached avatar fields
1793          *
1794          * @return void
1795          * @throws HTTPException\InternalServerErrorException
1796          * @throws HTTPException\NotFoundException
1797          * @throws \ImagickException
1798          */
1799         public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1800         {
1801                 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network'],
1802                         ['id' => $cid, 'self' => false]);
1803                 if (!DBA::isResult($contact)) {
1804                         return;
1805                 }
1806
1807                 $uid = $contact['uid'];
1808
1809                 // Only update the cached photo links of public contacts when they already are cached
1810                 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1811                         if ($contact['avatar'] != $avatar) {
1812                                 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1813                                 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1814                         }
1815                         return;
1816                 }
1817
1818                 // User contacts use are updated through the public contacts
1819                 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1820                         $pcid = self::getIdForURL($contact['url'], 0, false);
1821                         if (!empty($pcid)) {
1822                                 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1823                                 self::updateAvatar($pcid, $avatar, $force, true);
1824                                 return;
1825                         }
1826                 }
1827
1828                 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1829
1830                 if ($default_avatar) {
1831                         $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1832                 }
1833
1834                 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1835                         $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1836                                 'photo' => $avatar,
1837                                 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1838                                 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1839                         Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1840                 }
1841
1842                 // Use the data from the self account
1843                 if (empty($fields)) {
1844                         $local_uid = User::getIdForURL($contact['url']);
1845                         if (!empty($local_uid)) {
1846                                 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1847                                 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1848                         }
1849                 }
1850
1851                 if (empty($fields)) {
1852                         $update = ($contact['avatar'] != $avatar) || $force;
1853
1854                         if (!$update) {
1855                                 $data = [
1856                                         $contact['photo'] ?? '',
1857                                         $contact['thumb'] ?? '',
1858                                         $contact['micro'] ?? '',
1859                                 ];
1860
1861                                 foreach ($data as $image_uri) {
1862                                         $image_rid = Photo::ridFromURI($image_uri);
1863                                         if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1864                                                 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1865                                                 $update = true;
1866                                         }
1867                                 }
1868                         }
1869
1870                         if ($update) {
1871                                 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1872                                 if ($photos) {
1873                                         $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1874                                         $update = !empty($fields);
1875                                         Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1876                                 } else {
1877                                         $update = false;
1878                                 }
1879                         }
1880                 } else {
1881                         $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1882                 }
1883
1884                 if (!$update) {
1885                         return;
1886                 }
1887
1888                 $cids = [];
1889                 $uids = [];
1890                 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1891                         // Collect all user contacts of the given public contact
1892                         $personal_contacts = DBA::select('contact', ['id', 'uid'],
1893                                 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1894                         while ($personal_contact = DBA::fetch($personal_contacts)) {
1895                                 $cids[] = $personal_contact['id'];
1896                                 $uids[] = $personal_contact['uid'];
1897                         }
1898                         DBA::close($personal_contacts);
1899
1900                         if (!empty($cids)) {
1901                                 // Delete possibly existing cached user contact avatars
1902                                 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1903                         }
1904                 }
1905
1906                 $cids[] = $cid;
1907                 $uids[] = $uid;
1908                 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1909                 DBA::update('contact', $fields, ['id' => $cids]);
1910         }
1911
1912         public static function deleteContactByUrl(string $url)
1913         {
1914                 // Update contact data for all users
1915                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
1916                 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
1917                 while ($contact = DBA::fetch($contacts)) {
1918                         Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
1919                         self::remove($contact['id']);
1920                 }
1921         }
1922
1923         /**
1924          * Helper function for "updateFromProbe". Updates personal and public contact
1925          *
1926          * @param integer $id      contact id
1927          * @param integer $uid     user id
1928          * @param string  $old_url The previous profile URL of the contact
1929          * @param string  $new_url The profile URL of the contact
1930          * @param array   $fields  The fields that are updated
1931          *
1932          * @throws \Exception
1933          */
1934         private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
1935         {
1936                 if (!DBA::update('contact', $fields, ['id' => $id])) {
1937                         Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1938                         return;
1939                 }
1940
1941                 // Search for duplicated contacts and get rid of them
1942                 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
1943                         return;
1944                 }
1945
1946                 // Archive or unarchive the contact.
1947                 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1948                 if (!DBA::isResult($contact)) {
1949                         Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1950                         return;
1951                 }
1952
1953                 if (isset($fields['failed'])) {
1954                         if ($fields['failed']) {
1955                                 self::markForArchival($contact);
1956                         } else {
1957                                 self::unmarkForArchival($contact);
1958                         }
1959                 }
1960
1961                 if ($contact['uid'] != 0) {
1962                         return;
1963                 }
1964
1965                 // Update contact data for all users
1966                 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
1967
1968                 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
1969                 DBA::update('contact', $fields, $condition);
1970
1971                 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
1972                 $condition['network'] = Protocol::OSTATUS;
1973
1974                 // If the contact failed, propagate the update fields to all contacts
1975                 if (empty($fields['failed'])) {
1976                         unset($fields['last-update']);
1977                         unset($fields['success_update']);
1978                         unset($fields['failure_update']);
1979                 }
1980
1981                 if (empty($fields)) {
1982                         return;
1983                 }
1984
1985                 DBA::update('contact', $fields, $condition);
1986         }
1987
1988         /**
1989          * Remove duplicated contacts
1990          *
1991          * @param string  $nurl  Normalised contact url
1992          * @param integer $uid   User id
1993          * @return boolean
1994          * @throws \Exception
1995          */
1996         public static function removeDuplicates(string $nurl, int $uid)
1997         {
1998                 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
1999                 $count = DBA::count('contact', $condition);
2000                 if ($count <= 1) {
2001                         return false;
2002                 }
2003
2004                 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2005                 if (!DBA::isResult($first_contact)) {
2006                         // Shouldn't happen - so we handle it
2007                         return false;
2008                 }
2009
2010                 $first = $first_contact['id'];
2011                 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2012                 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2013                         // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2014                         Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2015                         return false;
2016                 }
2017
2018                 // Find all duplicates
2019                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2020                 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2021                 while ($duplicate = DBA::fetch($duplicates)) {
2022                         if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2023                                 continue;
2024                         }
2025
2026                         Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2027                 }
2028                 DBA::close($duplicates);
2029                 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2030                 return true;
2031         }
2032
2033         /**
2034          * @param integer $id      contact id
2035          * @param string  $network Optional network we are probing for
2036          * @return boolean
2037          * @throws HTTPException\InternalServerErrorException
2038          * @throws \ImagickException
2039          */
2040         public static function updateFromProbe(int $id, string $network = '')
2041         {
2042                 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2043                 if (!DBA::isResult($contact)) {
2044                         return false;
2045                 }
2046
2047                 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2048                 return self::updateFromProbeArray($id, $ret);
2049         }
2050
2051         /**
2052          * @param integer $id      contact id
2053          * @param array   $ret     Probed data
2054          * @return boolean
2055          * @throws HTTPException\InternalServerErrorException
2056          * @throws \ImagickException
2057          */
2058         private static function updateFromProbeArray(int $id, array $ret)
2059         {
2060                 /*
2061                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2062                   This will reliably kill your communication with old Friendica contacts.
2063                  */
2064
2065                 // These fields aren't updated by this routine:
2066                 // 'sensitive'
2067
2068                 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2069                         'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2070                         'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2071                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2072                 if (!DBA::isResult($contact)) {
2073                         return false;
2074                 }
2075
2076                 if (self::isLocal($ret['url'])) {
2077                         if ($contact['uid'] == 0) {
2078                                 Logger::info('Local contacts are not updated here.');
2079                         } else {
2080                                 self::updateFromPublicContact($id, $contact);
2081                         }
2082                         return true;
2083                 }
2084
2085                 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2086                         Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2087                         self::remove($id);
2088
2089                         // Delete all contacts with the same URL
2090                         self::deleteContactByUrl($ret['url']);
2091                         return true;
2092                 }
2093
2094                 $uid = $contact['uid'];
2095                 unset($contact['uid']);
2096
2097                 $uriid = $contact['uri-id'];
2098                 unset($contact['uri-id']);
2099
2100                 $pubkey = $contact['pubkey'];
2101                 unset($contact['pubkey']);
2102
2103                 $contact['photo'] = $contact['avatar'];
2104                 unset($contact['avatar']);
2105
2106                 $updated = DateTimeFormat::utcNow();
2107
2108                 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2109                         Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2110                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2111                         return false;
2112                 }
2113
2114                 // We must not try to update relay contacts via probe. They are no real contacts.
2115                 // We check after the probing to be able to correct falsely detected contact types.
2116                 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2117                         (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2118                         self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2119                         Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2120                         return true;
2121                 }
2122
2123                 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2124                 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2125                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2126                         return false;
2127                 }
2128
2129                 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2130                         $cid = self::getIdForURL($ret['url'], 0, false);
2131                         if (!empty($cid) && ($cid != $id)) {
2132                                 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2133                                 return self::updateFromProbeArray($cid, $ret);
2134                         }
2135                 }
2136
2137                 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2138                         $ret['unsearchable'] = $ret['hide'];
2139                 }
2140
2141                 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2142                         $ret['forum'] = false;
2143                         $ret['prv'] = false;
2144                         $ret['contact-type'] = $ret['account-type'];
2145                         if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2146                                 $ret['forum'] = (bool)!$ret['manually-approve'];
2147                                 $ret['prv'] = (bool)!$ret['forum'];
2148                         }
2149                 }
2150
2151                 $new_pubkey = $ret['pubkey'] ?? '';
2152
2153                 if ($uid == 0) {
2154                         $ret['last-item'] = Probe::getLastUpdate($ret);
2155                         Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2156                 }
2157
2158                 $update = false;
2159                 $guid = $ret['guid'] ?? '';
2160
2161                 // make sure to not overwrite existing values with blank entries except some technical fields
2162                 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2163                 foreach ($ret as $key => $val) {
2164                         if (!array_key_exists($key, $contact)) {
2165                                 unset($ret[$key]);
2166                         } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2167                                 $ret[$key] = $contact[$key];
2168                         } elseif ($ret[$key] != $contact[$key]) {
2169                                 $update = true;
2170                         }
2171                 }
2172
2173                 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2174                         $update = true;
2175                 } else {
2176                         unset($ret['last-item']);
2177                 }
2178
2179                 if (empty($uriid)) {
2180                         $update = true;
2181                 }
2182
2183                 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2184                         self::updateAvatar($id, $ret['photo'], $update);
2185                 }
2186
2187                 if (!$update) {
2188                         self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2189
2190                         if (Contact\Relation::isDiscoverable($ret['url'])) {
2191                                 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2192                         }
2193
2194                         // Update the public contact
2195                         if ($uid != 0) {
2196                                 $contact = self::getByURL($ret['url'], false, ['id']);
2197                                 if (!empty($contact['id'])) {
2198                                         self::updateFromProbeArray($contact['id'], $ret);
2199                                 }
2200                         }
2201
2202                         return true;
2203                 }
2204
2205                 if (empty($guid)) {
2206                         $ret['uri-id'] = ItemURI::getIdByURI($ret['url']);
2207                 } else {
2208                         $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2209                 }
2210
2211                 $ret['nurl']    = Strings::normaliseLink($ret['url']);
2212                 $ret['updated'] = $updated;
2213                 $ret['failed']  = false;
2214
2215                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2216                 if (empty($pubkey) && !empty($new_pubkey)) {
2217                         $ret['pubkey'] = $new_pubkey;
2218                 }
2219
2220                 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2221                         $ret['uri-date'] = $updated;
2222                 }
2223
2224                 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2225                         $ret['name-date'] = $updated;
2226                 }
2227
2228                 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2229                         $ret['last-update'] = $updated;
2230                         $ret['success_update'] = $updated;
2231                 }
2232
2233                 unset($ret['photo']);
2234
2235                 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2236
2237                 if (Contact\Relation::isDiscoverable($ret['url'])) {
2238                         Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2239                 }
2240
2241                 return true;
2242         }
2243
2244         private static function updateFromPublicContact(int $id, array $contact)
2245         {
2246                 $public = self::getByURL($contact['url'], false);
2247
2248                 $fields = [];
2249
2250                 foreach ($contact as $field => $value) {
2251                         if ($field == 'uid') {
2252                                 continue;
2253                         }
2254                         if ($public[$field] != $value) {
2255                                 $fields[$field] = $public[$field];
2256                         }
2257                 }
2258                 if (!empty($fields)) {
2259                         DBA::update('contact', $fields, ['id' => $id, 'self' => false]);
2260                         Logger::info('Updating local contact', ['id' => $id]);
2261                 }
2262         }
2263
2264         /**
2265          * @param integer $url contact url
2266          * @return integer Contact id
2267          * @throws HTTPException\InternalServerErrorException
2268          * @throws \ImagickException
2269          */
2270         public static function updateFromProbeByURL($url)
2271         {
2272                 $id = self::getIdForURL($url);
2273
2274                 if (empty($id)) {
2275                         return $id;
2276                 }
2277
2278                 self::updateFromProbe($id);
2279
2280                 return $id;
2281         }
2282
2283         /**
2284          * Detects the communication protocol for a given contact url.
2285          * This is used to detect Friendica contacts that we can communicate via AP.
2286          *
2287          * @param string $url contact url
2288          * @param string $network Network of that contact
2289          * @return string with protocol
2290          */
2291         public static function getProtocol($url, $network)
2292         {
2293                 if ($network != Protocol::DFRN) {
2294                         return $network;
2295                 }
2296
2297                 $apcontact = APContact::getByURL($url);
2298                 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2299                         return Protocol::ACTIVITYPUB;
2300                 } else {
2301                         return $network;
2302                 }
2303         }
2304
2305         /**
2306          * Takes a $uid and a url/handle and adds a new contact
2307          *
2308          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2309          * dfrn_request page.
2310          *
2311          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2312          *
2313          * Returns an array
2314          * $return['success'] boolean true if successful
2315          * $return['message'] error text if success is false.
2316          *
2317          * Takes a $uid and a url/handle and adds a new contact
2318          *
2319          * @param int    $uid         The user id the contact should be created for
2320          * @param string $url         The profile URL of the contact
2321          * @param string $network
2322          * @return array
2323          * @throws HTTPException\InternalServerErrorException
2324          * @throws HTTPException\NotFoundException
2325          * @throws \ImagickException
2326          */
2327         public static function createFromProbeForUser(int $uid, $url, $network = '')
2328         {
2329                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2330
2331                 // remove ajax junk, e.g. Twitter
2332                 $url = str_replace('/#!/', '/', $url);
2333
2334                 if (!Network::isUrlAllowed($url)) {
2335                         $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2336                         return $result;
2337                 }
2338
2339                 if (Network::isUrlBlocked($url)) {
2340                         $result['message'] = DI::l10n()->t('Blocked domain');
2341                         return $result;
2342                 }
2343
2344                 if (!$url) {
2345                         $result['message'] = DI::l10n()->t('Connect URL missing.');
2346                         return $result;
2347                 }
2348
2349                 $arr = ['url' => $url, 'contact' => []];
2350
2351                 Hook::callAll('follow', $arr);
2352
2353                 if (empty($arr)) {
2354                         $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2355                         return $result;
2356                 }
2357
2358                 if (!empty($arr['contact']['name'])) {
2359                         $probed = false;
2360                         $ret = $arr['contact'];
2361                 } else {
2362                         $probed = true;
2363                         $ret = Probe::uri($url, $network, $uid);
2364                 }
2365
2366                 if (($network != '') && ($ret['network'] != $network)) {
2367                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2368                         return $result;
2369                 }
2370
2371                 // check if we already have a contact
2372                 // the poll url is more reliable than the profile url, as we may have
2373                 // indirect links or webfinger links
2374
2375                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2376                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2377                 if (!DBA::isResult($contact)) {
2378                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2379                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2380                 }
2381
2382                 $protocol = self::getProtocol($ret['url'], $ret['network']);
2383
2384                 // This extra param just confuses things, remove it
2385                 if ($protocol === Protocol::DIASPORA) {
2386                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2387                 }
2388
2389                 // do we have enough information?
2390                 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2391                         $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2392                         if (empty($ret['poll'])) {
2393                                 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2394                         }
2395                         if (empty($ret['name'])) {
2396                                 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2397                         }
2398                         if (empty($ret['url'])) {
2399                                 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2400                         }
2401                         if (strpos($ret['url'], '@') !== false) {
2402                                 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2403                                 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2404                         }
2405                         return $result;
2406                 }
2407
2408                 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2409                         $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2410                         $ret['notify'] = '';
2411                 }
2412
2413                 if (!$ret['notify']) {
2414                         $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2415                 }
2416
2417                 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2418
2419                 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2420
2421                 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2422
2423                 $pending = false;
2424                 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2425                         $pending = (bool)$ret['manually-approve'];
2426                 }
2427
2428                 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2429                         $writeable = 1;
2430                 }
2431
2432                 if (DBA::isResult($contact)) {
2433                         // update contact
2434                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2435
2436                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2437                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2438                 } else {
2439                         $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2440
2441                         // create contact record
2442                         self::insert([
2443                                 'uid'     => $uid,
2444                                 'created' => DateTimeFormat::utcNow(),
2445                                 'url'     => $ret['url'],
2446                                 'nurl'    => Strings::normaliseLink($ret['url']),
2447                                 'addr'    => $ret['addr'],
2448                                 'alias'   => $ret['alias'],
2449                                 'batch'   => $ret['batch'],
2450                                 'notify'  => $ret['notify'],
2451                                 'poll'    => $ret['poll'],
2452                                 'poco'    => $ret['poco'],
2453                                 'name'    => $ret['name'],
2454                                 'nick'    => $ret['nick'],
2455                                 'network' => $ret['network'],
2456                                 'baseurl' => $ret['baseurl'],
2457                                 'gsid'    => $ret['gsid'] ?? null,
2458                                 'protocol' => $protocol,
2459                                 'pubkey'  => $ret['pubkey'],
2460                                 'rel'     => $new_relation,
2461                                 'priority'=> $ret['priority'],
2462                                 'writable'=> $writeable,
2463                                 'hidden'  => $hidden,
2464                                 'blocked' => 0,
2465                                 'readonly'=> 0,
2466                                 'pending' => $pending,
2467                                 'subhub'  => $subhub
2468                         ]);
2469                 }
2470
2471                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2472                 if (!DBA::isResult($contact)) {
2473                         $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2474                         return $result;
2475                 }
2476
2477                 $contact_id = $contact['id'];
2478                 $result['cid'] = $contact_id;
2479
2480                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2481
2482                 // Update the avatar
2483                 self::updateAvatar($contact_id, $ret['photo']);
2484
2485                 // pull feed and consume it, which should subscribe to the hub.
2486                 if ($contact['network'] == Protocol::OSTATUS) {
2487                         Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2488                 }
2489
2490                 if ($probed) {
2491                         self::updateFromProbeArray($contact_id, $ret);
2492                 } else {
2493                         Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2494                 }
2495
2496                 $owner = User::getOwnerDataById($uid);
2497
2498                 if (DBA::isResult($owner)) {
2499                         if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2500                                 // create a follow slap
2501                                 $item = [];
2502                                 $item['verb'] = Activity::FOLLOW;
2503                                 $item['gravity'] = GRAVITY_ACTIVITY;
2504                                 $item['follow'] = $contact["url"];
2505                                 $item['body'] = '';
2506                                 $item['title'] = '';
2507                                 $item['guid'] = '';
2508                                 $item['uri-id'] = 0;
2509
2510                                 $slap = OStatus::salmon($item, $owner);
2511
2512                                 if (!empty($contact['notify'])) {
2513                                         Salmon::slapper($owner, $contact['notify'], $slap);
2514                                 }
2515                         } elseif ($protocol == Protocol::DIASPORA) {
2516                                 $ret = Diaspora::sendShare($owner, $contact);
2517                                 Logger::log('share returns: ' . $ret);
2518                         } elseif ($protocol == Protocol::ACTIVITYPUB) {
2519                                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2520                                 if (empty($activity_id)) {
2521                                         // This really should never happen
2522                                         return false;
2523                                 }
2524
2525                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2526                                 Logger::log('Follow returns: ' . $ret);
2527                         }
2528                 }
2529
2530                 $result['success'] = true;
2531                 return $result;
2532         }
2533
2534         /**
2535          * Updated contact's SSL policy
2536          *
2537          * @param array  $contact    Contact array
2538          * @param string $new_policy New policy, valid: self,full
2539          *
2540          * @return array Contact array with updated values
2541          * @throws \Exception
2542          */
2543         public static function updateSslPolicy(array $contact, $new_policy)
2544         {
2545                 $ssl_changed = false;
2546                 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2547                         $ssl_changed = true;
2548                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
2549                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
2550                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
2551                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
2552                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
2553                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
2554                 }
2555
2556                 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2557                         $ssl_changed = true;
2558                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
2559                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
2560                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
2561                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
2562                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
2563                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
2564                 }
2565
2566                 if ($ssl_changed) {
2567                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2568                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
2569                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2570                         DBA::update('contact', $fields, ['id' => $contact['id']]);
2571                 }
2572
2573                 return $contact;
2574         }
2575
2576         /**
2577          * Follow a contact
2578          *
2579          * @param int $cid Public contact id
2580          * @param int $uid  User ID
2581          *
2582          * @return bool "true" if following had been successful
2583          */
2584         public static function follow(int $cid, int $uid)
2585         {
2586                 $contact = self::getById($cid, ['url']);
2587
2588                 $result = self::createFromProbeForUser($uid, $contact['url']);
2589
2590                 return $result['cid'];
2591         }
2592
2593         /**
2594          * Unfollow a contact
2595          *
2596          * @param int $cid Public contact id
2597          * @param int $uid  User ID
2598          *
2599          * @return bool "true" if unfollowing had been successful
2600          */
2601         public static function unfollow(int $cid, int $uid)
2602         {
2603                 $cdata = self::getPublicAndUserContactID($cid, $uid);
2604                 if (empty($cdata['user'])) {
2605                         return false;
2606                 }
2607
2608                 $contact = self::getById($cdata['user']);
2609
2610                 self::removeSharer([], $contact);
2611
2612                 return true;
2613         }
2614
2615         /**
2616          * @param array  $importer Owner (local user) data
2617          * @param array  $contact  Existing owner-specific contact data we want to expand the relationship with. Optional.
2618          * @param array  $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2619          * @param bool   $sharing  True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2620          * @param string $note     Introduction additional message
2621          * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2622          * @throws HTTPException\InternalServerErrorException
2623          * @throws \ImagickException
2624          */
2625         public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2626         {
2627                 // Should always be set
2628                 if (empty($datarray['author-id'])) {
2629                         return false;
2630                 }
2631
2632                 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2633                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2634                 if (!DBA::isResult($pub_contact)) {
2635                         // Should never happen
2636                         return false;
2637                 }
2638
2639                 // Contact is blocked at node-level
2640                 if (self::isBlocked($datarray['author-id'])) {
2641                         return false;
2642                 }
2643
2644                 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2645                 $name = $pub_contact['name'];
2646                 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2647                 $nick = $pub_contact['nick'];
2648                 $network = $pub_contact['network'];
2649
2650                 // Ensure that we don't create a new contact when there already is one
2651                 $cid = self::getIdForURL($url, $importer['uid']);
2652                 if (!empty($cid)) {
2653                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2654                 }
2655
2656                 if (!empty($contact)) {
2657                         if (!empty($contact['pending'])) {
2658                                 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2659                                 return null;
2660                         }
2661
2662                         // Contact is blocked at user-level
2663                         if (!empty($contact['id']) && !empty($importer['id']) &&
2664                                 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2665                                 return false;
2666                         }
2667
2668                         // Make sure that the existing contact isn't archived
2669                         self::unmarkForArchival($contact);
2670
2671                         if (($contact['rel'] == self::SHARING)
2672                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2673                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2674                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2675                         }
2676
2677                         // Ensure to always have the correct network type, independent from the connection request method
2678                         self::updateFromProbe($contact['id']);
2679
2680                         Post\UserNotification::insertNotication($contact['id'], Verb::getID(Activity::FOLLOW), $importer['uid']);
2681
2682                         return true;
2683                 } else {
2684                         // send email notification to owner?
2685                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2686                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2687                                 return null;
2688                         }
2689
2690                         // create contact record
2691                         $contact_id = self::insert([
2692                                 'uid'      => $importer['uid'],
2693                                 'created'  => DateTimeFormat::utcNow(),
2694                                 'url'      => $url,
2695                                 'nurl'     => Strings::normaliseLink($url),
2696                                 'name'     => $name,
2697                                 'nick'     => $nick,
2698                                 'network'  => $network,
2699                                 'rel'      => self::FOLLOWER,
2700                                 'blocked'  => 0,
2701                                 'readonly' => 0,
2702                                 'pending'  => 1,
2703                                 'writable' => 1,
2704                         ]);
2705
2706                         // Ensure to always have the correct network type, independent from the connection request method
2707                         self::updateFromProbe($contact_id);
2708
2709                         self::updateAvatar($contact_id, $photo, true);
2710
2711                         Post\UserNotification::insertNotication($contact_id, Verb::getID(Activity::FOLLOW), $importer['uid']);
2712
2713                         $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2714
2715                         /// @TODO Encapsulate this into a function/method
2716                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2717                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2718                         if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2719                                 // create notification
2720                                 $hash = Strings::getRandomHex();
2721
2722                                 if (is_array($contact_record)) {
2723                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2724                                                                 'blocked' => false, 'knowyou' => false, 'note' => $note,
2725                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2726                                 }
2727
2728                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2729
2730                                 if (($user['notify-flags'] & Notification\Type::INTRO) &&
2731                                         in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2732
2733                                         notification([
2734                                                 'type'  => Notification\Type::INTRO,
2735                                                 'otype' => Notification\ObjectType::INTRO,
2736                                                 'verb'  => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2737                                                 'uid'   => $user['uid'],
2738                                                 'cid'   => $contact_record['id'],
2739                                                 'link'  => DI::baseUrl() . '/notifications/intros',
2740                                         ]);
2741                                 }
2742                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2743                                 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2744                                         self::createFromProbeForUser($importer['uid'], $url, $network);
2745                                 }
2746
2747                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2748                                 $fields = ['pending' => false];
2749                                 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2750                                         $fields['rel'] = self::FRIEND;
2751                                 }
2752
2753                                 DBA::update('contact', $fields, $condition);
2754
2755                                 return true;
2756                         }
2757                 }
2758
2759                 return null;
2760         }
2761
2762         public static function removeFollower($importer, $contact)
2763         {
2764                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2765                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2766                 } else {
2767                         self::remove($contact['id']);
2768                 }
2769         }
2770
2771         public static function removeSharer($importer, $contact)
2772         {
2773                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2774                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2775                 } else {
2776                         self::remove($contact['id']);
2777                 }
2778         }
2779
2780         /**
2781          * Create a birthday event.
2782          *
2783          * Update the year and the birthday.
2784          */
2785         public static function updateBirthdays()
2786         {
2787                 $condition = [
2788                         '`bd` > ?
2789                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2790                         AND NOT `contact`.`pending`
2791                         AND NOT `contact`.`hidden`
2792                         AND NOT `contact`.`blocked`
2793                         AND NOT `contact`.`archive`
2794                         AND NOT `contact`.`deleted`',
2795                         DBA::NULL_DATE,
2796                         self::SHARING,
2797                         self::FRIEND
2798                 ];
2799
2800                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2801
2802                 while ($contact = DBA::fetch($contacts)) {
2803                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2804
2805                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2806
2807                         if (Event::createBirthday($contact, $nextbd)) {
2808                                 // update bdyear
2809                                 DBA::update(
2810                                         'contact',
2811                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2812                                         ['id' => $contact['id']]
2813                                 );
2814                         }
2815                 }
2816                 DBA::close($contacts);
2817         }
2818
2819         /**
2820          * Remove the unavailable contact ids from the provided list
2821          *
2822          * @param array $contact_ids Contact id list
2823          * @return array
2824          * @throws \Exception
2825          */
2826         public static function pruneUnavailable(array $contact_ids)
2827         {
2828                 if (empty($contact_ids)) {
2829                         return [];
2830                 }
2831
2832                 $contacts = self::selectToArray(['id'], [
2833                         'id'      => $contact_ids,
2834                         'blocked' => false,
2835                         'pending' => false,
2836                         'archive' => false,
2837                 ]);
2838
2839                 return array_column($contacts, 'id');
2840         }
2841
2842         /**
2843          * Returns a magic link to authenticate remote visitors
2844          *
2845          * @todo  check if the return is either a fully qualified URL or a relative path to Friendica basedir
2846          *
2847          * @param string $contact_url The address of the target contact profile
2848          * @param string $url         An url that we will be redirected to after the authentication
2849          *
2850          * @return string with "redir" link
2851          * @throws HTTPException\InternalServerErrorException
2852          * @throws \ImagickException
2853          */
2854         public static function magicLink($contact_url, $url = '')
2855         {
2856                 if (!Session::isAuthenticated()) {
2857                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2858                 }
2859
2860                 $contact = self::getByURL($contact_url, false);
2861                 if (empty($contact)) {
2862                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2863                 }
2864
2865                 // Prevents endless loop in case only a non-public contact exists for the contact URL
2866                 unset($contact['uid']);
2867
2868                 return self::magicLinkByContact($contact, $url ?: $contact_url);
2869         }
2870
2871         /**
2872          * Returns a magic link to authenticate remote visitors
2873          *
2874          * @param integer $cid The contact id of the target contact profile
2875          * @param string  $url An url that we will be redirected to after the authentication
2876          *
2877          * @return string with "redir" link
2878          * @throws HTTPException\InternalServerErrorException
2879          * @throws \ImagickException
2880          */
2881         public static function magicLinkById($cid, $url = '')
2882         {
2883                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2884
2885                 return self::magicLinkByContact($contact, $url);
2886         }
2887
2888         /**
2889          * Returns a magic link to authenticate remote visitors
2890          *
2891          * @param array  $contact The contact array with "uid", "network" and "url"
2892          * @param string $url     An url that we will be redirected to after the authentication
2893          *
2894          * @return string with "redir" link
2895          * @throws HTTPException\InternalServerErrorException
2896          * @throws \ImagickException
2897          */
2898         public static function magicLinkByContact($contact, $url = '')
2899         {
2900                 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2901
2902                 if (!Session::isAuthenticated()) {
2903                         return $destination;
2904                 }
2905
2906                 // Only redirections to the same host do make sense
2907                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2908                         return $url;
2909                 }
2910
2911                 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2912                         return 'contact/' . $contact['id'] . '/conversations';
2913                 }
2914
2915                 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
2916                         return $destination;
2917                 }
2918
2919                 if (empty($contact['id'])) {
2920                         return $destination;
2921                 }
2922
2923                 $redirect = 'redir/' . $contact['id'];
2924
2925                 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2926                         $redirect .= '?url=' . $url;
2927                 }
2928
2929                 return $redirect;
2930         }
2931
2932         /**
2933          * Is the contact a forum?
2934          *
2935          * @param integer $contactid ID of the contact
2936          *
2937          * @return boolean "true" if it is a forum
2938          */
2939         public static function isForum($contactid)
2940         {
2941                 $fields = ['forum', 'prv'];
2942                 $condition = ['id' => $contactid];
2943                 $contact = DBA::selectFirst('contact', $fields, $condition);
2944                 if (!DBA::isResult($contact)) {
2945                         return false;
2946                 }
2947
2948                 // Is it a forum?
2949                 return ($contact['forum'] || $contact['prv']);
2950         }
2951
2952         /**
2953          * Can the remote contact receive private messages?
2954          *
2955          * @param array $contact
2956          * @return bool
2957          */
2958         public static function canReceivePrivateMessages(array $contact)
2959         {
2960                 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2961                 $self = $contact['self'] ?? false;
2962
2963                 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2964         }
2965
2966         /**
2967          * Search contact table by nick or name
2968          *
2969          * @param string $search Name or nick
2970          * @param string $mode   Search mode (e.g. "community")
2971          * @param int    $uid    User ID
2972          *
2973          * @return array with search results
2974          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2975          */
2976         public static function searchByName(string $search, string $mode = '', int $uid = 0)
2977         {
2978                 if (empty($search)) {
2979                         return [];
2980                 }
2981
2982                 // check supported networks
2983                 if (DI::config()->get('system', 'diaspora_enabled')) {
2984                         $diaspora = Protocol::DIASPORA;
2985                 } else {
2986                         $diaspora = Protocol::DFRN;
2987                 }
2988
2989                 if (!DI::config()->get('system', 'ostatus_disabled')) {
2990                         $ostatus = Protocol::OSTATUS;
2991                 } else {
2992                         $ostatus = Protocol::DFRN;
2993                 }
2994
2995                 // check if we search only communities or every contact
2996                 if ($mode === 'community') {
2997                         $extra_sql = sprintf(' AND `contact-type` = %d', self::TYPE_COMMUNITY);
2998                 } else {
2999                         $extra_sql = '';
3000                 }
3001
3002                 $search .= '%';
3003
3004                 $results = DBA::p("SELECT * FROM `contact`
3005                         WHERE (NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` where `publish` OR `net-publish`))
3006                                 AND `network` IN (?, ?, ?, ?) AND
3007                                 NOT `failed` AND `uid` = ? AND
3008                                 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
3009                                 ORDER BY `nurl` DESC LIMIT 1000",
3010                         Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $uid, $search, $search, $search
3011                 );
3012
3013                 $contacts = DBA::toArray($results);
3014                 return $contacts;
3015         }
3016
3017         /**
3018          * Add public contacts from an array
3019          *
3020          * @param array $urls
3021          * @return array result "count", "added" and "updated"
3022          */
3023         public static function addByUrls(array $urls)
3024         {
3025                 $added = 0;
3026                 $updated = 0;
3027                 $unchanged = 0;
3028                 $count = 0;
3029
3030                 foreach ($urls as $url) {
3031                         if (empty($url) || !is_string($url)) {
3032                                 continue;
3033                         }
3034                         $contact = self::getByURL($url, false, ['id', 'updated']);
3035                         if (empty($contact['id'])) {
3036                                 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3037                                 ++$added;
3038                         } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3039                                 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3040                                 ++$updated;
3041                         } else {
3042                                 ++$unchanged;
3043                         }
3044                         ++$count;
3045                 }
3046
3047                 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3048         }
3049
3050         /**
3051          * Returns a random, global contact array of the current node
3052          *
3053          * @return array The profile array
3054          * @throws Exception
3055          */
3056         public static function getRandomContact()
3057         {
3058                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3059                         "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3060                         0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3061                 ], ['order' => ['RAND()']]);
3062
3063                 if (DBA::isResult($contact)) {
3064                         return $contact;
3065                 }
3066
3067                 return [];
3068         }
3069 }