3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Profile;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Protocol\DFRN;
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;
28 require_once 'boot.php';
29 require_once 'include/dba.php';
30 require_once 'include/text.php';
33 * @brief functions for interacting with a contact
35 class Contact extends BaseObject
38 * @name page/profile types
40 * PAGE_NORMAL is a typical personal profile account
41 * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
42 * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
43 * write access to wall and comments (no email and not included in page owner's ACL lists)
44 * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
48 const PAGE_NORMAL = 0;
49 const PAGE_SOAPBOX = 1;
50 const PAGE_COMMUNITY = 2;
51 const PAGE_FREELOVE = 3;
53 const PAGE_PRVGROUP = 5;
61 * ACCOUNT_TYPE_PERSON - the account belongs to a person
62 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
64 * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
65 * Associated page type: PAGE_SOAPBOX
67 * ACCOUNT_TYPE_NEWS - the account is a news reflector
68 * Associated page type: PAGE_SOAPBOX
70 * ACCOUNT_TYPE_COMMUNITY - the account is community forum
71 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
73 * ACCOUNT_TYPE_RELAY - the account is a relay
74 * This will only be assigned to contacts, not to user accounts
77 const ACCOUNT_TYPE_PERSON = 0;
78 const ACCOUNT_TYPE_ORGANISATION = 1;
79 const ACCOUNT_TYPE_NEWS = 2;
80 const ACCOUNT_TYPE_COMMUNITY = 3;
81 const ACCOUNT_TYPE_RELAY = 4;
100 * @brief Returns the contact id for the user and the public contact id for a given contact id
102 * @param int $cid Either public contact id or user's contact id
103 * @param int $uid User ID
105 * @return array with public and user's contact id
107 private static function getPublicAndUserContacID($cid, $uid)
109 if (empty($uid) || empty($cid)) {
113 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
114 if (!DBA::isResult($contact)) {
118 // We quit when the user id don't match the user id of the provided contact
119 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
123 if ($contact['uid'] != 0) {
124 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
128 $ucid = $contact['id'];
130 $pcid = $contact['id'];
131 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
134 return ['public' => $pcid, 'user' => $ucid];
138 * @brief Block contact id for user id
140 * @param int $cid Either public contact id or user's contact id
141 * @param int $uid User ID
142 * @param boolean $blocked Is the contact blocked or unblocked?
144 public static function setBlockedForUser($cid, $uid, $blocked)
146 $cdata = self::getPublicAndUserContacID($cid, $uid);
151 if ($cdata['user'] != 0) {
152 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
155 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
159 * @brief Returns "block" state for contact id and user id
161 * @param int $cid Either public contact id or user's contact id
162 * @param int $uid User ID
164 * @return boolean is the contact id blocked for the given user?
166 public static function isBlockedByUser($cid, $uid)
168 $cdata = self::getPublicAndUserContacID($cid, $uid);
173 $public_blocked = false;
175 if (!empty($cdata['public'])) {
176 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
177 if (DBA::isResult($public_contact)) {
178 $public_blocked = $public_contact['blocked'];
182 $user_blocked = $public_blocked;
184 if (!empty($cdata['user'])) {
185 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
186 if (DBA::isResult($user_contact)) {
187 $user_blocked = $user_contact['blocked'];
191 if ($user_blocked != $public_blocked) {
192 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
195 return $user_blocked;
199 * @brief Ignore contact id for user id
201 * @param int $cid Either public contact id or user's contact id
202 * @param int $uid User ID
203 * @param boolean $ignored Is the contact ignored or unignored?
205 public static function setIgnoredForUser($cid, $uid, $ignored)
207 $cdata = self::getPublicAndUserContacID($cid, $uid);
212 if ($cdata['user'] != 0) {
213 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
216 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
220 * @brief Returns "ignore" state for contact id and user id
222 * @param int $cid Either public contact id or user's contact id
223 * @param int $uid User ID
225 * @return boolean is the contact id ignored for the given user?
227 public static function isIgnoredByUser($cid, $uid)
229 $cdata = self::getPublicAndUserContacID($cid, $uid);
234 $public_ignored = false;
236 if (!empty($cdata['public'])) {
237 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
238 if (DBA::isResult($public_contact)) {
239 $public_ignored = $public_contact['ignored'];
243 $user_ignored = $public_ignored;
245 if (!empty($cdata['user'])) {
246 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
247 if (DBA::isResult($user_contact)) {
248 $user_ignored = $user_contact['readonly'];
252 if ($user_ignored != $public_ignored) {
253 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
256 return $user_ignored;
260 * @brief Set "collapsed" for contact id and user id
262 * @param int $cid Either public contact id or user's contact id
263 * @param int $uid User ID
264 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
266 public static function setCollapsedForUser($cid, $uid, $collapsed)
268 $cdata = self::getPublicAndUserContacID($cid, $uid);
273 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
277 * @brief Returns "collapsed" state for contact id and user id
279 * @param int $cid Either public contact id or user's contact id
280 * @param int $uid User ID
282 * @return boolean is the contact id blocked for the given user?
284 public static function isCollapsedByUser($cid, $uid)
286 $cdata = self::getPublicAndUserContacID($cid, $uid);
293 if (!empty($cdata['public'])) {
294 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
295 if (DBA::isResult($public_contact)) {
296 $collapsed = $public_contact['collapsed'];
304 * @brief Returns a list of contacts belonging in a group
309 public static function getByGroupId($gid)
314 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
316 INNER JOIN `group_member`
317 ON `contact`.`id` = `group_member`.`contact-id`
319 AND `contact`.`uid` = ?
320 AND NOT `contact`.`self`
321 AND NOT `contact`.`blocked`
322 AND NOT `contact`.`pending`
323 ORDER BY `contact`.`name` ASC',
328 if (DBA::isResult($stmt)) {
329 $return = DBA::toArray($stmt);
337 * @brief Returns the count of OStatus contacts in a group
342 public static function getOStatusCountByGroupId($gid)
346 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
348 INNER JOIN `group_member`
349 ON `contact`.`id` = `group_member`.`contact-id`
351 AND `contact`.`uid` = ?
352 AND `contact`.`network` = ?
353 AND `contact`.`notify` != ""',
358 $return = $contacts['count'];
365 * Creates the self-contact for the provided user id
368 * @return bool Operation success
370 public static function createSelfFromUserId($uid)
372 // Only create the entry if it doesn't exist yet
373 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
377 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
378 if (!DBA::isResult($user)) {
382 $return = DBA::insert('contact', [
383 'uid' => $user['uid'],
384 'created' => DateTimeFormat::utcNow(),
386 'name' => $user['username'],
387 'nick' => $user['nickname'],
388 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
389 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
390 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
393 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
394 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
395 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
396 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
397 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
398 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
399 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
400 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
401 'name-date' => DateTimeFormat::utcNow(),
402 'uri-date' => DateTimeFormat::utcNow(),
403 'avatar-date' => DateTimeFormat::utcNow(),
411 * Updates the self-contact for the provided user id
414 * @param boolean $update_avatar Force the avatar update
416 public static function updateSelfFromUserID($uid, $update_avatar = false)
418 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
419 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'nurl'];
420 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
421 if (!DBA::isResult($self)) {
425 $fields = ['nickname', 'page-flags', 'account-type'];
426 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
427 if (!DBA::isResult($user)) {
431 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
432 'country-name', 'gender', 'pub_keywords', 'xmpp'];
433 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
434 if (!DBA::isResult($profile)) {
438 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
439 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
440 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
441 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
442 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
444 $avatar = DBA::selectFirst('photo', ['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
445 if (DBA::isResult($avatar)) {
446 if ($update_avatar) {
447 $fields['avatar-date'] = DateTimeFormat::utcNow();
450 // Creating the path to the avatar, beginning with the file suffix
451 $types = Image::supportedTypes();
452 if (isset($types[$avatar['type']])) {
453 $file_suffix = $types[$avatar['type']];
455 $file_suffix = 'jpg';
458 // We are adding a timestamp value so that other systems won't use cached content
459 $timestamp = strtotime($fields['avatar-date']);
461 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
462 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
464 $fields['photo'] = $prefix . '4' . $suffix;
465 $fields['thumb'] = $prefix . '5' . $suffix;
466 $fields['micro'] = $prefix . '6' . $suffix;
468 // We hadn't found a photo entry, so we use the default avatar
469 $fields['photo'] = System::baseUrl() . '/images/person-175.jpg';
470 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
471 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
474 $fields['forum'] = $user['page-flags'] == self::PAGE_COMMUNITY;
475 $fields['prv'] = $user['page-flags'] == self::PAGE_PRVGROUP;
477 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
478 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
479 $fields['nurl'] = normalise_link($fields['url']);
480 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
481 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
482 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
483 $fields['poll'] = System::baseUrl() . '/dfrn_poll/' . $user['nickname'];
484 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
485 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
489 foreach ($fields as $field => $content) {
490 if (isset($self[$field]) && $self[$field] != $content) {
496 $fields['name-date'] = DateTimeFormat::utcNow();
497 DBA::update('contact', $fields, ['id' => $self['id']]);
499 // Update the public contact as well
500 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
502 // Update the profile
503 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
504 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
505 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
510 * @brief Marks a contact for removal
512 * @param int $id contact id
515 public static function remove($id)
517 // We want just to make sure that we don't delete our "self" contact
518 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
519 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
523 // Archive the contact
524 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM], ['id' => $id]);
526 // Delete it in the background
527 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
531 * @brief Sends an unfriend message. Does not remove the contact
533 * @param array $user User unfriending
534 * @param array $contact Contact unfriended
535 * @param boolean $dissolve Remove the contact on the remote side
538 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
540 if (($contact['network'] == Protocol::DFRN) && $dissolve) {
541 DFRN::deliver($user, $contact, 'placeholder', true);
542 } elseif (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
543 // create an unfollow slap
545 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
546 $item['follow'] = $contact["url"];
551 $item['attach'] = '';
552 $slap = OStatus::salmon($item, $user);
554 if (!empty($contact['notify'])) {
555 Salmon::slapper($user, $contact['notify'], $slap);
557 } elseif ($contact['network'] == Protocol::DIASPORA) {
558 Diaspora::sendUnshare($user, $contact);
559 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
560 ActivityPub::transmitContactUndo($contact['url'], $user['uid']);
563 ActivityPub::transmitContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
569 * @brief Marks a contact for archival after a communication issue delay
571 * Contact has refused to recognise us as a friend. We will start a countdown.
572 * If they still don't recognise us in 32 days, the relationship is over,
573 * and we won't waste any more time trying to communicate with them.
574 * This provides for the possibility that their database is temporarily messed
575 * up or some other transient event and that there's a possibility we could recover from it.
577 * @param array $contact contact to mark for archival
580 public static function markForArchival(array $contact)
582 if (!isset($contact['url']) && !empty($contact['id'])) {
583 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
584 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
585 if (!DBA::isResult($contact)) {
588 } elseif (!isset($contact['url'])) {
589 logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG);
592 // Contact already archived or "self" contact? => nothing to do
593 if ($contact['archive'] || $contact['self']) {
597 if ($contact['term-date'] <= NULL_DATE) {
598 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
599 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
602 * We really should send a notification to the owner after 2-3 weeks
603 * so they won't be surprised when the contact vanishes and can take
604 * remedial action if this was a serious mistake or glitch
607 /// @todo Check for contact vitality via probing
608 $archival_days = Config::get('system', 'archival_days', 32);
610 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
611 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
612 /* Relationship is really truly dead. archive them rather than
613 * delete, though if the owner tries to unarchive them we'll start
614 * the whole process over again.
616 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
617 DBA::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
623 * @brief Cancels the archival countdown
625 * @see Contact::markForArchival()
627 * @param array $contact contact to be unmarked for archival
630 public static function unmarkForArchival(array $contact)
632 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
633 $exists = DBA::exists('contact', $condition);
635 // We don't need to update, we never marked this contact for archival
640 if (!isset($contact['url']) && !empty($contact['id'])) {
641 $fields = ['id', 'url', 'batch'];
642 $contact = DBA::selectFirst('contact', [], ['id' => $contact['id']]);
643 if (!DBA::isResult($contact)) {
648 // It's a miracle. Our dead contact has inexplicably come back to life.
649 $fields = ['term-date' => NULL_DATE, 'archive' => false];
650 DBA::update('contact', $fields, ['id' => $contact['id']]);
651 DBA::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
653 if (!empty($contact['batch'])) {
654 $condition = ['batch' => $contact['batch'], 'contact-type' => self::ACCOUNT_TYPE_RELAY];
655 DBA::update('contact', $fields, $condition);
660 * @brief Get contact data for a given profile link
662 * The function looks at several places (contact table and gcontact table) for the contact
663 * It caches its result for the same script execution to prevent duplicate calls
665 * @param string $url The profile link
666 * @param int $uid User id
667 * @param array $default If not data was found take this data as default value
669 * @return array Contact data
671 public static function getDetailsByURL($url, $uid = -1, array $default = [])
683 if (isset($cache[$url][$uid])) {
684 return $cache[$url][$uid];
687 $ssl_url = str_replace('http://', 'https://', $url);
689 // Fetch contact data from the contact table for the given user
690 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
691 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
692 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
693 $r = DBA::toArray($s);
695 // Fetch contact data from the contact table for the given user, checking with the alias
696 if (!DBA::isResult($r)) {
697 $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`,
698 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
699 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
700 $r = DBA::toArray($s);
703 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
704 if (!DBA::isResult($r)) {
705 $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`,
706 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
707 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
708 $r = DBA::toArray($s);
711 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
712 if (!DBA::isResult($r)) {
713 $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`,
714 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
715 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
716 $r = DBA::toArray($s);
719 // Fetch the data from the gcontact table
720 if (!DBA::isResult($r)) {
721 $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`,
722 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
723 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
724 $r = DBA::toArray($s);
727 if (DBA::isResult($r)) {
728 // If there is more than one entry we filter out the connector networks
730 foreach ($r as $id => $result) {
731 if ($result["network"] == Protocol::STATUSNET) {
737 $profile = array_shift($r);
739 // "bd" always contains the upcoming birthday of a contact.
740 // "birthday" might contain the birthday including the year of birth.
741 if ($profile["birthday"] > '0001-01-01') {
742 $bd_timestamp = strtotime($profile["birthday"]);
743 $month = date("m", $bd_timestamp);
744 $day = date("d", $bd_timestamp);
746 $current_timestamp = time();
747 $current_year = date("Y", $current_timestamp);
748 $current_month = date("m", $current_timestamp);
749 $current_day = date("d", $current_timestamp);
751 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
752 $current = $current_year . "-" . $current_month . "-" . $current_day;
754 if ($profile["bd"] < $current) {
755 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
758 $profile["bd"] = '0001-01-01';
764 if (empty($profile["photo"]) && isset($default["photo"])) {
765 $profile["photo"] = $default["photo"];
768 if (empty($profile["name"]) && isset($default["name"])) {
769 $profile["name"] = $default["name"];
772 if (empty($profile["network"]) && isset($default["network"])) {
773 $profile["network"] = $default["network"];
776 if (empty($profile["thumb"]) && isset($profile["photo"])) {
777 $profile["thumb"] = $profile["photo"];
780 if (empty($profile["micro"]) && isset($profile["thumb"])) {
781 $profile["micro"] = $profile["thumb"];
784 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
785 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
787 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
790 // Show contact details of Diaspora contacts only if connected
791 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
792 $profile["location"] = "";
793 $profile["about"] = "";
794 $profile["gender"] = "";
795 $profile["birthday"] = '0001-01-01';
798 $cache[$url][$uid] = $profile;
804 * @brief Get contact data for a given address
806 * The function looks at several places (contact table and gcontact table) for the contact
808 * @param string $addr The profile link
809 * @param int $uid User id
811 * @return array Contact data
813 public static function getDetailsByAddr($addr, $uid = -1)
825 // Fetch contact data from the contact table for the given user
826 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
827 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
828 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
832 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
833 if (!DBA::isResult($r)) {
834 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
835 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
836 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
841 // Fetch the data from the gcontact table
842 if (!DBA::isResult($r)) {
843 $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`,
844 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
845 FROM `gcontact` WHERE `addr` = '%s'",
850 if (!DBA::isResult($r)) {
851 $data = Probe::uri($addr);
853 $profile = self::getDetailsByURL($data['url'], $uid);
862 * @brief Returns the data array for the photo menu of a given contact
864 * @param array $contact contact
865 * @param int $uid optional, default 0
868 public static function photoMenu(array $contact, $uid = 0)
870 // @todo Unused, to be removed
878 $contact_drop_link = '';
885 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
887 $profile_link = self::magicLink($contact['url']);
888 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
893 // Look for our own contact if the uid doesn't match and isn't public
894 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
895 if (DBA::isResult($contact_own)) {
896 return self::photoMenu($contact_own, $uid);
901 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
903 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
905 $profile_link = $contact['url'];
908 if ($profile_link === 'mailbox') {
913 $status_link = $profile_link . '?url=status';
914 $photos_link = $profile_link . '?url=photos';
915 $profile_link = $profile_link . '?url=profile';
918 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
919 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
922 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
923 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
926 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
928 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/conversations';
930 if (!$contact['self']) {
931 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
936 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
938 if (empty($contact['uid'])) {
939 $connlnk = 'follow/?url=' . $contact['url'];
941 'profile' => [L10n::t('View Profile'), $profile_link, true],
942 'network' => [L10n::t('Network Posts'), $posts_link, false],
943 'edit' => [L10n::t('View Contact'), $contact_url, false],
944 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
948 'status' => [L10n::t('View Status'), $status_link, true],
949 'profile' => [L10n::t('View Profile'), $profile_link, true],
950 'photos' => [L10n::t('View Photos'), $photos_link, true],
951 'network' => [L10n::t('Network Posts'), $posts_link, false],
952 'edit' => [L10n::t('View Contact'), $contact_url, false],
953 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
954 'pm' => [L10n::t('Send PM'), $pm_url, false],
955 'poke' => [L10n::t('Poke'), $poke_link, false],
959 $args = ['contact' => $contact, 'menu' => &$menu];
961 Addon::callHooks('contact_photo_menu', $args);
965 foreach ($menu as $menuname => $menuitem) {
966 if ($menuitem[1] != '') {
967 $menucondensed[$menuname] = $menuitem;
971 return $menucondensed;
975 * @brief Returns ungrouped contact count or list for user
977 * Returns either the total number of ungrouped contacts for the given user
978 * id or a paginated list of ungrouped contacts.
980 * @param int $uid uid
981 * @param int $start optional, default 0
982 * @param int $count optional, default 0
986 public static function getUngroupedList($uid)
995 SELECT DISTINCT(`contact-id`)
997 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
998 WHERE `group`.`uid` = %d
999 )", intval($uid), intval($uid));
1003 * @brief Fetch the contact id for a given URL and user
1005 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1006 * `addr` or `alias`.
1008 * If there's no record and we aren't looking for a public contact, we quit.
1009 * If there's one, we check that it isn't time to update the picture else we
1010 * directly return the found contact id.
1012 * Second, we probe the provided $url whether it's http://server.tld/profile or
1013 * nick@server.tld. We quit if we can't get any info back.
1015 * Third, we create the contact record if it doesn't exist
1017 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1018 * if there's any updates
1020 * @param string $url Contact URL
1021 * @param integer $uid The user id for the contact (0 = public contact)
1022 * @param boolean $no_update Don't update the contact
1023 * @param array $default Default value for creating the contact when every else fails
1025 * @return integer Contact ID
1027 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [])
1029 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
1037 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1038 // We first try the nurl (http://server.tld/nick), most common case
1039 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
1041 // Then the addr (nick@server.tld)
1042 if (!DBA::isResult($contact)) {
1043 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
1046 // Then the alias (which could be anything)
1047 if (!DBA::isResult($contact)) {
1048 // The link could be provided as http although we stored it as https
1049 $ssl_url = str_replace('http://', 'https://', $url);
1050 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
1051 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
1054 if (DBA::isResult($contact)) {
1055 $contact_id = $contact["id"];
1057 // Update the contact every 7 days
1058 $update_contact = ($contact['avatar-date'] < DateTimeFormat::utc('now -7 days'));
1060 // We force the update if the avatar is empty
1061 if (!x($contact, 'avatar')) {
1062 $update_contact = true;
1064 if (!$update_contact || $no_update) {
1067 } elseif ($uid != 0) {
1068 // Non-existing user-specific contact, exiting
1072 // When we don't want to update, we look if some of our users already know this contact
1074 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1075 'photo', 'keywords', 'location', 'about', 'network',
1076 'priority', 'batch', 'request', 'confirm', 'poco'];
1077 $data = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1079 if (DBA::isResult($data)) {
1080 // For security reasons we don't fetch key data from our users
1081 $data["pubkey"] = '';
1088 $data = Probe::uri($url, "", $uid);
1090 // Ensure that there is a gserver entry
1091 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1092 PortableContact::checkServer($data['baseurl']);
1096 // Last try in gcontact for unsupported networks
1097 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1102 // Get data from the gcontact table
1103 $fields = ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'];
1104 $contact = DBA::selectFirst('gcontact', $fields, ['nurl' => normalise_link($url)]);
1105 if (!DBA::isResult($contact)) {
1106 $contact = DBA::selectFirst('contact', $fields, ['nurl' => normalise_link($url)]);
1109 if (!DBA::isResult($contact)) {
1110 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1111 'photo', 'keywords', 'location', 'about', 'network',
1112 'priority', 'batch', 'request', 'confirm', 'poco'];
1113 $contact = DBA::selectFirst('contact', $fields, ['addr' => $url]);
1116 if (!DBA::isResult($contact)) {
1117 // The link could be provided as http although we stored it as https
1118 $ssl_url = str_replace('http://', 'https://', $url);
1119 $condition = ['alias' => [$url, normalise_link($url), $ssl_url]];
1120 $contact = DBA::selectFirst('contact', $fields, $condition);
1123 if (!DBA::isResult($contact)) {
1124 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1125 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1126 $condition = ['url' => [$url, normalise_link($url), $ssl_url]];
1127 $contact = DBA::selectFirst('fcontact', $fields, $condition);
1130 if (!empty($default)) {
1131 $contact = $default;
1134 if (!DBA::isResult($contact)) {
1137 $data = array_merge($data, $contact);
1141 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
1142 $contact_id = self::getIdForURL($data["alias"], $uid, true);
1145 $url = $data["url"];
1147 DBA::insert('contact', [
1149 'created' => DateTimeFormat::utcNow(),
1150 'url' => $data["url"],
1151 'nurl' => normalise_link($data["url"]),
1152 'addr' => $data["addr"],
1153 'alias' => $data["alias"],
1154 'notify' => $data["notify"],
1155 'poll' => $data["poll"],
1156 'name' => $data["name"],
1157 'nick' => $data["nick"],
1158 'photo' => $data["photo"],
1159 'keywords' => $data["keywords"],
1160 'location' => $data["location"],
1161 'about' => $data["about"],
1162 'network' => $data["network"],
1163 'pubkey' => $data["pubkey"],
1164 'rel' => self::SHARING,
1165 'priority' => $data["priority"],
1166 'batch' => $data["batch"],
1167 'request' => $data["request"],
1168 'confirm' => $data["confirm"],
1169 'poco' => $data["poco"],
1170 'name-date' => DateTimeFormat::utcNow(),
1171 'uri-date' => DateTimeFormat::utcNow(),
1172 'avatar-date' => DateTimeFormat::utcNow(),
1179 $s = DBA::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
1180 $contacts = DBA::toArray($s);
1181 if (!DBA::isResult($contacts)) {
1185 $contact_id = $contacts[0]["id"];
1187 // Update the newly created contact from data in the gcontact table
1188 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
1189 if (DBA::isResult($gcontact)) {
1190 // Only use the information when the probing hadn't fetched these values
1191 if ($data['keywords'] != '') {
1192 unset($gcontact['keywords']);
1194 if ($data['location'] != '') {
1195 unset($gcontact['location']);
1197 if ($data['about'] != '') {
1198 unset($gcontact['about']);
1200 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1203 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1204 DBA::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
1205 normalise_link($data["url"]), $contact_id]);
1209 self::updateAvatar($data["photo"], $uid, $contact_id);
1211 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1212 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1214 // This condition should always be true
1215 if (!DBA::isResult($contact)) {
1219 $updated = ['addr' => $data['addr'],
1220 'alias' => $data['alias'],
1221 'url' => $data['url'],
1222 'nurl' => normalise_link($data['url']),
1223 'name' => $data['name'],
1224 'nick' => $data['nick']];
1226 if ($data['keywords'] != '') {
1227 $updated['keywords'] = $data['keywords'];
1229 if ($data['location'] != '') {
1230 $updated['location'] = $data['location'];
1233 // Update the technical stuff as well - if filled
1234 if ($data['notify'] != '') {
1235 $updated['notify'] = $data['notify'];
1237 if ($data['poll'] != '') {
1238 $updated['poll'] = $data['poll'];
1240 if ($data['batch'] != '') {
1241 $updated['batch'] = $data['batch'];
1243 if ($data['request'] != '') {
1244 $updated['request'] = $data['request'];
1246 if ($data['confirm'] != '') {
1247 $updated['confirm'] = $data['confirm'];
1249 if ($data['poco'] != '') {
1250 $updated['poco'] = $data['poco'];
1253 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1254 if (empty($contact['pubkey'])) {
1255 $updated['pubkey'] = $data['pubkey'];
1258 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
1259 $updated['uri-date'] = DateTimeFormat::utcNow();
1261 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1262 $updated['name-date'] = DateTimeFormat::utcNow();
1265 $updated['avatar-date'] = DateTimeFormat::utcNow();
1267 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1273 * @brief Checks if the contact is blocked
1275 * @param int $cid contact id
1277 * @return boolean Is the contact blocked?
1279 public static function isBlocked($cid)
1285 $blocked = DBA::selectFirst('contact', ['blocked'], ['id' => $cid]);
1286 if (!DBA::isResult($blocked)) {
1289 return (bool) $blocked['blocked'];
1293 * @brief Checks if the contact is hidden
1295 * @param int $cid contact id
1297 * @return boolean Is the contact hidden?
1299 public static function isHidden($cid)
1305 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1306 if (!DBA::isResult($hidden)) {
1309 return (bool) $hidden['hidden'];
1313 * @brief Returns posts from a given contact url
1315 * @param string $contact_url Contact URL
1317 * @return string posts in HTML
1319 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1321 $a = self::getApp();
1323 require_once 'include/conversation.php';
1325 // There are no posts with "uid = 0" with connector networks
1326 // This speeds up the query a lot
1327 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
1328 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
1329 DBA::escape(normalise_link($contact_url))
1332 if (!DBA::isResult($r)) {
1336 if (in_array($r[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1337 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1339 $sql = "`item`.`uid` = ?";
1342 $author_id = intval($r[0]["author-id"]);
1344 $contact = ($r[0]["contact-type"] == self::ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1347 $condition = ["`$contact` = ? AND `gravity` = ? AND " . $sql,
1348 $author_id, GRAVITY_PARENT, local_user()];
1350 $condition = ["`$contact` = ? AND `gravity` IN (?, ?) AND " . $sql,
1351 $author_id, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1354 $params = ['order' => ['created' => true],
1355 'limit' => [$a->pager['start'], $a->pager['itemspage']]];
1358 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1360 $items = Item::inArray($r);
1362 $o = conversation($a, $items, 'contacts', $update);
1364 $r = Item::selectForUser(local_user(), [], $condition, $params);
1366 $items = Item::inArray($r);
1368 $o = conversation($a, $items, 'contact-posts', false);
1372 $o .= alt_pager($a, count($items));
1379 * @brief Returns the account type name
1381 * The function can be called with either the user or the contact array
1383 * @param array $contact contact or user array
1386 public static function getAccountType(array $contact)
1388 // There are several fields that indicate that the contact or user is a forum
1389 // "page-flags" is a field in the user table,
1390 // "forum" and "prv" are used in the contact table. They stand for self::PAGE_COMMUNITY and self::PAGE_PRVGROUP.
1391 // "community" is used in the gcontact table and is true if the contact is self::PAGE_COMMUNITY or self::PAGE_PRVGROUP.
1392 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_COMMUNITY))
1393 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == self::PAGE_PRVGROUP))
1394 || (isset($contact['forum']) && intval($contact['forum']))
1395 || (isset($contact['prv']) && intval($contact['prv']))
1396 || (isset($contact['community']) && intval($contact['community']))
1398 $type = self::ACCOUNT_TYPE_COMMUNITY;
1400 $type = self::ACCOUNT_TYPE_PERSON;
1403 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1404 if (isset($contact["contact-type"])) {
1405 $type = $contact["contact-type"];
1408 if (isset($contact["account-type"])) {
1409 $type = $contact["account-type"];
1413 case self::ACCOUNT_TYPE_ORGANISATION:
1414 $account_type = L10n::t("Organisation");
1417 case self::ACCOUNT_TYPE_NEWS:
1418 $account_type = L10n::t('News');
1421 case self::ACCOUNT_TYPE_COMMUNITY:
1422 $account_type = L10n::t("Forum");
1430 return $account_type;
1434 * @brief Blocks a contact
1439 public static function block($uid)
1441 $return = DBA::update('contact', ['blocked' => true], ['id' => $uid]);
1447 * @brief Unblocks a contact
1452 public static function unblock($uid)
1454 $return = DBA::update('contact', ['blocked' => false], ['id' => $uid]);
1460 * @brief Updates the avatar links in a contact only if needed
1462 * @param string $avatar Link to avatar picture
1463 * @param int $uid User id of contact owner
1464 * @param int $cid Contact id
1465 * @param bool $force force picture update
1467 * @return array Returns array of the different avatar sizes
1469 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1471 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1472 if (!DBA::isResult($contact)) {
1475 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1478 if (($contact["avatar"] != $avatar) || $force) {
1479 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1484 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1488 // Update the public contact (contact id = 0)
1490 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1491 if (DBA::isResult($pcontact)) {
1492 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1504 * @param integer $id contact id
1505 * @param string $network Optional network we are probing for
1508 public static function updateFromProbe($id, $network = '')
1511 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1512 This will reliably kill your communication with Friendica contacts.
1515 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1516 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1517 if (!DBA::isResult($contact)) {
1521 $ret = Probe::uri($contact["url"], $network);
1523 // If Probe::uri fails the network code will be different
1524 if (($ret["network"] != $contact["network"]) && ($ret["network"] != $network)) {
1530 // make sure to not overwrite existing values with blank entries
1531 foreach ($ret as $key => $val) {
1532 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1533 $ret[$key] = $contact[$key];
1536 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1547 'url' => $ret['url'],
1548 'nurl' => normalise_link($ret['url']),
1549 'network' => $ret['network'],
1550 'addr' => $ret['addr'],
1551 'alias' => $ret['alias'],
1552 'batch' => $ret['batch'],
1553 'notify' => $ret['notify'],
1554 'poll' => $ret['poll'],
1555 'poco' => $ret['poco']
1560 // Update the corresponding gcontact entry
1561 PortableContact::lastUpdated($ret["url"]);
1567 * Takes a $uid and a url/handle and adds a new contact
1568 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1569 * dfrn_request page.
1571 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1574 * $return['success'] boolean true if successful
1575 * $return['message'] error text if success is false.
1577 * @brief Takes a $uid and a url/handle and adds a new contact
1579 * @param string $url
1580 * @param bool $interactive
1581 * @param string $network
1582 * @return boolean|string
1584 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1586 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1590 // remove ajax junk, e.g. Twitter
1591 $url = str_replace('/#!/', '/', $url);
1593 if (!Network::isUrlAllowed($url)) {
1594 $result['message'] = L10n::t('Disallowed profile URL.');
1598 if (Network::isUrlBlocked($url)) {
1599 $result['message'] = L10n::t('Blocked domain');
1604 $result['message'] = L10n::t('Connect URL missing.');
1608 $arr = ['url' => $url, 'contact' => []];
1610 Addon::callHooks('follow', $arr);
1613 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1617 if (x($arr['contact'], 'name')) {
1618 $ret = $arr['contact'];
1620 $ret = Probe::uri($url, $network, $uid, false);
1623 if (($network != '') && ($ret['network'] != $network)) {
1624 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1628 // check if we already have a contact
1629 // the poll url is more reliable than the profile url, as we may have
1630 // indirect links or webfinger links
1632 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], normalise_link($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1633 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1634 if (!DBA::isResult($contact)) {
1635 $condition = ['uid' => $uid, 'nurl' => normalise_link($url), 'network' => $ret['network'], 'pending' => false];
1636 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1639 if (($ret['network'] === Protocol::DFRN) && !DBA::isResult($contact)) {
1641 if (strlen($a->urlpath)) {
1642 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1644 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1647 goaway($ret['request'] . "&addr=$myaddr");
1651 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1652 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1653 $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1657 // This extra param just confuses things, remove it
1658 if ($ret['network'] === Protocol::DIASPORA) {
1659 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1662 // do we have enough information?
1664 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1665 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1666 if (!x($ret, 'poll')) {
1667 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1669 if (!x($ret, 'name')) {
1670 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1672 if (!x($ret, 'url')) {
1673 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1675 if (strpos($url, '@') !== false) {
1676 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1677 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1682 if ($ret['network'] === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1683 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1684 $ret['notify'] = '';
1687 if (!$ret['notify']) {
1688 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1691 $writeable = ((($ret['network'] === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1693 $subhub = (($ret['network'] === Protocol::OSTATUS) ? true : false);
1695 $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
1697 if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1701 if (DBA::isResult($contact)) {
1703 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1705 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1706 DBA::update('contact', $fields, ['id' => $contact['id']]);
1708 $new_relation = (in_array($ret['network'], [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1710 // create contact record
1711 DBA::insert('contact', [
1713 'created' => DateTimeFormat::utcNow(),
1714 'url' => $ret['url'],
1715 'nurl' => normalise_link($ret['url']),
1716 'addr' => $ret['addr'],
1717 'alias' => $ret['alias'],
1718 'batch' => $ret['batch'],
1719 'notify' => $ret['notify'],
1720 'poll' => $ret['poll'],
1721 'poco' => $ret['poco'],
1722 'name' => $ret['name'],
1723 'nick' => $ret['nick'],
1724 'network' => $ret['network'],
1725 'pubkey' => $ret['pubkey'],
1726 'rel' => $new_relation,
1727 'priority'=> $ret['priority'],
1728 'writable'=> $writeable,
1729 'hidden' => $hidden,
1737 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1738 if (!DBA::isResult($contact)) {
1739 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1743 $contact_id = $contact['id'];
1744 $result['cid'] = $contact_id;
1746 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1748 // Update the avatar
1749 self::updateAvatar($ret['photo'], $uid, $contact_id);
1751 // pull feed and consume it, which should subscribe to the hub.
1753 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1755 $owner = User::getOwnerDataById($uid);
1757 if (DBA::isResult($owner)) {
1758 if (in_array($contact['network'], [Protocol::OSTATUS, Protocol::DFRN])) {
1759 // create a follow slap
1761 $item['verb'] = ACTIVITY_FOLLOW;
1762 $item['follow'] = $contact["url"];
1764 $item['title'] = '';
1767 $item['attach'] = '';
1769 $slap = OStatus::salmon($item, $owner);
1771 if (!empty($contact['notify'])) {
1772 Salmon::slapper($owner, $contact['notify'], $slap);
1774 } elseif ($contact['network'] == Protocol::DIASPORA) {
1775 $ret = Diaspora::sendShare($a->user, $contact);
1776 logger('share returns: ' . $ret);
1777 } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
1778 $ret = ActivityPub::transmitActivity('Follow', $contact['url'], $uid);
1779 logger('Follow returns: ' . $ret);
1783 $result['success'] = true;
1788 * @brief Updated contact's SSL policy
1790 * @param array $contact Contact array
1791 * @param string $new_policy New policy, valid: self,full
1793 * @return array Contact array with updated values
1795 public static function updateSslPolicy(array $contact, $new_policy)
1797 $ssl_changed = false;
1798 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1799 $ssl_changed = true;
1800 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
1801 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
1802 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
1803 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
1804 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
1805 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
1808 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1809 $ssl_changed = true;
1810 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
1811 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
1812 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
1813 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
1814 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
1815 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
1819 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1820 'notify' => $contact['notify'], 'poll' => $contact['poll'],
1821 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1822 DBA::update('contact', $fields, ['id' => $contact['id']]);
1828 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
1829 // Should always be set
1830 if (empty($datarray['author-id'])) {
1834 $fields = ['url', 'name', 'nick', 'photo', 'network'];
1835 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
1836 if (!DBA::isResult($pub_contact)) {
1837 // Should never happen
1841 $url = defaults($datarray, 'author-link', $pub_contact['url']);
1842 $name = $pub_contact['name'];
1843 $photo = $pub_contact['photo'];
1844 $nick = $pub_contact['nick'];
1845 $network = $pub_contact['network'];
1847 if (is_array($contact)) {
1848 if (($contact['rel'] == self::SHARING)
1849 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
1850 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
1851 ['id' => $contact['id'], 'uid' => $importer['uid']]);
1854 if ($contact['network'] == Protocol::ACTIVITYPUB) {
1855 ActivityPub::transmitContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
1858 // send email notification to owner?
1860 if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
1861 logger('ignoring duplicated connection request from pending contact ' . $url);
1864 // create contact record
1865 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
1866 `blocked`, `readonly`, `pending`, `writable`)
1867 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
1868 intval($importer['uid']),
1869 DBA::escape(DateTimeFormat::utcNow()),
1871 DBA::escape(normalise_link($url)),
1874 DBA::escape($photo),
1875 DBA::escape($network),
1876 intval(self::FOLLOWER)
1880 'id' => DBA::lastInsertId(),
1881 'network' => $network,
1887 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
1889 /// @TODO Encapsulate this into a function/method
1890 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
1891 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
1892 if (DBA::isResult($user) && !in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1893 // create notification
1894 $hash = random_string();
1896 if (is_array($contact_record)) {
1897 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
1898 'blocked' => false, 'knowyou' => false,
1899 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
1902 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
1904 if (($user['notify-flags'] & NOTIFY_INTRO) &&
1905 in_array($user['page-flags'], [self::PAGE_NORMAL])) {
1908 'type' => NOTIFY_INTRO,
1909 'notify_flags' => $user['notify-flags'],
1910 'language' => $user['language'],
1911 'to_name' => $user['username'],
1912 'to_email' => $user['email'],
1913 'uid' => $user['uid'],
1914 'link' => System::baseUrl() . '/notifications/intro',
1915 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
1916 'source_link' => $contact_record['url'],
1917 'source_photo' => $contact_record['photo'],
1918 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
1923 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [self::PAGE_SOAPBOX, self::PAGE_FREELOVE, self::PAGE_COMMUNITY])) {
1924 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
1925 DBA::update('contact', ['pending' => false], $condition);
1930 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
1932 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
1933 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
1935 Contact::remove($contact['id']);
1939 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
1941 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
1942 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
1944 Contact::remove($contact['id']);
1949 * @brief Create a birthday event.
1951 * Update the year and the birthday.
1953 public static function updateBirthdays()
1955 // This only handles foreign or alien networks where a birthday has been provided.
1956 // In-network birthdays are handled within local_delivery
1958 $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
1959 if (DBA::isResult($r)) {
1960 foreach ($r as $rr) {
1961 logger('update_contact_birthday: ' . $rr['bd']);
1963 $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);
1966 * Add new birthday event for this person
1968 * $bdtext is just a readable placeholder in case the event is shared
1969 * with others. We will replace it during presentation to our $importer
1970 * to contain a sparkle link and perhaps a photo.
1973 // Check for duplicates
1974 $condition = ['uid' => $rr['uid'], 'cid' => $rr['id'],
1975 'start' => DateTimeFormat::utc($nextbd), 'type' => 'birthday'];
1976 if (DBA::exists('event', $condition)) {
1980 $bdtext = L10n::t('%s\'s birthday', $rr['name']);
1981 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $rr['url'] . ']' . $rr['name'] . '[/url]');
1983 q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`,`adjust`)
1984 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d' ) ", intval($rr['uid']), intval($rr['id']),
1985 DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utcNow()), DBA::escape(DateTimeFormat::utc($nextbd)),
1986 DBA::escape(DateTimeFormat::utc($nextbd . ' + 1 day ')), DBA::escape($bdtext), DBA::escape($bdtext2), DBA::escape('birthday'),
1991 q("UPDATE `contact` SET `bdyear` = '%s', `bd` = '%s' WHERE `uid` = %d AND `id` = %d", DBA::escape(substr($nextbd, 0, 4)),
1992 DBA::escape($nextbd), intval($rr['uid']), intval($rr['id'])
1999 * Remove the unavailable contact ids from the provided list
2001 * @param array $contact_ids Contact id list
2003 public static function pruneUnavailable(array &$contact_ids)
2005 if (empty($contact_ids)) {
2009 $str = DBA::escape(implode(',', $contact_ids));
2011 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2014 while($contact = DBA::fetch($stmt)) {
2015 $return[] = $contact['id'];
2020 $contact_ids = $return;
2024 * @brief Returns a magic link to authenticate remote visitors
2026 * @param string $contact_url The address of the target contact profile
2027 * @param integer $url An url that we will be redirected to after the authentication
2029 * @return string with "redir" link
2031 public static function magicLink($contact_url, $url = '')
2033 $cid = self::getIdForURL($contact_url, 0, true);
2035 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2038 return self::magicLinkbyId($cid, $url);
2042 * @brief Returns a magic link to authenticate remote visitors
2044 * @param integer $cid The contact id of the target contact profile
2045 * @param integer $url An url that we will be redirected to after the authentication
2047 * @return string with "redir" link
2049 public static function magicLinkbyId($cid, $url = '')
2051 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2053 return self::magicLinkbyContact($contact, $url);
2057 * @brief Returns a magic link to authenticate remote visitors
2059 * @param array $contact The contact array with "uid", "network" and "url"
2060 * @param integer $url An url that we will be redirected to after the authentication
2062 * @return string with "redir" link
2064 public static function magicLinkbyContact($contact, $url = '')
2066 if ($contact['network'] != Protocol::DFRN) {
2067 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2070 // Only redirections to the same host do make sense
2071 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2075 if ($contact['uid'] != 0) {
2076 return self::magicLink($contact['url'], $url);
2079 $redirect = 'redir/' . $contact['id'];
2082 $redirect .= '?url=' . $url;