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