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