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