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