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