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\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Profile;
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;
29 require_once 'boot.php';
30 require_once 'include/dba.php';
31 require_once 'include/text.php';
34 * @brief functions for interacting with a contact
36 class Contact extends BaseObject
39 * @name page/profile types
41 * PAGE_NORMAL is a typical personal profile account
42 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
43 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
44 * write access to wall and comments (no email and not included in page owner's ACL lists)
45 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
49 const PAGE_NORMAL = 0;
50 const PAGE_SOAPBOX = 1;
51 const PAGE_COMMUNITY = 2;
52 const PAGE_FREELOVE = 3;
54 const PAGE_PRVGROUP = 5;
62 * ACCOUNT_TYPE_PERSON - the account belongs to a person
63 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
65 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
66 * Associated page type: PAGE_SOAPBOX
68 * ACCOUNT_TYPE_NEWS - the account is a news reflector
69 * Associated page type: PAGE_SOAPBOX
71 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
72 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
74 * ACCOUNT_TYPE_RELAY - the account is a relay
75 * This will only be assigned to contacts, not to user accounts
78 const ACCOUNT_TYPE_PERSON = 0;
79 const ACCOUNT_TYPE_ORGANISATION = 1;
80 const ACCOUNT_TYPE_NEWS = 2;
81 const ACCOUNT_TYPE_COMMUNITY = 3;
82 const ACCOUNT_TYPE_RELAY = 4;
101 * @brief Returns the contact id for the user and the public contact id for a given contact id
103 * @param int $cid Either public contact id or user's contact id
104 * @param int $uid User ID
106 * @return array with public and user's contact id
108 private static function getPublicAndUserContacID($cid, $uid)
110 if (empty($uid) || empty($cid)) {
114 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
115 if (!DBA::isResult($contact)) {
119 // We quit when the user id don't match the user id of the provided contact
120 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
124 if ($contact['uid'] != 0) {
125 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
129 $ucid = $contact['id'];
131 $pcid = $contact['id'];
132 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
135 return ['public' => $pcid, 'user' => $ucid];
139 * @brief Block contact id for user id
141 * @param int $cid Either public contact id or user's contact id
142 * @param int $uid User ID
143 * @param boolean $blocked Is the contact blocked or unblocked?
145 public static function setBlockedForUser($cid, $uid, $blocked)
147 $cdata = self::getPublicAndUserContacID($cid, $uid);
152 if ($cdata['user'] != 0) {
153 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
156 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
160 * @brief Returns "block" state for contact id and user id
162 * @param int $cid Either public contact id or user's contact id
163 * @param int $uid User ID
165 * @return boolean is the contact id blocked for the given user?
167 public static function isBlockedByUser($cid, $uid)
169 $cdata = self::getPublicAndUserContacID($cid, $uid);
174 $public_blocked = false;
176 if (!empty($cdata['public'])) {
177 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
178 if (DBA::isResult($public_contact)) {
179 $public_blocked = $public_contact['blocked'];
183 $user_blocked = $public_blocked;
185 if (!empty($cdata['user'])) {
186 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
187 if (DBA::isResult($user_contact)) {
188 $user_blocked = $user_contact['blocked'];
192 if ($user_blocked != $public_blocked) {
193 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
196 return $user_blocked;
200 * @brief Ignore contact id for user id
202 * @param int $cid Either public contact id or user's contact id
203 * @param int $uid User ID
204 * @param boolean $ignored Is the contact ignored or unignored?
206 public static function setIgnoredForUser($cid, $uid, $ignored)
208 $cdata = self::getPublicAndUserContacID($cid, $uid);
213 if ($cdata['user'] != 0) {
214 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
217 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
221 * @brief Returns "ignore" state for contact id and user id
223 * @param int $cid Either public contact id or user's contact id
224 * @param int $uid User ID
226 * @return boolean is the contact id ignored for the given user?
228 public static function isIgnoredByUser($cid, $uid)
230 $cdata = self::getPublicAndUserContacID($cid, $uid);
235 $public_ignored = false;
237 if (!empty($cdata['public'])) {
238 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
239 if (DBA::isResult($public_contact)) {
240 $public_ignored = $public_contact['ignored'];
244 $user_ignored = $public_ignored;
246 if (!empty($cdata['user'])) {
247 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
248 if (DBA::isResult($user_contact)) {
249 $user_ignored = $user_contact['readonly'];
253 if ($user_ignored != $public_ignored) {
254 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
257 return $user_ignored;
261 * @brief Set "collapsed" for contact id and user id
263 * @param int $cid Either public contact id or user's contact id
264 * @param int $uid User ID
265 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
267 public static function setCollapsedForUser($cid, $uid, $collapsed)
269 $cdata = self::getPublicAndUserContacID($cid, $uid);
274 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
278 * @brief Returns "collapsed" state for contact id and user id
280 * @param int $cid Either public contact id or user's contact id
281 * @param int $uid User ID
283 * @return boolean is the contact id blocked for the given user?
285 public static function isCollapsedByUser($cid, $uid)
287 $cdata = self::getPublicAndUserContacID($cid, $uid);
294 if (!empty($cdata['public'])) {
295 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
296 if (DBA::isResult($public_contact)) {
297 $collapsed = $public_contact['collapsed'];
305 * @brief Returns a list of contacts belonging in a group
310 public static function getByGroupId($gid)
315 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
317 INNER JOIN `group_member`
318 ON `contact`.`id` = `group_member`.`contact-id`
320 AND `contact`.`uid` = ?
321 AND NOT `contact`.`self`
322 AND NOT `contact`.`blocked`
323 AND NOT `contact`.`pending`
324 ORDER BY `contact`.`name` ASC',
329 if (DBA::isResult($stmt)) {
330 $return = DBA::toArray($stmt);
338 * @brief Returns the count of OStatus contacts in a group
343 public static function getOStatusCountByGroupId($gid)
347 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
349 INNER JOIN `group_member`
350 ON `contact`.`id` = `group_member`.`contact-id`
352 AND `contact`.`uid` = ?
353 AND `contact`.`network` = ?
354 AND `contact`.`notify` != ""',
359 $return = $contacts['count'];
366 * Creates the self-contact for the provided user id
369 * @return bool Operation success
371 public static function createSelfFromUserId($uid)
373 // Only create the entry if it doesn't exist yet
374 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
378 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
379 if (!DBA::isResult($user)) {
383 $return = DBA::insert('contact', [
384 'uid' => $user['uid'],
385 'created' => DateTimeFormat::utcNow(),
387 'name' => $user['username'],
388 'nick' => $user['nickname'],
389 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
390 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
391 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
394 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
395 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
396 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
397 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
398 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
399 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
400 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
401 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
402 'name-date' => DateTimeFormat::utcNow(),
403 'uri-date' => DateTimeFormat::utcNow(),
404 'avatar-date' => DateTimeFormat::utcNow(),
412 * Updates the self-contact for the provided user id
415 * @param boolean $update_avatar Force the avatar update
417 public static function updateSelfFromUserID($uid, $update_avatar = false)
419 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
420 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
421 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
422 if (!DBA::isResult($self)) {
426 $fields = ['nickname', 'page-flags', 'account-type'];
427 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
428 if (!DBA::isResult($user)) {
432 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
433 'country-name', 'gender', 'pub_keywords', 'xmpp'];
434 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
435 if (!DBA::isResult($profile)) {
439 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
440 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
441 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
442 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
443 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
445 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
446 if (DBA::isResult($avatar)) {
447 if ($update_avatar) {
448 $fields['avatar-date'] = DateTimeFormat::utcNow();
451 // Creating the path to the avatar, beginning with the file suffix
452 $types = Image::supportedTypes();
453 if (isset($types[$avatar['type']])) {
454 $file_suffix = $types[$avatar['type']];
456 $file_suffix = 'jpg';
459 // We are adding a timestamp value so that other systems won't use cached content
460 $timestamp = strtotime($fields['avatar-date']);
462 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
463 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
465 $fields['photo'] = $prefix . '4' . $suffix;
466 $fields['thumb'] = $prefix . '5' . $suffix;
467 $fields['micro'] = $prefix . '6' . $suffix;
469 // We hadn't found a photo entry, so we use the default avatar
470 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
471 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
472 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
475 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
476 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
478 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
479 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
480 $fields['nurl'] = normalise_link($fields['url']);
481 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
482 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
483 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
484 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
485 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
486 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
490 foreach ($fields as $field => $content) {
491 if (isset($self[$field]) && $self[$field] != $content) {
497 $fields['name-date'] = DateTimeFormat::utcNow();
498 DBA::update('contact', $fields, ['id' => $self['id']]);
500 // Update the public contact as well
501 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
503 // Update the profile
504 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
505 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
506 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
511 * @brief Marks a contact for removal
513 * @param int $id contact id
516 public static function remove($id)
518 // We want just to make sure that we don't delete our "self" contact
519 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
520 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
524 // Archive the contact
525 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
527 // Delete it in the background
528 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
532 * @brief Sends an unfriend message. Does not remove the contact
534 * @param array $user User unfriending
535 * @param array $contact Contact unfriended
536 * @param boolean $dissolve Remove the contact on the remote side
539 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
541 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
542 DFRN::deliver($user, $contact, 'placeholder', true);
543 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
544 // create an unfollow slap
546 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
547 $item['follow'] = $contact["url"];
552 $item['attach'] = '';
553 $slap = OStatus::salmon($item, $user);
555 if (!empty($contact['notify'])) {
556 Salmon::slapper($user, $contact['notify'], $slap);
558 } elseif ($contact['network'] == Protocol::DIASPORA) {
559 Diaspora::sendUnshare($user, $contact);
560 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
561 ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
564 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
570 * @brief Marks a contact for archival after a communication issue delay
572 * Contact has refused to recognise us as a friend. We will start a countdown.
573 * If they still don't recognise us in 32 days, the relationship is over,
574 * and we won't waste any more time trying to communicate with them.
575 * This provides for the possibility that their database is temporarily messed
576 * up or some other transient event and that there's a possibility we could recover from it.
578 * @param array $contact contact to mark for archival
581 public static function markForArchival(array $contact)
583 if (!isset($contact['url']) && !empty($contact['id'])) {
584 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
585 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
586 if (!DBA::isResult($contact)) {
589 } elseif (!isset($contact['url'])) {
590 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
593 // Contact already archived or "self" contact? => nothing to do
594 if ($contact['archive'] || $contact['self']) {
598 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
599 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
600 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), DBA::NULL_DATETIME]);
603 * We really should send a notification to the owner after 2-3 weeks
604 * so they won't be surprised when the contact vanishes and can take
605 * remedial action if this was a serious mistake or glitch
608 /// @todo Check for contact vitality via probing
609 $archival_days = Config::get('system', 'archival_days', 32);
611 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
612 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
613 /* Relationship is really truly dead. archive them rather than
614 * delete, though if the owner tries to unarchive them we'll start
615 * the whole process over again.
617 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
618 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
624 * @brief Cancels the archival countdown
626 * @see Contact::markForArchival()
628 * @param array $contact contact to be unmarked for archival
631 public static function unmarkForArchival(array $contact)
633 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
634 $exists = DBA::exists('contact', $condition);
636 // We don't need to update, we never marked this contact for archival
641 if (!isset($contact['url']) && !empty($contact['id'])) {
642 $fields = ['id', 'url', 'batch'];
643 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
644 if (!DBA::isResult($contact)) {
649 // It's a miracle. Our dead contact has inexplicably come back to life.
650 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
651 DBA::update('contact', $fields, ['id' => $contact['id']]);
652 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
654 if (!empty($contact['batch'])) {
655 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
656 DBA::update('contact', $fields, $condition);
661 * @brief Get contact data for a given profile link
663 * The function looks at several places (contact table and gcontact table) for the contact
664 * It caches its result for the same script execution to prevent duplicate calls
666 * @param string $url The profile link
667 * @param int $uid User id
668 * @param array $default If not data was found take this data as default value
670 * @return array Contact data
672 public static function getDetailsByURL($url, $uid = -1, array $default = [])
684 if (isset($cache[$url][$uid])) {
685 return $cache[$url][$uid];
688 $ssl_url = str_replace('http://', 'https://', $url);
690 // Fetch contact data from the contact table for the given user
691 $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`,
692 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
693 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
694 $r = DBA::toArray($s);
696 // Fetch contact data from the contact table for the given user, checking with the alias
697 if (!DBA::isResult($r)) {
698 $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`,
699 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
700 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
701 $r = DBA::toArray($s);
704 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
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 `nurl` = ? AND `uid` = 0", normalise_link($url));
709 $r = DBA::toArray($s);
712 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
713 if (!DBA::isResult($r)) {
714 $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`,
715 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
716 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
717 $r = DBA::toArray($s);
720 // Fetch the data from the gcontact table
721 if (!DBA::isResult($r)) {
722 $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`,
723 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
724 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
725 $r = DBA::toArray($s);
728 if (DBA::isResult($r)) {
729 // If there is more than one entry we filter out the connector networks
731 foreach ($r as $id => $result) {
732 if ($result["network"] == Protocol::STATUSNET) {
738 $profile = array_shift($r);
740 // "bd" always contains the upcoming birthday of a contact.
741 // "birthday" might contain the birthday including the year of birth.
742 if ($profile["birthday"] > '0001-01-01') {
743 $bd_timestamp = strtotime($profile["birthday"]);
744 $month = date("m", $bd_timestamp);
745 $day = date("d", $bd_timestamp);
747 $current_timestamp = time();
748 $current_year = date("Y", $current_timestamp);
749 $current_month = date("m", $current_timestamp);
750 $current_day = date("d", $current_timestamp);
752 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
753 $current = $current_year . "-" . $current_month . "-" . $current_day;
755 if ($profile["bd"] < $current) {
756 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
759 $profile["bd"] = '0001-01-01';
765 if (empty($profile["photo"]) && isset($default["photo"])) {
766 $profile["photo"] = $default["photo"];
769 if (empty($profile["name"]) && isset($default["name"])) {
770 $profile["name"] = $default["name"];
773 if (empty($profile["network"]) && isset($default["network"])) {
774 $profile["network"] = $default["network"];
777 if (empty($profile["thumb"]) && isset($profile["photo"])) {
778 $profile["thumb"] = $profile["photo"];
781 if (empty($profile["micro"]) && isset($profile["thumb"])) {
782 $profile["micro"] = $profile["thumb"];
785 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
786 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
788 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
791 // Show contact details of Diaspora contacts only if connected
792 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
793 $profile["location"] = "";
794 $profile["about"] = "";
795 $profile["gender"] = "";
796 $profile["birthday"] = '0001-01-01';
799 $cache[$url][$uid] = $profile;
805 * @brief Get contact data for a given address
807 * The function looks at several places (contact table and gcontact table) for the contact
809 * @param string $addr The profile link
810 * @param int $uid User id
812 * @return array Contact data
814 public static function getDetailsByAddr($addr, $uid = -1)
826 // Fetch contact data from the contact table for the given user
827 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `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`, `self`
829 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
833 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
834 if (!DBA::isResult($r)) {
835 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
836 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
837 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
842 // Fetch the data from the gcontact table
843 if (!DBA::isResult($r)) {
844 $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`,
845 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
846 FROM `gcontact` WHERE `addr` = '%s'",
851 if (!DBA::isResult($r)) {
852 $data = Probe::uri($addr);
854 $profile = self::getDetailsByURL($data['url'], $uid);
863 * @brief Returns the data array for the photo menu of a given contact
865 * @param array $contact contact
866 * @param int $uid optional, default 0
869 public static function photoMenu(array $contact, $uid = 0)
871 // @todo Unused, to be removed
879 $contact_drop_link = '';
886 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
888 $profile_link = self::magicLink($contact['url']);
889 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
894 // Look for our own contact if the uid doesn't match and isn't public
895 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
896 if (DBA::isResult($contact_own)) {
897 return self::photoMenu($contact_own, $uid);
902 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
904 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
906 $profile_link = $contact['url'];
909 if ($profile_link === 'mailbox') {
914 $status_link = $profile_link . '?url=status';
915 $photos_link = $profile_link . '?url=photos';
916 $profile_link = $profile_link . '?url=profile';
919 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
920 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
923 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
924 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
927 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
929 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
931 if (!$contact['self']) {
932 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
937 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
939 if (empty($contact['uid'])) {
940 $connlnk = 'follow/?url=' . $contact['url'];
942 'profile' => [L10n::t('View Profile'), $profile_link, true],
943 'network' => [L10n::t('Network Posts'), $posts_link, false],
944 'edit' => [L10n::t('View Contact'), $contact_url, false],
945 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
949 'status' => [L10n::t('View Status'), $status_link, true],
950 'profile' => [L10n::t('View Profile'), $profile_link, true],
951 'photos' => [L10n::t('View Photos'), $photos_link, true],
952 'network' => [L10n::t('Network Posts'), $posts_link, false],
953 'edit' => [L10n::t('View Contact'), $contact_url, false],
954 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
955 'pm' => [L10n::t('Send PM'), $pm_url, false],
956 'poke' => [L10n::t('Poke'), $poke_link, false],
960 $args = ['contact' => $contact, 'menu' => &$menu];
962 Addon::callHooks('contact_photo_menu', $args);
966 foreach ($menu as $menuname => $menuitem) {
967 if ($menuitem[1] != '') {
968 $menucondensed[$menuname] = $menuitem;
972 return $menucondensed;
976 * @brief Returns ungrouped contact count or list for user
978 * Returns either the total number of ungrouped contacts for the given user
979 * id or a paginated list of ungrouped contacts.
981 * @param int $uid uid
982 * @param int $start optional, default 0
983 * @param int $count optional, default 0
987 public static function getUngroupedList($uid)
996 SELECT DISTINCT(`contact-id`)
998 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
999 WHERE `group`.`uid` = %d
1000 )", intval($uid), intval($uid));
1004 * @brief Fetch the contact id for a given URL and user
1006 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1007 * `addr` or `alias`.
1009 * If there's no record and we aren't looking for a public contact, we quit.
1010 * If there's one, we check that it isn't time to update the picture else we
1011 * directly return the found contact id.
1013 * Second, we probe the provided $url whether it's http://server.tld/profile or
1014 * nick@server.tld. We quit if we can't get any info back.
1016 * Third, we create the contact record if it doesn't exist
1018 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1019 * if there's any updates
1021 * @param string $url Contact URL
1022 * @param integer $uid The user id for the contact (0 = public contact)
1023 * @param boolean $no_update Don't update the contact
1024 * @param array $default Default value for creating the contact when every else fails
1025 * @param boolean $in_loop Internally used variable to prevent an endless loop
1027 * @return integer Contact ID
1029 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1031 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1039 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1040 // We first try the nurl (http://server.tld/nick), most common case
1041 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid, 'deleted' => false]);
1043 // Then the addr (nick@server.tld)
1044 if (!DBA::isResult($contact)) {
1045 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1048 // Then the alias (which could be anything)
1049 if (!DBA::isResult($contact)) {
1050 // The link could be provided as http although we stored it as https
1051 $ssl_url = str_replace('http://', 'https://', $url);
1052 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, normalise_link($url), $ssl_url, $uid];
1053 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1056 if (DBA::isResult($contact)) {
1057 $contact_id = $contact["id"];
1059 // Update the contact every 7 days
1060 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1062 // We force the update if the avatar is empty
1063 if (!x($contact, 'avatar')) {
1064 $update_contact = true;
1066 if (!$update_contact || $no_update) {
1069 } elseif ($uid != 0) {
1070 // Non-existing user-specific contact, exiting
1074 // When we don't want to update, we look if some of our users already know this contact
1076 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1077 'photo', 'keywords', 'location', 'about', 'network',
1078 'priority', 'batch', 'request', 'confirm', 'poco'];
1079 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1081 if (DBA::isResult($data)) {
1082 // For security reasons we don't fetch key data from our users
1083 $data["pubkey"] = '';
1090 $data = Probe::uri($url, "", $uid);
1092 // Ensure that there is a gserver entry
1093 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1094 PortableContact::checkServer($data['baseurl']);
1098 // Last try in gcontact for unsupported networks
1099 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1104 // Get data from the gcontact table
1105 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1106 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
1107 if (!DBA::isResult($contact)) {
1108 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1111 if (!DBA::isResult($contact)) {
1112 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1113 'photo', 'keywords', 'location', 'about', 'network',
1114 'priority', 'batch', 'request', 'confirm', 'poco'];
1115 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1118 if (!DBA::isResult($contact)) {
1119 // The link could be provided as http although we stored it as https
1120 $ssl_url = str_replace('http://', 'https://', $url);
1121 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
1122 $contact = DBA::selectFirst('contact', $fields, $condition);
1125 if (!DBA::isResult($contact)) {
1126 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1127 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1128 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
1129 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1132 if (!empty($default)) {
1133 $contact = $default;
1136 if (!DBA::isResult($contact)) {
1139 $data = array_merge($data, $contact);
1143 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1144 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1147 $url = $data["url"];
1149 DBA::insert('contact', [
1151 'created' => DateTimeFormat::utcNow(),
1152 'url' => $data["url"],
1153 'nurl' => normalise_link($data["url"]),
1154 'addr' => $data["addr"],
1155 'alias' => $data["alias"],
1156 'notify' => $data["notify"],
1157 'poll' => $data["poll"],
1158 'name' => $data["name"],
1159 'nick' => $data["nick"],
1160 'photo' => $data["photo"],
1161 'keywords' => $data["keywords"],
1162 'location' => $data["location"],
1163 'about' => $data["about"],
1164 'network' => $data["network"],
1165 'pubkey' => $data["pubkey"],
1166 'rel' => self::SHARING,
1167 'priority' => $data["priority"],
1168 'batch' => $data["batch"],
1169 'request' => $data["request"],
1170 'confirm' => $data["confirm"],
1171 'poco' => $data["poco"],
1172 'name-date' => DateTimeFormat::utcNow(),
1173 'uri-date' => DateTimeFormat::utcNow(),
1174 'avatar-date' => DateTimeFormat::utcNow(),
1181 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1182 $contacts = DBA::toArray($s);
1183 if (!DBA::isResult($contacts)) {
1187 $contact_id = $contacts[0]["id"];
1189 // Update the newly created contact from data in the gcontact table
1190 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
1191 if (DBA::isResult($gcontact)) {
1192 // Only use the information when the probing hadn't fetched these values
1193 if ($data['keywords'] != '') {
1194 unset($gcontact['keywords']);
1196 if ($data['location'] != '') {
1197 unset($gcontact['location']);
1199 if ($data['about'] != '') {
1200 unset($gcontact['about']);
1202 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1205 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1206 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1207 normalise_link($data["url"]), $contact_id]);
1211 self::updateAvatar($data["photo"], $uid, $contact_id);
1213 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1214 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1216 // This condition should always be true
1217 if (!DBA::isResult($contact)) {
1221 $updated = ['addr' => $data['addr'],
1222 'alias' => $data['alias'],
1223 'url' => $data['url'],
1224 'nurl' => normalise_link($data['url']),
1225 'name' => $data['name'],
1226 'nick' => $data['nick']];
1228 if ($data['keywords'] != '') {
1229 $updated['keywords'] = $data['keywords'];
1231 if ($data['location'] != '') {
1232 $updated['location'] = $data['location'];
1235 // Update the technical stuff as well - if filled
1236 if ($data['notify'] != '') {
1237 $updated['notify'] = $data['notify'];
1239 if ($data['poll'] != '') {
1240 $updated['poll'] = $data['poll'];
1242 if ($data['batch'] != '') {
1243 $updated['batch'] = $data['batch'];
1245 if ($data['request'] != '') {
1246 $updated['request'] = $data['request'];
1248 if ($data['confirm'] != '') {
1249 $updated['confirm'] = $data['confirm'];
1251 if ($data['poco'] != '') {
1252 $updated['poco'] = $data['poco'];
1255 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1256 if (empty($contact['pubkey'])) {
1257 $updated['pubkey'] = $data['pubkey'];
1260 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1261 $updated['uri-date'] = DateTimeFormat::utcNow();
1263 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1264 $updated['name-date'] = DateTimeFormat::utcNow();
1267 $updated['avatar-date'] = DateTimeFormat::utcNow();
1269 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1275 * @brief Checks if the contact is blocked
1277 * @param int $cid contact id
1279 * @return boolean Is the contact blocked?
1281 public static function isBlocked($cid)
1287 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1288 if (!DBA::isResult($blocked)) {
1291 return (bool) $blocked['blocked'];
1295 * @brief Checks if the contact is hidden
1297 * @param int $cid contact id
1299 * @return boolean Is the contact hidden?
1301 public static function isHidden($cid)
1307 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1308 if (!DBA::isResult($hidden)) {
1311 return (bool) $hidden['hidden'];
1315 * @brief Returns posts from a given contact url
1317 * @param string $contact_url Contact URL
1319 * @return string posts in HTML
1321 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1323 $a = self::getApp();
1325 require_once 'include/conversation.php';
1327 $cid = Self::getIdForURL($contact_url);
1329 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1330 if (!DBA::isResult($contact)) {
1334 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1335 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1337 $sql = "`item`.`uid` = ?";
1340 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1343 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1344 $cid, GRAVITY_PARENT, local_user()];
1346 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1347 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1350 $pager = new Pager($a->query_string);
1352 $params = ['order' => ['created' => true],
1353 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1356 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1358 $items = Item::inArray($r);
1360 $o = conversation($a, $items, $pager, 'contacts', $update);
1362 $r = Item::selectForUser(local_user(), [], $condition, $params);
1364 $items = Item::inArray($r);
1366 $o = conversation($a, $items, $pager, 'contact-posts', false);
1370 $o .= $pager->renderMinimal(count($items));
1377 * @brief Returns the account type name
1379 * The function can be called with either the user or the contact array
1381 * @param array $contact contact or user array
1384 public static function getAccountType(array $contact)
1386 // There are several fields that indicate that the contact or user is a forum
1387 // "page-flags" is a field in the user table,
1388 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1389 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1390 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1391 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1392 || (isset($contact['forum']) && intval($contact['forum']))
1393 || (isset($contact['prv']) && intval($contact['prv']))
1394 || (isset($contact['community']) && intval($contact['community']))
1396 $type = self::ACCOUNT_TYPE_COMMUNITY;
1398 $type = self::ACCOUNT_TYPE_PERSON;
1401 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1402 if (isset($contact["contact-type"])) {
1403 $type = $contact["contact-type"];
1406 if (isset($contact["account-type"])) {
1407 $type = $contact["account-type"];
1411 case self::ACCOUNT_TYPE_ORGANISATION:
1412 $account_type = L10n::t("Organisation");
1415 case self::ACCOUNT_TYPE_NEWS:
1416 $account_type = L10n::t('News');
1419 case self::ACCOUNT_TYPE_COMMUNITY:
1420 $account_type = L10n::t("Forum");
1428 return $account_type;
1432 * @brief Blocks a contact
1437 public static function block($uid)
1439 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1445 * @brief Unblocks a contact
1450 public static function unblock($uid)
1452 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1458 * @brief Updates the avatar links in a contact only if needed
1460 * @param string $avatar Link to avatar picture
1461 * @param int $uid User id of contact owner
1462 * @param int $cid Contact id
1463 * @param bool $force force picture update
1465 * @return array Returns array of the different avatar sizes
1467 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1469 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1470 if (!DBA::isResult($contact)) {
1473 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1476 if (($contact["avatar"] != $avatar) || $force) {
1477 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1482 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1486 // Update the public contact (contact id = 0)
1488 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1489 if (DBA::isResult($pcontact)) {
1490 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1502 * @param integer $id contact id
1503 * @param string $network Optional network we are probing for
1506 public static function updateFromProbe($id, $network = '')
1509 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1510 This will reliably kill your communication with Friendica contacts.
1513 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1514 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1515 if (!DBA::isResult($contact)) {
1519 $ret = Probe::uri($contact["url"], $network);
1521 // If Probe::uri fails the network code will be different
1522 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1528 // make sure to not overwrite existing values with blank entries
1529 foreach ($ret as $key => $val) {
1530 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1531 $ret[$key] = $contact[$key];
1534 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1545 'url' => $ret['url'],
1546 'nurl' => normalise_link($ret['url']),
1547 'network' => $ret['network'],
1548 'addr' => $ret['addr'],
1549 'alias' => $ret['alias'],
1550 'batch' => $ret['batch'],
1551 'notify' => $ret['notify'],
1552 'poll' => $ret['poll'],
1553 'poco' => $ret['poco']
1558 // Update the corresponding gcontact entry
1559 PortableContact::lastUpdated($ret["url"]);
1565 * Takes a $uid and a url/handle and adds a new contact
1566 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1567 * dfrn_request page.
1569 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1572 * $return['success'] boolean true if successful
1573 * $return['message'] error text if success is false.
1575 * @brief Takes a $uid and a url/handle and adds a new contact
1577 * @param string $url
1578 * @param bool $interactive
1579 * @param string $network
1580 * @return boolean|string
1582 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1584 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1588 // remove ajax junk, e.g. Twitter
1589 $url = str_replace('/#!/', '/', $url);
1591 if (!Network::isUrlAllowed($url)) {
1592 $result['message'] = L10n::t('Disallowed profile URL.');
1596 if (Network::isUrlBlocked($url)) {
1597 $result['message'] = L10n::t('Blocked domain');
1602 $result['message'] = L10n::t('Connect URL missing.');
1606 $arr = ['url' => $url, 'contact' => []];
1608 Addon::callHooks('follow', $arr);
1611 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1615 if (x($arr['contact'], 'name')) {
1616 $ret = $arr['contact'];
1618 $ret = Probe::uri($url, $network, $uid, false);
1621 if (($network != '') && ($ret['network'] != $network)) {
1622 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1626 // check if we already have a contact
1627 // the poll url is more reliable than the profile url, as we may have
1628 // indirect links or webfinger links
1630 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1631 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1632 if (!DBA::isResult($contact)) {
1633 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1634 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1637 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1639 if (strlen($a->getURLPath())) {
1640 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1642 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1645 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1649 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1650 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1651 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1655 // This extra param just confuses things, remove it
1656 if ($ret['network'] === Protocol::DIASPORA) {
1657 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1660 // do we have enough information?
1662 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1663 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1664 if (!x($ret, 'poll')) {
1665 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1667 if (!x($ret, 'name')) {
1668 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1670 if (!x($ret, 'url')) {
1671 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1673 if (strpos($url, '@') !== false) {
1674 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1675 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1680 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1681 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1682 $ret['notify'] = '';
1685 if (!$ret['notify']) {
1686 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1689 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1691 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1693 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1695 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1699 if (DBA::isResult($contact)) {
1701 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1703 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1704 DBA::update('contact', $fields, ['id' => $contact['id']]);
1706 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1708 // create contact record
1709 DBA::insert('contact', [
1711 'created' => DateTimeFormat::utcNow(),
1712 'url' => $ret['url'],
1713 'nurl' => normalise_link($ret['url']),
1714 'addr' => $ret['addr'],
1715 'alias' => $ret['alias'],
1716 'batch' => $ret['batch'],
1717 'notify' => $ret['notify'],
1718 'poll' => $ret['poll'],
1719 'poco' => $ret['poco'],
1720 'name' => $ret['name'],
1721 'nick' => $ret['nick'],
1722 'network' => $ret['network'],
1723 'pubkey' => $ret['pubkey'],
1724 'rel' => $new_relation,
1725 'priority'=> $ret['priority'],
1726 'writable'=> $writeable,
1727 'hidden' => $hidden,
1735 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1736 if (!DBA::isResult($contact)) {
1737 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1741 $contact_id = $contact['id'];
1742 $result['cid'] = $contact_id;
1744 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1746 // Update the avatar
1747 self::updateAvatar($ret['photo'], $uid, $contact_id);
1749 // pull feed and consume it, which should subscribe to the hub.
1751 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1753 $owner = User::getOwnerDataById($uid);
1755 if (DBA::isResult($owner)) {
1756 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1757 // create a follow slap
1759 $item['verb'] = ACTIVITY_FOLLOW;
1760 $item['follow'] = $contact["url"];
1762 $item['title'] = '';
1765 $item['attach'] = '';
1767 $slap = OStatus::salmon($item, $owner);
1769 if (!empty($contact['notify'])) {
1770 Salmon::slapper($owner, $contact['notify'], $slap);
1772 } elseif ($contact['network'] == Protocol::DIASPORA) {
1773 $ret = Diaspora::sendShare($a->user, $contact);
1774 Logger::log('share returns: ' . $ret);
1775 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1776 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1777 Logger::log('Follow returns: ' . $ret);
1781 $result['success'] = true;
1786 * @brief Updated contact's SSL policy
1788 * @param array $contact Contact array
1789 * @param string $new_policy New policy, valid: self,full
1791 * @return array Contact array with updated values
1793 public static function updateSslPolicy(array $contact, $new_policy)
1795 $ssl_changed = false;
1796 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1797 $ssl_changed = true;
1798 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1799 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1800 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1801 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1802 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1803 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1806 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1807 $ssl_changed = true;
1808 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1809 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1810 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1811 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1812 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1813 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1817 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1818 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1819 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1820 DBA::update('contact', $fields, ['id' => $contact['id']]);
1826 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1827 // Should always be set
1828 if (empty($datarray['author-id'])) {
1832 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1833 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1834 if (!DBA::isResult($pub_contact)) {
1835 // Should never happen
1839 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1840 $name = $pub_contact['name'];
1841 $photo = $pub_contact['photo'];
1842 $nick = $pub_contact['nick'];
1843 $network = $pub_contact['network'];
1845 if (is_array($contact)) {
1846 if (($contact['rel'] == self::SHARING)
1847 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1848 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1849 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1852 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1853 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1856 // send email notification to owner?
1858 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1859 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1862 // create contact record
1863 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1864 `blocked`, `readonly`, `pending`, `writable`)
1865 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1866 intval($importer['uid']),
1867 DBA::escape(DateTimeFormat::utcNow()),
1869 DBA::escape(normalise_link($url)),
1872 DBA::escape($photo),
1873 DBA::escape($network),
1874 intval(self::FOLLOWER)
1878 'id' => DBA::lastInsertId(),
1879 'network' => $network,
1885 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1887 /// @TODO Encapsulate this into a function/method
1888 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1889 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1890 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1891 // create notification
1892 $hash = random_string();
1894 if (is_array($contact_record)) {
1895 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1896 'blocked' => false, 'knowyou' => false,
1897 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1900 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1902 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1903 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1906 'type' => NOTIFY_INTRO,
1907 'notify_flags' => $user['notify-flags'],
1908 'language' => $user['language'],
1909 'to_name' => $user['username'],
1910 'to_email' => $user['email'],
1911 'uid' => $user['uid'],
1912 'link' => System::baseUrl() . '/notifications/intro',
1913 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1914 'source_link' => $contact_record['url'],
1915 'source_photo' => $contact_record['photo'],
1916 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1921 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1922 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1923 DBA::update('contact', ['pending' => false], $condition);
1925 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1927 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1928 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1934 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1936 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1937 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1939 Contact::remove($contact['id']);
1943 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1945 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1946 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1948 Contact::remove($contact['id']);
1953 * @brief Create a birthday event.
1955 * Update the year and the birthday.
1957 public static function updateBirthdays()
1959 // This only handles foreign or alien networks where a birthday has been provided.
1960 // In-network birthdays are handled within local_delivery
1962 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1963 if (DBA::isResult($r)) {
1964 foreach ($r as $rr) {
1965 Logger::log('update_contact_birthday: ' . $rr['bd']);
1967 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1970 * Add new birthday event for this person
1972 * $bdtext is just a readable placeholder in case the event is shared
1973 * with others. We will replace it during presentation to our $importer
1974 * to contain a sparkle link and perhaps a photo.
1977 // Check for duplicates
1978 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1979 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1980 if (DBA::exists('event', $condition)) {
1984 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1985 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1987 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1988 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1989 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1990 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1995 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1996 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
2003 * Remove the unavailable contact ids from the provided list
2005 * @param array $contact_ids Contact id list
2007 public static function pruneUnavailable(array &$contact_ids)
2009 if (empty($contact_ids)) {
2013 $str = DBA::escape(implode(',', $contact_ids));
2015 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2018 while($contact = DBA::fetch($stmt)) {
2019 $return[] = $contact['id'];
2024 $contact_ids = $return;
2028 * @brief Returns a magic link to authenticate remote visitors
2030 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2032 * @param string $contact_url The address of the target contact profile
2033 * @param string $url An url that we will be redirected to after the authentication
2035 * @return string with "redir" link
2037 public static function magicLink($contact_url, $url = '')
2039 $cid = self::getIdForURL($contact_url, 0, true);
2041 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2044 return self::magicLinkbyId($cid, $url);
2048 * @brief Returns a magic link to authenticate remote visitors
2050 * @param integer $cid The contact id of the target contact profile
2051 * @param integer $url An url that we will be redirected to after the authentication
2053 * @return string with "redir" link
2055 public static function magicLinkbyId($cid, $url = '')
2057 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2059 return self::magicLinkbyContact($contact, $url);
2063 * @brief Returns a magic link to authenticate remote visitors
2065 * @param array $contact The contact array with "uid", "network" and "url"
2066 * @param string $url An url that we will be redirected to after the authentication
2068 * @return string with "redir" link
2070 public static function magicLinkbyContact($contact, $url = '')
2072 if ($contact['network'] != Protocol::DFRN) {
2073 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2076 // Only redirections to the same host do make sense
2077 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2081 if ($contact['uid'] != 0) {
2082 return self::magicLink($contact['url'], $url);
2085 $redirect = 'redir/' . $contact['id'];
2088 $redirect .= '?url=' . $url;