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