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