]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Update ParseUrl::getSiteinfo type recognition
[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                         // Ensure that there is a gserver entry
1081                         if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1082                                 PortableContact::checkServer($data['baseurl']);
1083                         }
1084                 }
1085
1086                 // Last try in gcontact for unsupported networks
1087                 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1088                         if ($uid != 0) {
1089                                 return 0;
1090                         }
1091
1092                         // Get data from the gcontact table
1093                         $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1094                         $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
1095                         if (!DBA::isResult($contact)) {
1096                                 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1097                         }
1098
1099                         if (!DBA::isResult($contact)) {
1100                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1101                                         'photo', 'keywords', 'location', 'about', 'network',
1102                                         'priority', 'batch', 'request', 'confirm', 'poco'];
1103                                 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1104                         }
1105
1106                         if (!DBA::isResult($contact)) {
1107                                 // The link could be provided as http although we stored it as https
1108                                 $ssl_url = str_replace('http://', 'https://', $url);
1109                                 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
1110                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1111                         }
1112
1113                         if (!DBA::isResult($contact)) {
1114                                 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1115                                         'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1116                                 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
1117                                 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1118                         }
1119
1120                         if (!empty($default)) {
1121                                 $contact = $default;
1122                         }
1123
1124                         if (!DBA::isResult($contact)) {
1125                                 return 0;
1126                         } else {
1127                                 $data = array_merge($data, $contact);
1128                         }
1129                 }
1130
1131                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
1132                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
1133                 }
1134
1135                 $url = $data["url"];
1136                 if (!$contact_id) {
1137                         DBA::insert('contact', [
1138                                 'uid'       => $uid,
1139                                 'created'   => DateTimeFormat::utcNow(),
1140                                 'url'       => $data["url"],
1141                                 'nurl'      => normalise_link($data["url"]),
1142                                 'addr'      => $data["addr"],
1143                                 'alias'     => $data["alias"],
1144                                 'notify'    => $data["notify"],
1145                                 'poll'      => $data["poll"],
1146                                 'name'      => $data["name"],
1147                                 'nick'      => $data["nick"],
1148                                 'photo'     => $data["photo"],
1149                                 'keywords'  => $data["keywords"],
1150                                 'location'  => $data["location"],
1151                                 'about'     => $data["about"],
1152                                 'network'   => $data["network"],
1153                                 'pubkey'    => $data["pubkey"],
1154                                 'rel'       => self::SHARING,
1155                                 'priority'  => $data["priority"],
1156                                 'batch'     => $data["batch"],
1157                                 'request'   => $data["request"],
1158                                 'confirm'   => $data["confirm"],
1159                                 'poco'      => $data["poco"],
1160                                 'name-date' => DateTimeFormat::utcNow(),
1161                                 'uri-date'  => DateTimeFormat::utcNow(),
1162                                 'avatar-date' => DateTimeFormat::utcNow(),
1163                                 'writable'  => 1,
1164                                 'blocked'   => 0,
1165                                 'readonly'  => 0,
1166                                 'pending'   => 0]
1167                         );
1168
1169                         $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1170                         $contacts = DBA::toArray($s);
1171                         if (!DBA::isResult($contacts)) {
1172                                 return 0;
1173                         }
1174
1175                         $contact_id = $contacts[0]["id"];
1176
1177                         // Update the newly created contact from data in the gcontact table
1178                         $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
1179                         if (DBA::isResult($gcontact)) {
1180                                 // Only use the information when the probing hadn't fetched these values
1181                                 if ($data['keywords'] != '') {
1182                                         unset($gcontact['keywords']);
1183                                 }
1184                                 if ($data['location'] != '') {
1185                                         unset($gcontact['location']);
1186                                 }
1187                                 if ($data['about'] != '') {
1188                                         unset($gcontact['about']);
1189                                 }
1190                                 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1191                         }
1192
1193                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1194                                 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1195                                         normalise_link($data["url"]), $contact_id]);
1196                         }
1197                 }
1198
1199                 self::updateAvatar($data["photo"], $uid, $contact_id);
1200
1201                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1202                 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1203
1204                 // This condition should always be true
1205                 if (!DBA::isResult($contact)) {
1206                         return $contact_id;
1207                 }
1208
1209                 $updated = ['addr' => $data['addr'],
1210                         'alias' => $data['alias'],
1211                         'url' => $data['url'],
1212                         'nurl' => normalise_link($data['url']),
1213                         'name' => $data['name'],
1214                         'nick' => $data['nick']];
1215
1216                 if ($data['keywords'] != '') {
1217                         $updated['keywords'] = $data['keywords'];
1218                 }
1219                 if ($data['location'] != '') {
1220                         $updated['location'] = $data['location'];
1221                 }
1222
1223                 // Update the technical stuff as well - if filled
1224                 if ($data['notify'] != '') {
1225                         $updated['notify'] = $data['notify'];
1226                 }
1227                 if ($data['poll'] != '') {
1228                         $updated['poll'] = $data['poll'];
1229                 }
1230                 if ($data['batch'] != '') {
1231                         $updated['batch'] = $data['batch'];
1232                 }
1233                 if ($data['request'] != '') {
1234                         $updated['request'] = $data['request'];
1235                 }
1236                 if ($data['confirm'] != '') {
1237                         $updated['confirm'] = $data['confirm'];
1238                 }
1239                 if ($data['poco'] != '') {
1240                         $updated['poco'] = $data['poco'];
1241                 }
1242
1243                 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1244                 if (empty($contact['pubkey'])) {
1245                         $updated['pubkey'] = $data['pubkey'];
1246                 }
1247
1248                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1249                         $updated['uri-date'] = DateTimeFormat::utcNow();
1250                 }
1251                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1252                         $updated['name-date'] = DateTimeFormat::utcNow();
1253                 }
1254
1255                 $updated['avatar-date'] = DateTimeFormat::utcNow();
1256
1257                 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1258
1259                 return $contact_id;
1260         }
1261
1262         /**
1263          * @brief Checks if the contact is blocked
1264          *
1265          * @param int $cid contact id
1266          *
1267          * @return boolean Is the contact blocked?
1268          */
1269         public static function isBlocked($cid)
1270         {
1271                 if ($cid == 0) {
1272                         return false;
1273                 }
1274
1275                 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1276                 if (!DBA::isResult($blocked)) {
1277                         return false;
1278                 }
1279                 return (bool) $blocked['blocked'];
1280         }
1281
1282         /**
1283          * @brief Checks if the contact is hidden
1284          *
1285          * @param int $cid contact id
1286          *
1287          * @return boolean Is the contact hidden?
1288          */
1289         public static function isHidden($cid)
1290         {
1291                 if ($cid == 0) {
1292                         return false;
1293                 }
1294
1295                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1296                 if (!DBA::isResult($hidden)) {
1297                         return false;
1298                 }
1299                 return (bool) $hidden['hidden'];
1300         }
1301
1302         /**
1303          * @brief Returns posts from a given contact url
1304          *
1305          * @param string $contact_url Contact URL
1306          *
1307          * @return string posts in HTML
1308          */
1309         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1310         {
1311                 $a = self::getApp();
1312
1313                 require_once 'include/conversation.php';
1314
1315                 // There are no posts with "uid = 0" with connector networks
1316                 // This speeds up the query a lot
1317                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1318                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1319                         DBA::escape(normalise_link($contact_url))
1320                 );
1321
1322                 if (!DBA::isResult($r)) {
1323                         return '';
1324                 }
1325
1326                 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1327                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1328                 } else {
1329                         $sql = "`item`.`uid` = ?";
1330                 }
1331
1332                 $author_id = intval($r[0]["author-id"]);
1333
1334                 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1335
1336                 if ($thread_mode) {
1337                         $condition = ["`$contact` = ? AND `gravity` = ? AND " . $sql,
1338                                 $author_id, GRAVITY_PARENT, local_user()];
1339                 } else {
1340                         $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1341                                 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1342                 }
1343
1344                 $params = ['order' => ['created' => true],
1345                         'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1346
1347                 if ($thread_mode) {
1348                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1349
1350                         $items = Item::inArray($r);
1351
1352                         $o = conversation($a, $items, 'contacts', $update);
1353                 } else {
1354                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1355
1356                         $items = Item::inArray($r);
1357
1358                         $o = conversation($a, $items, 'contact-posts', false);
1359                 }
1360
1361                 if (!$update) {
1362                         $o .= alt_pager($a, count($items));
1363                 }
1364
1365                 return $o;
1366         }
1367
1368         /**
1369          * @brief Returns the account type name
1370          *
1371          * The function can be called with either the user or the contact array
1372          *
1373          * @param array $contact contact or user array
1374          * @return string
1375          */
1376         public static function getAccountType(array $contact)
1377         {
1378                 // There are several fields that indicate that the contact or user is a forum
1379                 // "page-flags" is a field in the user table,
1380                 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1381                 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1382                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1383                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1384                         || (isset($contact['forum']) && intval($contact['forum']))
1385                         || (isset($contact['prv']) && intval($contact['prv']))
1386                         || (isset($contact['community']) && intval($contact['community']))
1387                 ) {
1388                         $type = self::ACCOUNT_TYPE_COMMUNITY;
1389                 } else {
1390                         $type = self::ACCOUNT_TYPE_PERSON;
1391                 }
1392
1393                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1394                 if (isset($contact["contact-type"])) {
1395                         $type = $contact["contact-type"];
1396                 }
1397
1398                 if (isset($contact["account-type"])) {
1399                         $type = $contact["account-type"];
1400                 }
1401
1402                 switch ($type) {
1403                         case self::ACCOUNT_TYPE_ORGANISATION:
1404                                 $account_type = L10n::t("Organisation");
1405                                 break;
1406
1407                         case self::ACCOUNT_TYPE_NEWS:
1408                                 $account_type = L10n::t('News');
1409                                 break;
1410
1411                         case self::ACCOUNT_TYPE_COMMUNITY:
1412                                 $account_type = L10n::t("Forum");
1413                                 break;
1414
1415                         default:
1416                                 $account_type = "";
1417                                 break;
1418                 }
1419
1420                 return $account_type;
1421         }
1422
1423         /**
1424          * @brief Blocks a contact
1425          *
1426          * @param int $uid
1427          * @return bool
1428          */
1429         public static function block($uid)
1430         {
1431                 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1432
1433                 return $return;
1434         }
1435
1436         /**
1437          * @brief Unblocks a contact
1438          *
1439          * @param int $uid
1440          * @return bool
1441          */
1442         public static function unblock($uid)
1443         {
1444                 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1445
1446                 return $return;
1447         }
1448
1449         /**
1450          * @brief Updates the avatar links in a contact only if needed
1451          *
1452          * @param string $avatar Link to avatar picture
1453          * @param int    $uid    User id of contact owner
1454          * @param int    $cid    Contact id
1455          * @param bool   $force  force picture update
1456          *
1457          * @return array Returns array of the different avatar sizes
1458          */
1459         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1460         {
1461                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1462                 if (!DBA::isResult($contact)) {
1463                         return false;
1464                 } else {
1465                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1466                 }
1467
1468                 if (($contact["avatar"] != $avatar) || $force) {
1469                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1470
1471                         if ($photos) {
1472                                 DBA::update(
1473                                         'contact',
1474                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1475                                         ['id' => $cid]
1476                                 );
1477
1478                                 // Update the public contact (contact id = 0)
1479                                 if ($uid != 0) {
1480                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1481                                         if (DBA::isResult($pcontact)) {
1482                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1483                                         }
1484                                 }
1485
1486                                 return $photos;
1487                         }
1488                 }
1489
1490                 return $data;
1491         }
1492
1493         /**
1494          * @param integer $id contact id
1495          * @return boolean
1496          */
1497         public static function updateFromProbe($id)
1498         {
1499                 /*
1500                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1501                   This will reliably kill your communication with Friendica contacts.
1502                  */
1503
1504                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1505                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1506                 if (!DBA::isResult($contact)) {
1507                         return false;
1508                 }
1509
1510                 $ret = Probe::uri($contact["url"]);
1511
1512                 // If Probe::uri fails the network code will be different
1513                 if ($ret["network"] != $contact["network"]) {
1514                         return false;
1515                 }
1516
1517                 $update = false;
1518
1519                 // make sure to not overwrite existing values with blank entries
1520                 foreach ($ret as $key => $val) {
1521                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1522                                 $ret[$key] = $contact[$key];
1523                         }
1524
1525                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1526                                 $update = true;
1527                         }
1528                 }
1529
1530                 if (!$update) {
1531                         return true;
1532                 }
1533
1534                 DBA::update(
1535                         'contact', [
1536                                 'url'    => $ret['url'],
1537                                 'nurl'   => normalise_link($ret['url']),
1538                                 'addr'   => $ret['addr'],
1539                                 'alias'  => $ret['alias'],
1540                                 'batch'  => $ret['batch'],
1541                                 'notify' => $ret['notify'],
1542                                 'poll'   => $ret['poll'],
1543                                 'poco'   => $ret['poco']
1544                         ],
1545                         ['id' => $id]
1546                 );
1547
1548                 // Update the corresponding gcontact entry
1549                 PortableContact::lastUpdated($ret["url"]);
1550
1551                 return true;
1552         }
1553
1554         /**
1555          * Takes a $uid and a url/handle and adds a new contact
1556          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1557          * dfrn_request page.
1558          *
1559          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1560          *
1561          * Returns an array
1562          * $return['success'] boolean true if successful
1563          * $return['message'] error text if success is false.
1564          *
1565          * @brief Takes a $uid and a url/handle and adds a new contact
1566          * @param int    $uid
1567          * @param string $url
1568          * @param bool   $interactive
1569          * @param string $network
1570          * @return boolean|string
1571          */
1572         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1573         {
1574                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1575
1576                 $a = get_app();
1577
1578                 // remove ajax junk, e.g. Twitter
1579                 $url = str_replace('/#!/', '/', $url);
1580
1581                 if (!Network::isUrlAllowed($url)) {
1582                         $result['message'] = L10n::t('Disallowed profile URL.');
1583                         return $result;
1584                 }
1585
1586                 if (Network::isUrlBlocked($url)) {
1587                         $result['message'] = L10n::t('Blocked domain');
1588                         return $result;
1589                 }
1590
1591                 if (!$url) {
1592                         $result['message'] = L10n::t('Connect URL missing.');
1593                         return $result;
1594                 }
1595
1596                 $arr = ['url' => $url, 'contact' => []];
1597
1598                 Addon::callHooks('follow', $arr);
1599
1600                 if (empty($arr)) {
1601                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1602                         return $result;
1603                 }
1604
1605                 if (x($arr['contact'], 'name')) {
1606                         $ret = $arr['contact'];
1607                 } else {
1608                         $ret = Probe::uri($url, $network, $uid, false);
1609                 }
1610
1611                 if (($network != '') && ($ret['network'] != $network)) {
1612                         logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1613                         return $result;
1614                 }
1615
1616                 // check if we already have a contact
1617                 // the poll url is more reliable than the profile url, as we may have
1618                 // indirect links or webfinger links
1619
1620                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1621                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1622                 if (!DBA::isResult($contact)) {
1623                         $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1624                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1625                 }
1626
1627                 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1628                         if ($interactive) {
1629                                 if (strlen($a->urlpath)) {
1630                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1631                                 } else {
1632                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1633                                 }
1634
1635                                 goaway($ret['request'] . "&addr=$myaddr");
1636
1637                                 // NOTREACHED
1638                         }
1639                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1640                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1641                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1642                         return $result;
1643                 }
1644
1645                 // This extra param just confuses things, remove it
1646                 if ($ret['network'] === Protocol::DIASPORA) {
1647                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1648                 }
1649
1650                 // do we have enough information?
1651
1652                 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1653                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1654                         if (!x($ret, 'poll')) {
1655                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1656                         }
1657                         if (!x($ret, 'name')) {
1658                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1659                         }
1660                         if (!x($ret, 'url')) {
1661                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1662                         }
1663                         if (strpos($url, '@') !== false) {
1664                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1665                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1666                         }
1667                         return $result;
1668                 }
1669
1670                 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1671                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1672                         $ret['notify'] = '';
1673                 }
1674
1675                 if (!$ret['notify']) {
1676                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1677                 }
1678
1679                 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1680
1681                 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1682
1683                 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1684
1685                 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1686                         $writeable = 1;
1687                 }
1688
1689                 if (DBA::isResult($contact)) {
1690                         // update contact
1691                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1692
1693                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1694                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1695                 } else {
1696                         $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1697
1698                         // create contact record
1699                         DBA::insert('contact', [
1700                                 'uid'     => $uid,
1701                                 'created' => DateTimeFormat::utcNow(),
1702                                 'url'     => $ret['url'],
1703                                 'nurl'    => normalise_link($ret['url']),
1704                                 'addr'    => $ret['addr'],
1705                                 'alias'   => $ret['alias'],
1706                                 'batch'   => $ret['batch'],
1707                                 'notify'  => $ret['notify'],
1708                                 'poll'    => $ret['poll'],
1709                                 'poco'    => $ret['poco'],
1710                                 'name'    => $ret['name'],
1711                                 'nick'    => $ret['nick'],
1712                                 'network' => $ret['network'],
1713                                 'pubkey'  => $ret['pubkey'],
1714                                 'rel'     => $new_relation,
1715                                 'priority'=> $ret['priority'],
1716                                 'writable'=> $writeable,
1717                                 'hidden'  => $hidden,
1718                                 'blocked' => 0,
1719                                 'readonly'=> 0,
1720                                 'pending' => 0,
1721                                 'subhub'  => $subhub
1722                         ]);
1723                 }
1724
1725                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1726                 if (!DBA::isResult($contact)) {
1727                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1728                         return $result;
1729                 }
1730
1731                 $contact_id = $contact['id'];
1732                 $result['cid'] = $contact_id;
1733
1734                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1735
1736                 // Update the avatar
1737                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1738
1739                 // pull feed and consume it, which should subscribe to the hub.
1740
1741                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1742
1743                 $owner = User::getOwnerDataById($uid);
1744
1745                 if (DBA::isResult($owner)) {
1746                         if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1747                                 // create a follow slap
1748                                 $item = [];
1749                                 $item['verb'] = ACTIVITY_FOLLOW;
1750                                 $item['follow'] = $contact["url"];
1751                                 $item['body'] = '';
1752                                 $item['title'] = '';
1753                                 $item['guid'] = '';
1754                                 $item['tag'] = '';
1755                                 $item['attach'] = '';
1756
1757                                 $slap = OStatus::salmon($item, $owner);
1758
1759                                 if (!empty($contact['notify'])) {
1760                                         Salmon::slapper($owner, $contact['notify'], $slap);
1761                                 }
1762                         } elseif ($contact['network'] == Protocol::DIASPORA) {
1763                                 $ret = Diaspora::sendShare($a->user, $contact);
1764                                 logger('share returns: ' . $ret);
1765                         }
1766                 }
1767
1768                 $result['success'] = true;
1769                 return $result;
1770         }
1771
1772         /**
1773          * @brief Updated contact's SSL policy
1774          *
1775          * @param array  $contact Contact array
1776          * @param string $new_policy New policy, valid: self,full
1777          *
1778          * @return array Contact array with updated values
1779          */
1780         public static function updateSslPolicy(array $contact, $new_policy)
1781         {
1782                 $ssl_changed = false;
1783                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1784                         $ssl_changed = true;
1785                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1786                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1787                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1788                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1789                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1790                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1791                 }
1792
1793                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1794                         $ssl_changed = true;
1795                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1796                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1797                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1798                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1799                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1800                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1801                 }
1802
1803                 if ($ssl_changed) {
1804                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1805                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1806                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1807                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1808                 }
1809
1810                 return $contact;
1811         }
1812
1813         public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1814                 // Should always be set
1815                 if (empty($datarray['author-id'])) {
1816                         return;
1817                 }
1818
1819                 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1820                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1821                 if (!DBA::isResult($pub_contact)) {
1822                         // Should never happen
1823                         return;
1824                 }
1825
1826                 $url = $pub_contact['url'];
1827                 $name = $pub_contact['name'];
1828                 $photo = $pub_contact['photo'];
1829                 $nick = $pub_contact['nick'];
1830                 $network = $pub_contact['network'];
1831
1832                 if (is_array($contact)) {
1833                         if (($contact['rel'] == self::SHARING)
1834                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1835                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1836                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1837                         }
1838                         // send email notification to owner?
1839                 } else {
1840                         if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1841                                 logger('ignoring duplicated connection request from pending contact ' . $url);
1842                                 return;
1843                         }
1844
1845                         // create contact record
1846                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1847                                 `blocked`, `readonly`, `pending`, `writable`)
1848                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1849                                 intval($importer['uid']),
1850                                 DBA::escape(DateTimeFormat::utcNow()),
1851                                 DBA::escape($url),
1852                                 DBA::escape(normalise_link($url)),
1853                                 DBA::escape($name),
1854                                 DBA::escape($nick),
1855                                 DBA::escape($photo),
1856                                 DBA::escape($network),
1857                                 intval(self::FOLLOWER)
1858                         );
1859
1860                         $contact_record = [
1861                                 'id' => DBA::lastInsertId(),
1862                                 'network' => $network,
1863                                 'name' => $name,
1864                                 'url' => $url,
1865                                 'photo' => $photo
1866                         ];
1867
1868                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1869
1870                         /// @TODO Encapsulate this into a function/method
1871                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1872                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1873                         if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1874                                 // create notification
1875                                 $hash = random_string();
1876
1877                                 if (is_array($contact_record)) {
1878                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1879                                                                 'blocked' => false, 'knowyou' => false,
1880                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1881                                 }
1882
1883                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1884
1885                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1886                                         in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1887
1888                                         notification([
1889                                                 'type'         => NOTIFY_INTRO,
1890                                                 'notify_flags' => $user['notify-flags'],
1891                                                 'language'     => $user['language'],
1892                                                 'to_name'      => $user['username'],
1893                                                 'to_email'     => $user['email'],
1894                                                 'uid'          => $user['uid'],
1895                                                 'link'         => System::baseUrl() . '/notifications/intro',
1896                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1897                                                 'source_link'  => $contact_record['url'],
1898                                                 'source_photo' => $contact_record['photo'],
1899                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1900                                                 'otype'        => 'intro'
1901                                         ]);
1902
1903                                 }
1904                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1905                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1906                                 DBA::update('contact', ['pending' => false], $condition);
1907                         }
1908                 }
1909         }
1910
1911         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1912         {
1913                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1914                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1915                 } else {
1916                         Contact::remove($contact['id']);
1917                 }
1918         }
1919
1920         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1921         {
1922                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1923                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1924                 } else {
1925                         Contact::remove($contact['id']);
1926                 }
1927         }
1928
1929         /**
1930          * @brief Create a birthday event.
1931          *
1932          * Update the year and the birthday.
1933          */
1934         public static function updateBirthdays()
1935         {
1936                 // This only handles foreign or alien networks where a birthday has been provided.
1937                 // In-network birthdays are handled within local_delivery
1938
1939                 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1940                 if (DBA::isResult($r)) {
1941                         foreach ($r as $rr) {
1942                                 logger('update_contact_birthday: ' . $rr['bd']);
1943
1944                                 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1945
1946                                 /*
1947                                  * Add new birthday event for this person
1948                                  *
1949                                  * $bdtext is just a readable placeholder in case the event is shared
1950                                  * with others. We will replace it during presentation to our $importer
1951                                  * to contain a sparkle link and perhaps a photo.
1952                                  */
1953
1954                                 // Check for duplicates
1955                                 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1956                                         'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1957                                 if (DBA::exists('event', $condition)) {
1958                                         continue;
1959                                 }
1960
1961                                 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1962                                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1963
1964                                 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1965                                 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1966                                         DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1967                                         DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1968                                         intval(0)
1969                                 );
1970
1971                                 // update bdyear
1972                                 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1973                                         DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1974                                 );
1975                         }
1976                 }
1977         }
1978
1979         /**
1980          * Remove the unavailable contact ids from the provided list
1981          *
1982          * @param array $contact_ids Contact id list
1983          */
1984         public static function pruneUnavailable(array &$contact_ids)
1985         {
1986                 if (empty($contact_ids)) {
1987                         return;
1988                 }
1989
1990                 $str = DBA::escape(implode(',', $contact_ids));
1991
1992                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1993
1994                 $return = [];
1995                 while($contact = DBA::fetch($stmt)) {
1996                         $return[] = $contact['id'];
1997                 }
1998
1999                 DBA::close($stmt);
2000
2001                 $contact_ids = $return;
2002         }
2003
2004         /**
2005          * @brief Returns a magic link to authenticate remote visitors
2006          *
2007          * @param string $contact_url The address of the target contact profile
2008          * @param integer $url An url that we will be redirected to after the authentication
2009          *
2010          * @return string with "redir" link
2011          */
2012         public static function magicLink($contact_url, $url = '')
2013         {
2014                 $cid = self::getIdForURL($contact_url, 0, true);
2015                 if (empty($cid)) {
2016                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2017                 }
2018
2019                 return self::magicLinkbyId($cid, $url);
2020         }
2021
2022         /**
2023          * @brief Returns a magic link to authenticate remote visitors
2024          *
2025          * @param integer $cid The contact id of the target contact profile
2026          * @param integer $url An url that we will be redirected to after the authentication
2027          *
2028          * @return string with "redir" link
2029          */
2030         public static function magicLinkbyId($cid, $url = '')
2031         {
2032                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2033
2034                 return self::magicLinkbyContact($contact, $url);
2035         }
2036
2037         /**
2038          * @brief Returns a magic link to authenticate remote visitors
2039          *
2040          * @param array $contact The contact array with "uid", "network" and "url"
2041          * @param integer $url An url that we will be redirected to after the authentication
2042          *
2043          * @return string with "redir" link
2044          */
2045         public static function magicLinkbyContact($contact, $url = '')
2046         {
2047                 if ($contact['network'] != Protocol::DFRN) {
2048                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2049                 }
2050
2051                 // Only redirections to the same host do make sense
2052                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2053                         return $url;
2054                 }
2055
2056                 if ($contact['uid'] != 0) {
2057                         return self::magicLink($contact['url'], $url);
2058                 }
2059
2060                 $redirect = 'redir/' . $contact['id'];
2061
2062                 if ($url != '') {
2063                         $redirect .= '?url=' . $url;
2064                 }
2065
2066                 return $redirect;
2067         }
2068 }