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
104 * @param string $url The contact link
106 * @return string basepath
108 public static function getBasepath($url)
110 $data = Probe::uri($url);
111 if (!empty($data['baseurl'])) {
112 return $data['baseurl'];
115 $urlarr = explode('/profile/', $url);
116 $basepath = $urlarr[0];
122 * @brief Returns the contact id for the user and the public contact id for a given contact id
124 * @param int $cid Either public contact id or user's contact id
125 * @param int $uid User ID
127 * @return array with public and user's contact id
129 private static function getPublicAndUserContacID($cid, $uid)
131 if (empty($uid) || empty($cid)) {
135 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
136 if (!DBA::isResult($contact)) {
140 // We quit when the user id don't match the user id of the provided contact
141 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
145 if ($contact['uid'] != 0) {
146 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
150 $ucid = $contact['id'];
152 $pcid = $contact['id'];
153 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
156 return ['public' => $pcid, 'user' => $ucid];
160 * @brief Block contact id for user id
162 * @param int $cid Either public contact id or user's contact id
163 * @param int $uid User ID
164 * @param boolean $blocked Is the contact blocked or unblocked?
166 public static function setBlockedForUser($cid, $uid, $blocked)
168 $cdata = self::getPublicAndUserContacID($cid, $uid);
173 if ($cdata['user'] != 0) {
174 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
177 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
181 * @brief Returns "block" state for contact id and user id
183 * @param int $cid Either public contact id or user's contact id
184 * @param int $uid User ID
186 * @return boolean is the contact id blocked for the given user?
188 public static function isBlockedByUser($cid, $uid)
190 $cdata = self::getPublicAndUserContacID($cid, $uid);
195 $public_blocked = false;
197 if (!empty($cdata['public'])) {
198 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
199 if (DBA::isResult($public_contact)) {
200 $public_blocked = $public_contact['blocked'];
204 $user_blocked = $public_blocked;
206 if (!empty($cdata['user'])) {
207 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
208 if (DBA::isResult($user_contact)) {
209 $user_blocked = $user_contact['blocked'];
213 if ($user_blocked != $public_blocked) {
214 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
217 return $user_blocked;
221 * @brief Ignore contact id for user id
223 * @param int $cid Either public contact id or user's contact id
224 * @param int $uid User ID
225 * @param boolean $ignored Is the contact ignored or unignored?
227 public static function setIgnoredForUser($cid, $uid, $ignored)
229 $cdata = self::getPublicAndUserContacID($cid, $uid);
234 if ($cdata['user'] != 0) {
235 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
238 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
242 * @brief Returns "ignore" state for contact id and user id
244 * @param int $cid Either public contact id or user's contact id
245 * @param int $uid User ID
247 * @return boolean is the contact id ignored for the given user?
249 public static function isIgnoredByUser($cid, $uid)
251 $cdata = self::getPublicAndUserContacID($cid, $uid);
256 $public_ignored = false;
258 if (!empty($cdata['public'])) {
259 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
260 if (DBA::isResult($public_contact)) {
261 $public_ignored = $public_contact['ignored'];
265 $user_ignored = $public_ignored;
267 if (!empty($cdata['user'])) {
268 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
269 if (DBA::isResult($user_contact)) {
270 $user_ignored = $user_contact['readonly'];
274 if ($user_ignored != $public_ignored) {
275 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
278 return $user_ignored;
282 * @brief Set "collapsed" for contact id and user id
284 * @param int $cid Either public contact id or user's contact id
285 * @param int $uid User ID
286 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
288 public static function setCollapsedForUser($cid, $uid, $collapsed)
290 $cdata = self::getPublicAndUserContacID($cid, $uid);
295 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
299 * @brief Returns "collapsed" state for contact id and user id
301 * @param int $cid Either public contact id or user's contact id
302 * @param int $uid User ID
304 * @return boolean is the contact id blocked for the given user?
306 public static function isCollapsedByUser($cid, $uid)
308 $cdata = self::getPublicAndUserContacID($cid, $uid);
315 if (!empty($cdata['public'])) {
316 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
317 if (DBA::isResult($public_contact)) {
318 $collapsed = $public_contact['collapsed'];
326 * @brief Returns a list of contacts belonging in a group
331 public static function getByGroupId($gid)
336 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
338 INNER JOIN `group_member`
339 ON `contact`.`id` = `group_member`.`contact-id`
341 AND `contact`.`uid` = ?
342 AND NOT `contact`.`self`
343 AND NOT `contact`.`blocked`
344 AND NOT `contact`.`pending`
345 ORDER BY `contact`.`name` ASC',
350 if (DBA::isResult($stmt)) {
351 $return = DBA::toArray($stmt);
359 * @brief Returns the count of OStatus contacts in a group
364 public static function getOStatusCountByGroupId($gid)
368 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
370 INNER JOIN `group_member`
371 ON `contact`.`id` = `group_member`.`contact-id`
373 AND `contact`.`uid` = ?
374 AND `contact`.`network` = ?
375 AND `contact`.`notify` != ""',
380 $return = $contacts['count'];
387 * Creates the self-contact for the provided user id
390 * @return bool Operation success
392 public static function createSelfFromUserId($uid)
394 // Only create the entry if it doesn't exist yet
395 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
399 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
400 if (!DBA::isResult($user)) {
404 $return = DBA::insert('contact', [
405 'uid' => $user['uid'],
406 'created' => DateTimeFormat::utcNow(),
408 'name' => $user['username'],
409 'nick' => $user['nickname'],
410 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
411 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
412 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
415 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
416 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
417 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
418 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
419 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
420 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
421 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
422 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
423 'name-date' => DateTimeFormat::utcNow(),
424 'uri-date' => DateTimeFormat::utcNow(),
425 'avatar-date' => DateTimeFormat::utcNow(),
433 * Updates the self-contact for the provided user id
436 * @param boolean $update_avatar Force the avatar update
438 public static function updateSelfFromUserID($uid, $update_avatar = false)
440 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
441 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
442 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
443 if (!DBA::isResult($self)) {
447 $fields = ['nickname', 'page-flags', 'account-type'];
448 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
449 if (!DBA::isResult($user)) {
453 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
454 'country-name', 'gender', 'pub_keywords', 'xmpp'];
455 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
456 if (!DBA::isResult($profile)) {
460 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
461 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
462 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
463 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
464 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
466 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
467 if (DBA::isResult($avatar)) {
468 if ($update_avatar) {
469 $fields['avatar-date'] = DateTimeFormat::utcNow();
472 // Creating the path to the avatar, beginning with the file suffix
473 $types = Image::supportedTypes();
474 if (isset($types[$avatar['type']])) {
475 $file_suffix = $types[$avatar['type']];
477 $file_suffix = 'jpg';
480 // We are adding a timestamp value so that other systems won't use cached content
481 $timestamp = strtotime($fields['avatar-date']);
483 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
484 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
486 $fields['photo'] = $prefix . '4' . $suffix;
487 $fields['thumb'] = $prefix . '5' . $suffix;
488 $fields['micro'] = $prefix . '6' . $suffix;
490 // We hadn't found a photo entry, so we use the default avatar
491 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
492 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
493 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
496 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
497 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
499 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
500 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
501 $fields['nurl'] = Strings::normaliseLink($fields['url']);
502 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
503 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
504 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
505 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
506 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
507 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
511 foreach ($fields as $field => $content) {
512 if (isset($self[$field]) && $self[$field] != $content) {
518 $fields['name-date'] = DateTimeFormat::utcNow();
519 DBA::update('contact', $fields, ['id' => $self['id']]);
521 // Update the public contact as well
522 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
524 // Update the profile
525 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
526 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
527 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
532 * @brief Marks a contact for removal
534 * @param int $id contact id
537 public static function remove($id)
539 // We want just to make sure that we don't delete our "self" contact
540 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
541 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
545 // Archive the contact
546 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
548 // Delete it in the background
549 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
553 * @brief Sends an unfriend message. Does not remove the contact
555 * @param array $user User unfriending
556 * @param array $contact Contact unfriended
557 * @param boolean $dissolve Remove the contact on the remote side
560 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
562 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
563 DFRN::deliver($user, $contact, 'placeholder', true);
564 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
565 // create an unfollow slap
567 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
568 $item['follow'] = $contact["url"];
573 $item['attach'] = '';
574 $slap = OStatus::salmon($item, $user);
576 if (!empty($contact['notify'])) {
577 Salmon::slapper($user, $contact['notify'], $slap);
579 } elseif ($contact['network'] == Protocol::DIASPORA) {
580 Diaspora::sendUnshare($user, $contact);
581 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
582 ActivityPub\Transmitter::sendContactUndo($contact['url'], $user['uid']);
585 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
591 * @brief Marks a contact for archival after a communication issue delay
593 * Contact has refused to recognise us as a friend. We will start a countdown.
594 * If they still don't recognise us in 32 days, the relationship is over,
595 * and we won't waste any more time trying to communicate with them.
596 * This provides for the possibility that their database is temporarily messed
597 * up or some other transient event and that there's a possibility we could recover from it.
599 * @param array $contact contact to mark for archival
602 public static function markForArchival(array $contact)
604 if (!isset($contact['url']) && !empty($contact['id'])) {
605 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
606 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
607 if (!DBA::isResult($contact)) {
610 } elseif (!isset($contact['url'])) {
611 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
614 // Contact already archived or "self" contact? => nothing to do
615 if ($contact['archive'] || $contact['self']) {
619 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
620 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
621 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
624 * We really should send a notification to the owner after 2-3 weeks
625 * so they won't be surprised when the contact vanishes and can take
626 * remedial action if this was a serious mistake or glitch
629 /// @todo Check for contact vitality via probing
630 $archival_days = Config::get('system', 'archival_days', 32);
632 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
633 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
634 /* Relationship is really truly dead. archive them rather than
635 * delete, though if the owner tries to unarchive them we'll start
636 * the whole process over again.
638 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
639 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
645 * @brief Cancels the archival countdown
647 * @see Contact::markForArchival()
649 * @param array $contact contact to be unmarked for archival
652 public static function unmarkForArchival(array $contact)
654 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
655 $exists = DBA::exists('contact', $condition);
657 // We don't need to update, we never marked this contact for archival
662 if (!isset($contact['url']) && !empty($contact['id'])) {
663 $fields = ['id', 'url', 'batch'];
664 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
665 if (!DBA::isResult($contact)) {
670 // It's a miracle. Our dead contact has inexplicably come back to life.
671 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
672 DBA::update('contact', $fields, ['id' => $contact['id']]);
673 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
675 if (!empty($contact['batch'])) {
676 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
677 DBA::update('contact', $fields, $condition);
682 * @brief Get contact data for a given profile link
684 * The function looks at several places (contact table and gcontact table) for the contact
685 * It caches its result for the same script execution to prevent duplicate calls
687 * @param string $url The profile link
688 * @param int $uid User id
689 * @param array $default If not data was found take this data as default value
691 * @return array Contact data
693 public static function getDetailsByURL($url, $uid = -1, array $default = [])
705 if (isset($cache[$url][$uid])) {
706 return $cache[$url][$uid];
709 $ssl_url = str_replace('http://', 'https://', $url);
711 // Fetch contact data from the contact table for the given user
712 $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`,
713 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
714 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
715 $r = DBA::toArray($s);
717 // Fetch contact data from the contact table for the given user, checking with the alias
718 if (!DBA::isResult($r)) {
719 $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`,
720 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
721 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
722 $r = DBA::toArray($s);
725 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
726 if (!DBA::isResult($r)) {
727 $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`,
728 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
729 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
730 $r = DBA::toArray($s);
733 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
734 if (!DBA::isResult($r)) {
735 $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`,
736 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
737 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
738 $r = DBA::toArray($s);
741 // Fetch the data from the gcontact table
742 if (!DBA::isResult($r)) {
743 $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`,
744 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
745 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
746 $r = DBA::toArray($s);
749 if (DBA::isResult($r)) {
750 // If there is more than one entry we filter out the connector networks
752 foreach ($r as $id => $result) {
753 if ($result["network"] == Protocol::STATUSNET) {
759 $profile = array_shift($r);
761 // "bd" always contains the upcoming birthday of a contact.
762 // "birthday" might contain the birthday including the year of birth.
763 if ($profile["birthday"] > DBA::NULL_DATE) {
764 $bd_timestamp = strtotime($profile["birthday"]);
765 $month = date("m", $bd_timestamp);
766 $day = date("d", $bd_timestamp);
768 $current_timestamp = time();
769 $current_year = date("Y", $current_timestamp);
770 $current_month = date("m", $current_timestamp);
771 $current_day = date("d", $current_timestamp);
773 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
774 $current = $current_year . "-" . $current_month . "-" . $current_day;
776 if ($profile["bd"] < $current) {
777 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
780 $profile["bd"] = DBA::NULL_DATE;
786 if (empty($profile["photo"]) && isset($default["photo"])) {
787 $profile["photo"] = $default["photo"];
790 if (empty($profile["name"]) && isset($default["name"])) {
791 $profile["name"] = $default["name"];
794 if (empty($profile["network"]) && isset($default["network"])) {
795 $profile["network"] = $default["network"];
798 if (empty($profile["thumb"]) && isset($profile["photo"])) {
799 $profile["thumb"] = $profile["photo"];
802 if (empty($profile["micro"]) && isset($profile["thumb"])) {
803 $profile["micro"] = $profile["thumb"];
806 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
807 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
809 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
812 // Show contact details of Diaspora contacts only if connected
813 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
814 $profile["location"] = "";
815 $profile["about"] = "";
816 $profile["gender"] = "";
817 $profile["birthday"] = DBA::NULL_DATE;
820 $cache[$url][$uid] = $profile;
826 * @brief Get contact data for a given address
828 * The function looks at several places (contact table and gcontact table) for the contact
830 * @param string $addr The profile link
831 * @param int $uid User id
833 * @return array Contact data
835 public static function getDetailsByAddr($addr, $uid = -1)
847 // Fetch contact data from the contact table for the given user
848 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
849 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
850 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
854 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
855 if (!DBA::isResult($r)) {
856 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
857 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
858 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
863 // Fetch the data from the gcontact table
864 if (!DBA::isResult($r)) {
865 $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`,
866 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
867 FROM `gcontact` WHERE `addr` = '%s'",
872 if (!DBA::isResult($r)) {
873 $data = Probe::uri($addr);
875 $profile = self::getDetailsByURL($data['url'], $uid);
884 * @brief Returns the data array for the photo menu of a given contact
886 * @param array $contact contact
887 * @param int $uid optional, default 0
890 public static function photoMenu(array $contact, $uid = 0)
892 // @todo Unused, to be removed
900 $contact_drop_link = '';
907 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
909 $profile_link = self::magicLink($contact['url']);
910 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
915 // Look for our own contact if the uid doesn't match and isn't public
916 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
917 if (DBA::isResult($contact_own)) {
918 return self::photoMenu($contact_own, $uid);
923 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
925 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
927 $profile_link = $contact['url'];
930 if ($profile_link === 'mailbox') {
935 $status_link = $profile_link . '?url=status';
936 $photos_link = $profile_link . '?url=photos';
937 $profile_link = $profile_link . '?url=profile';
940 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
941 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
944 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
945 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
948 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
950 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
952 if (!$contact['self']) {
953 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
958 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
960 if (empty($contact['uid'])) {
961 $connlnk = 'follow/?url=' . $contact['url'];
963 'profile' => [L10n::t('View Profile'), $profile_link, true],
964 'network' => [L10n::t('Network Posts'), $posts_link, false],
965 'edit' => [L10n::t('View Contact'), $contact_url, false],
966 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
970 'status' => [L10n::t('View Status'), $status_link, true],
971 'profile' => [L10n::t('View Profile'), $profile_link, true],
972 'photos' => [L10n::t('View Photos'), $photos_link, true],
973 'network' => [L10n::t('Network Posts'), $posts_link, false],
974 'edit' => [L10n::t('View Contact'), $contact_url, false],
975 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
976 'pm' => [L10n::t('Send PM'), $pm_url, false],
977 'poke' => [L10n::t('Poke'), $poke_link, false],
981 $args = ['contact' => $contact, 'menu' => &$menu];
983 Addon::callHooks('contact_photo_menu', $args);
987 foreach ($menu as $menuname => $menuitem) {
988 if ($menuitem[1] != '') {
989 $menucondensed[$menuname] = $menuitem;
993 return $menucondensed;
997 * @brief Returns ungrouped contact count or list for user
999 * Returns either the total number of ungrouped contacts for the given user
1000 * id or a paginated list of ungrouped contacts.
1002 * @param int $uid uid
1003 * @param int $start optional, default 0
1004 * @param int $count optional, default 0
1008 public static function getUngroupedList($uid)
1017 SELECT DISTINCT(`contact-id`)
1019 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1020 WHERE `group`.`uid` = %d
1021 )", intval($uid), intval($uid));
1025 * @brief Fetch the contact id for a given URL and user
1027 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1028 * `addr` or `alias`.
1030 * If there's no record and we aren't looking for a public contact, we quit.
1031 * If there's one, we check that it isn't time to update the picture else we
1032 * directly return the found contact id.
1034 * Second, we probe the provided $url whether it's http://server.tld/profile or
1035 * nick@server.tld. We quit if we can't get any info back.
1037 * Third, we create the contact record if it doesn't exist
1039 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1040 * if there's any updates
1042 * @param string $url Contact URL
1043 * @param integer $uid The user id for the contact (0 = public contact)
1044 * @param boolean $no_update Don't update the contact
1045 * @param array $default Default value for creating the contact when every else fails
1046 * @param boolean $in_loop Internally used variable to prevent an endless loop
1048 * @return integer Contact ID
1050 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1052 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1060 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1061 // We first try the nurl (http://server.tld/nick), most common case
1062 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1064 // Then the addr (nick@server.tld)
1065 if (!DBA::isResult($contact)) {
1066 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1069 // Then the alias (which could be anything)
1070 if (!DBA::isResult($contact)) {
1071 // The link could be provided as http although we stored it as https
1072 $ssl_url = str_replace('http://', 'https://', $url);
1073 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1074 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1077 if (DBA::isResult($contact)) {
1078 $contact_id = $contact["id"];
1080 // Update the contact every 7 days
1081 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1083 // We force the update if the avatar is empty
1084 if (empty($contact['avatar'])) {
1085 $update_contact = true;
1087 if (!$update_contact || $no_update) {
1090 } elseif ($uid != 0) {
1091 // Non-existing user-specific contact, exiting
1095 // When we don't want to update, we look if some of our users already know this contact
1097 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1098 'photo', 'keywords', 'location', 'about', 'network',
1099 'priority', 'batch', 'request', 'confirm', 'poco'];
1100 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1102 if (DBA::isResult($data)) {
1103 // For security reasons we don't fetch key data from our users
1104 $data["pubkey"] = '';
1111 $data = Probe::uri($url, "", $uid);
1113 // Ensure that there is a gserver entry
1114 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1115 PortableContact::checkServer($data['baseurl']);
1119 // Last try in gcontact for unsupported networks
1120 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1125 // Get data from the gcontact table
1126 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1127 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1128 if (!DBA::isResult($contact)) {
1129 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1132 if (!DBA::isResult($contact)) {
1133 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1134 'photo', 'keywords', 'location', 'about', 'network',
1135 'priority', 'batch', 'request', 'confirm', 'poco'];
1136 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1139 if (!DBA::isResult($contact)) {
1140 // The link could be provided as http although we stored it as https
1141 $ssl_url = str_replace('http://', 'https://', $url);
1142 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1143 $contact = DBA::selectFirst('contact', $fields, $condition);
1146 if (!DBA::isResult($contact)) {
1147 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1148 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1149 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1150 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1153 if (!empty($default)) {
1154 $contact = $default;
1157 if (!DBA::isResult($contact)) {
1160 $data = array_merge($data, $contact);
1164 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1165 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1168 $url = $data["url"];
1172 'created' => DateTimeFormat::utcNow(),
1173 'url' => $data["url"],
1174 'nurl' => Strings::normaliseLink($data["url"]),
1175 'addr' => $data["addr"],
1176 'alias' => $data["alias"],
1177 'notify' => $data["notify"],
1178 'poll' => $data["poll"],
1179 'name' => $data["name"],
1180 'nick' => $data["nick"],
1181 'photo' => $data["photo"],
1182 'keywords' => $data["keywords"],
1183 'location' => $data["location"],
1184 'about' => $data["about"],
1185 'network' => $data["network"],
1186 'pubkey' => $data["pubkey"],
1187 'rel' => self::SHARING,
1188 'priority' => $data["priority"],
1189 'batch' => $data["batch"],
1190 'request' => $data["request"],
1191 'confirm' => $data["confirm"],
1192 'poco' => $data["poco"],
1193 'name-date' => DateTimeFormat::utcNow(),
1194 'uri-date' => DateTimeFormat::utcNow(),
1195 'avatar-date' => DateTimeFormat::utcNow(),
1201 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1203 DBA::update('contact', $fields, $condition, true);
1205 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1206 $contacts = DBA::toArray($s);
1207 if (!DBA::isResult($contacts)) {
1211 $contact_id = $contacts[0]["id"];
1213 // Update the newly created contact from data in the gcontact table
1214 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1215 if (DBA::isResult($gcontact)) {
1216 // Only use the information when the probing hadn't fetched these values
1217 if ($data['keywords'] != '') {
1218 unset($gcontact['keywords']);
1220 if ($data['location'] != '') {
1221 unset($gcontact['location']);
1223 if ($data['about'] != '') {
1224 unset($gcontact['about']);
1226 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1229 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1230 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1231 Strings::normaliseLink($data["url"]), 0, $contact_id];
1232 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1233 DBA::delete('contact', $condition);
1237 self::updateAvatar($data["photo"], $uid, $contact_id);
1239 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1240 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1242 // This condition should always be true
1243 if (!DBA::isResult($contact)) {
1247 $updated = ['addr' => $data['addr'],
1248 'alias' => $data['alias'],
1249 'url' => $data['url'],
1250 'nurl' => Strings::normaliseLink($data['url']),
1251 'name' => $data['name'],
1252 'nick' => $data['nick']];
1254 if ($data['keywords'] != '') {
1255 $updated['keywords'] = $data['keywords'];
1257 if ($data['location'] != '') {
1258 $updated['location'] = $data['location'];
1261 // Update the technical stuff as well - if filled
1262 if ($data['notify'] != '') {
1263 $updated['notify'] = $data['notify'];
1265 if ($data['poll'] != '') {
1266 $updated['poll'] = $data['poll'];
1268 if ($data['batch'] != '') {
1269 $updated['batch'] = $data['batch'];
1271 if ($data['request'] != '') {
1272 $updated['request'] = $data['request'];
1274 if ($data['confirm'] != '') {
1275 $updated['confirm'] = $data['confirm'];
1277 if ($data['poco'] != '') {
1278 $updated['poco'] = $data['poco'];
1281 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1282 if (empty($contact['pubkey'])) {
1283 $updated['pubkey'] = $data['pubkey'];
1286 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1287 $updated['uri-date'] = DateTimeFormat::utcNow();
1289 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1290 $updated['name-date'] = DateTimeFormat::utcNow();
1293 $updated['avatar-date'] = DateTimeFormat::utcNow();
1295 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1301 * @brief Checks if the contact is blocked
1303 * @param int $cid contact id
1305 * @return boolean Is the contact blocked?
1307 public static function isBlocked($cid)
1313 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1314 if (!DBA::isResult($blocked)) {
1318 if (Network::isUrlBlocked($blocked['url'])) {
1322 return (bool) $blocked['blocked'];
1326 * @brief Checks if the contact is hidden
1328 * @param int $cid contact id
1330 * @return boolean Is the contact hidden?
1332 public static function isHidden($cid)
1338 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1339 if (!DBA::isResult($hidden)) {
1342 return (bool) $hidden['hidden'];
1346 * @brief Returns posts from a given contact url
1348 * @param string $contact_url Contact URL
1350 * @return string posts in HTML
1352 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1354 $a = self::getApp();
1356 require_once 'include/conversation.php';
1358 $cid = Self::getIdForURL($contact_url);
1360 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1361 if (!DBA::isResult($contact)) {
1365 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1366 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1368 $sql = "`item`.`uid` = ?";
1371 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1374 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1375 $cid, GRAVITY_PARENT, local_user()];
1377 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1378 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1381 $pager = new Pager($a->query_string);
1383 $params = ['order' => ['created' => true],
1384 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1387 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1389 $items = Item::inArray($r);
1391 $o = conversation($a, $items, $pager, 'contacts', $update);
1393 $r = Item::selectForUser(local_user(), [], $condition, $params);
1395 $items = Item::inArray($r);
1397 $o = conversation($a, $items, $pager, 'contact-posts', false);
1401 $o .= $pager->renderMinimal(count($items));
1408 * @brief Returns the account type name
1410 * The function can be called with either the user or the contact array
1412 * @param array $contact contact or user array
1415 public static function getAccountType(array $contact)
1417 // There are several fields that indicate that the contact or user is a forum
1418 // "page-flags" is a field in the user table,
1419 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1420 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1421 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1422 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1423 || (isset($contact['forum']) && intval($contact['forum']))
1424 || (isset($contact['prv']) && intval($contact['prv']))
1425 || (isset($contact['community']) && intval($contact['community']))
1427 $type = self::ACCOUNT_TYPE_COMMUNITY;
1429 $type = self::ACCOUNT_TYPE_PERSON;
1432 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1433 if (isset($contact["contact-type"])) {
1434 $type = $contact["contact-type"];
1437 if (isset($contact["account-type"])) {
1438 $type = $contact["account-type"];
1442 case self::ACCOUNT_TYPE_ORGANISATION:
1443 $account_type = L10n::t("Organisation");
1446 case self::ACCOUNT_TYPE_NEWS:
1447 $account_type = L10n::t('News');
1450 case self::ACCOUNT_TYPE_COMMUNITY:
1451 $account_type = L10n::t("Forum");
1459 return $account_type;
1463 * @brief Blocks a contact
1468 public static function block($uid)
1470 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1476 * @brief Unblocks a contact
1481 public static function unblock($uid)
1483 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1489 * @brief Updates the avatar links in a contact only if needed
1491 * @param string $avatar Link to avatar picture
1492 * @param int $uid User id of contact owner
1493 * @param int $cid Contact id
1494 * @param bool $force force picture update
1496 * @return array Returns array of the different avatar sizes
1498 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1500 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1501 if (!DBA::isResult($contact)) {
1504 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1507 if (($contact["avatar"] != $avatar) || $force) {
1508 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1513 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1517 // Update the public contact (contact id = 0)
1519 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1520 if (DBA::isResult($pcontact)) {
1521 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1533 * @param integer $id contact id
1534 * @param string $network Optional network we are probing for
1537 public static function updateFromProbe($id, $network = '')
1540 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1541 This will reliably kill your communication with Friendica contacts.
1544 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1545 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1546 if (!DBA::isResult($contact)) {
1550 $ret = Probe::uri($contact["url"], $network);
1552 // If Probe::uri fails the network code will be different
1553 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, $network])) {
1559 // make sure to not overwrite existing values with blank entries
1560 foreach ($ret as $key => $val) {
1561 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1562 $ret[$key] = $contact[$key];
1565 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1576 'url' => $ret['url'],
1577 'nurl' => Strings::normaliseLink($ret['url']),
1578 'network' => $ret['network'],
1579 'addr' => $ret['addr'],
1580 'alias' => $ret['alias'],
1581 'batch' => $ret['batch'],
1582 'notify' => $ret['notify'],
1583 'poll' => $ret['poll'],
1584 'poco' => $ret['poco']
1589 // Update the corresponding gcontact entry
1590 PortableContact::lastUpdated($ret["url"]);
1596 * Takes a $uid and a url/handle and adds a new contact
1597 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1598 * dfrn_request page.
1600 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1603 * $return['success'] boolean true if successful
1604 * $return['message'] error text if success is false.
1606 * @brief Takes a $uid and a url/handle and adds a new contact
1608 * @param string $url
1609 * @param bool $interactive
1610 * @param string $network
1611 * @return boolean|string
1613 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1615 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1619 // remove ajax junk, e.g. Twitter
1620 $url = str_replace('/#!/', '/', $url);
1622 if (!Network::isUrlAllowed($url)) {
1623 $result['message'] = L10n::t('Disallowed profile URL.');
1627 if (Network::isUrlBlocked($url)) {
1628 $result['message'] = L10n::t('Blocked domain');
1633 $result['message'] = L10n::t('Connect URL missing.');
1637 $arr = ['url' => $url, 'contact' => []];
1639 Hook::callAll('follow', $arr);
1642 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1646 if (!empty($arr['contact']['name'])) {
1647 $ret = $arr['contact'];
1649 $ret = Probe::uri($url, $network, $uid, false);
1652 if (($network != '') && ($ret['network'] != $network)) {
1653 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1657 // check if we already have a contact
1658 // the poll url is more reliable than the profile url, as we may have
1659 // indirect links or webfinger links
1661 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1662 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1663 if (!DBA::isResult($contact)) {
1664 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1665 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1668 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1670 if (strlen($a->getURLPath())) {
1671 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1673 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1676 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1680 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1681 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1682 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1686 // This extra param just confuses things, remove it
1687 if ($ret['network'] === Protocol::DIASPORA) {
1688 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1691 // do we have enough information?
1692 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1693 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1694 if (empty($ret['poll'])) {
1695 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1697 if (empty($ret['name'])) {
1698 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1700 if (empty($ret['url'])) {
1701 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1703 if (strpos($url, '@') !== false) {
1704 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1705 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1710 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1711 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1712 $ret['notify'] = '';
1715 if (!$ret['notify']) {
1716 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1719 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1721 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1723 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1725 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1729 if (DBA::isResult($contact)) {
1731 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1733 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1734 DBA::update('contact', $fields, ['id' => $contact['id']]);
1736 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1738 // create contact record
1739 DBA::insert('contact', [
1741 'created' => DateTimeFormat::utcNow(),
1742 'url' => $ret['url'],
1743 'nurl' => Strings::normaliseLink($ret['url']),
1744 'addr' => $ret['addr'],
1745 'alias' => $ret['alias'],
1746 'batch' => $ret['batch'],
1747 'notify' => $ret['notify'],
1748 'poll' => $ret['poll'],
1749 'poco' => $ret['poco'],
1750 'name' => $ret['name'],
1751 'nick' => $ret['nick'],
1752 'network' => $ret['network'],
1753 'pubkey' => $ret['pubkey'],
1754 'rel' => $new_relation,
1755 'priority'=> $ret['priority'],
1756 'writable'=> $writeable,
1757 'hidden' => $hidden,
1765 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1766 if (!DBA::isResult($contact)) {
1767 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1771 $contact_id = $contact['id'];
1772 $result['cid'] = $contact_id;
1774 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1776 // Update the avatar
1777 self::updateAvatar($ret['photo'], $uid, $contact_id);
1779 // pull feed and consume it, which should subscribe to the hub.
1781 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1783 $owner = User::getOwnerDataById($uid);
1785 if (DBA::isResult($owner)) {
1786 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1787 // create a follow slap
1789 $item['verb'] = ACTIVITY_FOLLOW;
1790 $item['follow'] = $contact["url"];
1792 $item['title'] = '';
1795 $item['attach'] = '';
1797 $slap = OStatus::salmon($item, $owner);
1799 if (!empty($contact['notify'])) {
1800 Salmon::slapper($owner, $contact['notify'], $slap);
1802 } elseif ($contact['network'] == Protocol::DIASPORA) {
1803 $ret = Diaspora::sendShare($a->user, $contact);
1804 Logger::log('share returns: ' . $ret);
1805 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1806 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
1807 Logger::log('Follow returns: ' . $ret);
1811 $result['success'] = true;
1816 * @brief Updated contact's SSL policy
1818 * @param array $contact Contact array
1819 * @param string $new_policy New policy, valid: self,full
1821 * @return array Contact array with updated values
1823 public static function updateSslPolicy(array $contact, $new_policy)
1825 $ssl_changed = false;
1826 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1827 $ssl_changed = true;
1828 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1829 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1830 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1831 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1832 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1833 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1836 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1837 $ssl_changed = true;
1838 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1839 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1840 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1841 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1842 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1843 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1847 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1848 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1849 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1850 DBA::update('contact', $fields, ['id' => $contact['id']]);
1856 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1857 // Should always be set
1858 if (empty($datarray['author-id'])) {
1862 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1863 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1864 if (!DBA::isResult($pub_contact)) {
1865 // Should never happen
1869 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1870 $name = $pub_contact['name'];
1871 $photo = $pub_contact['photo'];
1872 $nick = $pub_contact['nick'];
1873 $network = $pub_contact['network'];
1875 if (is_array($contact)) {
1876 if (($contact['rel'] == self::SHARING)
1877 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1878 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1879 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1882 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1883 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1886 // send email notification to owner?
1888 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1889 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1892 // create contact record
1893 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1894 `blocked`, `readonly`, `pending`, `writable`)
1895 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1896 intval($importer['uid']),
1897 DBA::escape(DateTimeFormat::utcNow()),
1899 DBA::escape(Strings::normaliseLink($url)),
1902 DBA::escape($photo),
1903 DBA::escape($network),
1904 intval(self::FOLLOWER)
1908 'id' => DBA::lastInsertId(),
1909 'network' => $network,
1915 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1917 /// @TODO Encapsulate this into a function/method
1918 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1919 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1920 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1921 // create notification
1922 $hash = Strings::getRandomHex();
1924 if (is_array($contact_record)) {
1925 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1926 'blocked' => false, 'knowyou' => false,
1927 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1930 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1932 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1933 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1936 'type' => NOTIFY_INTRO,
1937 'notify_flags' => $user['notify-flags'],
1938 'language' => $user['language'],
1939 'to_name' => $user['username'],
1940 'to_email' => $user['email'],
1941 'uid' => $user['uid'],
1942 'link' => System::baseUrl() . '/notifications/intro',
1943 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1944 'source_link' => $contact_record['url'],
1945 'source_photo' => $contact_record['photo'],
1946 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1951 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1952 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1953 DBA::update('contact', ['pending' => false], $condition);
1955 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1957 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1958 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1964 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1966 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1967 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1969 Contact::remove($contact['id']);
1973 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1975 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1976 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1978 Contact::remove($contact['id']);
1983 * @brief Create a birthday event.
1985 * Update the year and the birthday.
1987 public static function updateBirthdays()
1991 AND `bd` > "0001-01-01"
1992 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
1993 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
1994 AND NOT `contact`.`pending`
1995 AND NOT `contact`.`hidden`
1996 AND NOT `contact`.`blocked`
1997 AND NOT `contact`.`archive`
1998 AND NOT `contact`.`deleted`',
2003 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2005 while ($contact = DBA::fetch($contacts)) {
2006 Logger::log('update_contact_birthday: ' . $contact['bd']);
2008 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2010 if (Event::createBirthday($contact, $nextbd)) {
2014 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2015 ['id' => $contact['id']]
2022 * Remove the unavailable contact ids from the provided list
2024 * @param array $contact_ids Contact id list
2026 public static function pruneUnavailable(array &$contact_ids)
2028 if (empty($contact_ids)) {
2032 $str = DBA::escape(implode(',', $contact_ids));
2034 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2037 while($contact = DBA::fetch($stmt)) {
2038 $return[] = $contact['id'];
2043 $contact_ids = $return;
2047 * @brief Returns a magic link to authenticate remote visitors
2049 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2051 * @param string $contact_url The address of the target contact profile
2052 * @param string $url An url that we will be redirected to after the authentication
2054 * @return string with "redir" link
2056 public static function magicLink($contact_url, $url = '')
2058 $cid = self::getIdForURL($contact_url, 0, true);
2060 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2063 return self::magicLinkbyId($cid, $url);
2067 * @brief Returns a magic link to authenticate remote visitors
2069 * @param integer $cid The contact id of the target contact profile
2070 * @param integer $url An url that we will be redirected to after the authentication
2072 * @return string with "redir" link
2074 public static function magicLinkbyId($cid, $url = '')
2076 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2078 return self::magicLinkbyContact($contact, $url);
2082 * @brief Returns a magic link to authenticate remote visitors
2084 * @param array $contact The contact array with "uid", "network" and "url"
2085 * @param string $url An url that we will be redirected to after the authentication
2087 * @return string with "redir" link
2089 public static function magicLinkbyContact($contact, $url = '')
2091 if ($contact['network'] != Protocol::DFRN) {
2092 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2095 // Only redirections to the same host do make sense
2096 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2100 if ($contact['uid'] != 0) {
2101 return self::magicLink($contact['url'], $url);
2104 $redirect = 'redir/' . $contact['id'];
2107 $redirect .= '?url=' . $url;