]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Replace x() by isset(), !empty() or defaults()
[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"] > DBA::NULL_DATE) {
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"] = DBA::NULL_DATE;
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"] = DBA::NULL_DATE;
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 (empty($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', 'url'], ['id' => $cid]);
1289                 if (!DBA::isResult($blocked)) {
1290                         return false;
1291                 }
1292
1293                 if (Network::isUrlBlocked($blocked['url'])) {
1294                         return true;
1295                 }
1296
1297                 return (bool) $blocked['blocked'];
1298         }
1299
1300         /**
1301          * @brief Checks if the contact is hidden
1302          *
1303          * @param int $cid contact id
1304          *
1305          * @return boolean Is the contact hidden?
1306          */
1307         public static function isHidden($cid)
1308         {
1309                 if ($cid == 0) {
1310                         return false;
1311                 }
1312
1313                 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1314                 if (!DBA::isResult($hidden)) {
1315                         return false;
1316                 }
1317                 return (bool) $hidden['hidden'];
1318         }
1319
1320         /**
1321          * @brief Returns posts from a given contact url
1322          *
1323          * @param string $contact_url Contact URL
1324          *
1325          * @return string posts in HTML
1326          */
1327         public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1328         {
1329                 $a = self::getApp();
1330
1331                 require_once 'include/conversation.php';
1332
1333                 $cid = Self::getIdForURL($contact_url);
1334
1335                 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1336                 if (!DBA::isResult($contact)) {
1337                         return '';
1338                 }
1339
1340                 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1341                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1342                 } else {
1343                         $sql = "`item`.`uid` = ?";
1344                 }
1345
1346                 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1347
1348                 if ($thread_mode) {
1349                         $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1350                                 $cid, GRAVITY_PARENT, local_user()];
1351                 } else {
1352                         $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1353                                 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1354                 }
1355
1356                 $pager = new Pager($a->query_string);
1357
1358                 $params = ['order' => ['created' => true],
1359                         'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1360
1361                 if ($thread_mode) {
1362                         $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1363
1364                         $items = Item::inArray($r);
1365
1366                         $o = conversation($a, $items, $pager, 'contacts', $update);
1367                 } else {
1368                         $r = Item::selectForUser(local_user(), [], $condition, $params);
1369
1370                         $items = Item::inArray($r);
1371
1372                         $o = conversation($a, $items, $pager, 'contact-posts', false);
1373                 }
1374
1375                 if (!$update) {
1376                         $o .= $pager->renderMinimal(count($items));
1377                 }
1378
1379                 return $o;
1380         }
1381
1382         /**
1383          * @brief Returns the account type name
1384          *
1385          * The function can be called with either the user or the contact array
1386          *
1387          * @param array $contact contact or user array
1388          * @return string
1389          */
1390         public static function getAccountType(array $contact)
1391         {
1392                 // There are several fields that indicate that the contact or user is a forum
1393                 // "page-flags" is a field in the user table,
1394                 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1395                 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1396                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1397                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1398                         || (isset($contact['forum']) && intval($contact['forum']))
1399                         || (isset($contact['prv']) && intval($contact['prv']))
1400                         || (isset($contact['community']) && intval($contact['community']))
1401                 ) {
1402                         $type = self::ACCOUNT_TYPE_COMMUNITY;
1403                 } else {
1404                         $type = self::ACCOUNT_TYPE_PERSON;
1405                 }
1406
1407                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1408                 if (isset($contact["contact-type"])) {
1409                         $type = $contact["contact-type"];
1410                 }
1411
1412                 if (isset($contact["account-type"])) {
1413                         $type = $contact["account-type"];
1414                 }
1415
1416                 switch ($type) {
1417                         case self::ACCOUNT_TYPE_ORGANISATION:
1418                                 $account_type = L10n::t("Organisation");
1419                                 break;
1420
1421                         case self::ACCOUNT_TYPE_NEWS:
1422                                 $account_type = L10n::t('News');
1423                                 break;
1424
1425                         case self::ACCOUNT_TYPE_COMMUNITY:
1426                                 $account_type = L10n::t("Forum");
1427                                 break;
1428
1429                         default:
1430                                 $account_type = "";
1431                                 break;
1432                 }
1433
1434                 return $account_type;
1435         }
1436
1437         /**
1438          * @brief Blocks a contact
1439          *
1440          * @param int $uid
1441          * @return bool
1442          */
1443         public static function block($uid)
1444         {
1445                 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1446
1447                 return $return;
1448         }
1449
1450         /**
1451          * @brief Unblocks a contact
1452          *
1453          * @param int $uid
1454          * @return bool
1455          */
1456         public static function unblock($uid)
1457         {
1458                 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1459
1460                 return $return;
1461         }
1462
1463         /**
1464          * @brief Updates the avatar links in a contact only if needed
1465          *
1466          * @param string $avatar Link to avatar picture
1467          * @param int    $uid    User id of contact owner
1468          * @param int    $cid    Contact id
1469          * @param bool   $force  force picture update
1470          *
1471          * @return array Returns array of the different avatar sizes
1472          */
1473         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1474         {
1475                 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1476                 if (!DBA::isResult($contact)) {
1477                         return false;
1478                 } else {
1479                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1480                 }
1481
1482                 if (($contact["avatar"] != $avatar) || $force) {
1483                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1484
1485                         if ($photos) {
1486                                 DBA::update(
1487                                         'contact',
1488                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1489                                         ['id' => $cid]
1490                                 );
1491
1492                                 // Update the public contact (contact id = 0)
1493                                 if ($uid != 0) {
1494                                         $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1495                                         if (DBA::isResult($pcontact)) {
1496                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1497                                         }
1498                                 }
1499
1500                                 return $photos;
1501                         }
1502                 }
1503
1504                 return $data;
1505         }
1506
1507         /**
1508          * @param integer $id      contact id
1509          * @param string  $network Optional network we are probing for
1510          * @return boolean
1511          */
1512         public static function updateFromProbe($id, $network = '')
1513         {
1514                 /*
1515                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1516                   This will reliably kill your communication with Friendica contacts.
1517                  */
1518
1519                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1520                 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1521                 if (!DBA::isResult($contact)) {
1522                         return false;
1523                 }
1524
1525                 $ret = Probe::uri($contact["url"], $network);
1526
1527                 // If Probe::uri fails the network code will be different
1528                 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1529                         return false;
1530                 }
1531
1532                 $update = false;
1533
1534                 // make sure to not overwrite existing values with blank entries
1535                 foreach ($ret as $key => $val) {
1536                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1537                                 $ret[$key] = $contact[$key];
1538                         }
1539
1540                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1541                                 $update = true;
1542                         }
1543                 }
1544
1545                 if (!$update) {
1546                         return true;
1547                 }
1548
1549                 DBA::update(
1550                         'contact', [
1551                                 'url'     => $ret['url'],
1552                                 'nurl'    => Strings::normaliseLink($ret['url']),
1553                                 'network' => $ret['network'],
1554                                 'addr'    => $ret['addr'],
1555                                 'alias'   => $ret['alias'],
1556                                 'batch'   => $ret['batch'],
1557                                 'notify'  => $ret['notify'],
1558                                 'poll'    => $ret['poll'],
1559                                 'poco'    => $ret['poco']
1560                         ],
1561                         ['id' => $id]
1562                 );
1563
1564                 // Update the corresponding gcontact entry
1565                 PortableContact::lastUpdated($ret["url"]);
1566
1567                 return true;
1568         }
1569
1570         /**
1571          * Takes a $uid and a url/handle and adds a new contact
1572          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1573          * dfrn_request page.
1574          *
1575          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1576          *
1577          * Returns an array
1578          * $return['success'] boolean true if successful
1579          * $return['message'] error text if success is false.
1580          *
1581          * @brief Takes a $uid and a url/handle and adds a new contact
1582          * @param int    $uid
1583          * @param string $url
1584          * @param bool   $interactive
1585          * @param string $network
1586          * @return boolean|string
1587          */
1588         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1589         {
1590                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1591
1592                 $a = get_app();
1593
1594                 // remove ajax junk, e.g. Twitter
1595                 $url = str_replace('/#!/', '/', $url);
1596
1597                 if (!Network::isUrlAllowed($url)) {
1598                         $result['message'] = L10n::t('Disallowed profile URL.');
1599                         return $result;
1600                 }
1601
1602                 if (Network::isUrlBlocked($url)) {
1603                         $result['message'] = L10n::t('Blocked domain');
1604                         return $result;
1605                 }
1606
1607                 if (!$url) {
1608                         $result['message'] = L10n::t('Connect URL missing.');
1609                         return $result;
1610                 }
1611
1612                 $arr = ['url' => $url, 'contact' => []];
1613
1614                 Hook::callAll('follow', $arr);
1615
1616                 if (empty($arr)) {
1617                         $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1618                         return $result;
1619                 }
1620
1621                 if (!empty($arr['contact']['name'])) {
1622                         $ret = $arr['contact'];
1623                 } else {
1624                         $ret = Probe::uri($url, $network, $uid, false);
1625                 }
1626
1627                 if (($network != '') && ($ret['network'] != $network)) {
1628                         Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1629                         return $result;
1630                 }
1631
1632                 // check if we already have a contact
1633                 // the poll url is more reliable than the profile url, as we may have
1634                 // indirect links or webfinger links
1635
1636                 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1637                 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1638                 if (!DBA::isResult($contact)) {
1639                         $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1640                         $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1641                 }
1642
1643                 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1644                         if ($interactive) {
1645                                 if (strlen($a->getURLPath())) {
1646                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1647                                 } else {
1648                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1649                                 }
1650
1651                                 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1652
1653                                 // NOTREACHED
1654                         }
1655                 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1656                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1657                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1658                         return $result;
1659                 }
1660
1661                 // This extra param just confuses things, remove it
1662                 if ($ret['network'] === Protocol::DIASPORA) {
1663                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1664                 }
1665
1666                 // do we have enough information?
1667                 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1668                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1669                         if (empty($ret['poll'])) {
1670                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1671                         }
1672                         if (empty($ret['name'])) {
1673                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1674                         }
1675                         if (empty($ret['url'])) {
1676                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1677                         }
1678                         if (strpos($url, '@') !== false) {
1679                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1680                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1681                         }
1682                         return $result;
1683                 }
1684
1685                 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1686                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1687                         $ret['notify'] = '';
1688                 }
1689
1690                 if (!$ret['notify']) {
1691                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1692                 }
1693
1694                 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1695
1696                 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1697
1698                 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1699
1700                 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1701                         $writeable = 1;
1702                 }
1703
1704                 if (DBA::isResult($contact)) {
1705                         // update contact
1706                         $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1707
1708                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1709                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1710                 } else {
1711                         $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1712
1713                         // create contact record
1714                         DBA::insert('contact', [
1715                                 'uid'     => $uid,
1716                                 'created' => DateTimeFormat::utcNow(),
1717                                 'url'     => $ret['url'],
1718                                 'nurl'    => Strings::normaliseLink($ret['url']),
1719                                 'addr'    => $ret['addr'],
1720                                 'alias'   => $ret['alias'],
1721                                 'batch'   => $ret['batch'],
1722                                 'notify'  => $ret['notify'],
1723                                 'poll'    => $ret['poll'],
1724                                 'poco'    => $ret['poco'],
1725                                 'name'    => $ret['name'],
1726                                 'nick'    => $ret['nick'],
1727                                 'network' => $ret['network'],
1728                                 'pubkey'  => $ret['pubkey'],
1729                                 'rel'     => $new_relation,
1730                                 'priority'=> $ret['priority'],
1731                                 'writable'=> $writeable,
1732                                 'hidden'  => $hidden,
1733                                 'blocked' => 0,
1734                                 'readonly'=> 0,
1735                                 'pending' => 0,
1736                                 'subhub'  => $subhub
1737                         ]);
1738                 }
1739
1740                 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1741                 if (!DBA::isResult($contact)) {
1742                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1743                         return $result;
1744                 }
1745
1746                 $contact_id = $contact['id'];
1747                 $result['cid'] = $contact_id;
1748
1749                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1750
1751                 // Update the avatar
1752                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1753
1754                 // pull feed and consume it, which should subscribe to the hub.
1755
1756                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1757
1758                 $owner = User::getOwnerDataById($uid);
1759
1760                 if (DBA::isResult($owner)) {
1761                         if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1762                                 // create a follow slap
1763                                 $item = [];
1764                                 $item['verb'] = ACTIVITY_FOLLOW;
1765                                 $item['follow'] = $contact["url"];
1766                                 $item['body'] = '';
1767                                 $item['title'] = '';
1768                                 $item['guid'] = '';
1769                                 $item['tag'] = '';
1770                                 $item['attach'] = '';
1771
1772                                 $slap = OStatus::salmon($item, $owner);
1773
1774                                 if (!empty($contact['notify'])) {
1775                                         Salmon::slapper($owner, $contact['notify'], $slap);
1776                                 }
1777                         } elseif ($contact['network'] == Protocol::DIASPORA) {
1778                                 $ret = Diaspora::sendShare($a->user, $contact);
1779                                 Logger::log('share returns: ' . $ret);
1780                         } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1781                                 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1782                                 Logger::log('Follow returns: ' . $ret);
1783                         }
1784                 }
1785
1786                 $result['success'] = true;
1787                 return $result;
1788         }
1789
1790         /**
1791          * @brief Updated contact's SSL policy
1792          *
1793          * @param array  $contact Contact array
1794          * @param string $new_policy New policy, valid: self,full
1795          *
1796          * @return array Contact array with updated values
1797          */
1798         public static function updateSslPolicy(array $contact, $new_policy)
1799         {
1800                 $ssl_changed = false;
1801                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1802                         $ssl_changed = true;
1803                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1804                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1805                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1806                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1807                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1808                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1809                 }
1810
1811                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1812                         $ssl_changed = true;
1813                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1814                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1815                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1816                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1817                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1818                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1819                 }
1820
1821                 if ($ssl_changed) {
1822                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1823                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1824                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1825                         DBA::update('contact', $fields, ['id' => $contact['id']]);
1826                 }
1827
1828                 return $contact;
1829         }
1830
1831         public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1832                 // Should always be set
1833                 if (empty($datarray['author-id'])) {
1834                         return;
1835                 }
1836
1837                 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1838                 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1839                 if (!DBA::isResult($pub_contact)) {
1840                         // Should never happen
1841                         return;
1842                 }
1843
1844                 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1845                 $name = $pub_contact['name'];
1846                 $photo = $pub_contact['photo'];
1847                 $nick = $pub_contact['nick'];
1848                 $network = $pub_contact['network'];
1849
1850                 if (is_array($contact)) {
1851                         if (($contact['rel'] == self::SHARING)
1852                                 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1853                                 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1854                                                 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1855                         }
1856
1857                         if ($contact['network'] == Protocol::ACTIVITYPUB) {
1858                                 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1859                         }
1860
1861                         // send email notification to owner?
1862                 } else {
1863                         if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1864                                 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1865                                 return;
1866                         }
1867                         // create contact record
1868                         q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1869                                 `blocked`, `readonly`, `pending`, `writable`)
1870                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1871                                 intval($importer['uid']),
1872                                 DBA::escape(DateTimeFormat::utcNow()),
1873                                 DBA::escape($url),
1874                                 DBA::escape(Strings::normaliseLink($url)),
1875                                 DBA::escape($name),
1876                                 DBA::escape($nick),
1877                                 DBA::escape($photo),
1878                                 DBA::escape($network),
1879                                 intval(self::FOLLOWER)
1880                         );
1881
1882                         $contact_record = [
1883                                 'id' => DBA::lastInsertId(),
1884                                 'network' => $network,
1885                                 'name' => $name,
1886                                 'url' => $url,
1887                                 'photo' => $photo
1888                         ];
1889
1890                         Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1891
1892                         /// @TODO Encapsulate this into a function/method
1893                         $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1894                         $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1895                         if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1896                                 // create notification
1897                                 $hash = Strings::getRandomHex();
1898
1899                                 if (is_array($contact_record)) {
1900                                         DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1901                                                                 'blocked' => false, 'knowyou' => false,
1902                                                                 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1903                                 }
1904
1905                                 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1906
1907                                 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1908                                         in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1909
1910                                         notification([
1911                                                 'type'         => NOTIFY_INTRO,
1912                                                 'notify_flags' => $user['notify-flags'],
1913                                                 'language'     => $user['language'],
1914                                                 'to_name'      => $user['username'],
1915                                                 'to_email'     => $user['email'],
1916                                                 'uid'          => $user['uid'],
1917                                                 'link'         => System::baseUrl() . '/notifications/intro',
1918                                                 'source_name'  => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1919                                                 'source_link'  => $contact_record['url'],
1920                                                 'source_photo' => $contact_record['photo'],
1921                                                 'verb'         => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1922                                                 'otype'        => 'intro'
1923                                         ]);
1924
1925                                 }
1926                         } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1927                                 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1928                                 DBA::update('contact', ['pending' => false], $condition);
1929
1930                                 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1931
1932                                 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1933                                         ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1934                                 }
1935                         }
1936                 }
1937         }
1938
1939         public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1940         {
1941                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1942                         DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1943                 } else {
1944                         Contact::remove($contact['id']);
1945                 }
1946         }
1947
1948         public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1949         {
1950                 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1951                         DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1952                 } else {
1953                         Contact::remove($contact['id']);
1954                 }
1955         }
1956
1957         /**
1958          * @brief Create a birthday event.
1959          *
1960          * Update the year and the birthday.
1961          */
1962         public static function updateBirthdays()
1963         {
1964                 $condition = [
1965                         '`bd` != ""
1966                         AND `bd` > "0001-01-01"
1967                         AND SUBSTRING(`bd`, 1, 4) != `bdyear`
1968                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
1969                         AND NOT `contact`.`pending`
1970                         AND NOT `contact`.`hidden`
1971                         AND NOT `contact`.`blocked`
1972                         AND NOT `contact`.`archive`
1973                         AND NOT `contact`.`deleted`',
1974                         Contact::SHARING,
1975                         Contact::FRIEND
1976                 ];
1977
1978                 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
1979
1980                 while ($contact = DBA::fetch($contacts)) {
1981                         Logger::log('update_contact_birthday: ' . $contact['bd']);
1982
1983                         $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
1984
1985                         if (Event::createBirthday($contact, $nextbd)) {
1986                                 // update bdyear
1987                                 DBA::update(
1988                                         'contact',
1989                                         ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
1990                                         ['id' => $contact['id']]
1991                                 );
1992                         }
1993                 }
1994         }
1995
1996         /**
1997          * Remove the unavailable contact ids from the provided list
1998          *
1999          * @param array $contact_ids Contact id list
2000          */
2001         public static function pruneUnavailable(array &$contact_ids)
2002         {
2003                 if (empty($contact_ids)) {
2004                         return;
2005                 }
2006
2007                 $str = DBA::escape(implode(',', $contact_ids));
2008
2009                 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2010
2011                 $return = [];
2012                 while($contact = DBA::fetch($stmt)) {
2013                         $return[] = $contact['id'];
2014                 }
2015
2016                 DBA::close($stmt);
2017
2018                 $contact_ids = $return;
2019         }
2020
2021         /**
2022          * @brief Returns a magic link to authenticate remote visitors
2023          *
2024          * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2025          *
2026          * @param string $contact_url The address of the target contact profile
2027          * @param string $url An url that we will be redirected to after the authentication
2028          *
2029          * @return string with "redir" link
2030          */
2031         public static function magicLink($contact_url, $url = '')
2032         {
2033                 $cid = self::getIdForURL($contact_url, 0, true);
2034                 if (empty($cid)) {
2035                         return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2036                 }
2037
2038                 return self::magicLinkbyId($cid, $url);
2039         }
2040
2041         /**
2042          * @brief Returns a magic link to authenticate remote visitors
2043          *
2044          * @param integer $cid The contact id of the target contact profile
2045          * @param integer $url An url that we will be redirected to after the authentication
2046          *
2047          * @return string with "redir" link
2048          */
2049         public static function magicLinkbyId($cid, $url = '')
2050         {
2051                 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2052
2053                 return self::magicLinkbyContact($contact, $url);
2054         }
2055
2056         /**
2057          * @brief Returns a magic link to authenticate remote visitors
2058          *
2059          * @param array $contact The contact array with "uid", "network" and "url"
2060          * @param string $url An url that we will be redirected to after the authentication
2061          *
2062          * @return string with "redir" link
2063          */
2064         public static function magicLinkbyContact($contact, $url = '')
2065         {
2066                 if ($contact['network'] != Protocol::DFRN) {
2067                         return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2068                 }
2069
2070                 // Only redirections to the same host do make sense
2071                 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2072                         return $url;
2073                 }
2074
2075                 if ($contact['uid'] != 0) {
2076                         return self::magicLink($contact['url'], $url);
2077                 }
2078
2079                 $redirect = 'redir/' . $contact['id'];
2080
2081                 if ($url != '') {
2082                         $redirect .= '?url=' . $url;
2083                 }
2084
2085                 return $redirect;
2086         }
2087 }