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