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