3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Addon;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\PortableContact;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
30 require_once 'boot.php';
31 require_once 'include/dba.php';
32 require_once 'include/text.php';
35 * @brief functions for interacting with a contact
37 class Contact extends BaseObject
40 * @name page/profile types
42 * PAGE_NORMAL is a typical personal profile account
43 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
44 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
45 * write access to wall and comments (no email and not included in page owner's ACL lists)
46 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
50 const PAGE_NORMAL = 0;
51 const PAGE_SOAPBOX = 1;
52 const PAGE_COMMUNITY = 2;
53 const PAGE_FREELOVE = 3;
55 const PAGE_PRVGROUP = 5;
63 * ACCOUNT_TYPE_PERSON - the account belongs to a person
64 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
66 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
67 * Associated page type: PAGE_SOAPBOX
69 * ACCOUNT_TYPE_NEWS - the account is a news reflector
70 * Associated page type: PAGE_SOAPBOX
72 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
73 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
75 * ACCOUNT_TYPE_RELAY - the account is a relay
76 * This will only be assigned to contacts, not to user accounts
79 const ACCOUNT_TYPE_PERSON = 0;
80 const ACCOUNT_TYPE_ORGANISATION = 1;
81 const ACCOUNT_TYPE_NEWS = 2;
82 const ACCOUNT_TYPE_COMMUNITY = 3;
83 const ACCOUNT_TYPE_RELAY = 4;
102 * @brief Get the basepath for a given contact link
103 * @todo Add functionality to store this value in the contact table
105 * @param string $url The contact link
107 * @return string basepath
109 public static function getBasepath($url)
111 $data = Probe::uri($url);
112 if (!empty($data['baseurl'])) {
113 return $data['baseurl'];
116 // When we can't probe the server, we use some ugly function that does some pattern matching
117 return PortableContact::detectServer($url);
121 * @brief Returns the contact id for the user and the public contact id for a given contact id
123 * @param int $cid Either public contact id or user's contact id
124 * @param int $uid User ID
126 * @return array with public and user's contact id
128 private static function getPublicAndUserContacID($cid, $uid)
130 if (empty($uid) || empty($cid)) {
134 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
135 if (!DBA::isResult($contact)) {
139 // We quit when the user id don't match the user id of the provided contact
140 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
144 if ($contact['uid'] != 0) {
145 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
149 $ucid = $contact['id'];
151 $pcid = $contact['id'];
152 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
155 return ['public' => $pcid, 'user' => $ucid];
159 * @brief Block contact id for user id
161 * @param int $cid Either public contact id or user's contact id
162 * @param int $uid User ID
163 * @param boolean $blocked Is the contact blocked or unblocked?
165 public static function setBlockedForUser($cid, $uid, $blocked)
167 $cdata = self::getPublicAndUserContacID($cid, $uid);
172 if ($cdata['user'] != 0) {
173 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
176 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
180 * @brief Returns "block" state for contact id and user id
182 * @param int $cid Either public contact id or user's contact id
183 * @param int $uid User ID
185 * @return boolean is the contact id blocked for the given user?
187 public static function isBlockedByUser($cid, $uid)
189 $cdata = self::getPublicAndUserContacID($cid, $uid);
194 $public_blocked = false;
196 if (!empty($cdata['public'])) {
197 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
198 if (DBA::isResult($public_contact)) {
199 $public_blocked = $public_contact['blocked'];
203 $user_blocked = $public_blocked;
205 if (!empty($cdata['user'])) {
206 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
207 if (DBA::isResult($user_contact)) {
208 $user_blocked = $user_contact['blocked'];
212 if ($user_blocked != $public_blocked) {
213 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
216 return $user_blocked;
220 * @brief Ignore contact id for user id
222 * @param int $cid Either public contact id or user's contact id
223 * @param int $uid User ID
224 * @param boolean $ignored Is the contact ignored or unignored?
226 public static function setIgnoredForUser($cid, $uid, $ignored)
228 $cdata = self::getPublicAndUserContacID($cid, $uid);
233 if ($cdata['user'] != 0) {
234 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
237 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
241 * @brief Returns "ignore" state for contact id and user id
243 * @param int $cid Either public contact id or user's contact id
244 * @param int $uid User ID
246 * @return boolean is the contact id ignored for the given user?
248 public static function isIgnoredByUser($cid, $uid)
250 $cdata = self::getPublicAndUserContacID($cid, $uid);
255 $public_ignored = false;
257 if (!empty($cdata['public'])) {
258 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
259 if (DBA::isResult($public_contact)) {
260 $public_ignored = $public_contact['ignored'];
264 $user_ignored = $public_ignored;
266 if (!empty($cdata['user'])) {
267 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
268 if (DBA::isResult($user_contact)) {
269 $user_ignored = $user_contact['readonly'];
273 if ($user_ignored != $public_ignored) {
274 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
277 return $user_ignored;
281 * @brief Set "collapsed" for contact id and user id
283 * @param int $cid Either public contact id or user's contact id
284 * @param int $uid User ID
285 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
287 public static function setCollapsedForUser($cid, $uid, $collapsed)
289 $cdata = self::getPublicAndUserContacID($cid, $uid);
294 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
298 * @brief Returns "collapsed" state for contact id and user id
300 * @param int $cid Either public contact id or user's contact id
301 * @param int $uid User ID
303 * @return boolean is the contact id blocked for the given user?
305 public static function isCollapsedByUser($cid, $uid)
307 $cdata = self::getPublicAndUserContacID($cid, $uid);
314 if (!empty($cdata['public'])) {
315 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
316 if (DBA::isResult($public_contact)) {
317 $collapsed = $public_contact['collapsed'];
325 * @brief Returns a list of contacts belonging in a group
330 public static function getByGroupId($gid)
335 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
337 INNER JOIN `group_member`
338 ON `contact`.`id` = `group_member`.`contact-id`
340 AND `contact`.`uid` = ?
341 AND NOT `contact`.`self`
342 AND NOT `contact`.`blocked`
343 AND NOT `contact`.`pending`
344 ORDER BY `contact`.`name` ASC',
349 if (DBA::isResult($stmt)) {
350 $return = DBA::toArray($stmt);
358 * @brief Returns the count of OStatus contacts in a group
363 public static function getOStatusCountByGroupId($gid)
367 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
369 INNER JOIN `group_member`
370 ON `contact`.`id` = `group_member`.`contact-id`
372 AND `contact`.`uid` = ?
373 AND `contact`.`network` = ?
374 AND `contact`.`notify` != ""',
379 $return = $contacts['count'];
386 * Creates the self-contact for the provided user id
389 * @return bool Operation success
391 public static function createSelfFromUserId($uid)
393 // Only create the entry if it doesn't exist yet
394 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
398 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
399 if (!DBA::isResult($user)) {
403 $return = DBA::insert('contact', [
404 'uid' => $user['uid'],
405 'created' => DateTimeFormat::utcNow(),
407 'name' => $user['username'],
408 'nick' => $user['nickname'],
409 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
410 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
411 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
414 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
415 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
416 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
417 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
418 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
419 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
420 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
421 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
422 'name-date' => DateTimeFormat::utcNow(),
423 'uri-date' => DateTimeFormat::utcNow(),
424 'avatar-date' => DateTimeFormat::utcNow(),
432 * Updates the self-contact for the provided user id
435 * @param boolean $update_avatar Force the avatar update
437 public static function updateSelfFromUserID($uid, $update_avatar = false)
439 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
440 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
441 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
442 if (!DBA::isResult($self)) {
446 $fields = ['nickname', 'page-flags', 'account-type'];
447 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
448 if (!DBA::isResult($user)) {
452 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
453 'country-name', 'gender', 'pub_keywords', 'xmpp'];
454 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
455 if (!DBA::isResult($profile)) {
459 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
460 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
461 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
462 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
463 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
465 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
466 if (DBA::isResult($avatar)) {
467 if ($update_avatar) {
468 $fields['avatar-date'] = DateTimeFormat::utcNow();
471 // Creating the path to the avatar, beginning with the file suffix
472 $types = Image::supportedTypes();
473 if (isset($types[$avatar['type']])) {
474 $file_suffix = $types[$avatar['type']];
476 $file_suffix = 'jpg';
479 // We are adding a timestamp value so that other systems won't use cached content
480 $timestamp = strtotime($fields['avatar-date']);
482 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
483 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
485 $fields['photo'] = $prefix . '4' . $suffix;
486 $fields['thumb'] = $prefix . '5' . $suffix;
487 $fields['micro'] = $prefix . '6' . $suffix;
489 // We hadn't found a photo entry, so we use the default avatar
490 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
491 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
492 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
495 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
496 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
498 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
499 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
500 $fields['nurl'] = Strings::normaliseLink($fields['url']);
501 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
502 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
503 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
504 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
505 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
506 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
510 foreach ($fields as $field => $content) {
511 if (isset($self[$field]) && $self[$field] != $content) {
517 $fields['name-date'] = DateTimeFormat::utcNow();
518 DBA::update('contact', $fields, ['id' => $self['id']]);
520 // Update the public contact as well
521 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
523 // Update the profile
524 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
525 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
526 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
531 * @brief Marks a contact for removal
533 * @param int $id contact id
536 public static function remove($id)
538 // We want just to make sure that we don't delete our "self" contact
539 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
540 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
544 // Archive the contact
545 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
547 // Delete it in the background
548 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
552 * @brief Sends an unfriend message. Does not remove the contact
554 * @param array $user User unfriending
555 * @param array $contact Contact unfriended
556 * @param boolean $dissolve Remove the contact on the remote side
559 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
561 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
562 DFRN::deliver($user, $contact, 'placeholder', true);
563 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
564 // create an unfollow slap
566 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
567 $item['follow'] = $contact["url"];
572 $item['attach'] = '';
573 $slap = OStatus::salmon($item, $user);
575 if (!empty($contact['notify'])) {
576 Salmon::slapper($user, $contact['notify'], $slap);
578 } elseif ($contact['network'] == Protocol::DIASPORA) {
579 Diaspora::sendUnshare($user, $contact);
580 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
581 ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
584 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
590 * @brief Marks a contact for archival after a communication issue delay
592 * Contact has refused to recognise us as a friend. We will start a countdown.
593 * If they still don't recognise us in 32 days, the relationship is over,
594 * and we won't waste any more time trying to communicate with them.
595 * This provides for the possibility that their database is temporarily messed
596 * up or some other transient event and that there's a possibility we could recover from it.
598 * @param array $contact contact to mark for archival
601 public static function markForArchival(array $contact)
603 if (!isset($contact['url']) && !empty($contact['id'])) {
604 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
605 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
606 if (!DBA::isResult($contact)) {
609 } elseif (!isset($contact['url'])) {
610 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
613 // Contact already archived or "self" contact? => nothing to do
614 if ($contact['archive'] || $contact['self']) {
618 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
619 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
620 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
623 * We really should send a notification to the owner after 2-3 weeks
624 * so they won't be surprised when the contact vanishes and can take
625 * remedial action if this was a serious mistake or glitch
628 /// @todo Check for contact vitality via probing
629 $archival_days = Config::get('system', 'archival_days', 32);
631 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
632 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
633 /* Relationship is really truly dead. archive them rather than
634 * delete, though if the owner tries to unarchive them we'll start
635 * the whole process over again.
637 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
638 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
644 * @brief Cancels the archival countdown
646 * @see Contact::markForArchival()
648 * @param array $contact contact to be unmarked for archival
651 public static function unmarkForArchival(array $contact)
653 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
654 $exists = DBA::exists('contact', $condition);
656 // We don't need to update, we never marked this contact for archival
661 if (!isset($contact['url']) && !empty($contact['id'])) {
662 $fields = ['id', 'url', 'batch'];
663 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
664 if (!DBA::isResult($contact)) {
669 // It's a miracle. Our dead contact has inexplicably come back to life.
670 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
671 DBA::update('contact', $fields, ['id' => $contact['id']]);
672 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
674 if (!empty($contact['batch'])) {
675 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
676 DBA::update('contact', $fields, $condition);
681 * @brief Get contact data for a given profile link
683 * The function looks at several places (contact table and gcontact table) for the contact
684 * It caches its result for the same script execution to prevent duplicate calls
686 * @param string $url The profile link
687 * @param int $uid User id
688 * @param array $default If not data was found take this data as default value
690 * @return array Contact data
692 public static function getDetailsByURL($url, $uid = -1, array $default = [])
704 if (isset($cache[$url][$uid])) {
705 return $cache[$url][$uid];
708 $ssl_url = str_replace('http://', 'https://', $url);
710 // Fetch contact data from the contact table for the given user
711 $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`,
712 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
713 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
714 $r = DBA::toArray($s);
716 // Fetch contact data from the contact table for the given user, checking with the alias
717 if (!DBA::isResult($r)) {
718 $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`,
719 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
720 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
721 $r = DBA::toArray($s);
724 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
725 if (!DBA::isResult($r)) {
726 $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`,
727 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
728 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
729 $r = DBA::toArray($s);
732 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
733 if (!DBA::isResult($r)) {
734 $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`,
735 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
736 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
737 $r = DBA::toArray($s);
740 // Fetch the data from the gcontact table
741 if (!DBA::isResult($r)) {
742 $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`,
743 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
744 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
745 $r = DBA::toArray($s);
748 if (DBA::isResult($r)) {
749 // If there is more than one entry we filter out the connector networks
751 foreach ($r as $id => $result) {
752 if ($result["network"] == Protocol::STATUSNET) {
758 $profile = array_shift($r);
760 // "bd" always contains the upcoming birthday of a contact.
761 // "birthday" might contain the birthday including the year of birth.
762 if ($profile["birthday"] > DBA::NULL_DATE) {
763 $bd_timestamp = strtotime($profile["birthday"]);
764 $month = date("m", $bd_timestamp);
765 $day = date("d", $bd_timestamp);
767 $current_timestamp = time();
768 $current_year = date("Y", $current_timestamp);
769 $current_month = date("m", $current_timestamp);
770 $current_day = date("d", $current_timestamp);
772 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
773 $current = $current_year . "-" . $current_month . "-" . $current_day;
775 if ($profile["bd"] < $current) {
776 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
779 $profile["bd"] = DBA::NULL_DATE;
785 if (empty($profile["photo"]) && isset($default["photo"])) {
786 $profile["photo"] = $default["photo"];
789 if (empty($profile["name"]) && isset($default["name"])) {
790 $profile["name"] = $default["name"];
793 if (empty($profile["network"]) && isset($default["network"])) {
794 $profile["network"] = $default["network"];
797 if (empty($profile["thumb"]) && isset($profile["photo"])) {
798 $profile["thumb"] = $profile["photo"];
801 if (empty($profile["micro"]) && isset($profile["thumb"])) {
802 $profile["micro"] = $profile["thumb"];
805 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
806 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
808 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
811 // Show contact details of Diaspora contacts only if connected
812 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
813 $profile["location"] = "";
814 $profile["about"] = "";
815 $profile["gender"] = "";
816 $profile["birthday"] = DBA::NULL_DATE;
819 $cache[$url][$uid] = $profile;
825 * @brief Get contact data for a given address
827 * The function looks at several places (contact table and gcontact table) for the contact
829 * @param string $addr The profile link
830 * @param int $uid User id
832 * @return array Contact data
834 public static function getDetailsByAddr($addr, $uid = -1)
846 // Fetch contact data from the contact table for the given user
847 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
848 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
849 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
853 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
854 if (!DBA::isResult($r)) {
855 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
856 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
857 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
862 // Fetch the data from the gcontact table
863 if (!DBA::isResult($r)) {
864 $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`,
865 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
866 FROM `gcontact` WHERE `addr` = '%s'",
871 if (!DBA::isResult($r)) {
872 $data = Probe::uri($addr);
874 $profile = self::getDetailsByURL($data['url'], $uid);
883 * @brief Returns the data array for the photo menu of a given contact
885 * @param array $contact contact
886 * @param int $uid optional, default 0
889 public static function photoMenu(array $contact, $uid = 0)
891 // @todo Unused, to be removed
899 $contact_drop_link = '';
906 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
908 $profile_link = self::magicLink($contact['url']);
909 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
914 // Look for our own contact if the uid doesn't match and isn't public
915 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
916 if (DBA::isResult($contact_own)) {
917 return self::photoMenu($contact_own, $uid);
922 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
924 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
926 $profile_link = $contact['url'];
929 if ($profile_link === 'mailbox') {
934 $status_link = $profile_link . '?url=status';
935 $photos_link = $profile_link . '?url=photos';
936 $profile_link = $profile_link . '?url=profile';
939 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
940 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
943 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
944 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
947 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
949 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
951 if (!$contact['self']) {
952 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
957 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
959 if (empty($contact['uid'])) {
960 $connlnk = 'follow/?url=' . $contact['url'];
962 'profile' => [L10n::t('View Profile'), $profile_link, true],
963 'network' => [L10n::t('Network Posts'), $posts_link, false],
964 'edit' => [L10n::t('View Contact'), $contact_url, false],
965 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
969 'status' => [L10n::t('View Status'), $status_link, true],
970 'profile' => [L10n::t('View Profile'), $profile_link, true],
971 'photos' => [L10n::t('View Photos'), $photos_link, true],
972 'network' => [L10n::t('Network Posts'), $posts_link, false],
973 'edit' => [L10n::t('View Contact'), $contact_url, false],
974 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
975 'pm' => [L10n::t('Send PM'), $pm_url, false],
976 'poke' => [L10n::t('Poke'), $poke_link, false],
980 $args = ['contact' => $contact, 'menu' => &$menu];
982 Addon::callHooks('contact_photo_menu', $args);
986 foreach ($menu as $menuname => $menuitem) {
987 if ($menuitem[1] != '') {
988 $menucondensed[$menuname] = $menuitem;
992 return $menucondensed;
996 * @brief Returns ungrouped contact count or list for user
998 * Returns either the total number of ungrouped contacts for the given user
999 * id or a paginated list of ungrouped contacts.
1001 * @param int $uid uid
1002 * @param int $start optional, default 0
1003 * @param int $count optional, default 0
1007 public static function getUngroupedList($uid)
1016 SELECT DISTINCT(`contact-id`)
1018 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1019 WHERE `group`.`uid` = %d
1020 )", intval($uid), intval($uid));
1024 * @brief Fetch the contact id for a given URL and user
1026 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1027 * `addr` or `alias`.
1029 * If there's no record and we aren't looking for a public contact, we quit.
1030 * If there's one, we check that it isn't time to update the picture else we
1031 * directly return the found contact id.
1033 * Second, we probe the provided $url whether it's http://server.tld/profile or
1034 * nick@server.tld. We quit if we can't get any info back.
1036 * Third, we create the contact record if it doesn't exist
1038 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1039 * if there's any updates
1041 * @param string $url Contact URL
1042 * @param integer $uid The user id for the contact (0 = public contact)
1043 * @param boolean $no_update Don't update the contact
1044 * @param array $default Default value for creating the contact when every else fails
1045 * @param boolean $in_loop Internally used variable to prevent an endless loop
1047 * @return integer Contact ID
1049 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1051 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1059 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1060 // We first try the nurl (http://server.tld/nick), most common case
1061 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1063 // Then the addr (nick@server.tld)
1064 if (!DBA::isResult($contact)) {
1065 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1068 // Then the alias (which could be anything)
1069 if (!DBA::isResult($contact)) {
1070 // The link could be provided as http although we stored it as https
1071 $ssl_url = str_replace('http://', 'https://', $url);
1072 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1073 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1076 if (DBA::isResult($contact)) {
1077 $contact_id = $contact["id"];
1079 // Update the contact every 7 days
1080 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1082 // We force the update if the avatar is empty
1083 if (empty($contact['avatar'])) {
1084 $update_contact = true;
1086 if (!$update_contact || $no_update) {
1089 } elseif ($uid != 0) {
1090 // Non-existing user-specific contact, exiting
1094 // When we don't want to update, we look if some of our users already know this contact
1096 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1097 'photo', 'keywords', 'location', 'about', 'network',
1098 'priority', 'batch', 'request', 'confirm', 'poco'];
1099 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1101 if (DBA::isResult($data)) {
1102 // For security reasons we don't fetch key data from our users
1103 $data["pubkey"] = '';
1110 $data = Probe::uri($url, "", $uid);
1112 // Ensure that there is a gserver entry
1113 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1114 PortableContact::checkServer($data['baseurl']);
1118 // Last try in gcontact for unsupported networks
1119 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1124 // Get data from the gcontact table
1125 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1126 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1127 if (!DBA::isResult($contact)) {
1128 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1131 if (!DBA::isResult($contact)) {
1132 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1133 'photo', 'keywords', 'location', 'about', 'network',
1134 'priority', 'batch', 'request', 'confirm', 'poco'];
1135 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1138 if (!DBA::isResult($contact)) {
1139 // The link could be provided as http although we stored it as https
1140 $ssl_url = str_replace('http://', 'https://', $url);
1141 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1142 $contact = DBA::selectFirst('contact', $fields, $condition);
1145 if (!DBA::isResult($contact)) {
1146 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1147 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1148 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1149 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1152 if (!empty($default)) {
1153 $contact = $default;
1156 if (!DBA::isResult($contact)) {
1159 $data = array_merge($data, $contact);
1163 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1164 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1167 $url = $data["url"];
1171 'created' => DateTimeFormat::utcNow(),
1172 'url' => $data["url"],
1173 'nurl' => Strings::normaliseLink($data["url"]),
1174 'addr' => $data["addr"],
1175 'alias' => $data["alias"],
1176 'notify' => $data["notify"],
1177 'poll' => $data["poll"],
1178 'name' => $data["name"],
1179 'nick' => $data["nick"],
1180 'photo' => $data["photo"],
1181 'keywords' => $data["keywords"],
1182 'location' => $data["location"],
1183 'about' => $data["about"],
1184 'network' => $data["network"],
1185 'pubkey' => $data["pubkey"],
1186 'rel' => self::SHARING,
1187 'priority' => $data["priority"],
1188 'batch' => $data["batch"],
1189 'request' => $data["request"],
1190 'confirm' => $data["confirm"],
1191 'poco' => $data["poco"],
1192 'name-date' => DateTimeFormat::utcNow(),
1193 'uri-date' => DateTimeFormat::utcNow(),
1194 'avatar-date' => DateTimeFormat::utcNow(),
1200 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1202 DBA::update('contact', $fields, $condition, true);
1204 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1205 $contacts = DBA::toArray($s);
1206 if (!DBA::isResult($contacts)) {
1210 $contact_id = $contacts[0]["id"];
1212 // Update the newly created contact from data in the gcontact table
1213 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1214 if (DBA::isResult($gcontact)) {
1215 // Only use the information when the probing hadn't fetched these values
1216 if ($data['keywords'] != '') {
1217 unset($gcontact['keywords']);
1219 if ($data['location'] != '') {
1220 unset($gcontact['location']);
1222 if ($data['about'] != '') {
1223 unset($gcontact['about']);
1225 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1228 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1229 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1230 Strings::normaliseLink($data["url"]), 0, $contact_id];
1231 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1232 DBA::delete('contact', $condition);
1236 self::updateAvatar($data["photo"], $uid, $contact_id);
1238 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1239 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1241 // This condition should always be true
1242 if (!DBA::isResult($contact)) {
1246 $updated = ['addr' => $data['addr'],
1247 'alias' => $data['alias'],
1248 'url' => $data['url'],
1249 'nurl' => Strings::normaliseLink($data['url']),
1250 'name' => $data['name'],
1251 'nick' => $data['nick']];
1253 if ($data['keywords'] != '') {
1254 $updated['keywords'] = $data['keywords'];
1256 if ($data['location'] != '') {
1257 $updated['location'] = $data['location'];
1260 // Update the technical stuff as well - if filled
1261 if ($data['notify'] != '') {
1262 $updated['notify'] = $data['notify'];
1264 if ($data['poll'] != '') {
1265 $updated['poll'] = $data['poll'];
1267 if ($data['batch'] != '') {
1268 $updated['batch'] = $data['batch'];
1270 if ($data['request'] != '') {
1271 $updated['request'] = $data['request'];
1273 if ($data['confirm'] != '') {
1274 $updated['confirm'] = $data['confirm'];
1276 if ($data['poco'] != '') {
1277 $updated['poco'] = $data['poco'];
1280 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1281 if (empty($contact['pubkey'])) {
1282 $updated['pubkey'] = $data['pubkey'];
1285 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1286 $updated['uri-date'] = DateTimeFormat::utcNow();
1288 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1289 $updated['name-date'] = DateTimeFormat::utcNow();
1292 $updated['avatar-date'] = DateTimeFormat::utcNow();
1294 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1300 * @brief Checks if the contact is blocked
1302 * @param int $cid contact id
1304 * @return boolean Is the contact blocked?
1306 public static function isBlocked($cid)
1312 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1313 if (!DBA::isResult($blocked)) {
1317 if (Network::isUrlBlocked($blocked['url'])) {
1321 return (bool) $blocked['blocked'];
1325 * @brief Checks if the contact is hidden
1327 * @param int $cid contact id
1329 * @return boolean Is the contact hidden?
1331 public static function isHidden($cid)
1337 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1338 if (!DBA::isResult($hidden)) {
1341 return (bool) $hidden['hidden'];
1345 * @brief Returns posts from a given contact url
1347 * @param string $contact_url Contact URL
1349 * @return string posts in HTML
1351 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1353 $a = self::getApp();
1355 require_once 'include/conversation.php';
1357 $cid = Self::getIdForURL($contact_url);
1359 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1360 if (!DBA::isResult($contact)) {
1364 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1365 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1367 $sql = "`item`.`uid` = ?";
1370 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1373 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1374 $cid, GRAVITY_PARENT, local_user()];
1376 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1377 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1380 $pager = new Pager($a->query_string);
1382 $params = ['order' => ['created' => true],
1383 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1386 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1388 $items = Item::inArray($r);
1390 $o = conversation($a, $items, $pager, 'contacts', $update);
1392 $r = Item::selectForUser(local_user(), [], $condition, $params);
1394 $items = Item::inArray($r);
1396 $o = conversation($a, $items, $pager, 'contact-posts', false);
1400 $o .= $pager->renderMinimal(count($items));
1407 * @brief Returns the account type name
1409 * The function can be called with either the user or the contact array
1411 * @param array $contact contact or user array
1414 public static function getAccountType(array $contact)
1416 // There are several fields that indicate that the contact or user is a forum
1417 // "page-flags" is a field in the user table,
1418 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1419 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1420 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1421 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1422 || (isset($contact['forum']) && intval($contact['forum']))
1423 || (isset($contact['prv']) && intval($contact['prv']))
1424 || (isset($contact['community']) && intval($contact['community']))
1426 $type = self::ACCOUNT_TYPE_COMMUNITY;
1428 $type = self::ACCOUNT_TYPE_PERSON;
1431 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1432 if (isset($contact["contact-type"])) {
1433 $type = $contact["contact-type"];
1436 if (isset($contact["account-type"])) {
1437 $type = $contact["account-type"];
1441 case self::ACCOUNT_TYPE_ORGANISATION:
1442 $account_type = L10n::t("Organisation");
1445 case self::ACCOUNT_TYPE_NEWS:
1446 $account_type = L10n::t('News');
1449 case self::ACCOUNT_TYPE_COMMUNITY:
1450 $account_type = L10n::t("Forum");
1458 return $account_type;
1462 * @brief Blocks a contact
1467 public static function block($uid)
1469 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1475 * @brief Unblocks a contact
1480 public static function unblock($uid)
1482 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1488 * @brief Updates the avatar links in a contact only if needed
1490 * @param string $avatar Link to avatar picture
1491 * @param int $uid User id of contact owner
1492 * @param int $cid Contact id
1493 * @param bool $force force picture update
1495 * @return array Returns array of the different avatar sizes
1497 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1499 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1500 if (!DBA::isResult($contact)) {
1503 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1506 if (($contact["avatar"] != $avatar) || $force) {
1507 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1512 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1516 // Update the public contact (contact id = 0)
1518 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1519 if (DBA::isResult($pcontact)) {
1520 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1532 * @param integer $id contact id
1533 * @param string $network Optional network we are probing for
1536 public static function updateFromProbe($id, $network = '')
1539 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1540 This will reliably kill your communication with Friendica contacts.
1543 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1544 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1545 if (!DBA::isResult($contact)) {
1549 $ret = Probe::uri($contact["url"], $network);
1551 // If Probe::uri fails the network code will be different
1552 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1558 // make sure to not overwrite existing values with blank entries
1559 foreach ($ret as $key => $val) {
1560 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1561 $ret[$key] = $contact[$key];
1564 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1575 'url' => $ret['url'],
1576 'nurl' => Strings::normaliseLink($ret['url']),
1577 'network' => $ret['network'],
1578 'addr' => $ret['addr'],
1579 'alias' => $ret['alias'],
1580 'batch' => $ret['batch'],
1581 'notify' => $ret['notify'],
1582 'poll' => $ret['poll'],
1583 'poco' => $ret['poco']
1588 // Update the corresponding gcontact entry
1589 PortableContact::lastUpdated($ret["url"]);
1595 * Takes a $uid and a url/handle and adds a new contact
1596 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1597 * dfrn_request page.
1599 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1602 * $return['success'] boolean true if successful
1603 * $return['message'] error text if success is false.
1605 * @brief Takes a $uid and a url/handle and adds a new contact
1607 * @param string $url
1608 * @param bool $interactive
1609 * @param string $network
1610 * @return boolean|string
1612 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1614 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1618 // remove ajax junk, e.g. Twitter
1619 $url = str_replace('/#!/', '/', $url);
1621 if (!Network::isUrlAllowed($url)) {
1622 $result['message'] = L10n::t('Disallowed profile URL.');
1626 if (Network::isUrlBlocked($url)) {
1627 $result['message'] = L10n::t('Blocked domain');
1632 $result['message'] = L10n::t('Connect URL missing.');
1636 $arr = ['url' => $url, 'contact' => []];
1638 Hook::callAll('follow', $arr);
1641 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1645 if (!empty($arr['contact']['name'])) {
1646 $ret = $arr['contact'];
1648 $ret = Probe::uri($url, $network, $uid, false);
1651 if (($network != '') && ($ret['network'] != $network)) {
1652 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1656 // check if we already have a contact
1657 // the poll url is more reliable than the profile url, as we may have
1658 // indirect links or webfinger links
1660 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1661 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1662 if (!DBA::isResult($contact)) {
1663 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1664 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1667 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1669 if (strlen($a->getURLPath())) {
1670 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1672 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1675 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1679 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1680 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1681 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1685 // This extra param just confuses things, remove it
1686 if ($ret['network'] === Protocol::DIASPORA) {
1687 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1690 // do we have enough information?
1691 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1692 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1693 if (empty($ret['poll'])) {
1694 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1696 if (empty($ret['name'])) {
1697 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1699 if (empty($ret['url'])) {
1700 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1702 if (strpos($url, '@') !== false) {
1703 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1704 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1709 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1710 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1711 $ret['notify'] = '';
1714 if (!$ret['notify']) {
1715 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1718 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1720 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1722 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1724 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1728 if (DBA::isResult($contact)) {
1730 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1732 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1733 DBA::update('contact', $fields, ['id' => $contact['id']]);
1735 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1737 // create contact record
1738 DBA::insert('contact', [
1740 'created' => DateTimeFormat::utcNow(),
1741 'url' => $ret['url'],
1742 'nurl' => Strings::normaliseLink($ret['url']),
1743 'addr' => $ret['addr'],
1744 'alias' => $ret['alias'],
1745 'batch' => $ret['batch'],
1746 'notify' => $ret['notify'],
1747 'poll' => $ret['poll'],
1748 'poco' => $ret['poco'],
1749 'name' => $ret['name'],
1750 'nick' => $ret['nick'],
1751 'network' => $ret['network'],
1752 'pubkey' => $ret['pubkey'],
1753 'rel' => $new_relation,
1754 'priority'=> $ret['priority'],
1755 'writable'=> $writeable,
1756 'hidden' => $hidden,
1764 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1765 if (!DBA::isResult($contact)) {
1766 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1770 $contact_id = $contact['id'];
1771 $result['cid'] = $contact_id;
1773 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1775 // Update the avatar
1776 self::updateAvatar($ret['photo'], $uid, $contact_id);
1778 // pull feed and consume it, which should subscribe to the hub.
1780 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1782 $owner = User::getOwnerDataById($uid);
1784 if (DBA::isResult($owner)) {
1785 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1786 // create a follow slap
1788 $item['verb'] = ACTIVITY_FOLLOW;
1789 $item['follow'] = $contact["url"];
1791 $item['title'] = '';
1794 $item['attach'] = '';
1796 $slap = OStatus::salmon($item, $owner);
1798 if (!empty($contact['notify'])) {
1799 Salmon::slapper($owner, $contact['notify'], $slap);
1801 } elseif ($contact['network'] == Protocol::DIASPORA) {
1802 $ret = Diaspora::sendShare($a->user, $contact);
1803 Logger::log('share returns: ' . $ret);
1804 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1805 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1806 Logger::log('Follow returns: ' . $ret);
1810 $result['success'] = true;
1815 * @brief Updated contact's SSL policy
1817 * @param array $contact Contact array
1818 * @param string $new_policy New policy, valid: self,full
1820 * @return array Contact array with updated values
1822 public static function updateSslPolicy(array $contact, $new_policy)
1824 $ssl_changed = false;
1825 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1826 $ssl_changed = true;
1827 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1828 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1829 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1830 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1831 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1832 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1835 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1836 $ssl_changed = true;
1837 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1838 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1839 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1840 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1841 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1842 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1846 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1847 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1848 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1849 DBA::update('contact', $fields, ['id' => $contact['id']]);
1855 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1856 // Should always be set
1857 if (empty($datarray['author-id'])) {
1861 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1862 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1863 if (!DBA::isResult($pub_contact)) {
1864 // Should never happen
1868 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1869 $name = $pub_contact['name'];
1870 $photo = $pub_contact['photo'];
1871 $nick = $pub_contact['nick'];
1872 $network = $pub_contact['network'];
1874 if (is_array($contact)) {
1875 if (($contact['rel'] == self::SHARING)
1876 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1877 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1878 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1881 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1882 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1885 // send email notification to owner?
1887 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1888 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1891 // create contact record
1892 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1893 `blocked`, `readonly`, `pending`, `writable`)
1894 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1895 intval($importer['uid']),
1896 DBA::escape(DateTimeFormat::utcNow()),
1898 DBA::escape(Strings::normaliseLink($url)),
1901 DBA::escape($photo),
1902 DBA::escape($network),
1903 intval(self::FOLLOWER)
1907 'id' => DBA::lastInsertId(),
1908 'network' => $network,
1914 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1916 /// @TODO Encapsulate this into a function/method
1917 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1918 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1919 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1920 // create notification
1921 $hash = Strings::getRandomHex();
1923 if (is_array($contact_record)) {
1924 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1925 'blocked' => false, 'knowyou' => false,
1926 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1929 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1931 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1932 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1935 'type' => NOTIFY_INTRO,
1936 'notify_flags' => $user['notify-flags'],
1937 'language' => $user['language'],
1938 'to_name' => $user['username'],
1939 'to_email' => $user['email'],
1940 'uid' => $user['uid'],
1941 'link' => System::baseUrl() . '/notifications/intro',
1942 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1943 'source_link' => $contact_record['url'],
1944 'source_photo' => $contact_record['photo'],
1945 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1950 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1951 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1952 DBA::update('contact', ['pending' => false], $condition);
1954 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1956 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1957 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1963 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1965 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1966 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1968 Contact::remove($contact['id']);
1972 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1974 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1975 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1977 Contact::remove($contact['id']);
1982 * @brief Create a birthday event.
1984 * Update the year and the birthday.
1986 public static function updateBirthdays()
1990 AND `bd` > "0001-01-01"
1991 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
1992 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
1993 AND NOT `contact`.`pending`
1994 AND NOT `contact`.`hidden`
1995 AND NOT `contact`.`blocked`
1996 AND NOT `contact`.`archive`
1997 AND NOT `contact`.`deleted`',
2002 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2004 while ($contact = DBA::fetch($contacts)) {
2005 Logger::log('update_contact_birthday: ' . $contact['bd']);
2007 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2009 if (Event::createBirthday($contact, $nextbd)) {
2013 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2014 ['id' => $contact['id']]
2021 * Remove the unavailable contact ids from the provided list
2023 * @param array $contact_ids Contact id list
2025 public static function pruneUnavailable(array &$contact_ids)
2027 if (empty($contact_ids)) {
2031 $str = DBA::escape(implode(',', $contact_ids));
2033 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2036 while($contact = DBA::fetch($stmt)) {
2037 $return[] = $contact['id'];
2042 $contact_ids = $return;
2046 * @brief Returns a magic link to authenticate remote visitors
2048 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2050 * @param string $contact_url The address of the target contact profile
2051 * @param string $url An url that we will be redirected to after the authentication
2053 * @return string with "redir" link
2055 public static function magicLink($contact_url, $url = '')
2057 $cid = self::getIdForURL($contact_url, 0, true);
2059 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2062 return self::magicLinkbyId($cid, $url);
2066 * @brief Returns a magic link to authenticate remote visitors
2068 * @param integer $cid The contact id of the target contact profile
2069 * @param integer $url An url that we will be redirected to after the authentication
2071 * @return string with "redir" link
2073 public static function magicLinkbyId($cid, $url = '')
2075 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2077 return self::magicLinkbyContact($contact, $url);
2081 * @brief Returns a magic link to authenticate remote visitors
2083 * @param array $contact The contact array with "uid", "network" and "url"
2084 * @param string $url An url that we will be redirected to after the authentication
2086 * @return string with "redir" link
2088 public static function magicLinkbyContact($contact, $url = '')
2090 if ($contact['network'] != Protocol::DFRN) {
2091 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2094 // Only redirections to the same host do make sense
2095 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2099 if ($contact['uid'] != 0) {
2100 return self::magicLink($contact['url'], $url);
2103 $redirect = 'redir/' . $contact['id'];
2106 $redirect .= '?url=' . $url;