3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Profile;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\Diaspora;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Protocol\OStatus;
22 use Friendica\Protocol\PortableContact;
23 use Friendica\Protocol\Salmon;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\Network;
27 require_once 'boot.php';
28 require_once 'include/dba.php';
29 require_once 'include/text.php';
32 * @brief functions for interacting with a contact
34 class Contact extends BaseObject
37 * @name page/profile types
39 * PAGE_NORMAL is a typical personal profile account
40 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
41 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
42 * write access to wall and comments (no email and not included in page owner's ACL lists)
43 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
47 const PAGE_NORMAL = 0;
48 const PAGE_SOAPBOX = 1;
49 const PAGE_COMMUNITY = 2;
50 const PAGE_FREELOVE = 3;
52 const PAGE_PRVGROUP = 5;
60 * ACCOUNT_TYPE_PERSON - the account belongs to a person
61 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
63 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
64 * Associated page type: PAGE_SOAPBOX
66 * ACCOUNT_TYPE_NEWS - the account is a news reflector
67 * Associated page type: PAGE_SOAPBOX
69 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
70 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
72 * ACCOUNT_TYPE_RELAY - the account is a relay
73 * This will only be assigned to contacts, not to user accounts
76 const ACCOUNT_TYPE_PERSON = 0;
77 const ACCOUNT_TYPE_ORGANISATION = 1;
78 const ACCOUNT_TYPE_NEWS = 2;
79 const ACCOUNT_TYPE_COMMUNITY = 3;
80 const ACCOUNT_TYPE_RELAY = 4;
99 * @brief Returns the contact id for the user and the public contact id for a given contact id
101 * @param int $cid Either public contact id or user's contact id
102 * @param int $uid User ID
104 * @return array with public and user's contact id
106 private static function getPublicAndUserContacID($cid, $uid)
108 if (empty($uid) || empty($cid)) {
112 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
113 if (!DBA::isResult($contact)) {
117 // We quit when the user id don't match the user id of the provided contact
118 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
122 if ($contact['uid'] != 0) {
123 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
127 $ucid = $contact['id'];
129 $pcid = $contact['id'];
130 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
133 return ['public' => $pcid, 'user' => $ucid];
137 * @brief Block contact id for user id
139 * @param int $cid Either public contact id or user's contact id
140 * @param int $uid User ID
141 * @param boolean $blocked Is the contact blocked or unblocked?
143 public static function setBlockedForUser($cid, $uid, $blocked)
145 $cdata = self::getPublicAndUserContacID($cid, $uid);
150 if ($cdata['user'] != 0) {
151 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
154 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
158 * @brief Returns "block" state for contact id and user id
160 * @param int $cid Either public contact id or user's contact id
161 * @param int $uid User ID
163 * @return boolean is the contact id blocked for the given user?
165 public static function isBlockedByUser($cid, $uid)
167 $cdata = self::getPublicAndUserContacID($cid, $uid);
172 $public_blocked = false;
174 if (!empty($cdata['public'])) {
175 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
176 if (DBA::isResult($public_contact)) {
177 $public_blocked = $public_contact['blocked'];
181 $user_blocked = $public_blocked;
183 if (!empty($cdata['user'])) {
184 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
185 if (DBA::isResult($user_contact)) {
186 $user_blocked = $user_contact['blocked'];
190 if ($user_blocked != $public_blocked) {
191 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
194 return $user_blocked;
198 * @brief Ignore contact id for user id
200 * @param int $cid Either public contact id or user's contact id
201 * @param int $uid User ID
202 * @param boolean $ignored Is the contact ignored or unignored?
204 public static function setIgnoredForUser($cid, $uid, $ignored)
206 $cdata = self::getPublicAndUserContacID($cid, $uid);
211 if ($cdata['user'] != 0) {
212 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
215 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
219 * @brief Returns "ignore" state for contact id and user id
221 * @param int $cid Either public contact id or user's contact id
222 * @param int $uid User ID
224 * @return boolean is the contact id ignored for the given user?
226 public static function isIgnoredByUser($cid, $uid)
228 $cdata = self::getPublicAndUserContacID($cid, $uid);
233 $public_ignored = false;
235 if (!empty($cdata['public'])) {
236 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
237 if (DBA::isResult($public_contact)) {
238 $public_ignored = $public_contact['ignored'];
242 $user_ignored = $public_ignored;
244 if (!empty($cdata['user'])) {
245 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
246 if (DBA::isResult($user_contact)) {
247 $user_ignored = $user_contact['readonly'];
251 if ($user_ignored != $public_ignored) {
252 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
255 return $user_ignored;
259 * @brief Set "collapsed" for contact id and user id
261 * @param int $cid Either public contact id or user's contact id
262 * @param int $uid User ID
263 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
265 public static function setCollapsedForUser($cid, $uid, $collapsed)
267 $cdata = self::getPublicAndUserContacID($cid, $uid);
272 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
276 * @brief Returns "collapsed" state for contact id and user id
278 * @param int $cid Either public contact id or user's contact id
279 * @param int $uid User ID
281 * @return boolean is the contact id blocked for the given user?
283 public static function isCollapsedByUser($cid, $uid)
285 $cdata = self::getPublicAndUserContacID($cid, $uid);
292 if (!empty($cdata['public'])) {
293 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
294 if (DBA::isResult($public_contact)) {
295 $collapsed = $public_contact['collapsed'];
303 * @brief Returns a list of contacts belonging in a group
308 public static function getByGroupId($gid)
313 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
315 INNER JOIN `group_member`
316 ON `contact`.`id` = `group_member`.`contact-id`
318 AND `contact`.`uid` = ?
319 AND NOT `contact`.`self`
320 AND NOT `contact`.`blocked`
321 AND NOT `contact`.`pending`
322 ORDER BY `contact`.`name` ASC',
327 if (DBA::isResult($stmt)) {
328 $return = DBA::toArray($stmt);
336 * @brief Returns the count of OStatus contacts in a group
341 public static function getOStatusCountByGroupId($gid)
345 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
347 INNER JOIN `group_member`
348 ON `contact`.`id` = `group_member`.`contact-id`
350 AND `contact`.`uid` = ?
351 AND `contact`.`network` = ?
352 AND `contact`.`notify` != ""',
357 $return = $contacts['count'];
364 * Creates the self-contact for the provided user id
367 * @return bool Operation success
369 public static function createSelfFromUserId($uid)
371 // Only create the entry if it doesn't exist yet
372 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
376 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
377 if (!DBA::isResult($user)) {
381 $return = DBA::insert('contact', [
382 'uid' => $user['uid'],
383 'created' => DateTimeFormat::utcNow(),
385 'name' => $user['username'],
386 'nick' => $user['nickname'],
387 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
388 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
389 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
392 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
393 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
394 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
395 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
396 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
397 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
398 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
399 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
400 'name-date' => DateTimeFormat::utcNow(),
401 'uri-date' => DateTimeFormat::utcNow(),
402 'avatar-date' => DateTimeFormat::utcNow(),
410 * Updates the self-contact for the provided user id
413 * @param boolean $update_avatar Force the avatar update
415 public static function updateSelfFromUserID($uid, $update_avatar = false)
417 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
418 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
419 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
420 if (!DBA::isResult($self)) {
424 $fields = ['nickname', 'page-flags', 'account-type'];
425 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
426 if (!DBA::isResult($user)) {
430 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
431 'country-name', 'gender', 'pub_keywords', 'xmpp'];
432 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
433 if (!DBA::isResult($profile)) {
437 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
438 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
439 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
440 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
441 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
443 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
444 if (DBA::isResult($avatar)) {
445 if ($update_avatar) {
446 $fields['avatar-date'] = DateTimeFormat::utcNow();
449 // Creating the path to the avatar, beginning with the file suffix
450 $types = Image::supportedTypes();
451 if (isset($types[$avatar['type']])) {
452 $file_suffix = $types[$avatar['type']];
454 $file_suffix = 'jpg';
457 // We are adding a timestamp value so that other systems won't use cached content
458 $timestamp = strtotime($fields['avatar-date']);
460 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
461 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
463 $fields['photo'] = $prefix . '4' . $suffix;
464 $fields['thumb'] = $prefix . '5' . $suffix;
465 $fields['micro'] = $prefix . '6' . $suffix;
467 // We hadn't found a photo entry, so we use the default avatar
468 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
469 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
470 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
473 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
474 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
476 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
477 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
478 $fields['nurl'] = normalise_link($fields['url']);
479 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
480 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
481 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
482 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
483 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
484 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
488 foreach ($fields as $field => $content) {
489 if (isset($self[$field]) && $self[$field] != $content) {
495 $fields['name-date'] = DateTimeFormat::utcNow();
496 DBA::update('contact', $fields, ['id' => $self['id']]);
498 // Update the public contact as well
499 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
501 // Update the profile
502 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
503 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
504 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
509 * @brief Marks a contact for removal
511 * @param int $id contact id
514 public static function remove($id)
516 // We want just to make sure that we don't delete our "self" contact
517 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
518 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
522 // Archive the contact
523 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM], ['id' => $id]);
525 // Delete it in the background
526 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
530 * @brief Sends an unfriend message. Does not remove the contact
532 * @param array $user User unfriending
533 * @param array $contact Contact unfriended
534 * @param boolean $dissolve Remove the contact on the remote side
537 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
539 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
540 DFRN::deliver($user, $contact, 'placeholder', true);
541 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
542 // create an unfollow slap
544 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
545 $item['follow'] = $contact["url"];
550 $item['attach'] = '';
551 $slap = OStatus::salmon($item, $user);
553 if (!empty($contact['notify'])) {
554 Salmon::slapper($user, $contact['notify'], $slap);
556 } elseif ($contact['network'] == Protocol::DIASPORA) {
557 Diaspora::sendUnshare($user, $contact);
562 * @brief Marks a contact for archival after a communication issue delay
564 * Contact has refused to recognise us as a friend. We will start a countdown.
565 * If they still don't recognise us in 32 days, the relationship is over,
566 * and we won't waste any more time trying to communicate with them.
567 * This provides for the possibility that their database is temporarily messed
568 * up or some other transient event and that there's a possibility we could recover from it.
570 * @param array $contact contact to mark for archival
573 public static function markForArchival(array $contact)
575 if (!isset($contact['url']) && !empty($contact['id'])) {
576 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
577 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
578 if (!DBA::isResult($contact)) {
581 } elseif (!isset($contact['url'])) {
582 logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG);
585 // Contact already archived or "self" contact? => nothing to do
586 if ($contact['archive'] || $contact['self']) {
590 if ($contact['term-date'] <= NULL_DATE) {
591 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
592 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
595 * We really should send a notification to the owner after 2-3 weeks
596 * so they won't be surprised when the contact vanishes and can take
597 * remedial action if this was a serious mistake or glitch
600 /// @todo Check for contact vitality via probing
601 $archival_days = Config::get('system', 'archival_days', 32);
603 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
604 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
605 /* Relationship is really truly dead. archive them rather than
606 * delete, though if the owner tries to unarchive them we'll start
607 * the whole process over again.
609 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
610 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
616 * @brief Cancels the archival countdown
618 * @see Contact::markForArchival()
620 * @param array $contact contact to be unmarked for archival
623 public static function unmarkForArchival(array $contact)
625 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
626 $exists = DBA::exists('contact', $condition);
628 // We don't need to update, we never marked this contact for archival
633 if (!isset($contact['url']) && !empty($contact['id'])) {
634 $fields = ['id', 'url', 'batch'];
635 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
636 if (!DBA::isResult($contact)) {
641 // It's a miracle. Our dead contact has inexplicably come back to life.
642 $fields = ['term-date' => NULL_DATE, 'archive' => false];
643 DBA::update('contact', $fields, ['id' => $contact['id']]);
644 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
646 if (!empty($contact['batch'])) {
647 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
648 DBA::update('contact', $fields, $condition);
653 * @brief Get contact data for a given profile link
655 * The function looks at several places (contact table and gcontact table) for the contact
656 * It caches its result for the same script execution to prevent duplicate calls
658 * @param string $url The profile link
659 * @param int $uid User id
660 * @param array $default If not data was found take this data as default value
662 * @return array Contact data
664 public static function getDetailsByURL($url, $uid = -1, array $default = [])
676 if (isset($cache[$url][$uid])) {
677 return $cache[$url][$uid];
680 $ssl_url = str_replace('http://', 'https://', $url);
682 // Fetch contact data from the contact table for the given user
683 $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`,
684 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
685 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
686 $r = DBA::toArray($s);
688 // Fetch contact data from the contact table for the given user, checking with the alias
689 if (!DBA::isResult($r)) {
690 $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`,
691 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
692 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
693 $r = DBA::toArray($s);
696 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
697 if (!DBA::isResult($r)) {
698 $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`,
699 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
700 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
701 $r = DBA::toArray($s);
704 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
705 if (!DBA::isResult($r)) {
706 $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`,
707 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
708 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
709 $r = DBA::toArray($s);
712 // Fetch the data from the gcontact table
713 if (!DBA::isResult($r)) {
714 $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`,
715 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
716 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
717 $r = DBA::toArray($s);
720 if (DBA::isResult($r)) {
721 // If there is more than one entry we filter out the connector networks
723 foreach ($r as $id => $result) {
724 if ($result["network"] == Protocol::STATUSNET) {
730 $profile = array_shift($r);
732 // "bd" always contains the upcoming birthday of a contact.
733 // "birthday" might contain the birthday including the year of birth.
734 if ($profile["birthday"] > '0001-01-01') {
735 $bd_timestamp = strtotime($profile["birthday"]);
736 $month = date("m", $bd_timestamp);
737 $day = date("d", $bd_timestamp);
739 $current_timestamp = time();
740 $current_year = date("Y", $current_timestamp);
741 $current_month = date("m", $current_timestamp);
742 $current_day = date("d", $current_timestamp);
744 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
745 $current = $current_year . "-" . $current_month . "-" . $current_day;
747 if ($profile["bd"] < $current) {
748 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
751 $profile["bd"] = '0001-01-01';
757 if (empty($profile["photo"]) && isset($default["photo"])) {
758 $profile["photo"] = $default["photo"];
761 if (empty($profile["name"]) && isset($default["name"])) {
762 $profile["name"] = $default["name"];
765 if (empty($profile["network"]) && isset($default["network"])) {
766 $profile["network"] = $default["network"];
769 if (empty($profile["thumb"]) && isset($profile["photo"])) {
770 $profile["thumb"] = $profile["photo"];
773 if (empty($profile["micro"]) && isset($profile["thumb"])) {
774 $profile["micro"] = $profile["thumb"];
777 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
778 && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
780 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
783 // Show contact details of Diaspora contacts only if connected
784 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
785 $profile["location"] = "";
786 $profile["about"] = "";
787 $profile["gender"] = "";
788 $profile["birthday"] = '0001-01-01';
791 $cache[$url][$uid] = $profile;
797 * @brief Get contact data for a given address
799 * The function looks at several places (contact table and gcontact table) for the contact
801 * @param string $addr The profile link
802 * @param int $uid User id
804 * @return array Contact data
806 public static function getDetailsByAddr($addr, $uid = -1)
818 // Fetch contact data from the contact table for the given user
819 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
820 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
821 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
825 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
826 if (!DBA::isResult($r)) {
827 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
828 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
829 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
834 // Fetch the data from the gcontact table
835 if (!DBA::isResult($r)) {
836 $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`,
837 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
838 FROM `gcontact` WHERE `addr` = '%s'",
843 if (!DBA::isResult($r)) {
844 $data = Probe::uri($addr);
846 $profile = self::getDetailsByURL($data['url'], $uid);
855 * @brief Returns the data array for the photo menu of a given contact
857 * @param array $contact contact
858 * @param int $uid optional, default 0
861 public static function photoMenu(array $contact, $uid = 0)
863 // @todo Unused, to be removed
871 $contact_drop_link = '';
878 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
880 $profile_link = self::magicLink($contact['url']);
881 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
886 // Look for our own contact if the uid doesn't match and isn't public
887 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
888 if (DBA::isResult($contact_own)) {
889 return self::photoMenu($contact_own, $uid);
894 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
896 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
898 $profile_link = $contact['url'];
901 if ($profile_link === 'mailbox') {
906 $status_link = $profile_link . '?url=status';
907 $photos_link = $profile_link . '?url=photos';
908 $profile_link = $profile_link . '?url=profile';
911 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
912 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
915 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
916 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
919 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
921 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/conversations';
923 if (!$contact['self']) {
924 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
929 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
931 if (empty($contact['uid'])) {
932 $connlnk = 'follow/?url=' . $contact['url'];
934 'profile' => [L10n::t('View Profile'), $profile_link, true],
935 'network' => [L10n::t('Network Posts'), $posts_link, false],
936 'edit' => [L10n::t('View Contact'), $contact_url, false],
937 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
941 'status' => [L10n::t('View Status'), $status_link, true],
942 'profile' => [L10n::t('View Profile'), $profile_link, true],
943 'photos' => [L10n::t('View Photos'), $photos_link, true],
944 'network' => [L10n::t('Network Posts'), $posts_link, false],
945 'edit' => [L10n::t('View Contact'), $contact_url, false],
946 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
947 'pm' => [L10n::t('Send PM'), $pm_url, false],
948 'poke' => [L10n::t('Poke'), $poke_link, false],
952 $args = ['contact' => $contact, 'menu' => &$menu];
954 Addon::callHooks('contact_photo_menu', $args);
958 foreach ($menu as $menuname => $menuitem) {
959 if ($menuitem[1] != '') {
960 $menucondensed[$menuname] = $menuitem;
964 return $menucondensed;
968 * @brief Returns ungrouped contact count or list for user
970 * Returns either the total number of ungrouped contacts for the given user
971 * id or a paginated list of ungrouped contacts.
973 * @param int $uid uid
974 * @param int $start optional, default 0
975 * @param int $count optional, default 0
979 public static function getUngroupedList($uid)
988 SELECT DISTINCT(`contact-id`)
990 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
991 WHERE `group`.`uid` = %d
992 )", intval($uid), intval($uid));
996 * @brief Fetch the contact id for a given URL and user
998 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1001 * If there's no record and we aren't looking for a public contact, we quit.
1002 * If there's one, we check that it isn't time to update the picture else we
1003 * directly return the found contact id.
1005 * Second, we probe the provided $url whether it's http://server.tld/profile or
1006 * nick@server.tld. We quit if we can't get any info back.
1008 * Third, we create the contact record if it doesn't exist
1010 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1011 * if there's any updates
1013 * @param string $url Contact URL
1014 * @param integer $uid The user id for the contact (0 = public contact)
1015 * @param boolean $no_update Don't update the contact
1016 * @param array $default Default value for creating the contact when every else fails
1018 * @return integer Contact ID
1020 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
1022 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
1030 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1031 // We first try the nurl (http://server.tld/nick), most common case
1032 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
1034 // Then the addr (nick@server.tld)
1035 if (!DBA::isResult($contact)) {
1036 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
1039 // Then the alias (which could be anything)
1040 if (!DBA::isResult($contact)) {
1041 // The link could be provided as http although we stored it as https
1042 $ssl_url = str_replace('http://', 'https://', $url);
1043 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
1044 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1047 if (DBA::isResult($contact)) {
1048 $contact_id = $contact["id"];
1050 // Update the contact every 7 days
1051 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1053 // We force the update if the avatar is empty
1054 if (!x($contact, 'avatar')) {
1055 $update_contact = true;
1058 if (!$update_contact || $no_update) {
1061 } elseif ($uid != 0) {
1062 // Non-existing user-specific contact, exiting
1066 // When we don't want to update, we look if some of our users already know this contact
1068 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1069 'photo', 'keywords', 'location', 'about', 'network',
1070 'priority', 'batch', 'request', 'confirm', 'poco'];
1071 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1073 if (DBA::isResult($data)) {
1074 // For security reasons we don't fetch key data from our users
1075 $data["pubkey"] = '';
1082 $data = Probe::uri($url, "", $uid);
1084 // Ensure that there is a gserver entry
1085 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1086 PortableContact::checkServer($data['baseurl']);
1090 // Last try in gcontact for unsupported networks
1091 if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1096 // Get data from the gcontact table
1097 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1098 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
1099 if (!DBA::isResult($contact)) {
1100 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1103 if (!DBA::isResult($contact)) {
1104 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1105 'photo', 'keywords', 'location', 'about', 'network',
1106 'priority', 'batch', 'request', 'confirm', 'poco'];
1107 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1110 if (!DBA::isResult($contact)) {
1111 // The link could be provided as http although we stored it as https
1112 $ssl_url = str_replace('http://', 'https://', $url);
1113 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
1114 $contact = DBA::selectFirst('contact', $fields, $condition);
1117 if (!DBA::isResult($contact)) {
1118 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1119 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1120 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
1121 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1124 if (!empty($default)) {
1125 $contact = $default;
1128 if (!DBA::isResult($contact)) {
1131 $data = array_merge($data, $contact);
1135 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
1136 $contact_id = self::getIdForURL($data["alias"], $uid, true);
1139 $url = $data["url"];
1141 DBA::insert('contact', [
1143 'created' => DateTimeFormat::utcNow(),
1144 'url' => $data["url"],
1145 'nurl' => normalise_link($data["url"]),
1146 'addr' => $data["addr"],
1147 'alias' => $data["alias"],
1148 'notify' => $data["notify"],
1149 'poll' => $data["poll"],
1150 'name' => $data["name"],
1151 'nick' => $data["nick"],
1152 'photo' => $data["photo"],
1153 'keywords' => $data["keywords"],
1154 'location' => $data["location"],
1155 'about' => $data["about"],
1156 'network' => $data["network"],
1157 'pubkey' => $data["pubkey"],
1158 'rel' => self::SHARING,
1159 'priority' => $data["priority"],
1160 'batch' => $data["batch"],
1161 'request' => $data["request"],
1162 'confirm' => $data["confirm"],
1163 'poco' => $data["poco"],
1164 'name-date' => DateTimeFormat::utcNow(),
1165 'uri-date' => DateTimeFormat::utcNow(),
1166 'avatar-date' => DateTimeFormat::utcNow(),
1173 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1174 $contacts = DBA::toArray($s);
1175 if (!DBA::isResult($contacts)) {
1179 $contact_id = $contacts[0]["id"];
1181 // Update the newly created contact from data in the gcontact table
1182 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
1183 if (DBA::isResult($gcontact)) {
1184 // Only use the information when the probing hadn't fetched these values
1185 if ($data['keywords'] != '') {
1186 unset($gcontact['keywords']);
1188 if ($data['location'] != '') {
1189 unset($gcontact['location']);
1191 if ($data['about'] != '') {
1192 unset($gcontact['about']);
1194 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1197 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1198 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1199 normalise_link($data["url"]), $contact_id]);
1203 self::updateAvatar($data["photo"], $uid, $contact_id);
1205 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1206 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1208 // This condition should always be true
1209 if (!DBA::isResult($contact)) {
1213 $updated = ['addr' => $data['addr'],
1214 'alias' => $data['alias'],
1215 'url' => $data['url'],
1216 'nurl' => normalise_link($data['url']),
1217 'name' => $data['name'],
1218 'nick' => $data['nick']];
1220 if ($data['keywords'] != '') {
1221 $updated['keywords'] = $data['keywords'];
1223 if ($data['location'] != '') {
1224 $updated['location'] = $data['location'];
1227 // Update the technical stuff as well - if filled
1228 if ($data['notify'] != '') {
1229 $updated['notify'] = $data['notify'];
1231 if ($data['poll'] != '') {
1232 $updated['poll'] = $data['poll'];
1234 if ($data['batch'] != '') {
1235 $updated['batch'] = $data['batch'];
1237 if ($data['request'] != '') {
1238 $updated['request'] = $data['request'];
1240 if ($data['confirm'] != '') {
1241 $updated['confirm'] = $data['confirm'];
1243 if ($data['poco'] != '') {
1244 $updated['poco'] = $data['poco'];
1247 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1248 if (empty($contact['pubkey'])) {
1249 $updated['pubkey'] = $data['pubkey'];
1252 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1253 $updated['uri-date'] = DateTimeFormat::utcNow();
1255 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1256 $updated['name-date'] = DateTimeFormat::utcNow();
1259 $updated['avatar-date'] = DateTimeFormat::utcNow();
1261 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1267 * @brief Checks if the contact is blocked
1269 * @param int $cid contact id
1271 * @return boolean Is the contact blocked?
1273 public static function isBlocked($cid)
1279 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1280 if (!DBA::isResult($blocked)) {
1283 return (bool) $blocked['blocked'];
1287 * @brief Checks if the contact is hidden
1289 * @param int $cid contact id
1291 * @return boolean Is the contact hidden?
1293 public static function isHidden($cid)
1299 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1300 if (!DBA::isResult($hidden)) {
1303 return (bool) $hidden['hidden'];
1307 * @brief Returns posts from a given contact url
1309 * @param string $contact_url Contact URL
1311 * @return string posts in HTML
1313 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1315 $a = self::getApp();
1317 require_once 'include/conversation.php';
1319 // There are no posts with "uid = 0" with connector networks
1320 // This speeds up the query a lot
1321 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1322 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1323 DBA::escape(normalise_link($contact_url))
1326 if (!DBA::isResult($r)) {
1330 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1331 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1333 $sql = "`item`.`uid` = ?";
1336 $author_id = intval($r[0]["author-id"]);
1338 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1341 $condition = ["`$contact` = ? AND `gravity` = ? AND " . $sql,
1342 $author_id, GRAVITY_PARENT, local_user()];
1344 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1345 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1348 $params = ['order' => ['created' => true],
1349 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1352 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1354 $items = Item::inArray($r);
1356 $o = conversation($a, $items, 'contacts', $update);
1358 $r = Item::selectForUser(local_user(), [], $condition, $params);
1360 $items = Item::inArray($r);
1362 $o = conversation($a, $items, 'contact-posts', false);
1366 $o .= alt_pager($a, count($items));
1373 * @brief Returns the account type name
1375 * The function can be called with either the user or the contact array
1377 * @param array $contact contact or user array
1380 public static function getAccountType(array $contact)
1382 // There are several fields that indicate that the contact or user is a forum
1383 // "page-flags" is a field in the user table,
1384 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1385 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1386 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1387 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1388 || (isset($contact['forum']) && intval($contact['forum']))
1389 || (isset($contact['prv']) && intval($contact['prv']))
1390 || (isset($contact['community']) && intval($contact['community']))
1392 $type = self::ACCOUNT_TYPE_COMMUNITY;
1394 $type = self::ACCOUNT_TYPE_PERSON;
1397 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1398 if (isset($contact["contact-type"])) {
1399 $type = $contact["contact-type"];
1402 if (isset($contact["account-type"])) {
1403 $type = $contact["account-type"];
1407 case self::ACCOUNT_TYPE_ORGANISATION:
1408 $account_type = L10n::t("Organisation");
1411 case self::ACCOUNT_TYPE_NEWS:
1412 $account_type = L10n::t('News');
1415 case self::ACCOUNT_TYPE_COMMUNITY:
1416 $account_type = L10n::t("Forum");
1424 return $account_type;
1428 * @brief Blocks a contact
1433 public static function block($uid)
1435 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1441 * @brief Unblocks a contact
1446 public static function unblock($uid)
1448 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1454 * @brief Updates the avatar links in a contact only if needed
1456 * @param string $avatar Link to avatar picture
1457 * @param int $uid User id of contact owner
1458 * @param int $cid Contact id
1459 * @param bool $force force picture update
1461 * @return array Returns array of the different avatar sizes
1463 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1465 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1466 if (!DBA::isResult($contact)) {
1469 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1472 if (($contact["avatar"] != $avatar) || $force) {
1473 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1478 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1482 // Update the public contact (contact id = 0)
1484 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1485 if (DBA::isResult($pcontact)) {
1486 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1498 * @param integer $id contact id
1501 public static function updateFromProbe($id)
1504 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1505 This will reliably kill your communication with Friendica contacts.
1508 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1509 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1510 if (!DBA::isResult($contact)) {
1514 $ret = Probe::uri($contact["url"]);
1516 // If Probe::uri fails the network code will be different
1517 if ($ret["network"] != $contact["network"]) {
1523 // make sure to not overwrite existing values with blank entries
1524 foreach ($ret as $key => $val) {
1525 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1526 $ret[$key] = $contact[$key];
1529 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1540 'url' => $ret['url'],
1541 'nurl' => normalise_link($ret['url']),
1542 'addr' => $ret['addr'],
1543 'alias' => $ret['alias'],
1544 'batch' => $ret['batch'],
1545 'notify' => $ret['notify'],
1546 'poll' => $ret['poll'],
1547 'poco' => $ret['poco']
1552 // Update the corresponding gcontact entry
1553 PortableContact::lastUpdated($ret["url"]);
1559 * Takes a $uid and a url/handle and adds a new contact
1560 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1561 * dfrn_request page.
1563 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1566 * $return['success'] boolean true if successful
1567 * $return['message'] error text if success is false.
1569 * @brief Takes a $uid and a url/handle and adds a new contact
1571 * @param string $url
1572 * @param bool $interactive
1573 * @param string $network
1574 * @return boolean|string
1576 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1578 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1582 // remove ajax junk, e.g. Twitter
1583 $url = str_replace('/#!/', '/', $url);
1585 if (!Network::isUrlAllowed($url)) {
1586 $result['message'] = L10n::t('Disallowed profile URL.');
1590 if (Network::isUrlBlocked($url)) {
1591 $result['message'] = L10n::t('Blocked domain');
1596 $result['message'] = L10n::t('Connect URL missing.');
1600 $arr = ['url' => $url, 'contact' => []];
1602 Addon::callHooks('follow', $arr);
1605 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1609 if (x($arr['contact'], 'name')) {
1610 $ret = $arr['contact'];
1612 $ret = Probe::uri($url, $network, $uid, false);
1615 if (($network != '') && ($ret['network'] != $network)) {
1616 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1620 // check if we already have a contact
1621 // the poll url is more reliable than the profile url, as we may have
1622 // indirect links or webfinger links
1624 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1625 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1626 if (!DBA::isResult($contact)) {
1627 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1628 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1631 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1633 if (strlen($a->urlpath)) {
1634 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1636 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1639 goaway($ret['request'] . "&addr=$myaddr");
1643 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1644 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1645 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1649 // This extra param just confuses things, remove it
1650 if ($ret['network'] === Protocol::DIASPORA) {
1651 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1654 // do we have enough information?
1656 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1657 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1658 if (!x($ret, 'poll')) {
1659 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1661 if (!x($ret, 'name')) {
1662 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1664 if (!x($ret, 'url')) {
1665 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1667 if (strpos($url, '@') !== false) {
1668 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1669 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1674 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1675 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1676 $ret['notify'] = '';
1679 if (!$ret['notify']) {
1680 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1683 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1685 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1687 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1689 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
1693 if (DBA::isResult($contact)) {
1695 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1697 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1698 DBA::update('contact', $fields, ['id' => $contact['id']]);
1700 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1702 // create contact record
1703 DBA::insert('contact', [
1705 'created' => DateTimeFormat::utcNow(),
1706 'url' => $ret['url'],
1707 'nurl' => normalise_link($ret['url']),
1708 'addr' => $ret['addr'],
1709 'alias' => $ret['alias'],
1710 'batch' => $ret['batch'],
1711 'notify' => $ret['notify'],
1712 'poll' => $ret['poll'],
1713 'poco' => $ret['poco'],
1714 'name' => $ret['name'],
1715 'nick' => $ret['nick'],
1716 'network' => $ret['network'],
1717 'pubkey' => $ret['pubkey'],
1718 'rel' => $new_relation,
1719 'priority'=> $ret['priority'],
1720 'writable'=> $writeable,
1721 'hidden' => $hidden,
1729 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1730 if (!DBA::isResult($contact)) {
1731 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1735 $contact_id = $contact['id'];
1736 $result['cid'] = $contact_id;
1738 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1740 // Update the avatar
1741 self::updateAvatar($ret['photo'], $uid, $contact_id);
1743 // pull feed and consume it, which should subscribe to the hub.
1745 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1747 $owner = User::getOwnerDataById($uid);
1749 if (DBA::isResult($owner)) {
1750 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1751 // create a follow slap
1753 $item['verb'] = ACTIVITY_FOLLOW;
1754 $item['follow'] = $contact["url"];
1756 $item['title'] = '';
1759 $item['attach'] = '';
1761 $slap = OStatus::salmon($item, $owner);
1763 if (!empty($contact['notify'])) {
1764 Salmon::slapper($owner, $contact['notify'], $slap);
1766 } elseif ($contact['network'] == Protocol::DIASPORA) {
1767 $ret = Diaspora::sendShare($a->user, $contact);
1768 logger('share returns: ' . $ret);
1772 $result['success'] = true;
1777 * @brief Updated contact's SSL policy
1779 * @param array $contact Contact array
1780 * @param string $new_policy New policy, valid: self,full
1782 * @return array Contact array with updated values
1784 public static function updateSslPolicy(array $contact, $new_policy)
1786 $ssl_changed = false;
1787 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1788 $ssl_changed = true;
1789 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1790 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1791 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1792 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1793 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1794 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1797 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1798 $ssl_changed = true;
1799 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1800 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1801 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1802 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1803 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1804 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1808 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1809 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1810 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1811 DBA::update('contact', $fields, ['id' => $contact['id']]);
1817 public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
1818 // Should always be set
1819 if (empty($datarray['author-id'])) {
1823 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1824 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1825 if (!DBA::isResult($pub_contact)) {
1826 // Should never happen
1830 $url = $pub_contact['url'];
1831 $name = $pub_contact['name'];
1832 $photo = $pub_contact['photo'];
1833 $nick = $pub_contact['nick'];
1834 $network = $pub_contact['network'];
1836 if (is_array($contact)) {
1837 if (($contact['rel'] == self::SHARING)
1838 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1839 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1840 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1842 // send email notification to owner?
1844 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1845 logger('ignoring duplicated connection request from pending contact ' . $url);
1849 // create contact record
1850 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1851 `blocked`, `readonly`, `pending`, `writable`)
1852 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1853 intval($importer['uid']),
1854 DBA::escape(DateTimeFormat::utcNow()),
1856 DBA::escape(normalise_link($url)),
1859 DBA::escape($photo),
1860 DBA::escape($network),
1861 intval(self::FOLLOWER)
1865 'id' => DBA::lastInsertId(),
1866 'network' => $network,
1872 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1874 /// @TODO Encapsulate this into a function/method
1875 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1876 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1877 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1878 // create notification
1879 $hash = random_string();
1881 if (is_array($contact_record)) {
1882 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1883 'blocked' => false, 'knowyou' => false,
1884 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1887 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1889 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1890 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1893 'type' => NOTIFY_INTRO,
1894 'notify_flags' => $user['notify-flags'],
1895 'language' => $user['language'],
1896 'to_name' => $user['username'],
1897 'to_email' => $user['email'],
1898 'uid' => $user['uid'],
1899 'link' => System::baseUrl() . '/notifications/intro',
1900 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1901 'source_link' => $contact_record['url'],
1902 'source_photo' => $contact_record['photo'],
1903 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1908 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1909 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1910 DBA::update('contact', ['pending' => false], $condition);
1915 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1917 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1918 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1920 Contact::remove($contact['id']);
1924 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1926 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1927 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1929 Contact::remove($contact['id']);
1934 * @brief Create a birthday event.
1936 * Update the year and the birthday.
1938 public static function updateBirthdays()
1940 // This only handles foreign or alien networks where a birthday has been provided.
1941 // In-network birthdays are handled within local_delivery
1943 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1944 if (DBA::isResult($r)) {
1945 foreach ($r as $rr) {
1946 logger('update_contact_birthday: ' . $rr['bd']);
1948 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1951 * Add new birthday event for this person
1953 * $bdtext is just a readable placeholder in case the event is shared
1954 * with others. We will replace it during presentation to our $importer
1955 * to contain a sparkle link and perhaps a photo.
1958 // Check for duplicates
1959 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1960 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1961 if (DBA::exists('event', $condition)) {
1965 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1966 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1968 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1969 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1970 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1971 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1976 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1977 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1984 * Remove the unavailable contact ids from the provided list
1986 * @param array $contact_ids Contact id list
1988 public static function pruneUnavailable(array &$contact_ids)
1990 if (empty($contact_ids)) {
1994 $str = DBA::escape(implode(',', $contact_ids));
1996 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
1999 while($contact = DBA::fetch($stmt)) {
2000 $return[] = $contact['id'];
2005 $contact_ids = $return;
2009 * @brief Returns a magic link to authenticate remote visitors
2011 * @param string $contact_url The address of the target contact profile
2012 * @param integer $url An url that we will be redirected to after the authentication
2014 * @return string with "redir" link
2016 public static function magicLink($contact_url, $url = '')
2018 $cid = self::getIdForURL($contact_url, 0, true);
2020 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2023 return self::magicLinkbyId($cid, $url);
2027 * @brief Returns a magic link to authenticate remote visitors
2029 * @param integer $cid The contact id of the target contact profile
2030 * @param integer $url An url that we will be redirected to after the authentication
2032 * @return string with "redir" link
2034 public static function magicLinkbyId($cid, $url = '')
2036 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2038 return self::magicLinkbyContact($contact, $url);
2042 * @brief Returns a magic link to authenticate remote visitors
2044 * @param array $contact The contact array with "uid", "network" and "url"
2045 * @param integer $url An url that we will be redirected to after the authentication
2047 * @return string with "redir" link
2049 public static function magicLinkbyContact($contact, $url = '')
2051 if ($contact['network'] != Protocol::DFRN) {
2052 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2055 // Only redirections to the same host do make sense
2056 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2060 if ($contact['uid'] != 0) {
2061 return self::magicLink($contact['url'], $url);
2064 $redirect = 'redir/' . $contact['id'];
2067 $redirect .= '?url=' . $url;