3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
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\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Protocol\PortableContact;
24 use Friendica\Protocol\Salmon;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Strings;
30 * @brief functions for interacting with a contact
32 class Contact extends BaseObject
35 * @name page/profile types
37 * PAGE_NORMAL is a typical personal profile account
38 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
39 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
40 * write access to wall and comments (no email and not included in page owner's ACL lists)
41 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
45 const PAGE_NORMAL = 0;
46 const PAGE_SOAPBOX = 1;
47 const PAGE_COMMUNITY = 2;
48 const PAGE_FREELOVE = 3;
50 const PAGE_PRVGROUP = 5;
58 * ACCOUNT_TYPE_PERSON - the account belongs to a person
59 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
61 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
62 * Associated page type: PAGE_SOAPBOX
64 * ACCOUNT_TYPE_NEWS - the account is a news reflector
65 * Associated page type: PAGE_SOAPBOX
67 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
68 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
70 * ACCOUNT_TYPE_RELAY - the account is a relay
71 * This will only be assigned to contacts, not to user accounts
74 const ACCOUNT_TYPE_PERSON = 0;
75 const ACCOUNT_TYPE_ORGANISATION = 1;
76 const ACCOUNT_TYPE_NEWS = 2;
77 const ACCOUNT_TYPE_COMMUNITY = 3;
78 const ACCOUNT_TYPE_RELAY = 4;
97 * @brief Tests if the given contact is a follower
99 * @param int $cid Either public contact id or user's contact id
100 * @param int $uid User ID
102 * @return boolean is the contact id a follower?
104 public static function isFollower($cid, $uid)
106 if (self::isBlockedByUser($cid, $uid)) {
110 $cdata = self::getPublicAndUserContacID($cid, $uid);
111 if (empty($cdata['user'])) {
115 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
116 return DBA::exists('contact', $condition);
120 * @brief Get the basepath for a given contact link
121 * @todo Add functionality to store this value in the contact table
123 * @param string $url The contact link
125 * @return string basepath
127 public static function getBasepath($url)
129 $data = Probe::uri($url);
130 if (!empty($data['baseurl'])) {
131 return $data['baseurl'];
134 // When we can't probe the server, we use some ugly function that does some pattern matching
135 return PortableContact::detectServer($url);
139 * @brief Returns the contact id for the user and the public contact id for a given contact id
141 * @param int $cid Either public contact id or user's contact id
142 * @param int $uid User ID
144 * @return array with public and user's contact id
146 public static function getPublicAndUserContacID($cid, $uid)
148 if (empty($uid) || empty($cid)) {
152 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
153 if (!DBA::isResult($contact)) {
157 // We quit when the user id don't match the user id of the provided contact
158 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
162 if ($contact['uid'] != 0) {
163 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
167 $ucid = $contact['id'];
169 $pcid = $contact['id'];
170 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
173 return ['public' => $pcid, 'user' => $ucid];
177 * @brief Block contact id for user id
179 * @param int $cid Either public contact id or user's contact id
180 * @param int $uid User ID
181 * @param boolean $blocked Is the contact blocked or unblocked?
183 public static function setBlockedForUser($cid, $uid, $blocked)
185 $cdata = self::getPublicAndUserContacID($cid, $uid);
190 if ($cdata['user'] != 0) {
191 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
194 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
198 * @brief Returns "block" state for contact id and user id
200 * @param int $cid Either public contact id or user's contact id
201 * @param int $uid User ID
203 * @return boolean is the contact id blocked for the given user?
205 public static function isBlockedByUser($cid, $uid)
207 $cdata = self::getPublicAndUserContacID($cid, $uid);
212 $public_blocked = false;
214 if (!empty($cdata['public'])) {
215 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
216 if (DBA::isResult($public_contact)) {
217 $public_blocked = $public_contact['blocked'];
221 $user_blocked = $public_blocked;
223 if (!empty($cdata['user'])) {
224 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
225 if (DBA::isResult($user_contact)) {
226 $user_blocked = $user_contact['blocked'];
230 if ($user_blocked != $public_blocked) {
231 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
234 return $user_blocked;
238 * @brief Ignore contact id for user id
240 * @param int $cid Either public contact id or user's contact id
241 * @param int $uid User ID
242 * @param boolean $ignored Is the contact ignored or unignored?
244 public static function setIgnoredForUser($cid, $uid, $ignored)
246 $cdata = self::getPublicAndUserContacID($cid, $uid);
251 if ($cdata['user'] != 0) {
252 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
255 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
259 * @brief Returns "ignore" state for contact id and user id
261 * @param int $cid Either public contact id or user's contact id
262 * @param int $uid User ID
264 * @return boolean is the contact id ignored for the given user?
266 public static function isIgnoredByUser($cid, $uid)
268 $cdata = self::getPublicAndUserContacID($cid, $uid);
273 $public_ignored = false;
275 if (!empty($cdata['public'])) {
276 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
277 if (DBA::isResult($public_contact)) {
278 $public_ignored = $public_contact['ignored'];
282 $user_ignored = $public_ignored;
284 if (!empty($cdata['user'])) {
285 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
286 if (DBA::isResult($user_contact)) {
287 $user_ignored = $user_contact['readonly'];
291 if ($user_ignored != $public_ignored) {
292 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
295 return $user_ignored;
299 * @brief Set "collapsed" 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
303 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
305 public static function setCollapsedForUser($cid, $uid, $collapsed)
307 $cdata = self::getPublicAndUserContacID($cid, $uid);
312 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
316 * @brief Returns "collapsed" state for contact id and user id
318 * @param int $cid Either public contact id or user's contact id
319 * @param int $uid User ID
321 * @return boolean is the contact id blocked for the given user?
323 public static function isCollapsedByUser($cid, $uid)
325 $cdata = self::getPublicAndUserContacID($cid, $uid);
332 if (!empty($cdata['public'])) {
333 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
334 if (DBA::isResult($public_contact)) {
335 $collapsed = $public_contact['collapsed'];
343 * @brief Returns a list of contacts belonging in a group
348 public static function getByGroupId($gid)
353 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
355 INNER JOIN `group_member`
356 ON `contact`.`id` = `group_member`.`contact-id`
358 AND `contact`.`uid` = ?
359 AND NOT `contact`.`self`
360 AND NOT `contact`.`deleted`
361 AND NOT `contact`.`blocked`
362 AND NOT `contact`.`pending`
363 ORDER BY `contact`.`name` ASC',
368 if (DBA::isResult($stmt)) {
369 $return = DBA::toArray($stmt);
377 * @brief Returns the count of OStatus contacts in a group
382 public static function getOStatusCountByGroupId($gid)
386 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
388 INNER JOIN `group_member`
389 ON `contact`.`id` = `group_member`.`contact-id`
391 AND `contact`.`uid` = ?
392 AND `contact`.`network` = ?
393 AND `contact`.`notify` != ""',
398 $return = $contacts['count'];
405 * Creates the self-contact for the provided user id
408 * @return bool Operation success
410 public static function createSelfFromUserId($uid)
412 // Only create the entry if it doesn't exist yet
413 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
417 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
418 if (!DBA::isResult($user)) {
422 $return = DBA::insert('contact', [
423 'uid' => $user['uid'],
424 'created' => DateTimeFormat::utcNow(),
426 'name' => $user['username'],
427 'nick' => $user['nickname'],
428 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
429 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
430 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
433 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
434 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
435 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
436 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
437 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
438 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
439 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
440 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
441 'name-date' => DateTimeFormat::utcNow(),
442 'uri-date' => DateTimeFormat::utcNow(),
443 'avatar-date' => DateTimeFormat::utcNow(),
451 * Updates the self-contact for the provided user id
454 * @param boolean $update_avatar Force the avatar update
456 public static function updateSelfFromUserID($uid, $update_avatar = false)
458 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
459 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
460 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
461 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
462 if (!DBA::isResult($self)) {
466 $fields = ['nickname', 'page-flags', 'account-type'];
467 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
468 if (!DBA::isResult($user)) {
472 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
473 'country-name', 'gender', 'pub_keywords', 'xmpp'];
474 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
475 if (!DBA::isResult($profile)) {
479 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
480 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
481 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
482 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
483 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
485 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
486 if (DBA::isResult($avatar)) {
487 if ($update_avatar) {
488 $fields['avatar-date'] = DateTimeFormat::utcNow();
491 // Creating the path to the avatar, beginning with the file suffix
492 $types = Image::supportedTypes();
493 if (isset($types[$avatar['type']])) {
494 $file_suffix = $types[$avatar['type']];
496 $file_suffix = 'jpg';
499 // We are adding a timestamp value so that other systems won't use cached content
500 $timestamp = strtotime($fields['avatar-date']);
502 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
503 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
505 $fields['photo'] = $prefix . '4' . $suffix;
506 $fields['thumb'] = $prefix . '5' . $suffix;
507 $fields['micro'] = $prefix . '6' . $suffix;
509 // We hadn't found a photo entry, so we use the default avatar
510 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
511 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
512 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
515 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
516 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
518 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
519 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
520 $fields['nurl'] = Strings::normaliseLink($fields['url']);
521 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
522 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
523 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
524 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
525 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
526 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
530 foreach ($fields as $field => $content) {
531 if ($self[$field] != $content) {
537 $fields['name-date'] = DateTimeFormat::utcNow();
538 DBA::update('contact', $fields, ['id' => $self['id']]);
540 // Update the public contact as well
541 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
543 // Update the profile
544 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
545 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
546 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
551 * @brief Marks a contact for removal
553 * @param int $id contact id
556 public static function remove($id)
558 // We want just to make sure that we don't delete our "self" contact
559 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
560 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
564 // Archive the contact
565 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
567 // Delete it in the background
568 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
572 * @brief Sends an unfriend message. Does not remove the contact
574 * @param array $user User unfriending
575 * @param array $contact Contact unfriended
576 * @param boolean $dissolve Remove the contact on the remote side
579 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
581 if (empty($contact['network'])) {
584 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
585 DFRN::deliver($user, $contact, 'placeholder', true);
586 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
587 // create an unfollow slap
589 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
590 $item['follow'] = $contact["url"];
595 $item['attach'] = '';
596 $slap = OStatus::salmon($item, $user);
598 if (!empty($contact['notify'])) {
599 Salmon::slapper($user, $contact['notify'], $slap);
601 } elseif ($contact['network'] == Protocol::DIASPORA) {
602 Diaspora::sendUnshare($user, $contact);
603 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
604 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
607 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
613 * @brief Marks a contact for archival after a communication issue delay
615 * Contact has refused to recognise us as a friend. We will start a countdown.
616 * If they still don't recognise us in 32 days, the relationship is over,
617 * and we won't waste any more time trying to communicate with them.
618 * This provides for the possibility that their database is temporarily messed
619 * up or some other transient event and that there's a possibility we could recover from it.
621 * @param array $contact contact to mark for archival
624 public static function markForArchival(array $contact)
626 if (!isset($contact['url']) && !empty($contact['id'])) {
627 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
628 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
629 if (!DBA::isResult($contact)) {
632 } elseif (!isset($contact['url'])) {
633 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
636 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
638 // Contact already archived or "self" contact? => nothing to do
639 if ($contact['archive'] || $contact['self']) {
643 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
644 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
645 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
648 * We really should send a notification to the owner after 2-3 weeks
649 * so they won't be surprised when the contact vanishes and can take
650 * remedial action if this was a serious mistake or glitch
653 /// @todo Check for contact vitality via probing
654 $archival_days = Config::get('system', 'archival_days', 32);
656 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
657 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
658 /* Relationship is really truly dead. archive them rather than
659 * delete, though if the owner tries to unarchive them we'll start
660 * the whole process over again.
662 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
663 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
669 * @brief Cancels the archival countdown
671 * @see Contact::markForArchival()
673 * @param array $contact contact to be unmarked for archival
676 public static function unmarkForArchival(array $contact)
678 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
679 $exists = DBA::exists('contact', $condition);
681 // We don't need to update, we never marked this contact for archival
686 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
688 if (!isset($contact['url']) && !empty($contact['id'])) {
689 $fields = ['id', 'url', 'batch'];
690 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
691 if (!DBA::isResult($contact)) {
696 // It's a miracle. Our dead contact has inexplicably come back to life.
697 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
698 DBA::update('contact', $fields, ['id' => $contact['id']]);
699 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
701 if (!empty($contact['batch'])) {
702 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
703 DBA::update('contact', $fields, $condition);
708 * @brief Get contact data for a given profile link
710 * The function looks at several places (contact table and gcontact table) for the contact
711 * It caches its result for the same script execution to prevent duplicate calls
713 * @param string $url The profile link
714 * @param int $uid User id
715 * @param array $default If not data was found take this data as default value
717 * @return array Contact data
719 public static function getDetailsByURL($url, $uid = -1, array $default = [])
731 if (isset($cache[$url][$uid])) {
732 return $cache[$url][$uid];
735 $ssl_url = str_replace('http://', 'https://', $url);
737 // Fetch contact data from the contact table for the given user
738 $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`,
739 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
740 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
741 $r = DBA::toArray($s);
743 // Fetch contact data from the contact table for the given user, checking with the alias
744 if (!DBA::isResult($r)) {
745 $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`,
746 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
747 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
748 $r = DBA::toArray($s);
751 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
752 if (!DBA::isResult($r)) {
753 $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`,
754 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
755 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
756 $r = DBA::toArray($s);
759 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
760 if (!DBA::isResult($r)) {
761 $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`,
762 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
763 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
764 $r = DBA::toArray($s);
767 // Fetch the data from the gcontact table
768 if (!DBA::isResult($r)) {
769 $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`,
770 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
771 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
772 $r = DBA::toArray($s);
775 if (DBA::isResult($r)) {
776 // If there is more than one entry we filter out the connector networks
778 foreach ($r as $id => $result) {
779 if ($result["network"] == Protocol::STATUSNET) {
785 $profile = array_shift($r);
787 // "bd" always contains the upcoming birthday of a contact.
788 // "birthday" might contain the birthday including the year of birth.
789 if ($profile["birthday"] > DBA::NULL_DATE) {
790 $bd_timestamp = strtotime($profile["birthday"]);
791 $month = date("m", $bd_timestamp);
792 $day = date("d", $bd_timestamp);
794 $current_timestamp = time();
795 $current_year = date("Y", $current_timestamp);
796 $current_month = date("m", $current_timestamp);
797 $current_day = date("d", $current_timestamp);
799 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
800 $current = $current_year . "-" . $current_month . "-" . $current_day;
802 if ($profile["bd"] < $current) {
803 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
806 $profile["bd"] = DBA::NULL_DATE;
812 if (empty($profile["photo"]) && isset($default["photo"])) {
813 $profile["photo"] = $default["photo"];
816 if (empty($profile["name"]) && isset($default["name"])) {
817 $profile["name"] = $default["name"];
820 if (empty($profile["network"]) && isset($default["network"])) {
821 $profile["network"] = $default["network"];
824 if (empty($profile["thumb"]) && isset($profile["photo"])) {
825 $profile["thumb"] = $profile["photo"];
828 if (empty($profile["micro"]) && isset($profile["thumb"])) {
829 $profile["micro"] = $profile["thumb"];
832 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
833 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
835 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
838 // Show contact details of Diaspora contacts only if connected
839 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
840 $profile["location"] = "";
841 $profile["about"] = "";
842 $profile["gender"] = "";
843 $profile["birthday"] = DBA::NULL_DATE;
846 $cache[$url][$uid] = $profile;
852 * @brief Get contact data for a given address
854 * The function looks at several places (contact table and gcontact table) for the contact
856 * @param string $addr The profile link
857 * @param int $uid User id
859 * @return array Contact data
861 public static function getDetailsByAddr($addr, $uid = -1)
873 // Fetch contact data from the contact table for the given user
874 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
875 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
876 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
880 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
881 if (!DBA::isResult($r)) {
882 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
883 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
884 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
889 // Fetch the data from the gcontact table
890 if (!DBA::isResult($r)) {
891 $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`,
892 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
893 FROM `gcontact` WHERE `addr` = '%s'",
898 if (!DBA::isResult($r)) {
899 $data = Probe::uri($addr);
901 $profile = self::getDetailsByURL($data['url'], $uid);
910 * @brief Returns the data array for the photo menu of a given contact
912 * @param array $contact contact
913 * @param int $uid optional, default 0
916 public static function photoMenu(array $contact, $uid = 0)
918 // @todo Unused, to be removed
926 $contact_drop_link = '';
933 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
935 $profile_link = self::magicLink($contact['url']);
936 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
941 // Look for our own contact if the uid doesn't match and isn't public
942 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
943 if (DBA::isResult($contact_own)) {
944 return self::photoMenu($contact_own, $uid);
949 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
951 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
953 $profile_link = $contact['url'];
956 if ($profile_link === 'mailbox') {
961 $status_link = $profile_link . '?url=status';
962 $photos_link = $profile_link . '?url=photos';
963 $profile_link = $profile_link . '?url=profile';
966 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
967 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
970 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
971 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
974 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
976 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
978 if (!$contact['self']) {
979 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
984 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
986 if (empty($contact['uid'])) {
987 $connlnk = 'follow/?url=' . $contact['url'];
989 'profile' => [L10n::t('View Profile'), $profile_link, true],
990 'network' => [L10n::t('Network Posts'), $posts_link, false],
991 'edit' => [L10n::t('View Contact'), $contact_url, false],
992 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
996 'status' => [L10n::t('View Status'), $status_link, true],
997 'profile' => [L10n::t('View Profile'), $profile_link, true],
998 'photos' => [L10n::t('View Photos'), $photos_link, true],
999 'network' => [L10n::t('Network Posts'), $posts_link, false],
1000 'edit' => [L10n::t('View Contact'), $contact_url, false],
1001 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1002 'pm' => [L10n::t('Send PM'), $pm_url, false],
1003 'poke' => [L10n::t('Poke'), $poke_link, false],
1007 $args = ['contact' => $contact, 'menu' => &$menu];
1009 Hook::callAll('contact_photo_menu', $args);
1011 $menucondensed = [];
1013 foreach ($menu as $menuname => $menuitem) {
1014 if ($menuitem[1] != '') {
1015 $menucondensed[$menuname] = $menuitem;
1019 return $menucondensed;
1023 * @brief Returns ungrouped contact count or list for user
1025 * Returns either the total number of ungrouped contacts for the given user
1026 * id or a paginated list of ungrouped contacts.
1028 * @param int $uid uid
1029 * @param int $start optional, default 0
1030 * @param int $count optional, default 0
1034 public static function getUngroupedList($uid)
1044 SELECT DISTINCT(`contact-id`)
1046 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1047 WHERE `group`.`uid` = %d
1048 )", intval($uid), intval($uid));
1052 * @brief Fetch the contact id for a given URL and user
1054 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1055 * `addr` or `alias`.
1057 * If there's no record and we aren't looking for a public contact, we quit.
1058 * If there's one, we check that it isn't time to update the picture else we
1059 * directly return the found contact id.
1061 * Second, we probe the provided $url whether it's http://server.tld/profile or
1062 * nick@server.tld. We quit if we can't get any info back.
1064 * Third, we create the contact record if it doesn't exist
1066 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1067 * if there's any updates
1069 * @param string $url Contact URL
1070 * @param integer $uid The user id for the contact (0 = public contact)
1071 * @param boolean $no_update Don't update the contact
1072 * @param array $default Default value for creating the contact when every else fails
1073 * @param boolean $in_loop Internally used variable to prevent an endless loop
1075 * @return integer Contact ID
1077 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1079 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1087 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1088 // We first try the nurl (http://server.tld/nick), most common case
1089 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1091 // Then the addr (nick@server.tld)
1092 if (!DBA::isResult($contact)) {
1093 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1096 // Then the alias (which could be anything)
1097 if (!DBA::isResult($contact)) {
1098 // The link could be provided as http although we stored it as https
1099 $ssl_url = str_replace('http://', 'https://', $url);
1100 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1101 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1104 if (DBA::isResult($contact)) {
1105 $contact_id = $contact["id"];
1107 // Update the contact every 7 days
1108 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1110 // We force the update if the avatar is empty
1111 if (empty($contact['avatar'])) {
1112 $update_contact = true;
1114 if (!$update_contact || $no_update) {
1117 } elseif ($uid != 0) {
1118 // Non-existing user-specific contact, exiting
1122 // When we don't want to update, we look if some of our users already know this contact
1124 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1125 'photo', 'keywords', 'location', 'about', 'network',
1126 'priority', 'batch', 'request', 'confirm', 'poco'];
1127 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1129 if (DBA::isResult($data)) {
1130 // For security reasons we don't fetch key data from our users
1131 $data["pubkey"] = '';
1138 $data = Probe::uri($url, "", $uid);
1140 // Ensure that there is a gserver entry
1141 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1142 PortableContact::checkServer($data['baseurl']);
1146 // Last try in gcontact for unsupported networks
1147 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1152 // Get data from the gcontact table
1153 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1154 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1155 if (!DBA::isResult($contact)) {
1156 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1159 if (!DBA::isResult($contact)) {
1160 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1161 'photo', 'keywords', 'location', 'about', 'network',
1162 'priority', 'batch', 'request', 'confirm', 'poco'];
1163 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1166 if (!DBA::isResult($contact)) {
1167 // The link could be provided as http although we stored it as https
1168 $ssl_url = str_replace('http://', 'https://', $url);
1169 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1170 $contact = DBA::selectFirst('contact', $fields, $condition);
1173 if (!DBA::isResult($contact)) {
1174 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1175 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1176 $condition = ['url' => [$url, Strings::normaliseLink($url), $ssl_url]];
1177 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1180 if (!empty($default)) {
1181 $contact = $default;
1184 if (!DBA::isResult($contact)) {
1187 $data = array_merge($data, $contact);
1191 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url) && !$in_loop) {
1192 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1195 $url = $data["url"];
1199 'created' => DateTimeFormat::utcNow(),
1200 'url' => $data["url"],
1201 'nurl' => Strings::normaliseLink($data["url"]),
1202 'addr' => $data["addr"],
1203 'alias' => $data["alias"],
1204 'notify' => $data["notify"],
1205 'poll' => $data["poll"],
1206 'name' => $data["name"],
1207 'nick' => $data["nick"],
1208 'photo' => $data["photo"],
1209 'keywords' => $data["keywords"],
1210 'location' => $data["location"],
1211 'about' => $data["about"],
1212 'network' => $data["network"],
1213 'pubkey' => $data["pubkey"],
1214 'rel' => self::SHARING,
1215 'priority' => $data["priority"],
1216 'batch' => $data["batch"],
1217 'request' => $data["request"],
1218 'confirm' => $data["confirm"],
1219 'poco' => $data["poco"],
1220 'name-date' => DateTimeFormat::utcNow(),
1221 'uri-date' => DateTimeFormat::utcNow(),
1222 'avatar-date' => DateTimeFormat::utcNow(),
1228 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1230 DBA::update('contact', $fields, $condition, true);
1232 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1233 $contacts = DBA::toArray($s);
1234 if (!DBA::isResult($contacts)) {
1238 $contact_id = $contacts[0]["id"];
1240 // Update the newly created contact from data in the gcontact table
1241 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1242 if (DBA::isResult($gcontact)) {
1243 // Only use the information when the probing hadn't fetched these values
1244 if ($data['keywords'] != '') {
1245 unset($gcontact['keywords']);
1247 if ($data['location'] != '') {
1248 unset($gcontact['location']);
1250 if ($data['about'] != '') {
1251 unset($gcontact['about']);
1253 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1256 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1257 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1258 Strings::normaliseLink($data["url"]), 0, $contact_id];
1259 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1260 DBA::delete('contact', $condition);
1264 self::updateAvatar($data["photo"], $uid, $contact_id);
1266 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1267 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1269 // This condition should always be true
1270 if (!DBA::isResult($contact)) {
1274 $updated = ['addr' => $data['addr'],
1275 'alias' => $data['alias'],
1276 'url' => $data['url'],
1277 'nurl' => Strings::normaliseLink($data['url']),
1278 'name' => $data['name'],
1279 'nick' => $data['nick']];
1281 if ($data['keywords'] != '') {
1282 $updated['keywords'] = $data['keywords'];
1284 if ($data['location'] != '') {
1285 $updated['location'] = $data['location'];
1288 // Update the technical stuff as well - if filled
1289 if ($data['notify'] != '') {
1290 $updated['notify'] = $data['notify'];
1292 if ($data['poll'] != '') {
1293 $updated['poll'] = $data['poll'];
1295 if ($data['batch'] != '') {
1296 $updated['batch'] = $data['batch'];
1298 if ($data['request'] != '') {
1299 $updated['request'] = $data['request'];
1301 if ($data['confirm'] != '') {
1302 $updated['confirm'] = $data['confirm'];
1304 if ($data['poco'] != '') {
1305 $updated['poco'] = $data['poco'];
1308 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1309 if (empty($contact['pubkey'])) {
1310 $updated['pubkey'] = $data['pubkey'];
1313 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1314 $updated['uri-date'] = DateTimeFormat::utcNow();
1316 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1317 $updated['name-date'] = DateTimeFormat::utcNow();
1320 $updated['avatar-date'] = DateTimeFormat::utcNow();
1322 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1328 * @brief Checks if the contact is blocked
1330 * @param int $cid contact id
1332 * @return boolean Is the contact blocked?
1334 public static function isBlocked($cid)
1340 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1341 if (!DBA::isResult($blocked)) {
1345 if (Network::isUrlBlocked($blocked['url'])) {
1349 return (bool) $blocked['blocked'];
1353 * @brief Checks if the contact is hidden
1355 * @param int $cid contact id
1357 * @return boolean Is the contact hidden?
1359 public static function isHidden($cid)
1365 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1366 if (!DBA::isResult($hidden)) {
1369 return (bool) $hidden['hidden'];
1373 * @brief Returns posts from a given contact url
1375 * @param string $contact_url Contact URL
1377 * @return string posts in HTML
1379 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1381 $a = self::getApp();
1383 $cid = Self::getIdForURL($contact_url);
1385 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1386 if (!DBA::isResult($contact)) {
1390 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1391 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1393 $sql = "`item`.`uid` = ?";
1396 $contact_field = ($contact["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1399 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1400 $cid, GRAVITY_PARENT, local_user()];
1402 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1403 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1406 $pager = new Pager($a->query_string);
1408 $params = ['order' => ['created' => true],
1409 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1412 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1414 $items = Item::inArray($r);
1416 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1418 $r = Item::selectForUser(local_user(), [], $condition, $params);
1420 $items = Item::inArray($r);
1422 $o = conversation($a, $items, $pager, 'contact-posts', false);
1426 $o .= $pager->renderMinimal(count($items));
1433 * @brief Returns the account type name
1435 * The function can be called with either the user or the contact array
1437 * @param array $contact contact or user array
1440 public static function getAccountType(array $contact)
1442 // There are several fields that indicate that the contact or user is a forum
1443 // "page-flags" is a field in the user table,
1444 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1445 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1446 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1447 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1448 || (isset($contact['forum']) && intval($contact['forum']))
1449 || (isset($contact['prv']) && intval($contact['prv']))
1450 || (isset($contact['community']) && intval($contact['community']))
1452 $type = self::ACCOUNT_TYPE_COMMUNITY;
1454 $type = self::ACCOUNT_TYPE_PERSON;
1457 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1458 if (isset($contact["contact-type"])) {
1459 $type = $contact["contact-type"];
1462 if (isset($contact["account-type"])) {
1463 $type = $contact["account-type"];
1467 case self::ACCOUNT_TYPE_ORGANISATION:
1468 $account_type = L10n::t("Organisation");
1471 case self::ACCOUNT_TYPE_NEWS:
1472 $account_type = L10n::t('News');
1475 case self::ACCOUNT_TYPE_COMMUNITY:
1476 $account_type = L10n::t("Forum");
1484 return $account_type;
1488 * @brief Blocks a contact
1493 public static function block($uid)
1495 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1501 * @brief Unblocks a contact
1506 public static function unblock($uid)
1508 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1514 * @brief Updates the avatar links in a contact only if needed
1516 * @param string $avatar Link to avatar picture
1517 * @param int $uid User id of contact owner
1518 * @param int $cid Contact id
1519 * @param bool $force force picture update
1521 * @return array Returns array of the different avatar sizes
1523 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1525 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1526 if (!DBA::isResult($contact)) {
1529 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1532 if (($contact["avatar"] != $avatar) || $force) {
1533 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1538 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1542 // Update the public contact (contact id = 0)
1544 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1545 if (DBA::isResult($pcontact)) {
1546 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1558 * @param integer $id contact id
1559 * @param string $network Optional network we are probing for
1562 public static function updateFromProbe($id, $network = '')
1565 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1566 This will reliably kill your communication with Friendica contacts.
1569 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1570 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1571 if (!DBA::isResult($contact)) {
1575 $ret = Probe::uri($contact["url"], $network);
1577 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1578 if (($ret["network"] != $contact["network"]) && !in_array($ret["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, $network])) {
1584 // make sure to not overwrite existing values with blank entries
1585 foreach ($ret as $key => $val) {
1586 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1587 $ret[$key] = $contact[$key];
1590 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1601 'url' => $ret['url'],
1602 'nurl' => Strings::normaliseLink($ret['url']),
1603 'network' => $ret['network'],
1604 'addr' => $ret['addr'],
1605 'alias' => $ret['alias'],
1606 'batch' => $ret['batch'],
1607 'notify' => $ret['notify'],
1608 'poll' => $ret['poll'],
1609 'poco' => $ret['poco']
1614 // Update the corresponding gcontact entry
1615 PortableContact::lastUpdated($ret["url"]);
1621 * Takes a $uid and a url/handle and adds a new contact
1622 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1623 * dfrn_request page.
1625 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1628 * $return['success'] boolean true if successful
1629 * $return['message'] error text if success is false.
1631 * @brief Takes a $uid and a url/handle and adds a new contact
1633 * @param string $url
1634 * @param bool $interactive
1635 * @param string $network
1636 * @return boolean|string
1638 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1640 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1644 // remove ajax junk, e.g. Twitter
1645 $url = str_replace('/#!/', '/', $url);
1647 if (!Network::isUrlAllowed($url)) {
1648 $result['message'] = L10n::t('Disallowed profile URL.');
1652 if (Network::isUrlBlocked($url)) {
1653 $result['message'] = L10n::t('Blocked domain');
1658 $result['message'] = L10n::t('Connect URL missing.');
1662 $arr = ['url' => $url, 'contact' => []];
1664 Hook::callAll('follow', $arr);
1667 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1671 if (!empty($arr['contact']['name'])) {
1672 $ret = $arr['contact'];
1674 $ret = Probe::uri($url, $network, $uid, false);
1677 if (($network != '') && ($ret['network'] != $network)) {
1678 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1682 // check if we already have a contact
1683 // the poll url is more reliable than the profile url, as we may have
1684 // indirect links or webfinger links
1686 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1687 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1688 if (!DBA::isResult($contact)) {
1689 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1690 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1693 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1695 if (strlen($a->getURLPath())) {
1696 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1698 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1701 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1705 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1706 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1707 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1711 // This extra param just confuses things, remove it
1712 if ($ret['network'] === Protocol::DIASPORA) {
1713 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1716 // do we have enough information?
1717 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1718 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1719 if (empty($ret['poll'])) {
1720 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1722 if (empty($ret['name'])) {
1723 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1725 if (empty($ret['url'])) {
1726 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1728 if (strpos($url, '@') !== false) {
1729 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1730 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1735 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1736 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1737 $ret['notify'] = '';
1740 if (!$ret['notify']) {
1741 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1744 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1746 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1748 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1750 $pending = in_array($ret['network'], [Protocol::ACTIVITYPUB]);
1752 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1756 if (DBA::isResult($contact)) {
1758 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1760 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1761 DBA::update('contact', $fields, ['id' => $contact['id']]);
1763 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1765 // create contact record
1766 DBA::insert('contact', [
1768 'created' => DateTimeFormat::utcNow(),
1769 'url' => $ret['url'],
1770 'nurl' => Strings::normaliseLink($ret['url']),
1771 'addr' => $ret['addr'],
1772 'alias' => $ret['alias'],
1773 'batch' => $ret['batch'],
1774 'notify' => $ret['notify'],
1775 'poll' => $ret['poll'],
1776 'poco' => $ret['poco'],
1777 'name' => $ret['name'],
1778 'nick' => $ret['nick'],
1779 'network' => $ret['network'],
1780 'pubkey' => $ret['pubkey'],
1781 'rel' => $new_relation,
1782 'priority'=> $ret['priority'],
1783 'writable'=> $writeable,
1784 'hidden' => $hidden,
1787 'pending' => $pending,
1792 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1793 if (!DBA::isResult($contact)) {
1794 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1798 $contact_id = $contact['id'];
1799 $result['cid'] = $contact_id;
1801 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1803 // Update the avatar
1804 self::updateAvatar($ret['photo'], $uid, $contact_id);
1806 // pull feed and consume it, which should subscribe to the hub.
1808 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1810 $owner = User::getOwnerDataById($uid);
1812 if (DBA::isResult($owner)) {
1813 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1814 // create a follow slap
1816 $item['verb'] = ACTIVITY_FOLLOW;
1817 $item['follow'] = $contact["url"];
1819 $item['title'] = '';
1822 $item['attach'] = '';
1824 $slap = OStatus::salmon($item, $owner);
1826 if (!empty($contact['notify'])) {
1827 Salmon::slapper($owner, $contact['notify'], $slap);
1829 } elseif ($contact['network'] == Protocol::DIASPORA) {
1830 $ret = Diaspora::sendShare($a->user, $contact);
1831 Logger::log('share returns: ' . $ret);
1832 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1833 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
1834 if (empty($activity_id)) {
1835 // This really should never happen
1839 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
1840 Logger::log('Follow returns: ' . $ret);
1844 $result['success'] = true;
1849 * @brief Updated contact's SSL policy
1851 * @param array $contact Contact array
1852 * @param string $new_policy New policy, valid: self,full
1854 * @return array Contact array with updated values
1856 public static function updateSslPolicy(array $contact, $new_policy)
1858 $ssl_changed = false;
1859 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1860 $ssl_changed = true;
1861 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1862 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1863 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1864 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1865 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1866 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1869 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1870 $ssl_changed = true;
1871 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1872 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1873 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1874 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1875 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1876 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1880 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1881 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1882 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1883 DBA::update('contact', $fields, ['id' => $contact['id']]);
1889 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1890 // Should always be set
1891 if (empty($datarray['author-id'])) {
1895 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1896 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1897 if (!DBA::isResult($pub_contact)) {
1898 // Should never happen
1902 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1903 $name = $pub_contact['name'];
1904 $photo = $pub_contact['photo'];
1905 $nick = $pub_contact['nick'];
1906 $network = $pub_contact['network'];
1908 if (is_array($contact)) {
1909 if (($contact['rel'] == self::SHARING)
1910 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1911 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1912 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1915 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1916 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1919 // send email notification to owner?
1921 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
1922 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
1925 // create contact record
1926 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1927 `blocked`, `readonly`, `pending`, `writable`)
1928 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1929 intval($importer['uid']),
1930 DBA::escape(DateTimeFormat::utcNow()),
1932 DBA::escape(Strings::normaliseLink($url)),
1935 DBA::escape($photo),
1936 DBA::escape($network),
1937 intval(self::FOLLOWER)
1941 'id' => DBA::lastInsertId(),
1942 'network' => $network,
1948 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1950 /// @TODO Encapsulate this into a function/method
1951 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1952 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1953 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1954 // create notification
1955 $hash = Strings::getRandomHex();
1957 if (is_array($contact_record)) {
1958 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1959 'blocked' => false, 'knowyou' => false,
1960 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1963 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1965 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1966 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1969 'type' => NOTIFY_INTRO,
1970 'notify_flags' => $user['notify-flags'],
1971 'language' => $user['language'],
1972 'to_name' => $user['username'],
1973 'to_email' => $user['email'],
1974 'uid' => $user['uid'],
1975 'link' => System::baseUrl() . '/notifications/intro',
1976 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1977 'source_link' => $contact_record['url'],
1978 'source_photo' => $contact_record['photo'],
1979 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1984 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1985 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1986 DBA::update('contact', ['pending' => false], $condition);
1988 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
1990 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1991 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1997 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1999 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2000 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2002 Contact::remove($contact['id']);
2006 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2008 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2009 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2011 Contact::remove($contact['id']);
2016 * @brief Create a birthday event.
2018 * Update the year and the birthday.
2020 public static function updateBirthdays()
2024 AND `bd` > "0001-01-01"
2025 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2026 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2027 AND NOT `contact`.`pending`
2028 AND NOT `contact`.`hidden`
2029 AND NOT `contact`.`blocked`
2030 AND NOT `contact`.`archive`
2031 AND NOT `contact`.`deleted`',
2036 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2038 while ($contact = DBA::fetch($contacts)) {
2039 Logger::log('update_contact_birthday: ' . $contact['bd']);
2041 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2043 if (Event::createBirthday($contact, $nextbd)) {
2047 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2048 ['id' => $contact['id']]
2055 * Remove the unavailable contact ids from the provided list
2057 * @param array $contact_ids Contact id list
2059 public static function pruneUnavailable(array &$contact_ids)
2061 if (empty($contact_ids)) {
2065 $str = DBA::escape(implode(',', $contact_ids));
2067 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2070 while($contact = DBA::fetch($stmt)) {
2071 $return[] = $contact['id'];
2076 $contact_ids = $return;
2080 * @brief Returns a magic link to authenticate remote visitors
2082 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2084 * @param string $contact_url The address of the target contact profile
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 magicLink($contact_url, $url = '')
2091 if (!local_user() && !remote_user()) {
2092 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2095 $cid = self::getIdForURL($contact_url, 0, true);
2097 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2100 return self::magicLinkbyId($cid, $url);
2104 * @brief Returns a magic link to authenticate remote visitors
2106 * @param integer $cid The contact id of the target contact profile
2107 * @param integer $url An url that we will be redirected to after the authentication
2109 * @return string with "redir" link
2111 public static function magicLinkbyId($cid, $url = '')
2113 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2115 return self::magicLinkbyContact($contact, $url);
2119 * @brief Returns a magic link to authenticate remote visitors
2121 * @param array $contact The contact array with "uid", "network" and "url"
2122 * @param string $url An url that we will be redirected to after the authentication
2124 * @return string with "redir" link
2126 public static function magicLinkbyContact($contact, $url = '')
2128 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2129 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2132 // Only redirections to the same host do make sense
2133 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2137 if ($contact['uid'] != 0) {
2138 return self::magicLink($contact['url'], $url);
2141 $redirect = 'redir/' . $contact['id'];
2144 $redirect .= '?url=' . $url;