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