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 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
149 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
153 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
155 dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
159 dba::delete('contact', array('id' => $id));
161 // Delete the rest in the background
162 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
166 * @brief Sends an unfriend message. Does not remove the contact
168 * @param array $user User unfriending
169 * @param array $contact Contact unfriended
172 public static function terminateFriendship(array $user, array $contact)
174 if ($contact['network'] === NETWORK_OSTATUS) {
175 // create an unfollow slap
177 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
178 $item['follow'] = $contact["url"];
179 $slap = OStatus::salmon($item, $user);
181 if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
182 Salmon::slapper($user, $contact['notify'], $slap);
184 } elseif ($contact['network'] === NETWORK_DIASPORA) {
185 Diaspora::sendUnshare($user, $contact);
186 } elseif ($contact['network'] === NETWORK_DFRN) {
187 DFRN::deliver($user, $contact, 'placeholder', 1);
192 * @brief Marks a contact for archival after a communication issue delay
194 * Contact has refused to recognise us as a friend. We will start a countdown.
195 * If they still don't recognise us in 32 days, the relationship is over,
196 * and we won't waste any more time trying to communicate with them.
197 * This provides for the possibility that their database is temporarily messed
198 * up or some other transient event and that there's a possibility we could recover from it.
200 * @param array $contact contact to mark for archival
203 public static function markForArchival(array $contact)
205 // Contact already archived or "self" contact? => nothing to do
206 if ($contact['archive'] || $contact['self']) {
210 if ($contact['term-date'] <= NULL_DATE) {
211 dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
213 if ($contact['url'] != '') {
214 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE));
218 * We really should send a notification to the owner after 2-3 weeks
219 * so they won't be surprised when the contact vanishes and can take
220 * remedial action if this was a serious mistake or glitch
223 /// @todo Check for contact vitality via probing
224 $expiry = $contact['term-date'] . ' + 32 days ';
225 if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
226 /* Relationship is really truly dead. archive them rather than
227 * delete, though if the owner tries to unarchive them we'll start
228 * the whole process over again.
230 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
232 if ($contact['url'] != '') {
233 dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url']), 'self' => false));
240 * @brief Cancels the archival countdown
242 * @see Contact::markForArchival()
244 * @param array $contact contact to be unmarked for archival
247 public static function unmarkForArchival(array $contact)
249 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE);
250 $exists = dba::exists('contact', $condition);
252 // We don't need to update, we never marked this contact for archival
257 // It's a miracle. Our dead contact has inexplicably come back to life.
258 $fields = array('term-date' => NULL_DATE, 'archive' => false);
259 dba::update('contact', $fields, array('id' => $contact['id']));
261 if ($contact['url'] != '') {
262 dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
267 * @brief Get contact data for a given profile link
269 * The function looks at several places (contact table and gcontact table) for the contact
270 * It caches its result for the same script execution to prevent duplicate calls
272 * @param string $url The profile link
273 * @param int $uid User id
274 * @param array $default If not data was found take this data as default value
276 * @return array Contact data
278 public static function getDetailsByURL($url, $uid = -1, array $default = [])
280 static $cache = array();
290 if (isset($cache[$url][$uid])) {
291 return $cache[$url][$uid];
294 $ssl_url = str_replace('http://', 'https://', $url);
296 // Fetch contact data from the contact table for the given user
297 $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`,
298 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
299 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
300 $r = dba::inArray($s);
302 // Fetch contact data from the contact table for the given user, checking with the alias
303 if (!DBM::is_result($r)) {
304 $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`,
305 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
306 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
307 $r = dba::inArray($s);
310 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
311 if (!DBM::is_result($r)) {
312 $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`,
313 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
314 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
315 $r = dba::inArray($s);
318 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
319 if (!DBM::is_result($r)) {
320 $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`,
321 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
322 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
323 $r = dba::inArray($s);
326 // Fetch the data from the gcontact table
327 if (!DBM::is_result($r)) {
328 $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`,
329 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
330 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
331 $r = dba::inArray($s);
334 if (DBM::is_result($r)) {
335 // If there is more than one entry we filter out the connector networks
337 foreach ($r as $id => $result) {
338 if ($result["network"] == NETWORK_STATUSNET) {
344 $profile = array_shift($r);
346 // "bd" always contains the upcoming birthday of a contact.
347 // "birthday" might contain the birthday including the year of birth.
348 if ($profile["birthday"] > '0001-01-01') {
349 $bd_timestamp = strtotime($profile["birthday"]);
350 $month = date("m", $bd_timestamp);
351 $day = date("d", $bd_timestamp);
353 $current_timestamp = time();
354 $current_year = date("Y", $current_timestamp);
355 $current_month = date("m", $current_timestamp);
356 $current_day = date("d", $current_timestamp);
358 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
359 $current = $current_year . "-" . $current_month . "-" . $current_day;
361 if ($profile["bd"] < $current) {
362 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
365 $profile["bd"] = '0001-01-01';
371 if (($profile["photo"] == "") && isset($default["photo"])) {
372 $profile["photo"] = $default["photo"];
375 if (($profile["name"] == "") && isset($default["name"])) {
376 $profile["name"] = $default["name"];
379 if (($profile["network"] == "") && isset($default["network"])) {
380 $profile["network"] = $default["network"];
383 if (($profile["thumb"] == "") && isset($profile["photo"])) {
384 $profile["thumb"] = $profile["photo"];
387 if (($profile["micro"] == "") && isset($profile["thumb"])) {
388 $profile["micro"] = $profile["thumb"];
391 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
392 && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
394 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
397 // Show contact details of Diaspora contacts only if connected
398 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
399 $profile["location"] = "";
400 $profile["about"] = "";
401 $profile["gender"] = "";
402 $profile["birthday"] = '0001-01-01';
405 $cache[$url][$uid] = $profile;
411 * @brief Get contact data for a given address
413 * The function looks at several places (contact table and gcontact table) for the contact
415 * @param string $addr The profile link
416 * @param int $uid User id
418 * @return array Contact data
420 public static function getDetailsByAddr($addr, $uid = -1)
422 static $cache = array();
432 // Fetch contact data from the contact table for the given user
433 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
434 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
435 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d", dbesc($addr), intval($uid));
437 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
438 if (!DBM::is_result($r))
439 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
440 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
441 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
443 // Fetch the data from the gcontact table
444 if (!DBM::is_result($r))
445 $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`,
446 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
447 FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
449 if (!DBM::is_result($r)) {
450 $data = Probe::uri($addr);
452 $profile = self::getDetailsByURL($data['url'], $uid);
461 * @brief Returns the data array for the photo menu of a given contact
463 * @param array $contact contact
464 * @param int $uid optional, default 0
467 public static function photoMenu(array $contact, $uid = 0)
469 // @todo Unused, to be removed
477 $contact_drop_link = '';
484 if ($contact['uid'] != $uid) {
486 $profile_link = zrl($contact['url']);
487 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
492 // Look for our own contact if the uid doesn't match and isn't public
493 $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
494 if (DBM::is_result($contact_own)) {
495 return self::photoMenu($contact_own, $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 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
668 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
671 if (DBM::is_result($contact)) {
672 $contact_id = $contact["id"];
674 // Update the contact every 7 days
675 $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
677 // We force the update if the avatar is empty
678 if (!x($contact, 'avatar')) {
679 $update_contact = true;
682 if (!$update_contact || $no_update) {
685 } elseif ($uid != 0) {
686 // Non-existing user-specific contact, exiting
690 $data = Probe::uri($url, "", $uid);
692 // Last try in gcontact for unsupported networks
693 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
698 // Get data from the gcontact table
699 $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
700 if (!DBM::is_result($gcontact)) {
704 $data = array_merge($data, $gcontact);
707 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
708 $contact_id = self::getIdForURL($data["alias"], $uid, true);
714 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
715 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
716 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
717 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
718 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
719 'network' => $data["network"], 'pubkey' => $data["pubkey"],
720 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
721 'batch' => $data["batch"], 'request' => $data["request"],
722 'confirm' => $data["confirm"], 'poco' => $data["poco"],
723 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
724 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
725 'readonly' => 0, 'pending' => 0)
728 $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
729 $contacts = dba::inArray($s);
730 if (!DBM::is_result($contacts)) {
734 $contact_id = $contacts[0]["id"];
736 // Update the newly created contact from data in the gcontact table
737 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
738 if (DBM::is_result($gcontact)) {
739 // Only use the information when the probing hadn't fetched these values
740 if ($data['keywords'] != '') {
741 unset($gcontact['keywords']);
743 if ($data['location'] != '') {
744 unset($gcontact['location']);
746 if ($data['about'] != '') {
747 unset($gcontact['about']);
749 dba::update('contact', $gcontact, array('id' => $contact_id));
752 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
753 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
754 normalise_link($data["url"]), $contact_id));
758 self::updateAvatar($data["photo"], $uid, $contact_id);
760 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
761 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
763 // This condition should always be true
764 if (!DBM::is_result($contact)) {
768 $updated = array('addr' => $data['addr'],
769 'alias' => $data['alias'],
770 'url' => $data['url'],
771 'nurl' => normalise_link($data['url']),
772 'name' => $data['name'],
773 'nick' => $data['nick']);
775 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
776 if (!empty($contact['pubkey'])) {
777 unset($contact['pubkey']);
779 $updated['pubkey'] = $data['pubkey'];
782 if ($data['keywords'] != '') {
783 $updated['keywords'] = $data['keywords'];
785 if ($data['location'] != '') {
786 $updated['location'] = $data['location'];
788 if ($data['about'] != '') {
789 $updated['about'] = $data['about'];
792 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
793 $updated['uri-date'] = datetime_convert();
795 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
796 $updated['name-date'] = datetime_convert();
799 $updated['avatar-date'] = datetime_convert();
801 dba::update('contact', $updated, array('id' => $contact_id), $contact);
807 * @brief Checks if the contact is blocked
809 * @param int $cid contact id
811 * @return boolean Is the contact blocked?
813 public static function isBlocked($cid)
819 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
820 if (!DBM::is_result($blocked)) {
823 return (bool) $blocked['blocked'];
827 * @brief Checks if the contact is hidden
829 * @param int $cid contact id
831 * @return boolean Is the contact hidden?
833 public static function isHidden($cid)
839 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
840 if (!DBM::is_result($hidden)) {
843 return (bool) $hidden['hidden'];
847 * @brief Returns posts from a given contact url
849 * @param string $contact_url Contact URL
851 * @return string posts in HTML
853 public static function getPostsFromUrl($contact_url)
857 require_once 'include/conversation.php';
859 // There are no posts with "uid = 0" with connector networks
860 // This speeds up the query a lot
861 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
862 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
864 if (!DBM::is_result($r)) {
868 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
869 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
871 $sql = "`item`.`uid` = %d";
874 $author_id = intval($r[0]["author-id"]);
876 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
878 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
879 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
880 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
881 intval($a->pager['start']), intval($a->pager['itemspage'])
885 $o = conversation($a, $r, 'contact-posts', false);
887 $o .= alt_pager($a, count($r));
893 * @brief Returns the account type name
895 * The function can be called with either the user or the contact array
897 * @param array $contact contact or user array
900 public static function getAccountType(array $contact)
902 // There are several fields that indicate that the contact or user is a forum
903 // "page-flags" is a field in the user table,
904 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
905 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
906 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
907 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
908 || (isset($contact['forum']) && intval($contact['forum']))
909 || (isset($contact['prv']) && intval($contact['prv']))
910 || (isset($contact['community']) && intval($contact['community']))
912 $type = ACCOUNT_TYPE_COMMUNITY;
914 $type = ACCOUNT_TYPE_PERSON;
917 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
918 if (isset($contact["contact-type"])) {
919 $type = $contact["contact-type"];
921 if (isset($contact["account-type"])) {
922 $type = $contact["account-type"];
926 case ACCOUNT_TYPE_ORGANISATION:
927 $account_type = t("Organisation");
929 case ACCOUNT_TYPE_NEWS:
930 $account_type = t('News');
932 case ACCOUNT_TYPE_COMMUNITY:
933 $account_type = t("Forum");
940 return $account_type;
944 * @brief Blocks a contact
949 public static function block($uid)
951 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
957 * @brief Unblocks a contact
962 public static function unblock($uid)
964 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
970 * @brief Updates the avatar links in a contact only if needed
972 * @param string $avatar Link to avatar picture
973 * @param int $uid User id of contact owner
974 * @param int $cid Contact id
975 * @param bool $force force picture update
977 * @return array Returns array of the different avatar sizes
979 public static function updateAvatar($avatar, $uid, $cid, $force = false)
981 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
982 if (!DBM::is_result($contact)) {
985 $data = array($contact["photo"], $contact["thumb"], $contact["micro"]);
988 if (($contact["avatar"] != $avatar) || $force) {
989 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
994 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
998 // Update the public contact (contact id = 0)
1000 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1001 if (DBM::is_result($pcontact)) {
1002 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1014 * @param integer $id contact id
1017 public static function updateFromProbe($id)
1020 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1021 This will reliably kill your communication with Friendica contacts.
1024 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1025 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1026 if (!DBM::is_result($contact)) {
1030 $ret = Probe::uri($contact["url"]);
1032 // If Probe::uri fails the network code will be different
1033 if ($ret["network"] != $contact["network"]) {
1039 // make sure to not overwrite existing values with blank entries
1040 foreach ($ret as $key => $val) {
1041 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1042 $ret[$key] = $contact[$key];
1045 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1057 'url' => $ret['url'],
1058 'nurl' => normalise_link($ret['url']),
1059 'addr' => $ret['addr'],
1060 'alias' => $ret['alias'],
1061 'batch' => $ret['batch'],
1062 'notify' => $ret['notify'],
1063 'poll' => $ret['poll'],
1064 'poco' => $ret['poco']
1069 // Update the corresponding gcontact entry
1070 PortableContact::lastUpdated($ret["url"]);
1076 * Takes a $uid and a url/handle and adds a new contact
1077 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1078 * dfrn_request page.
1080 * Otherwise this can be used to bulk add statusnet contacts, twitter contacts, etc.
1083 * $return['success'] boolean true if successful
1084 * $return['message'] error text if success is false.
1086 * @brief Takes a $uid and a url/handle and adds a new contact
1088 * @param string $url
1089 * @param bool $interactive
1090 * @param string $network
1091 * @return boolean|string
1093 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1095 $result = array('cid' => -1, 'success' => false, 'message' => '');
1099 // remove ajax junk, e.g. Twitter
1100 $url = str_replace('/#!/', '/', $url);
1102 if (!allowed_url($url)) {
1103 $result['message'] = t('Disallowed profile URL.');
1107 if (blocked_url($url)) {
1108 $result['message'] = t('Blocked domain');
1113 $result['message'] = t('Connect URL missing.');
1117 $arr = array('url' => $url, 'contact' => array());
1119 call_hooks('follow', $arr);
1121 if (x($arr['contact'], 'name')) {
1122 $ret = $arr['contact'];
1124 $ret = Probe::uri($url, $network, $uid, false);
1127 if (($network != '') && ($ret['network'] != $network)) {
1128 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1132 if ($ret['network'] === NETWORK_DFRN) {
1134 if (strlen($a->path)) {
1135 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1137 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1140 goaway($ret['request'] . "&addr=$myaddr");
1144 } elseif (Config::get('system', 'dfrn_only')) {
1145 $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1146 $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1150 // This extra param just confuses things, remove it
1151 if ($ret['network'] === NETWORK_DIASPORA) {
1152 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1155 // do we have enough information?
1157 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1158 $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1159 if (!x($ret, 'poll')) {
1160 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1162 if (!x($ret, 'name')) {
1163 $result['message'] .= t('An author or name was not found.') . EOL;
1165 if (!x($ret, 'url')) {
1166 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1168 if (strpos($url, '@') !== false) {
1169 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1170 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1175 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1176 $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1177 $ret['notify'] = '';
1180 if (!$ret['notify']) {
1181 $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1184 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1186 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1188 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1190 if (in_array($ret['network'], array(NETWORK_MAIL, NETWORK_DIASPORA))) {
1194 // check if we already have a contact
1195 // the poll url is more reliable than the profile url, as we may have
1196 // indirect links or webfinger links
1198 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1200 dbesc($ret['poll']),
1201 dbesc(normalise_link($ret['poll'])),
1202 dbesc($ret['network'])
1205 if (!DBM::is_result($r)) {
1206 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1207 intval($uid), dbesc(normalise_link($url)), dbesc($ret['network'])
1211 if (DBM::is_result($r)) {
1213 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1215 $fields = array('rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false);
1216 dba::update('contact', $fields, array('id' => $r[0]['id']));
1218 $new_relation = ((in_array($ret['network'], array(NETWORK_MAIL))) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1220 // create contact record
1225 'created' => datetime_convert(),
1226 'url' => $ret['url'],
1227 'nurl' => normalise_link($ret['url']),
1228 'addr' => $ret['addr'],
1229 'alias' => $ret['alias'],
1230 'batch' => $ret['batch'],
1231 'notify' => $ret['notify'],
1232 'poll' => $ret['poll'],
1233 'poco' => $ret['poco'],
1234 'name' => $ret['name'],
1235 'nick' => $ret['nick'],
1236 'network' => $ret['network'],
1237 'pubkey' => $ret['pubkey'],
1238 'rel' => $new_relation,
1239 'priority' => $ret['priority'],
1240 'writable' => $writeable,
1241 'hidden' => $hidden,
1250 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1251 if (!DBM::is_result($contact)) {
1252 $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1256 $contact_id = $contact['id'];
1257 $result['cid'] = $contact_id;
1259 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1261 // Update the avatar
1262 self::updateAvatar($ret['photo'], $uid, $contact_id);
1264 // pull feed and consume it, which should subscribe to the hub.
1266 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1268 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1269 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1273 if (DBM::is_result($r)) {
1274 if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1275 // create a follow slap
1277 $item['verb'] = ACTIVITY_FOLLOW;
1278 $item['follow'] = $contact["url"];
1279 $slap = OStatus::salmon($item, $r[0]);
1280 Salmon::slapper($r[0], $contact['notify'], $slap);
1283 if ($contact['network'] == NETWORK_DIASPORA) {
1284 $ret = Diaspora::sendShare($a->user, $contact);
1285 logger('share returns: ' . $ret);
1289 $result['success'] = true;