]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
5894814ea6c0e58dddda35b8c2272b779f5c27a5
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @file src/Model/Contact.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\PortableContact;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
29
30 require_once 'boot.php';
31 require_once 'include/dba.php';
32 require_once 'include/text.php';
33
34 /**
35  * @brief functions for interacting with a contact
36  */
37 class Contact extends BaseObject
38 {
39         /**
40          * @name page/profile types
41          *
42          * PAGE_NORMAL is a typical personal profile account
43          * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
44          * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
45          *      write access to wall and comments (no email and not included in page owner's ACL lists)
46          * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
47          *
48          * @{
49          */
50         const PAGE_NORMAL    = 0;
51         const PAGE_SOAPBOX   = 1;
52         const PAGE_COMMUNITY = 2;
53         const PAGE_FREELOVE  = 3;
54         const PAGE_BLOG      = 4;
55         const PAGE_PRVGROUP  = 5;
56         /**
57          * @}
58          */
59
60         /**
61          * @name account types
62          *
63          * ACCOUNT_TYPE_PERSON - the account belongs to a person
64          *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
65          *
66          * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
67          *      Associated page type: PAGE_SOAPBOX
68          *
69          * ACCOUNT_TYPE_NEWS - the account is a news reflector
70          *      Associated page type: PAGE_SOAPBOX
71          *
72          * ACCOUNT_TYPE_COMMUNITY - the account is community forum
73          *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
74          *
75          * ACCOUNT_TYPE_RELAY - the account is a relay
76          *      This will only be assigned to contacts, not to user accounts
77          * @{
78          */
79         const ACCOUNT_TYPE_PERSON =       0;
80         const ACCOUNT_TYPE_ORGANISATION = 1;
81         const ACCOUNT_TYPE_NEWS =         2;
82         const ACCOUNT_TYPE_COMMUNITY =    3;
83         const ACCOUNT_TYPE_RELAY =        4;
84         /**
85          * @}
86          */
87
88         /**
89          * @name Contact_is
90          *
91          * Relationship types
92          * @{
93          */
94         const FOLLOWER = 1;
95         const SHARING  = 2;
96         const FRIEND   = 3;
97         /**
98          * @}
99          */
100
101         /**
102          * @brief Tests if the given contact is a follower
103          *
104          * @param int $cid Either public contact id or user's contact id
105          * @param int $uid User ID
106          *
107          * @return boolean is the contact id a follower?
108          */
109         public static function isFollower($cid, $uid)
110         {
111                 if (self::isBlockedByUser($cid, $uid)) {
112                         return false;
113                 }
114
115                 $cdata = self::getPublicAndUserContacID($cid, $uid);
116                 if (empty($cdata['user'])) {
117                         return false;
118                 }
119
120                 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
121                 return DBA::exists('contact', $condition);
122         }
123
124         /**
125          * @brief Get the basepath for a given contact link
126          * @todo Add functionality to store this value in the contact table
127          *
128          * @param string $url The contact link
129          *
130          * @return string basepath
131          */
132         public static function getBasepath($url)
133         {
134                 $data = Probe::uri($url);
135                 if (!empty($data['baseurl'])) {
136                         return $data['baseurl'];
137                 }
138
139                 // When we can't probe the server, we use some ugly function that does some pattern matching
140                 return PortableContact::detectServer($url);
141         }
142
143         /**
144          * @brief Returns the contact id for the user and the public contact id for a given contact id
145          *
146          * @param int $cid Either public contact id or user's contact id
147          * @param int $uid User ID
148          *
149          * @return array with public and user's contact id
150          */
151         public static function getPublicAndUserContacID($cid, $uid)
152         {
153                 if (empty($uid) || empty($cid)) {
154                         return [];
155                 }
156
157                 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
158                 if (!DBA::isResult($contact)) {
159                         return [];
160                 }
161
162                 // We quit when the user id don't match the user id of the provided contact
163                 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
164                         return [];
165                 }
166
167                 if ($contact['uid'] != 0) {
168                         $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
169                         if (empty($pcid)) {
170                                 return [];
171                         }
172                         $ucid = $contact['id'];
173                 } else {
174                         $pcid = $contact['id'];
175                         $ucid = Contact::getIdForURL($contact['url'], $uid, true);
176                 }
177
178                 return ['public' => $pcid, 'user' => $ucid];
179         }
180
181         /**
182          * @brief Block contact id for user id
183          *
184          * @param int     $cid     Either public contact id or user's contact id
185          * @param int     $uid     User ID
186          * @param boolean $blocked Is the contact blocked or unblocked?
187          */
188         public static function setBlockedForUser($cid, $uid, $blocked)
189         {
190                 $cdata = self::getPublicAndUserContacID($cid, $uid);
191                 if (empty($cdata)) {
192                         return;
193                 }
194
195                 if ($cdata['user'] != 0) {
196                         DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
197                 }
198
199                 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
200         }
201
202         /**
203          * @brief Returns "block" state for contact id and user id
204          *
205          * @param int $cid Either public contact id or user's contact id
206          * @param int $uid User ID
207          *
208          * @return boolean is the contact id blocked for the given user?
209          */
210         public static function isBlockedByUser($cid, $uid)
211         {
212                 $cdata = self::getPublicAndUserContacID($cid, $uid);
213                 if (empty($cdata)) {
214                         return;
215                 }
216
217                 $public_blocked = false;
218
219                 if (!empty($cdata['public'])) {
220                         $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
221                         if (DBA::isResult($public_contact)) {
222                                 $public_blocked = $public_contact['blocked'];
223                         }
224                 }
225
226                 $user_blocked = $public_blocked;
227
228                 if (!empty($cdata['user'])) {
229                         $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
230                         if (DBA::isResult($user_contact)) {
231                                 $user_blocked = $user_contact['blocked'];
232                         }
233                 }
234
235                 if ($user_blocked != $public_blocked) {
236                         DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
237                 }
238
239                 return $user_blocked;
240         }
241
242         /**
243          * @brief Ignore contact id for user id
244          *
245          * @param int     $cid     Either public contact id or user's contact id
246          * @param int     $uid     User ID
247          * @param boolean $ignored Is the contact ignored or unignored?
248          */
249         public static function setIgnoredForUser($cid, $uid, $ignored)
250         {
251                 $cdata = self::getPublicAndUserContacID($cid, $uid);
252                 if (empty($cdata)) {
253                         return;
254                 }
255
256                 if ($cdata['user'] != 0) {
257                         DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
258                 }
259
260                 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
261         }
262
263         /**
264          * @brief Returns "ignore" state for contact id and user id
265          *
266          * @param int $cid Either public contact id or user's contact id
267          * @param int $uid User ID
268          *
269          * @return boolean is the contact id ignored for the given user?
270          */
271         public static function isIgnoredByUser($cid, $uid)
272         {
273                 $cdata = self::getPublicAndUserContacID($cid, $uid);
274                 if (empty($cdata)) {
275                         return;
276                 }
277
278                 $public_ignored = false;
279
280                 if (!empty($cdata['public'])) {
281                         $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
282                         if (DBA::isResult($public_contact)) {
283                                 $public_ignored = $public_contact['ignored'];
284                         }
285                 }
286
287                 $user_ignored = $public_ignored;
288
289                 if (!empty($cdata['user'])) {
290                         $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
291                         if (DBA::isResult($user_contact)) {
292                                 $user_ignored = $user_contact['readonly'];
293                         }
294                 }
295
296                 if ($user_ignored != $public_ignored) {
297                         DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
298                 }
299
300                 return $user_ignored;
301         }
302
303         /**
304          * @brief Set "collapsed" for contact id and user id
305          *
306          * @param int     $cid       Either public contact id or user's contact id
307          * @param int     $uid       User ID
308          * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
309          */
310         public static function setCollapsedForUser($cid, $uid, $collapsed)
311         {
312                 $cdata = self::getPublicAndUserContacID($cid, $uid);
313                 if (empty($cdata)) {
314                         return;
315                 }
316
317                 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
318         }
319
320         /**
321          * @brief Returns "collapsed" state for contact id and user id
322          *
323          * @param int $cid Either public contact id or user's contact id
324          * @param int $uid User ID
325          *
326          * @return boolean is the contact id blocked for the given user?
327          */
328         public static function isCollapsedByUser($cid, $uid)
329         {
330                 $cdata = self::getPublicAndUserContacID($cid, $uid);
331                 if (empty($cdata)) {
332                         return;
333                 }
334
335                 $collapsed = false;
336
337                 if (!empty($cdata['public'])) {
338                         $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
339                         if (DBA::isResult($public_contact)) {
340                                 $collapsed = $public_contact['collapsed'];
341                         }
342                 }
343
344                 return $collapsed;
345         }
346
347         /**
348          * @brief Returns a list of contacts belonging in a group
349          *
350          * @param int $gid
351          * @return array
352          */
353         public static function getByGroupId($gid)
354         {
355                 $return = [];
356
357                 if (intval($gid)) {
358                         $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
359                                 FROM `contact`
360                                 INNER JOIN `group_member`
361                                         ON `contact`.`id` = `group_member`.`contact-id`
362                                 WHERE `gid` = ?
363                                 AND `contact`.`uid` = ?
364                                 AND NOT `contact`.`self`
365                                 AND NOT `contact`.`blocked`
366                                 AND NOT `contact`.`pending`
367                                 ORDER BY `contact`.`name` ASC',
368                                 $gid,
369                                 local_user()
370                         );
371
372                         if (DBA::isResult($stmt)) {
373                                 $return = DBA::toArray($stmt);
374                         }
375                 }
376
377                 return $return;
378         }
379
380         /**
381          * @brief Returns the count of OStatus contacts in a group
382          *
383          * @param int $gid
384          * @return int
385          */
386         public static function getOStatusCountByGroupId($gid)
387         {
388                 $return = 0;
389                 if (intval($gid)) {
390                         $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
391                                 FROM `contact`
392                                 INNER JOIN `group_member`
393                                         ON `contact`.`id` = `group_member`.`contact-id`
394                                 WHERE `gid` = ?
395                                 AND `contact`.`uid` = ?
396                                 AND `contact`.`network` = ?
397                                 AND `contact`.`notify` != ""',
398                                 $gid,
399                                 local_user(),
400                                 Protocol::OSTATUS
401                         );
402                         $return = $contacts['count'];
403                 }
404
405                 return $return;
406         }
407
408         /**
409          * Creates the self-contact for the provided user id
410          *
411          * @param int $uid
412          * @return bool Operation success
413          */
414         public static function createSelfFromUserId($uid)
415         {
416                 // Only create the entry if it doesn't exist yet
417                 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
418                         return true;
419                 }
420
421                 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
422                 if (!DBA::isResult($user)) {
423                         return false;
424                 }
425
426                 $return = DBA::insert('contact', [
427                         'uid'         => $user['uid'],
428                         'created'     => DateTimeFormat::utcNow(),
429                         'self'        => 1,
430                         'name'        => $user['username'],
431                         'nick'        => $user['nickname'],
432                         'photo'       => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
433                         'thumb'       => System::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
434                         'micro'       => System::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
435                         'blocked'     => 0,
436                         'pending'     => 0,
437                         'url'         => System::baseUrl() . '/profile/' . $user['nickname'],
438                         'nurl'        => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
439                         'addr'        => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
440                         'request'     => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
441                         'notify'      => System::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
442                         'poll'        => System::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
443                         'confirm'     => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
444                         'poco'        => System::baseUrl() . '/poco/'         . $user['nickname'],
445                         'name-date'   => DateTimeFormat::utcNow(),
446                         'uri-date'    => DateTimeFormat::utcNow(),
447                         'avatar-date' => DateTimeFormat::utcNow(),
448                         'closeness'   => 0
449                 ]);
450
451                 return $return;
452         }
453
454         /**
455          * Updates the self-contact for the provided user id
456          *
457          * @param int $uid
458          * @param boolean $update_avatar Force the avatar update
459          */
460         public static function updateSelfFromUserID($uid, $update_avatar = false)
461         {
462                 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
463                         'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
464                         'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
465                 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
466                 if (!DBA::isResult($self)) {
467                         return;
468                 }
469
470                 $fields = ['nickname', 'page-flags', 'account-type'];
471                 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
472                 if (!DBA::isResult($user)) {
473                         return;
474                 }
475
476                 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
477                         'country-name', 'gender', 'pub_keywords', 'xmpp'];
478                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
479                 if (!DBA::isResult($profile)) {
480                         return;
481                 }
482
483                 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
484                         'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
485                         'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
486                         'gender' => $profile['gender'], 'avatar' => $profile['photo'],
487                         'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
488
489                 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
490                 if (DBA::isResult($avatar)) {
491                         if ($update_avatar) {
492                                 $fields['avatar-date'] = DateTimeFormat::utcNow();
493                         }
494
495                         // Creating the path to the avatar, beginning with the file suffix
496                         $types = Image::supportedTypes();
497                         if (isset($types[$avatar['type']])) {
498                                 $file_suffix = $types[$avatar['type']];
499                         } else {
500                                 $file_suffix = 'jpg';
501                         }
502
503                         // We are adding a timestamp value so that other systems won't use cached content
504                         $timestamp = strtotime($fields['avatar-date']);
505
506                         $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
507                         $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
508
509                         $fields['photo'] = $prefix . '4' . $suffix;
510                         $fields['thumb'] = $prefix . '5' . $suffix;
511                         $fields['micro'] = $prefix . '6' . $suffix;
512                 } else {
513                         // We hadn't found a photo entry, so we use the default avatar
514                         $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
515                         $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
516                         $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
517                 }
518
519                 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
520                 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
521
522                 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
523                 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
524                 $fields['nurl'] = Strings::normaliseLink($fields['url']);
525                 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
526                 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
527                 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
528                 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
529                 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
530                 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
531
532                 $update = false;
533
534                 foreach ($fields as $field => $content) {
535                         if ($self[$field] != $content) {
536                                 $update = true;
537                         }
538                 }
539
540                 if ($update) {
541                         $fields['name-date'] = DateTimeFormat::utcNow();
542                         DBA::update('contact', $fields, ['id' => $self['id']]);
543
544                         // Update the public contact as well
545                         DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
546
547                         // Update the profile
548                         $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
549                                 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
550                         DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
551                 }
552         }
553
554         /**
555          * @brief Marks a contact for removal
556          *
557          * @param int $id contact id
558          * @return null
559          */
560         public static function remove($id)
561         {
562                 // We want just to make sure that we don't delete our "self" contact
563                 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
564                 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
565                         return;
566                 }
567
568                 // Archive the contact
569                 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
570
571                 // Delete it in the background
572                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
573         }
574
575         /**
576          * @brief Sends an unfriend message. Does not remove the contact
577          *
578          * @param array   $user     User unfriending
579          * @param array   $contact  Contact unfriended
580          * @param boolean $dissolve Remove the contact on the remote side
581          * @return void
582          */
583         public static function terminateFriendship(array $user, array $contact, $dissolve = false)
584         {
585                 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
586                         DFRN::deliver($user, $contact, 'placeholder', true);
587                 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
588                         // create an unfollow slap
589                         $item = [];
590                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
591                         $item['follow'] = $contact["url"];
592                         $item['body'] = '';
593                         $item['title'] = '';
594                         $item['guid'] = '';
595                         $item['tag'] = '';
596                         $item['attach'] = '';
597                         $slap = OStatus::salmon($item, $user);
598
599                         if (!empty($contact['notify'])) {
600                                 Salmon::slapper($user, $contact['notify'], $slap);
601                         }
602                 } elseif ($contact['network'] == Protocol::DIASPORA) {
603                         Diaspora::sendUnshare($user, $contact);
604                 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
605                         ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
606
607                         if ($dissolve) {
608                                 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
609                         }
610                 }
611         }
612
613         /**
614          * @brief Marks a contact for archival after a communication issue delay
615          *
616          * Contact has refused to recognise us as a friend. We will start a countdown.
617          * If they still don't recognise us in 32 days, the relationship is over,
618          * and we won't waste any more time trying to communicate with them.
619          * This provides for the possibility that their database is temporarily messed
620          * up or some other transient event and that there's a possibility we could recover from it.
621          *
622          * @param array $contact contact to mark for archival
623          * @return null
624          */
625         public static function markForArchival(array $contact)
626         {
627                 if (!isset($contact['url']) && !empty($contact['id'])) {
628                         $fields = ['id', 'url', 'archive', 'self', 'term-date'];
629                         $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
630                         if (!DBA::isResult($contact)) {
631                                 return;
632                         }
633                 } elseif (!isset($contact['url'])) {
634                         Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
635                 }
636
637                 // Contact already archived or "self" contact? => nothing to do
638                 if ($contact['archive'] || $contact['self']) {
639                         return;
640                 }
641
642                 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
643                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
644                         DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
645                 } else {
646                         /* @todo
647                          * We really should send a notification to the owner after 2-3 weeks
648                          * so they won't be surprised when the contact vanishes and can take
649                          * remedial action if this was a serious mistake or glitch
650                          */
651
652                         /// @todo Check for contact vitality via probing
653                         $archival_days = Config::get('system', 'archival_days', 32);
654
655                         $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
656                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
657                                 /* Relationship is really truly dead. archive them rather than
658                                  * delete, though if the owner tries to unarchive them we'll start
659                                  * the whole process over again.
660                                  */
661                                 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
662                                 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
663                         }
664                 }
665         }
666
667         /**
668          * @brief Cancels the archival countdown
669          *
670          * @see Contact::markForArchival()
671          *
672          * @param array $contact contact to be unmarked for archival
673          * @return null
674          */
675         public static function unmarkForArchival(array $contact)
676         {
677                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
678                 $exists = DBA::exists('contact', $condition);
679
680                 // We don't need to update, we never marked this contact for archival
681                 if (!$exists) {
682                         return;
683                 }
684
685                 if (!isset($contact['url']) && !empty($contact['id'])) {
686                         $fields = ['id', 'url', 'batch'];
687                         $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
688                         if (!DBA::isResult($contact)) {
689                                 return;
690                         }
691                 }
692
693                 // It's a miracle. Our dead contact has inexplicably come back to life.
694                 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
695                 DBA::update('contact', $fields, ['id' => $contact['id']]);
696                 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
697
698                 if (!empty($contact['batch'])) {
699                         $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
700                         DBA::update('contact', $fields, $condition);
701                 }
702         }
703
704         /**
705          * @brief Get contact data for a given profile link
706          *
707          * The function looks at several places (contact table and gcontact table) for the contact
708          * It caches its result for the same script execution to prevent duplicate calls
709          *
710          * @param string $url     The profile link
711          * @param int    $uid     User id
712          * @param array  $default If not data was found take this data as default value
713          *
714          * @return array Contact data
715          */
716         public static function getDetailsByURL($url, $uid = -1, array $default = [])
717         {
718                 static $cache = [];
719
720                 if ($url == '') {
721                         return $default;
722                 }
723
724                 if ($uid == -1) {
725                         $uid = local_user();
726                 }
727
728                 if (isset($cache[$url][$uid])) {
729                         return $cache[$url][$uid];
730                 }
731
732                 $ssl_url = str_replace('http://', 'https://', $url);
733
734                 // Fetch contact data from the contact table for the given user
735                 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
736                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
737                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
738                 $r = DBA::toArray($s);
739
740                 // Fetch contact data from the contact table for the given user, checking with the alias
741                 if (!DBA::isResult($r)) {
742                         $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
743                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
744                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
745                         $r = DBA::toArray($s);
746                 }
747
748                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
749                 if (!DBA::isResult($r)) {
750                         $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
751                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
752                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
753                         $r = DBA::toArray($s);
754                 }
755
756                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
757                 if (!DBA::isResult($r)) {
758                         $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
759                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
760                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
761                         $r = DBA::toArray($s);
762                 }
763
764                 // Fetch the data from the gcontact table
765                 if (!DBA::isResult($r)) {
766                         $s = DBA::p("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
767                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
768                         FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
769                         $r = DBA::toArray($s);
770                 }
771
772                 if (DBA::isResult($r)) {
773                         // If there is more than one entry we filter out the connector networks
774                         if (count($r) > 1) {
775                                 foreach ($r as $id => $result) {
776                                         if ($result["network"] == Protocol::STATUSNET) {
777                                                 unset($r[$id]);
778                                         }
779                                 }
780                         }
781
782                         $profile = array_shift($r);
783
784                         // "bd" always contains the upcoming birthday of a contact.
785                         // "birthday" might contain the birthday including the year of birth.
786                         if ($profile["birthday"] > DBA::NULL_DATE) {
787                                 $bd_timestamp = strtotime($profile["birthday"]);
788                                 $month = date("m", $bd_timestamp);
789                                 $day = date("d", $bd_timestamp);
790
791                                 $current_timestamp = time();
792                                 $current_year = date("Y", $current_timestamp);
793                                 $current_month = date("m", $current_timestamp);
794                                 $current_day = date("d", $current_timestamp);
795
796                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
797                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
798
799                                 if ($profile["bd"] < $current) {
800                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
801                                 }
802                         } else {
803                                 $profile["bd"] = DBA::NULL_DATE;
804                         }
805                 } else {
806                         $profile = $default;
807                 }
808
809                 if (empty($profile["photo"]) && isset($default["photo"])) {
810                         $profile["photo"] = $default["photo"];
811                 }
812
813                 if (empty($profile["name"]) && isset($default["name"])) {
814                         $profile["name"] = $default["name"];
815                 }
816
817                 if (empty($profile["network"]) && isset($default["network"])) {
818                         $profile["network"] = $default["network"];
819                 }
820
821                 if (empty($profile["thumb"]) && isset($profile["photo"])) {
822                         $profile["thumb"] = $profile["photo"];
823                 }
824
825                 if (empty($profile["micro"]) && isset($profile["thumb"])) {
826                         $profile["micro"] = $profile["thumb"];
827                 }
828
829                 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
830                         && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
831                 ) {
832                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
833                 }
834
835                 // Show contact details of Diaspora contacts only if connected
836                 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
837                         $profile["location"] = "";
838                         $profile["about"] = "";
839                         $profile["gender"] = "";
840                         $profile["birthday"] = DBA::NULL_DATE;
841                 }
842
843                 $cache[$url][$uid] = $profile;
844
845                 return $profile;
846         }
847
848         /**
849          * @brief Get contact data for a given address
850          *
851          * The function looks at several places (contact table and gcontact table) for the contact
852          *
853          * @param string $addr The profile link
854          * @param int    $uid  User id
855          *
856          * @return array Contact data
857          */
858         public static function getDetailsByAddr($addr, $uid = -1)
859         {
860                 static $cache = [];
861
862                 if ($addr == '') {
863                         return [];
864                 }
865
866                 if ($uid == -1) {
867                         $uid = local_user();
868                 }
869
870                 // Fetch contact data from the contact table for the given user
871                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
872                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
873                         FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
874                         DBA::escape($addr),
875                         intval($uid)
876                 );
877                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
878                 if (!DBA::isResult($r)) {
879                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
880                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
881                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
882                                 DBA::escape($addr)
883                         );
884                 }
885
886                 // Fetch the data from the gcontact table
887                 if (!DBA::isResult($r)) {
888                         $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
889                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
890                                 FROM `gcontact` WHERE `addr` = '%s'",
891                                 DBA::escape($addr)
892                         );
893                 }
894
895                 if (!DBA::isResult($r)) {
896                         $data = Probe::uri($addr);
897
898                         $profile = self::getDetailsByURL($data['url'], $uid);
899                 } else {
900                         $profile = $r[0];
901                 }
902
903                 return $profile;
904         }
905
906         /**
907          * @brief Returns the data array for the photo menu of a given contact
908          *
909          * @param array $contact contact
910          * @param int   $uid     optional, default 0
911          * @return array
912          */
913         public static function photoMenu(array $contact, $uid = 0)
914         {
915                 // @todo Unused, to be removed
916                 $a = get_app();
917
918                 $contact_url = '';
919                 $pm_url = '';
920                 $status_link = '';
921                 $photos_link = '';
922                 $posts_link = '';
923                 $contact_drop_link = '';
924                 $poke_link = '';
925
926                 if ($uid == 0) {
927                         $uid = local_user();
928                 }
929
930                 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
931                         if ($uid == 0) {
932                                 $profile_link = self::magicLink($contact['url']);
933                                 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
934
935                                 return $menu;
936                         }
937
938                         // Look for our own contact if the uid doesn't match and isn't public
939                         $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
940                         if (DBA::isResult($contact_own)) {
941                                 return self::photoMenu($contact_own, $uid);
942                         }
943                 }
944
945                 $sparkle = false;
946                 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
947                         $sparkle = true;
948                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
949                 } else {
950                         $profile_link = $contact['url'];
951                 }
952
953                 if ($profile_link === 'mailbox') {
954                         $profile_link = '';
955                 }
956
957                 if ($sparkle) {
958                         $status_link = $profile_link . '?url=status';
959                         $photos_link = $profile_link . '?url=photos';
960                         $profile_link = $profile_link . '?url=profile';
961                 }
962
963                 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
964                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
965                 }
966
967                 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
968                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
969                 }
970
971                 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
972
973                 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
974
975                 if (!$contact['self']) {
976                         $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
977                 }
978
979                 /**
980                  * Menu array:
981                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
982                  */
983                 if (empty($contact['uid'])) {
984                         $connlnk = 'follow/?url=' . $contact['url'];
985                         $menu = [
986                                 'profile' => [L10n::t('View Profile'),   $profile_link, true],
987                                 'network' => [L10n::t('Network Posts'),  $posts_link,   false],
988                                 'edit'    => [L10n::t('View Contact'),   $contact_url,  false],
989                                 'follow'  => [L10n::t('Connect/Follow'), $connlnk,      true],
990                         ];
991                 } else {
992                         $menu = [
993                                 'status'  => [L10n::t('View Status'),   $status_link,       true],
994                                 'profile' => [L10n::t('View Profile'),  $profile_link,      true],
995                                 'photos'  => [L10n::t('View Photos'),   $photos_link,       true],
996                                 'network' => [L10n::t('Network Posts'), $posts_link,        false],
997                                 'edit'    => [L10n::t('View Contact'),  $contact_url,       false],
998                                 'drop'    => [L10n::t('Drop Contact'),  $contact_drop_link, false],
999                                 'pm'      => [L10n::t('Send PM'),       $pm_url,            false],
1000                                 'poke'    => [L10n::t('Poke'),          $poke_link,         false],
1001                         ];
1002                 }
1003
1004                 $args = ['contact' => $contact, 'menu' => &$menu];
1005
1006                 Addon::callHooks('contact_photo_menu', $args);
1007
1008                 $menucondensed = [];
1009
1010                 foreach ($menu as $menuname => $menuitem) {
1011                         if ($menuitem[1] != '') {
1012                                 $menucondensed[$menuname] = $menuitem;
1013                         }
1014                 }
1015
1016                 return $menucondensed;
1017         }
1018
1019         /**
1020          * @brief Returns ungrouped contact count or list for user
1021          *
1022          * Returns either the total number of ungrouped contacts for the given user
1023          * id or a paginated list of ungrouped contacts.
1024          *
1025          * @param int $uid   uid
1026          * @param int $start optional, default 0
1027          * @param int $count optional, default 0
1028          *
1029          * @return array
1030          */
1031         public static function getUngroupedList($uid)
1032         {
1033                 return q("SELECT *
1034                            FROM `contact`
1035                            WHERE `uid` = %d
1036                            AND NOT `self`
1037                            AND NOT `blocked`
1038                            AND NOT `pending`
1039                            AND `id` NOT IN (
1040                                 SELECT DISTINCT(`contact-id`)
1041                                 FROM `group_member`
1042                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1043                                 WHERE `group`.`uid` = %d
1044                            )", intval($uid), intval($uid));
1045         }
1046
1047         /**
1048          * @brief Fetch the contact id for a given URL and user
1049          *
1050          * First lookup in the contact table to find a record matching either `url`, `nurl`,
1051          * `addr` or `alias`.
1052          *
1053          * If there's no record and we aren't looking for a public contact, we quit.
1054          * If there's one, we check that it isn't time to update the picture else we
1055          * directly return the found contact id.
1056          *
1057          * Second, we probe the provided $url whether it's http://server.tld/profile or
1058          * nick@server.tld. We quit if we can't get any info back.
1059          *
1060          * Third, we create the contact record if it doesn't exist
1061          *
1062          * Fourth, we update the existing record with the new data (avatar, alias, nick)
1063          * if there's any updates
1064          *
1065          * @param string  $url       Contact URL
1066          * @param integer $uid       The user id for the contact (0 = public contact)
1067          * @param boolean $no_update Don't update the contact
1068          * @param array   $default   Default value for creating the contact when every else fails
1069          * @param boolean $in_loop   Internally used variable to prevent an endless loop
1070          *
1071          * @return integer Contact ID
1072          */
1073         public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1074         {
1075                 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1076
1077                 $contact_id = 0;
1078
1079                 if ($url == '') {
1080                         return 0;
1081                 }
1082
1083                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1084                 // We first try the nurl (http://server.tld/nick), most common case
1085                 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1086
1087                 // Then the addr (nick@server.tld)
1088                 if (!DBA::isResult($contact)) {
1089                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1090                 }
1091
1092                 // Then the alias (which could be anything)
1093                 if (!DBA::isResult($contact)) {
1094                         // The link could be provided as http although we stored it as https
1095                         $ssl_url = str_replace('http://', 'https://', $url);
1096                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1097                         $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1098                 }
1099
1100                 if (DBA::isResult($contact)) {
1101                         $contact_id = $contact["id"];
1102
1103                         // Update the contact every 7 days
1104                         $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1105
1106                         // We force the update if the avatar is empty
1107                         if (empty($contact['avatar'])) {
1108                                 $update_contact = true;
1109                         }
1110                         if (!$update_contact || $no_update) {
1111                                 return $contact_id;
1112                         }
1113                 } elseif ($uid != 0) {
1114                         // Non-existing user-specific contact, exiting
1115                         return 0;
1116                 }
1117
1118                 // When we don't want to update, we look if some of our users already know this contact
1119                 if ($no_update) {
1120                         $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1121                                 'photo', 'keywords', 'location', 'about', 'network',
1122                                 'priority', 'batch', 'request', 'confirm', 'poco'];
1123                         $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1124
1125                         if (DBA::isResult($data)) {
1126                                 // For security reasons we don't fetch key data from our users
1127                                 $data["pubkey"] = '';
1128                         }
1129                 } else {
1130                         $data = [];
1131                 }
1132
1133                 if (empty($data)) {
1134                         $data = Probe::uri($url, "", $uid);
1135
1136                         // Ensure that there is a gserver entry
1137                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1138                                 PortableContact::checkServer($data['baseurl']);
1139                         }
1140                 }
1141
1142                 // Last try in gcontact for unsupported networks
1143                 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1144                         if ($uid != 0) {
1145                                 return 0;
1146                         }
1147
1148                         // Get data from the gcontact table
1149                         $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1150                         $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1151                         if (!DBA::isResult($contact)) {
1152                                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1153                         }
1154
1155                         if (!DBA::isResult($contact)) {
1156                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1157                                         'photo', 'keywords', 'location', 'about', 'network',
1158                                         'priority', 'batch', 'request', 'confirm', 'poco'];
1159                                 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1160                         }
1161
1162                         if (!DBA::isResult($contact)) {
1163                                 // The link could be provided as http although we stored it as https
1164                                 $ssl_url = str_replace('http://', 'https://', $url);
1165                                 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1166                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1167                         }
1168
1169                         if (!DBA::isResult($contact)) {
1170                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1171                                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1172                                 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1173                                 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1174                         }
1175
1176                         if (!empty($default)) {
1177                                 $contact = $default;
1178                         }
1179
1180                         if (!DBA::isResult($contact)) {
1181                                 return 0;
1182                         } else {
1183                                 $data = array_merge($data, $contact);
1184                         }
1185                 }
1186
1187                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1188                         $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1189                 }
1190
1191                 $url = $data["url"];
1192                 if (!$contact_id) {
1193                         $fields = [
1194                                 'uid'       => $uid,
1195                                 'created'   => DateTimeFormat::utcNow(),
1196                                 'url'       => $data["url"],
1197                                 'nurl'      => Strings::normaliseLink($data["url"]),
1198                                 'addr'      => $data["addr"],
1199                                 'alias'     => $data["alias"],
1200                                 'notify'    => $data["notify"],
1201                                 'poll'      => $data["poll"],
1202                                 'name'      => $data["name"],
1203                                 'nick'      => $data["nick"],
1204                                 'photo'     => $data["photo"],
1205                                 'keywords'  => $data["keywords"],
1206                                 'location'  => $data["location"],
1207                                 'about'     => $data["about"],
1208                                 'network'   => $data["network"],
1209                                 'pubkey'    => $data["pubkey"],
1210                                 'rel'       => self::SHARING,
1211                                 'priority'  => $data["priority"],
1212                                 'batch'     => $data["batch"],
1213                                 'request'   => $data["request"],
1214                                 'confirm'   => $data["confirm"],
1215                                 'poco'      => $data["poco"],
1216                                 'name-date' => DateTimeFormat::utcNow(),
1217                                 'uri-date'  => DateTimeFormat::utcNow(),
1218                                 'avatar-date' => DateTimeFormat::utcNow(),
1219                                 'writable'  => 1,
1220                                 'blocked'   => 0,
1221                                 'readonly'  => 0,
1222                                 'pending'   => 0];
1223
1224                         $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1225
1226                         DBA::update('contact', $fields, $condition, true);
1227
1228                         $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1229                         $contacts = DBA::toArray($s);
1230                         if (!DBA::isResult($contacts)) {
1231                                 return 0;
1232                         }
1233
1234                         $contact_id = $contacts[0]["id"];
1235
1236                         // Update the newly created contact from data in the gcontact table
1237                         $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1238                         if (DBA::isResult($gcontact)) {
1239                                 // Only use the information when the probing hadn't fetched these values
1240                                 if ($data['keywords'] != '') {
1241                                         unset($gcontact['keywords']);
1242                                 }
1243                                 if ($data['location'] != '') {
1244                                         unset($gcontact['location']);
1245                                 }
1246                                 if ($data['about'] != '') {
1247                                         unset($gcontact['about']);
1248                                 }
1249                                 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1250                         }
1251
1252                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1253                                 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1254                                         Strings::normaliseLink($data["url"]), 0, $contact_id];
1255                                 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1256                                 DBA::delete('contact', $condition);
1257                         }
1258                 }
1259
1260                 self::updateAvatar($data["photo"], $uid, $contact_id);
1261
1262                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1263                 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1264
1265                 // This condition should always be true
1266                 if (!DBA::isResult($contact)) {
1267                         return $contact_id;
1268                 }
1269
1270                 $updated = ['addr' => $data['addr'],
1271                         'alias' => $data['alias'],
1272                         'url' => $data['url'],
1273                         'nurl' => Strings::normaliseLink($data['url']),
1274                         'name' => $data['name'],
1275                         'nick' => $data['nick']];
1276
1277                 if ($data['keywords'] != '') {
1278                         $updated['keywords'] = $data['keywords'];
1279                 }
1280                 if ($data['location'] != '') {
1281                         $updated['location'] = $data['location'];
1282                 }
1283
1284                 // Update the technical stuff as well - if filled
1285                 if ($data['notify'] != '') {
1286                         $updated['notify'] = $data['notify'];
1287                 }
1288                 if ($data['poll'] != '') {
1289                         $updated['poll'] = $data['poll'];
1290                 }
1291                 if ($data['batch'] != '') {
1292                         $updated['batch'] = $data['batch'];
1293                 }
1294                 if ($data['request'] != '') {
1295                         $updated['request'] = $data['request'];
1296                 }
1297                 if ($data['confirm'] != '') {
1298                         $updated['confirm'] = $data['confirm'];
1299                 }
1300                 if ($data['poco'] != '') {
1301                         $updated['poco'] = $data['poco'];
1302                 }
1303
1304                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1305                 if (empty($contact['pubkey'])) {
1306                         $updated['pubkey'] = $data['pubkey'];
1307                 }
1308
1309                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1310                         $updated['uri-date'] = DateTimeFormat::utcNow();
1311                 }
1312                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1313                         $updated['name-date'] = DateTimeFormat::utcNow();
1314                 }
1315
1316                 $updated['avatar-date'] = DateTimeFormat::utcNow();
1317
1318                 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1319
1320                 return $contact_id;
1321         }
1322
1323         /**
1324          * @brief Checks if the contact is blocked
1325          *
1326          * @param int $cid contact id
1327          *
1328          * @return boolean Is the contact blocked?
1329          */
1330         public static function isBlocked($cid)
1331         {
1332                 if ($cid == 0) {
1333                         return false;
1334                 }
1335
1336                 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1337                 if (!DBA::isResult($blocked)) {
1338                         return false;
1339                 }
1340
1341                 if (Network::isUrlBlocked($blocked['url'])) {
1342                         return true;
1343                 }
1344
1345                 return (bool) $blocked['blocked'];
1346         }
1347
1348         /**
1349          * @brief Checks if the contact is hidden
1350          *
1351          * @param int $cid contact id
1352          *
1353          * @return boolean Is the contact hidden?
1354          */
1355         public static function isHidden($cid)
1356         {
1357                 if ($cid == 0) {
1358                         return false;
1359                 }
1360
1361                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1362                 if (!DBA::isResult($hidden)) {
1363                         return false;
1364                 }
1365                 return (bool) $hidden['hidden'];
1366         }
1367
1368         /**
1369          * @brief Returns posts from a given contact url
1370          *
1371          * @param string $contact_url Contact URL
1372          *
1373          * @return string posts in HTML
1374          */
1375         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1376         {
1377                 $a = self::getApp();
1378
1379                 require_once 'include/conversation.php';
1380
1381                 $cid = Self::getIdForURL($contact_url);
1382
1383                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1384                 if (!DBA::isResult($contact)) {
1385                         return '';
1386                 }
1387
1388                 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1389                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1390                 } else {
1391                         $sql = "`item`.`uid` = ?";
1392                 }
1393
1394                 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1395
1396                 if ($thread_mode) {
1397                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1398                                 $cid, GRAVITY_PARENT, local_user()];
1399                 } else {
1400                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1401                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1402                 }
1403
1404                 $pager = new Pager($a->query_string);
1405
1406                 $params = ['order' => ['created' => true],
1407                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1408
1409                 if ($thread_mode) {
1410                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1411
1412                         $items = Item::inArray($r);
1413
1414                         $o = conversation($a, $items, $pager, 'contacts', $update);
1415                 } else {
1416                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1417
1418                         $items = Item::inArray($r);
1419
1420                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1421                 }
1422
1423                 if (!$update) {
1424                         $o .= $pager->renderMinimal(count($items));
1425                 }
1426
1427                 return $o;
1428         }
1429
1430         /**
1431          * @brief Returns the account type name
1432          *
1433          * The function can be called with either the user or the contact array
1434          *
1435          * @param array $contact contact or user array
1436          * @return string
1437          */
1438         public static function getAccountType(array $contact)
1439         {
1440                 // There are several fields that indicate that the contact or user is a forum
1441                 // "page-flags" is a field in the user table,
1442                 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1443                 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1444                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1445                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1446                         || (isset($contact['forum']) && intval($contact['forum']))
1447                         || (isset($contact['prv']) && intval($contact['prv']))
1448                         || (isset($contact['community']) && intval($contact['community']))
1449                 ) {
1450                         $type = self::ACCOUNT_TYPE_COMMUNITY;
1451                 } else {
1452                         $type = self::ACCOUNT_TYPE_PERSON;
1453                 }
1454
1455                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1456                 if (isset($contact["contact-type"])) {
1457                         $type = $contact["contact-type"];
1458                 }
1459
1460                 if (isset($contact["account-type"])) {
1461                         $type = $contact["account-type"];
1462                 }
1463
1464                 switch ($type) {
1465                         case self::ACCOUNT_TYPE_ORGANISATION:
1466                                 $account_type = L10n::t("Organisation");
1467                                 break;
1468
1469                         case self::ACCOUNT_TYPE_NEWS:
1470                                 $account_type = L10n::t('News');
1471                                 break;
1472
1473                         case self::ACCOUNT_TYPE_COMMUNITY:
1474                                 $account_type = L10n::t("Forum");
1475                                 break;
1476
1477                         default:
1478                                 $account_type = "";
1479                                 break;
1480                 }
1481
1482                 return $account_type;
1483         }
1484
1485         /**
1486          * @brief Blocks a contact
1487          *
1488          * @param int $uid
1489          * @return bool
1490          */
1491         public static function block($uid)
1492         {
1493                 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1494
1495                 return $return;
1496         }
1497
1498         /**
1499          * @brief Unblocks a contact
1500          *
1501          * @param int $uid
1502          * @return bool
1503          */
1504         public static function unblock($uid)
1505         {
1506                 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1507
1508                 return $return;
1509         }
1510
1511         /**
1512          * @brief Updates the avatar links in a contact only if needed
1513          *
1514          * @param string $avatar Link to avatar picture
1515          * @param int    $uid    User id of contact owner
1516          * @param int    $cid    Contact id
1517          * @param bool   $force  force picture update
1518          *
1519          * @return array Returns array of the different avatar sizes
1520          */
1521         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1522         {
1523                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1524                 if (!DBA::isResult($contact)) {
1525                         return false;
1526                 } else {
1527                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1528                 }
1529
1530                 if (($contact["avatar"] != $avatar) || $force) {
1531                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1532
1533                         if ($photos) {
1534                                 DBA::update(
1535                                         'contact',
1536                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1537                                         ['id' => $cid]
1538                                 );
1539
1540                                 // Update the public contact (contact id = 0)
1541                                 if ($uid != 0) {
1542                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1543                                         if (DBA::isResult($pcontact)) {
1544                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1545                                         }
1546                                 }
1547
1548                                 return $photos;
1549                         }
1550                 }
1551
1552                 return $data;
1553         }
1554
1555         /**
1556          * @param integer $id      contact id
1557          * @param string  $network Optional network we are probing for
1558          * @return boolean
1559          */
1560         public static function updateFromProbe($id, $network = '')
1561         {
1562                 /*
1563                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1564                   This will reliably kill your communication with Friendica contacts.
1565                  */
1566
1567                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1568                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1569                 if (!DBA::isResult($contact)) {
1570                         return false;
1571                 }
1572
1573                 $ret = Probe::uri($contact["url"], $network);
1574
1575                 // If Probe::uri fails the network code will be different
1576                 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1577                         return false;
1578                 }
1579
1580                 $update = false;
1581
1582                 // make sure to not overwrite existing values with blank entries
1583                 foreach ($ret as $key => $val) {
1584                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1585                                 $ret[$key] = $contact[$key];
1586                         }
1587
1588                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1589                                 $update = true;
1590                         }
1591                 }
1592
1593                 if (!$update) {
1594                         return true;
1595                 }
1596
1597                 DBA::update(
1598                         'contact', [
1599                                 'url'     => $ret['url'],
1600                                 'nurl'    => Strings::normaliseLink($ret['url']),
1601                                 'network' => $ret['network'],
1602                                 'addr'    => $ret['addr'],
1603                                 'alias'   => $ret['alias'],
1604                                 'batch'   => $ret['batch'],
1605                                 'notify'  => $ret['notify'],
1606                                 'poll'    => $ret['poll'],
1607                                 'poco'    => $ret['poco']
1608                         ],
1609                         ['id' => $id]
1610                 );
1611
1612                 // Update the corresponding gcontact entry
1613                 PortableContact::lastUpdated($ret["url"]);
1614
1615                 return true;
1616         }
1617
1618         /**
1619          * Takes a $uid and a url/handle and adds a new contact
1620          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1621          * dfrn_request page.
1622          *
1623          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1624          *
1625          * Returns an array
1626          * $return['success'] boolean true if successful
1627          * $return['message'] error text if success is false.
1628          *
1629          * @brief Takes a $uid and a url/handle and adds a new contact
1630          * @param int    $uid
1631          * @param string $url
1632          * @param bool   $interactive
1633          * @param string $network
1634          * @return boolean|string
1635          */
1636         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1637         {
1638                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1639
1640                 $a = get_app();
1641
1642                 // remove ajax junk, e.g. Twitter
1643                 $url = str_replace('/#!/', '/', $url);
1644
1645                 if (!Network::isUrlAllowed($url)) {
1646                         $result['message'] = L10n::t('Disallowed profile URL.');
1647                         return $result;
1648                 }
1649
1650                 if (Network::isUrlBlocked($url)) {
1651                         $result['message'] = L10n::t('Blocked domain');
1652                         return $result;
1653                 }
1654
1655                 if (!$url) {
1656                         $result['message'] = L10n::t('Connect URL missing.');
1657                         return $result;
1658                 }
1659
1660                 $arr = ['url' => $url, 'contact' => []];
1661
1662                 Hook::callAll('follow', $arr);
1663
1664                 if (empty($arr)) {
1665                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1666                         return $result;
1667                 }
1668
1669                 if (!empty($arr['contact']['name'])) {
1670                         $ret = $arr['contact'];
1671                 } else {
1672                         $ret = Probe::uri($url, $network, $uid, false);
1673                 }
1674
1675                 if (($network != '') && ($ret['network'] != $network)) {
1676                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1677                         return $result;
1678                 }
1679
1680                 // check if we already have a contact
1681                 // the poll url is more reliable than the profile url, as we may have
1682                 // indirect links or webfinger links
1683
1684                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1685                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1686                 if (!DBA::isResult($contact)) {
1687                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1688                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1689                 }
1690
1691                 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1692                         if ($interactive) {
1693                                 if (strlen($a->getURLPath())) {
1694                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1695                                 } else {
1696                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1697                                 }
1698
1699                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1700
1701                                 // NOTREACHED
1702                         }
1703                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1704                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1705                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1706                         return $result;
1707                 }
1708
1709                 // This extra param just confuses things, remove it
1710                 if ($ret['network'] === Protocol::DIASPORA) {
1711                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1712                 }
1713
1714                 // do we have enough information?
1715                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1716                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1717                         if (empty($ret['poll'])) {
1718                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1719                         }
1720                         if (empty($ret['name'])) {
1721                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1722                         }
1723                         if (empty($ret['url'])) {
1724                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1725                         }
1726                         if (strpos($url, '@') !== false) {
1727                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1728                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1729                         }
1730                         return $result;
1731                 }
1732
1733                 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1734                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1735                         $ret['notify'] = '';
1736                 }
1737
1738                 if (!$ret['notify']) {
1739                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1740                 }
1741
1742                 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1743
1744                 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1745
1746                 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1747
1748                 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1749                         $writeable = 1;
1750                 }
1751
1752                 if (DBA::isResult($contact)) {
1753                         // update contact
1754                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1755
1756                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1757                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1758                 } else {
1759                         $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1760
1761                         // create contact record
1762                         DBA::insert('contact', [
1763                                 'uid'     => $uid,
1764                                 'created' => DateTimeFormat::utcNow(),
1765                                 'url'     => $ret['url'],
1766                                 'nurl'    => Strings::normaliseLink($ret['url']),
1767                                 'addr'    => $ret['addr'],
1768                                 'alias'   => $ret['alias'],
1769                                 'batch'   => $ret['batch'],
1770                                 'notify'  => $ret['notify'],
1771                                 'poll'    => $ret['poll'],
1772                                 'poco'    => $ret['poco'],
1773                                 'name'    => $ret['name'],
1774                                 'nick'    => $ret['nick'],
1775                                 'network' => $ret['network'],
1776                                 'pubkey'  => $ret['pubkey'],
1777                                 'rel'     => $new_relation,
1778                                 'priority'=> $ret['priority'],
1779                                 'writable'=> $writeable,
1780                                 'hidden'  => $hidden,
1781                                 'blocked' => 0,
1782                                 'readonly'=> 0,
1783                                 'pending' => 0,
1784                                 'subhub'  => $subhub
1785                         ]);
1786                 }
1787
1788                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1789                 if (!DBA::isResult($contact)) {
1790                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1791                         return $result;
1792                 }
1793
1794                 $contact_id = $contact['id'];
1795                 $result['cid'] = $contact_id;
1796
1797                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1798
1799                 // Update the avatar
1800                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1801
1802                 // pull feed and consume it, which should subscribe to the hub.
1803
1804                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1805
1806                 $owner = User::getOwnerDataById($uid);
1807
1808                 if (DBA::isResult($owner)) {
1809                         if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1810                                 // create a follow slap
1811                                 $item = [];
1812                                 $item['verb'] = ACTIVITY_FOLLOW;
1813                                 $item['follow'] = $contact["url"];
1814                                 $item['body'] = '';
1815                                 $item['title'] = '';
1816                                 $item['guid'] = '';
1817                                 $item['tag'] = '';
1818                                 $item['attach'] = '';
1819
1820                                 $slap = OStatus::salmon($item, $owner);
1821
1822                                 if (!empty($contact['notify'])) {
1823                                         Salmon::slapper($owner, $contact['notify'], $slap);
1824                                 }
1825                         } elseif ($contact['network'] == Protocol::DIASPORA) {
1826                                 $ret = Diaspora::sendShare($a->user, $contact);
1827                                 Logger::log('share returns: ' . $ret);
1828                         } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1829                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1830                                 Logger::log('Follow returns: ' . $ret);
1831                         }
1832                 }
1833
1834                 $result['success'] = true;
1835                 return $result;
1836         }
1837
1838         /**
1839          * @brief Updated contact's SSL policy
1840          *
1841          * @param array  $contact Contact array
1842          * @param string $new_policy New policy, valid: self,full
1843          *
1844          * @return array Contact array with updated values
1845          */
1846         public static function updateSslPolicy(array $contact, $new_policy)
1847         {
1848                 $ssl_changed = false;
1849                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1850                         $ssl_changed = true;
1851                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1852                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1853                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1854                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1855                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1856                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1857                 }
1858
1859                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1860                         $ssl_changed = true;
1861                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1862                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1863                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1864                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1865                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1866                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1867                 }
1868
1869                 if ($ssl_changed) {
1870                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1871                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1872                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1873                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1874                 }
1875
1876                 return $contact;
1877         }
1878
1879         public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1880                 // Should always be set
1881                 if (empty($datarray['author-id'])) {
1882                         return;
1883                 }
1884
1885                 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1886                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1887                 if (!DBA::isResult($pub_contact)) {
1888                         // Should never happen
1889                         return;
1890                 }
1891
1892                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1893                 $name = $pub_contact['name'];
1894                 $photo = $pub_contact['photo'];
1895                 $nick = $pub_contact['nick'];
1896                 $network = $pub_contact['network'];
1897
1898                 if (is_array($contact)) {
1899                         if (($contact['rel'] == self::SHARING)
1900                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1901                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1902                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1903                         }
1904
1905                         if ($contact['network'] == Protocol::ACTIVITYPUB) {
1906                                 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1907                         }
1908
1909                         // send email notification to owner?
1910                 } else {
1911                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1912                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1913                                 return;
1914                         }
1915                         // create contact record
1916                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1917                                 `blocked`, `readonly`, `pending`, `writable`)
1918                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1919                                 intval($importer['uid']),
1920                                 DBA::escape(DateTimeFormat::utcNow()),
1921                                 DBA::escape($url),
1922                                 DBA::escape(Strings::normaliseLink($url)),
1923                                 DBA::escape($name),
1924                                 DBA::escape($nick),
1925                                 DBA::escape($photo),
1926                                 DBA::escape($network),
1927                                 intval(self::FOLLOWER)
1928                         );
1929
1930                         $contact_record = [
1931                                 'id' => DBA::lastInsertId(),
1932                                 'network' => $network,
1933                                 'name' => $name,
1934                                 'url' => $url,
1935                                 'photo' => $photo
1936                         ];
1937
1938                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1939
1940                         /// @TODO Encapsulate this into a function/method
1941                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1942                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1943                         if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1944                                 // create notification
1945                                 $hash = Strings::getRandomHex();
1946
1947                                 if (is_array($contact_record)) {
1948                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1949                                                                 'blocked' => false, 'knowyou' => false,
1950                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1951                                 }
1952
1953                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1954
1955                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1956                                         in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1957
1958                                         notification([
1959                                                 'type'         => NOTIFY_INTRO,
1960                                                 'notify_flags' => $user['notify-flags'],
1961                                                 'language'     => $user['language'],
1962                                                 'to_name'      => $user['username'],
1963                                                 'to_email'     => $user['email'],
1964                                                 'uid'          => $user['uid'],
1965                                                 'link'         => System::baseUrl() . '/notifications/intro',
1966                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1967                                                 'source_link'  => $contact_record['url'],
1968                                                 'source_photo' => $contact_record['photo'],
1969                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1970                                                 'otype'        => 'intro'
1971                                         ]);
1972
1973                                 }
1974                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1975                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1976                                 DBA::update('contact', ['pending' => false], $condition);
1977
1978                                 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1979
1980                                 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1981                                         ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1982                                 }
1983                         }
1984                 }
1985         }
1986
1987         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1988         {
1989                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1990                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1991                 } else {
1992                         Contact::remove($contact['id']);
1993                 }
1994         }
1995
1996         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1997         {
1998                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1999                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2000                 } else {
2001                         Contact::remove($contact['id']);
2002                 }
2003         }
2004
2005         /**
2006          * @brief Create a birthday event.
2007          *
2008          * Update the year and the birthday.
2009          */
2010         public static function updateBirthdays()
2011         {
2012                 $condition = [
2013                         '`bd` != ""
2014                         AND `bd` > "0001-01-01"
2015                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2016                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2017                         AND NOT `contact`.`pending`
2018                         AND NOT `contact`.`hidden`
2019                         AND NOT `contact`.`blocked`
2020                         AND NOT `contact`.`archive`
2021                         AND NOT `contact`.`deleted`',
2022                         Contact::SHARING,
2023                         Contact::FRIEND
2024                 ];
2025
2026                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2027
2028                 while ($contact = DBA::fetch($contacts)) {
2029                         Logger::log('update_contact_birthday: ' . $contact['bd']);
2030
2031                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2032
2033                         if (Event::createBirthday($contact, $nextbd)) {
2034                                 // update bdyear
2035                                 DBA::update(
2036                                         'contact',
2037                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2038                                         ['id' => $contact['id']]
2039                                 );
2040                         }
2041                 }
2042         }
2043
2044         /**
2045          * Remove the unavailable contact ids from the provided list
2046          *
2047          * @param array $contact_ids Contact id list
2048          */
2049         public static function pruneUnavailable(array &$contact_ids)
2050         {
2051                 if (empty($contact_ids)) {
2052                         return;
2053                 }
2054
2055                 $str = DBA::escape(implode(',', $contact_ids));
2056
2057                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2058
2059                 $return = [];
2060                 while($contact = DBA::fetch($stmt)) {
2061                         $return[] = $contact['id'];
2062                 }
2063
2064                 DBA::close($stmt);
2065
2066                 $contact_ids = $return;
2067         }
2068
2069         /**
2070          * @brief Returns a magic link to authenticate remote visitors
2071          *
2072          * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2073          *
2074          * @param string $contact_url The address of the target contact profile
2075          * @param string $url An url that we will be redirected to after the authentication
2076          *
2077          * @return string with "redir" link
2078          */
2079         public static function magicLink($contact_url, $url = '')
2080         {
2081                 if (!local_user()) {
2082                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2083                 }
2084
2085                 $cid = self::getIdForURL($contact_url, 0, true);
2086                 if (empty($cid)) {
2087                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2088                 }
2089
2090                 return self::magicLinkbyId($cid, $url);
2091         }
2092
2093         /**
2094          * @brief Returns a magic link to authenticate remote visitors
2095          *
2096          * @param integer $cid The contact id of the target contact profile
2097          * @param integer $url An url that we will be redirected to after the authentication
2098          *
2099          * @return string with "redir" link
2100          */
2101         public static function magicLinkbyId($cid, $url = '')
2102         {
2103                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2104
2105                 return self::magicLinkbyContact($contact, $url);
2106         }
2107
2108         /**
2109          * @brief Returns a magic link to authenticate remote visitors
2110          *
2111          * @param array $contact The contact array with "uid", "network" and "url"
2112          * @param string $url An url that we will be redirected to after the authentication
2113          *
2114          * @return string with "redir" link
2115          */
2116         public static function magicLinkbyContact($contact, $url = '')
2117         {
2118                 if (!local_user() || ($contact['network'] != Protocol::DFRN)) {
2119                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2120                 }
2121
2122                 // Only redirections to the same host do make sense
2123                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2124                         return $url;
2125                 }
2126
2127                 if ($contact['uid'] != 0) {
2128                         return self::magicLink($contact['url'], $url);
2129                 }
2130
2131                 $redirect = 'redir/' . $contact['id'];
2132
2133                 if ($url != '') {
2134                         $redirect .= '?url=' . $url;
2135                 }
2136
2137                 return $redirect;
2138         }
2139 }