4 * @file src/Model/Contact.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Core\Config;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Network\Probe;
16 use Friendica\Model\Photo;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\OStatus;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Protocol\Salmon;
24 require_once 'boot.php';
25 require_once 'include/dba.php';
26 require_once 'include/text.php';
29 * @brief functions for interacting with a contact
31 class Contact extends BaseObject
34 * @brief Returns a list of contacts belonging in a group
39 public static function getByGroupId($gid)
43 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
45 INNER JOIN `group_member`
46 ON `contact`.`id` = `group_member`.`contact-id`
48 AND `contact`.`uid` = ?
49 AND NOT `contact`.`self`
50 AND NOT `contact`.`blocked`
51 AND NOT `contact`.`pending`
52 ORDER BY `contact`.`name` ASC',
56 if (DBM::is_result($stmt)) {
57 $return = dba::inArray($stmt);
65 * @brief Returns the count of OStatus contacts in a group
70 public static function getOStatusCountByGroupId($gid)
74 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
76 INNER JOIN `group_member`
77 ON `contact`.`id` = `group_member`.`contact-id`
79 AND `contact`.`uid` = ?
80 AND `contact`.`network` = ?
81 AND `contact`.`notify` != ""',
86 $return = $contacts['count'];
94 * Creates the self-contact for the provided user id
97 * @return bool Operation success
99 public static function createSelfFromUserId($uid)
101 // Only create the entry if it doesn't exist yet
102 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
106 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
107 if (!DBM::is_result($user)) {
111 $return = dba::insert('contact', [
112 'uid' => $user['uid'],
113 'created' => datetime_convert(),
115 'name' => $user['username'],
116 'nick' => $user['nickname'],
117 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
118 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
119 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
122 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
123 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
124 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
125 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
126 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
127 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
128 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
129 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
130 'name-date' => datetime_convert(),
131 'uri-date' => datetime_convert(),
132 'avatar-date' => datetime_convert(),
140 * @brief Marks a contact for removal
142 * @param int $id contact id
145 public static function remove($id)
147 // We want just to make sure that we don't delete our "self" contact
148 $r = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
150 if (!DBM::is_result($r) || !intval($r['uid'])) {
154 $archive = PConfig::get($r['uid'], 'system', 'archive_removed_contacts');
156 dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
160 dba::delete('contact', array('id' => $id));
162 // Delete the rest in the background
163 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
167 * @brief Sends an unfriend message. Does not remove the contact
169 * @param array $user User unfriending
170 * @param array $contact Contact unfriended
173 public static function terminateFriendship(array $user, array $contact)
175 if ($contact['network'] === NETWORK_OSTATUS) {
176 // create an unfollow slap
178 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
179 $item['follow'] = $contact["url"];
180 $slap = OStatus::salmon($item, $user);
182 if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
183 Salmon::slapper($user, $contact['notify'], $slap);
185 } elseif ($contact['network'] === NETWORK_DIASPORA) {
186 Diaspora::sendUnshare($user, $contact);
187 } elseif ($contact['network'] === NETWORK_DFRN) {
188 DFRN::deliver($user, $contact, 'placeholder', 1);
193 * @brief Marks a contact for archival after a communication issue delay
195 * Contact has refused to recognise us as a friend. We will start a countdown.
196 * If they still don't recognise us in 32 days, the relationship is over,
197 * and we won't waste any more time trying to communicate with them.
198 * This provides for the possibility that their database is temporarily messed
199 * up or some other transient event and that there's a possibility we could recover from it.
201 * @param array $contact contact to mark for archival
204 public static function markForArchival(array $contact)
206 // Contact already archived or "self" contact? => nothing to do
207 if ($contact['archive'] || $contact['self']) {
211 if ($contact['term-date'] <= NULL_DATE) {
212 dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
214 if ($contact['url'] != '') {
215 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE));
219 * We really should send a notification to the owner after 2-3 weeks
220 * so they won't be surprised when the contact vanishes and can take
221 * remedial action if this was a serious mistake or glitch
224 /// @todo Check for contact vitality via probing
225 $expiry = $contact['term-date'] . ' + 32 days ';
226 if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
227 /* Relationship is really truly dead. archive them rather than
228 * delete, though if the owner tries to unarchive them we'll start
229 * the whole process over again.
231 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
233 if ($contact['url'] != '') {
234 dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url']), 'self' => false));
241 * @brief Cancels the archival countdown
243 * @see Contact::markForArchival()
245 * @param array $contact contact to be unmarked for archival
248 public static function unmarkForArchival(array $contact)
250 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE);
251 $exists = dba::exists('contact', $condition);
253 // We don't need to update, we never marked this contact for archival
258 // It's a miracle. Our dead contact has inexplicably come back to life.
259 $fields = array('term-date' => NULL_DATE, 'archive' => false);
260 dba::update('contact', $fields, array('id' => $contact['id']));
262 if ($contact['url'] != '') {
263 dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
268 * @brief Get contact data for a given profile link
270 * The function looks at several places (contact table and gcontact table) for the contact
271 * It caches its result for the same script execution to prevent duplicate calls
273 * @param string $url The profile link
274 * @param int $uid User id
275 * @param array $default If not data was found take this data as default value
277 * @return array Contact data
279 public static function getDetailsByURL($url, $uid = -1, array $default = [])
281 static $cache = array();
291 if (isset($cache[$url][$uid])) {
292 return $cache[$url][$uid];
295 $ssl_url = str_replace('http://', 'https://', $url);
297 // Fetch contact data from the contact table for the given user
298 $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`,
299 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
300 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
301 $r = dba::inArray($s);
303 // Fetch contact data from the contact table for the given user, checking with the alias
304 if (!DBM::is_result($r)) {
305 $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`,
306 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
307 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
308 $r = dba::inArray($s);
311 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
312 if (!DBM::is_result($r)) {
313 $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`,
314 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
315 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
316 $r = dba::inArray($s);
319 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
320 if (!DBM::is_result($r)) {
321 $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`,
322 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
323 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
324 $r = dba::inArray($s);
327 // Fetch the data from the gcontact table
328 if (!DBM::is_result($r)) {
329 $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`,
330 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
331 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
332 $r = dba::inArray($s);
335 if (DBM::is_result($r)) {
336 // If there is more than one entry we filter out the connector networks
338 foreach ($r as $id => $result) {
339 if ($result["network"] == NETWORK_STATUSNET) {
345 $profile = array_shift($r);
347 // "bd" always contains the upcoming birthday of a contact.
348 // "birthday" might contain the birthday including the year of birth.
349 if ($profile["birthday"] > '0001-01-01') {
350 $bd_timestamp = strtotime($profile["birthday"]);
351 $month = date("m", $bd_timestamp);
352 $day = date("d", $bd_timestamp);
354 $current_timestamp = time();
355 $current_year = date("Y", $current_timestamp);
356 $current_month = date("m", $current_timestamp);
357 $current_day = date("d", $current_timestamp);
359 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
360 $current = $current_year . "-" . $current_month . "-" . $current_day;
362 if ($profile["bd"] < $current) {
363 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
366 $profile["bd"] = '0001-01-01';
372 if (($profile["photo"] == "") && isset($default["photo"])) {
373 $profile["photo"] = $default["photo"];
376 if (($profile["name"] == "") && isset($default["name"])) {
377 $profile["name"] = $default["name"];
380 if (($profile["network"] == "") && isset($default["network"])) {
381 $profile["network"] = $default["network"];
384 if (($profile["thumb"] == "") && isset($profile["photo"])) {
385 $profile["thumb"] = $profile["photo"];
388 if (($profile["micro"] == "") && isset($profile["thumb"])) {
389 $profile["micro"] = $profile["thumb"];
392 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
393 && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
395 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
398 // Show contact details of Diaspora contacts only if connected
399 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
400 $profile["location"] = "";
401 $profile["about"] = "";
402 $profile["gender"] = "";
403 $profile["birthday"] = '0001-01-01';
406 $cache[$url][$uid] = $profile;
412 * @brief Get contact data for a given address
414 * The function looks at several places (contact table and gcontact table) for the contact
416 * @param string $addr The profile link
417 * @param int $uid User id
419 * @return array Contact data
421 public static function getDetailsByAddr($addr, $uid = -1)
423 static $cache = array();
433 // Fetch contact data from the contact table for the given user
434 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
435 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
436 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d", dbesc($addr), intval($uid));
438 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
439 if (!DBM::is_result($r))
440 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
441 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
442 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
444 // Fetch the data from the gcontact table
445 if (!DBM::is_result($r))
446 $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`,
447 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
448 FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
450 if (!DBM::is_result($r)) {
451 $data = Probe::uri($addr);
453 $profile = self::getDetailsByURL($data['url'], $uid);
462 * @brief Returns the data array for the photo menu of a given contact
464 * @param array $contact contact
465 * @param int $uid optional, default 0
468 public static function photoMenu(array $contact, $uid = 0)
470 // @todo Unused, to be removed
478 $contact_drop_link = '';
485 if ($contact['uid'] != $uid) {
487 $profile_link = zrl($contact['url']);
488 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
493 $r = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
495 return self::photoMenu($r, $uid);
497 $profile_link = zrl($contact['url']);
498 $connlnk = 'follow/?url=' . $contact['url'];
500 'profile' => array(t('View Profile'), $profile_link, true),
501 'follow' => array(t('Connect/Follow'), $connlnk, true)
509 if ($contact['network'] === NETWORK_DFRN) {
511 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
513 $profile_link = $contact['url'];
516 if ($profile_link === 'mailbox') {
521 $status_link = $profile_link . '?url=status';
522 $photos_link = $profile_link . '?url=photos';
523 $profile_link = $profile_link . '?url=profile';
526 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
527 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
530 if ($contact['network'] == NETWORK_DFRN) {
531 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
534 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
536 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
537 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
541 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
544 'status' => array(t("View Status"), $status_link, true),
545 'profile' => array(t("View Profile"), $profile_link, true),
546 'photos' => array(t("View Photos"), $photos_link, true),
547 'network' => array(t("Network Posts"), $posts_link, false),
548 'edit' => array(t("View Contact"), $contact_url, false),
549 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
550 'pm' => array(t("Send PM"), $pm_url, false),
551 'poke' => array(t("Poke"), $poke_link, false),
555 $args = array('contact' => $contact, 'menu' => &$menu);
557 call_hooks('contact_photo_menu', $args);
559 $menucondensed = array();
561 foreach ($menu as $menuname => $menuitem) {
562 if ($menuitem[1] != '') {
563 $menucondensed[$menuname] = $menuitem;
567 return $menucondensed;
571 * @brief Returns ungrouped contact count or list for user
573 * Returns either the total number of ungrouped contacts for the given user
574 * id or a paginated list of ungrouped contacts.
576 * @param int $uid uid
577 * @param int $start optional, default 0
578 * @param int $count optional, default 0
582 public static function getUngroupedList($uid, $start = 0, $count = 0)
586 "SELECT COUNT(*) AS `total`
593 SELECT DISTINCT(`contact-id`)
596 )", intval($uid), intval($uid)
610 SELECT DISTINCT(`contact-id`)
612 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
613 WHERE `group`.`uid` = %d
615 LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
621 * @brief Fetch the contact id for a given url and user
623 * First lookup in the contact table to find a record matching either `url`, `nurl`,
626 * If there's no record and we aren't looking for a public contact, we quit.
627 * If there's one, we check that it isn't time to update the picture else we
628 * directly return the found contact id.
630 * Second, we probe the provided $url wether it's http://server.tld/profile or
631 * nick@server.tld. We quit if we can't get any info back.
633 * Third, we create the contact record if it doesn't exist
635 * Fourth, we update the existing record with the new data (avatar, alias, nick)
636 * if there's any updates
638 * @param string $url Contact URL
639 * @param integer $uid The user id for the contact (0 = public contact)
640 * @param boolean $no_update Don't update the contact
642 * @return integer Contact ID
644 public static function getIdForURL($url, $uid = 0, $no_update = false)
646 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
654 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
655 // We first try the nurl (http://server.tld/nick), most common case
656 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
658 // Then the addr (nick@server.tld)
659 if (!DBM::is_result($contact)) {
660 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
663 // Then the alias (which could be anything)
664 if (!DBM::is_result($contact)) {
665 // The link could be provided as http although we stored it as https
666 $ssl_url = str_replace('http://', 'https://', $url);
667 $r = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid]);
668 $contact = dba::fetch($r);
672 if (DBM::is_result($contact)) {
673 $contact_id = $contact["id"];
675 // Update the contact every 7 days
676 $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
678 // We force the update if the avatar is empty
679 if (!x($contact, 'avatar')) {
680 $update_contact = true;
683 if (!$update_contact || $no_update) {
686 } elseif ($uid != 0) {
687 // Non-existing user-specific contact, exiting
691 $data = Probe::uri($url, "", $uid);
693 // Last try in gcontact for unsupported networks
694 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
699 // Get data from the gcontact table
700 $gcontacts = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
701 if (!DBM::is_result($gcontacts)) {
705 $data = array_merge($data, $gcontacts);
708 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
709 $contact_id = self::getIdForURL($data["alias"], $uid, true);
715 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
716 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
717 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
718 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
719 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
720 'network' => $data["network"], 'pubkey' => $data["pubkey"],
721 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
722 'batch' => $data["batch"], 'request' => $data["request"],
723 'confirm' => $data["confirm"], 'poco' => $data["poco"],
724 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
725 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
726 'readonly' => 0, 'pending' => 0)
729 $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
730 $contacts = dba::inArray($s);
731 if (!DBM::is_result($contacts)) {
735 $contact_id = $contacts[0]["id"];
737 // Update the newly created contact from data in the gcontact table
738 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
739 if (DBM::is_result($gcontact)) {
740 // Only use the information when the probing hadn't fetched these values
741 if ($data['keywords'] != '') {
742 unset($gcontact['keywords']);
744 if ($data['location'] != '') {
745 unset($gcontact['location']);
747 if ($data['about'] != '') {
748 unset($gcontact['about']);
750 dba::update('contact', $gcontact, array('id' => $contact_id));
753 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
754 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
755 normalise_link($data["url"]), $contact_id));
759 self::updateAvatar($data["photo"], $uid, $contact_id);
761 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
762 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
764 // This condition should always be true
765 if (!DBM::is_result($contact)) {
769 $updated = array('addr' => $data['addr'],
770 'alias' => $data['alias'],
771 'url' => $data['url'],
772 'nurl' => normalise_link($data['url']),
773 'name' => $data['name'],
774 'nick' => $data['nick']);
776 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
777 if (!empty($contact['pubkey'])) {
778 unset($contact['pubkey']);
780 $updated['pubkey'] = $data['pubkey'];
783 if ($data['keywords'] != '') {
784 $updated['keywords'] = $data['keywords'];
786 if ($data['location'] != '') {
787 $updated['location'] = $data['location'];
789 if ($data['about'] != '') {
790 $updated['about'] = $data['about'];
793 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
794 $updated['uri-date'] = datetime_convert();
796 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
797 $updated['name-date'] = datetime_convert();
800 $updated['avatar-date'] = datetime_convert();
802 dba::update('contact', $updated, array('id' => $contact_id), $contact);
808 * @brief Checks if the contact is blocked
810 * @param int $cid contact id
812 * @return boolean Is the contact blocked?
814 public static function isBlocked($cid)
820 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
821 if (!DBM::is_result($blocked)) {
824 return (bool) $blocked['blocked'];
828 * @brief Checks if the contact is hidden
830 * @param int $cid contact id
832 * @return boolean Is the contact hidden?
834 public static function isHidden($cid)
840 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
841 if (!DBM::is_result($hidden)) {
844 return (bool) $hidden['hidden'];
848 * @brief Returns posts from a given contact url
850 * @param string $contact_url Contact URL
852 * @return string posts in HTML
854 public static function getPostsFromUrl($contact_url)
858 require_once 'include/conversation.php';
860 // There are no posts with "uid = 0" with connector networks
861 // This speeds up the query a lot
862 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
863 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
865 if (!DBM::is_result($r)) {
869 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
870 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
872 $sql = "`item`.`uid` = %d";
875 $author_id = intval($r[0]["author-id"]);
877 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
879 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
880 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
881 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
882 intval($a->pager['start']), intval($a->pager['itemspage'])
886 $o = conversation($a, $r, 'contact-posts', false);
888 $o .= alt_pager($a, count($r));
894 * @brief Returns the account type name
896 * The function can be called with either the user or the contact array
898 * @param array $contact contact or user array
901 public static function getAccountType(array $contact)
903 // There are several fields that indicate that the contact or user is a forum
904 // "page-flags" is a field in the user table,
905 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
906 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
907 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
908 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
909 || (isset($contact['forum']) && intval($contact['forum']))
910 || (isset($contact['prv']) && intval($contact['prv']))
911 || (isset($contact['community']) && intval($contact['community']))
913 $type = ACCOUNT_TYPE_COMMUNITY;
915 $type = ACCOUNT_TYPE_PERSON;
918 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
919 if (isset($contact["contact-type"])) {
920 $type = $contact["contact-type"];
922 if (isset($contact["account-type"])) {
923 $type = $contact["account-type"];
927 case ACCOUNT_TYPE_ORGANISATION:
928 $account_type = t("Organisation");
930 case ACCOUNT_TYPE_NEWS:
931 $account_type = t('News');
933 case ACCOUNT_TYPE_COMMUNITY:
934 $account_type = t("Forum");
941 return $account_type;
945 * @brief Blocks a contact
950 public static function block($uid)
952 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
958 * @brief Unblocks a contact
963 public static function unblock($uid)
965 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
971 * @brief Updates the avatar links in a contact only if needed
973 * @param string $avatar Link to avatar picture
974 * @param int $uid User id of contact owner
975 * @param int $cid Contact id
976 * @param bool $force force picture update
978 * @return array Returns array of the different avatar sizes
980 public static function updateAvatar($avatar, $uid, $cid, $force = false)
982 // Limit = 1 returns the row so no need for dba:inArray()
983 $r = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
984 if (!DBM::is_result($r)) {
987 $data = array($r["photo"], $r["thumb"], $r["micro"]);
990 if (($r["avatar"] != $avatar) || $force) {
991 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
996 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
1000 // Update the public contact (contact id = 0)
1002 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $r[0]['nurl']]);
1003 if (DBM::is_result($pcontact)) {
1004 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1016 * @param integer $id contact id
1019 public static function updateFromProbe($id)
1022 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1023 This will reliably kill your communication with Friendica contacts.
1026 $r = dba::selectFirst('contact', ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'], ['id' => $id]);
1027 if (!DBM::is_result($r)) {
1031 $ret = Probe::uri($r["url"]);
1033 // If Probe::uri fails the network code will be different
1034 if ($ret["network"] != $r["network"]) {
1040 // make sure to not overwrite existing values with blank entries
1041 foreach ($ret as $key => $val) {
1042 if (isset($r[$key]) && ($r[$key] != "") && ($val == ""))
1043 $ret[$key] = $r[$key];
1045 if (isset($r[$key]) && ($ret[$key] != $r[$key]))
1056 'url' => $ret['url'],
1057 'nurl' => normalise_link($ret['url']),
1058 'addr' => $ret['addr'],
1059 'alias' => $ret['alias'],
1060 'batch' => $ret['batch'],
1061 'notify' => $ret['notify'],
1062 'poll' => $ret['poll'],
1063 'poco' => $ret['poco']
1068 // Update the corresponding gcontact entry
1069 PortableContact::lastUpdated($ret["url"]);
1075 * Takes a $uid and a url/handle and adds a new contact
1076 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1077 * dfrn_request page.
1079 * Otherwise this can be used to bulk add statusnet contacts, twitter contacts, etc.
1082 * $return['success'] boolean true if successful
1083 * $return['message'] error text if success is false.
1085 * @brief Takes a $uid and a url/handle and adds a new contact
1087 * @param string $url
1088 * @param bool $interactive
1089 * @param string $network
1090 * @return boolean|string
1092 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1094 $result = array('cid' => -1, 'success' => false, 'message' => '');
1098 // remove ajax junk, e.g. Twitter
1099 $url = str_replace('/#!/', '/', $url);
1101 if (!allowed_url($url)) {
1102 $result['message'] = t('Disallowed profile URL.');
1106 if (blocked_url($url)) {
1107 $result['message'] = t('Blocked domain');
1112 $result['message'] = t('Connect URL missing.');
1116 $arr = array('url' => $url, 'contact' => array());
1118 call_hooks('follow', $arr);
1120 if (x($arr['contact'], 'name')) {
1121 $ret = $arr['contact'];
1123 $ret = Probe::uri($url, $network, $uid, false);
1126 if (($network != '') && ($ret['network'] != $network)) {
1127 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1131 if ($ret['network'] === NETWORK_DFRN) {
1133 if (strlen($a->path)) {
1134 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1136 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1139 goaway($ret['request'] . "&addr=$myaddr");
1143 } elseif (Config::get('system', 'dfrn_only')) {
1144 $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1145 $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1149 // This extra param just confuses things, remove it
1150 if ($ret['network'] === NETWORK_DIASPORA) {
1151 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1154 // do we have enough information?
1156 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1157 $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1158 if (!x($ret, 'poll')) {
1159 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1161 if (!x($ret, 'name')) {
1162 $result['message'] .= t('An author or name was not found.') . EOL;
1164 if (!x($ret, 'url')) {
1165 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1167 if (strpos($url, '@') !== false) {
1168 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1169 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1174 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1175 $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1176 $ret['notify'] = '';
1179 if (!$ret['notify']) {
1180 $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1183 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1185 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1187 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1189 if (in_array($ret['network'], array(NETWORK_MAIL, NETWORK_DIASPORA))) {
1193 // check if we already have a contact
1194 // the poll url is more reliable than the profile url, as we may have
1195 // indirect links or webfinger links
1197 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1199 dbesc($ret['poll']),
1200 dbesc(normalise_link($ret['poll'])),
1201 dbesc($ret['network'])
1204 if (!DBM::is_result($r)) {
1205 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1206 intval($uid), dbesc(normalise_link($url)), dbesc($ret['network'])
1210 if (DBM::is_result($r)) {
1212 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1214 $fields = array('rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false);
1215 dba::update('contact', $fields, array('id' => $r[0]['id']));
1217 $new_relation = ((in_array($ret['network'], array(NETWORK_MAIL))) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1219 // create contact record
1224 'created' => datetime_convert(),
1225 'url' => $ret['url'],
1226 'nurl' => normalise_link($ret['url']),
1227 'addr' => $ret['addr'],
1228 'alias' => $ret['alias'],
1229 'batch' => $ret['batch'],
1230 'notify' => $ret['notify'],
1231 'poll' => $ret['poll'],
1232 'poco' => $ret['poco'],
1233 'name' => $ret['name'],
1234 'nick' => $ret['nick'],
1235 'network' => $ret['network'],
1236 'pubkey' => $ret['pubkey'],
1237 'rel' => $new_relation,
1238 'priority' => $ret['priority'],
1239 'writable' => $writeable,
1240 'hidden' => $hidden,
1249 $r = dba::selectFirst('contact', ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1251 if (!DBM::is_result($r)) {
1252 $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1257 $contact_id = $r['id'];
1258 $result['cid'] = $contact_id;
1260 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1262 // Update the avatar
1263 self::updateAvatar($ret['photo'], $uid, $contact_id);
1265 // pull feed and consume it, which should subscribe to the hub.
1267 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1269 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1270 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1274 if (DBM::is_result($r)) {
1275 if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1276 // create a follow slap
1278 $item['verb'] = ACTIVITY_FOLLOW;
1279 $item['follow'] = $contact["url"];
1280 $slap = OStatus::salmon($item, $r[0]);
1281 Salmon::slapper($r[0], $contact['notify'], $slap);
1284 if ($contact['network'] == NETWORK_DIASPORA) {
1285 $ret = Diaspora::sendShare($a->user, $contact);
1286 logger('share returns: ' . $ret);
1290 $result['success'] = true;