4 * @file src/Model/Contact.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Network\Probe;
15 use Friendica\Model\Photo;
16 use Friendica\Protocol\Diaspora;
17 use Friendica\Protocol\DFRN;
18 use Friendica\Protocol\OStatus;
19 use Friendica\Protocol\PortableContact;
20 use Friendica\Protocol\Salmon;
23 require_once 'boot.php';
24 require_once 'include/dba.php';
25 require_once 'include/text.php';
28 * @brief functions for interacting with a contact
30 class Contact extends BaseObject
33 * @brief Returns a list of contacts belonging in a group
38 public static function getByGroupId($gid)
42 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
44 INNER JOIN `group_member`
45 ON `contact`.`id` = `group_member`.`contact-id`
47 AND `contact`.`uid` = ?
48 AND NOT `contact`.`self`
49 AND NOT `contact`.`blocked`
50 AND NOT `contact`.`pending`
51 ORDER BY `contact`.`name` ASC',
55 if (DBM::is_result($stmt)) {
56 $return = dba::inArray($stmt);
64 * @brief Returns the count of OStatus contacts in a group
69 public static function getOStatusCountByGroupId($gid)
73 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
75 INNER JOIN `group_member`
76 ON `contact`.`id` = `group_member`.`contact-id`
78 AND `contact`.`uid` = ?
79 AND `contact`.`network` = ?
80 AND `contact`.`notify` != ""',
85 $return = $contacts['count'];
93 * Creates the self-contact for the provided user id
96 * @return bool Operation success
98 public static function createSelfFromUserId($uid)
100 // Only create the entry if it doesn't exist yet
101 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
105 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]);
106 if (!DBM::is_result($user)) {
110 $return = dba::insert('contact', [
111 'uid' => $user['uid'],
112 'created' => datetime_convert(),
114 'name' => $user['username'],
115 'nick' => $user['nickname'],
116 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
117 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
118 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
121 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
122 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
123 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
124 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
125 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
126 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
127 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
128 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
129 'name-date' => datetime_convert(),
130 'uri-date' => datetime_convert(),
131 'avatar-date' => datetime_convert(),
139 * @brief Marks a contact for removal
141 * @param int $id contact id
144 public static function remove($id)
146 // We want just to make sure that we don't delete our "self" contact
147 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
149 if (!DBM::is_result($r) || !intval($r['uid'])) {
153 $archive = PConfig::get($r['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 $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1));
494 return self::photoMenu($r, $uid);
496 $profile_link = zrl($contact['url']);
497 $connlnk = 'follow/?url=' . $contact['url'];
499 'profile' => array(t('View Profile'), $profile_link, true),
500 'follow' => array(t('Connect/Follow'), $connlnk, true)
508 if ($contact['network'] === NETWORK_DFRN) {
510 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
512 $profile_link = $contact['url'];
515 if ($profile_link === 'mailbox') {
520 $status_link = $profile_link . '?url=status';
521 $photos_link = $profile_link . '?url=photos';
522 $profile_link = $profile_link . '?url=profile';
525 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
526 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
529 if ($contact['network'] == NETWORK_DFRN) {
530 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
533 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
535 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
536 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
540 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
543 'status' => array(t("View Status"), $status_link, true),
544 'profile' => array(t("View Profile"), $profile_link, true),
545 'photos' => array(t("View Photos"), $photos_link, true),
546 'network' => array(t("Network Posts"), $posts_link, false),
547 'edit' => array(t("View Contact"), $contact_url, false),
548 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
549 'pm' => array(t("Send PM"), $pm_url, false),
550 'poke' => array(t("Poke"), $poke_link, false),
554 $args = array('contact' => $contact, 'menu' => &$menu);
556 call_hooks('contact_photo_menu', $args);
558 $menucondensed = array();
560 foreach ($menu as $menuname => $menuitem) {
561 if ($menuitem[1] != '') {
562 $menucondensed[$menuname] = $menuitem;
566 return $menucondensed;
570 * @brief Returns ungrouped contact count or list for user
572 * Returns either the total number of ungrouped contacts for the given user
573 * id or a paginated list of ungrouped contacts.
575 * @param int $uid uid
576 * @param int $start optional, default 0
577 * @param int $count optional, default 0
581 public static function getUngroupedList($uid, $start = 0, $count = 0)
585 "SELECT COUNT(*) AS `total`
592 SELECT DISTINCT(`contact-id`)
595 )", intval($uid), intval($uid)
609 SELECT DISTINCT(`contact-id`)
611 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
612 WHERE `group`.`uid` = %d
614 LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
620 * @brief Fetch the contact id for a given url and user
622 * First lookup in the contact table to find a record matching either `url`, `nurl`,
625 * If there's no record and we aren't looking for a public contact, we quit.
626 * If there's one, we check that it isn't time to update the picture else we
627 * directly return the found contact id.
629 * Second, we probe the provided $url wether it's http://server.tld/profile or
630 * nick@server.tld. We quit if we can't get any info back.
632 * Third, we create the contact record if it doesn't exist
634 * Fourth, we update the existing record with the new data (avatar, alias, nick)
635 * if there's any updates
637 * @param string $url Contact URL
638 * @param integer $uid The user id for the contact (0 = public contact)
639 * @param boolean $no_update Don't update the contact
641 * @return integer Contact ID
643 public static function getIdForURL($url, $uid = 0, $no_update = false)
645 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
653 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
654 // We first try the nurl (http://server.tld/nick), most common case
655 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
657 // Then the addr (nick@server.tld)
658 if (!DBM::is_result($contact)) {
659 $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
662 // Then the alias (which could be anything)
663 if (!DBM::is_result($contact)) {
664 // The link could be provided as http although we stored it as https
665 $ssl_url = str_replace('http://', 'https://', $url);
666 $r = dba::select('contact', array('id', 'avatar', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
667 $contact = dba::fetch($r);
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 $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
700 if (!DBM::is_result($gcontacts)) {
704 $data = array_merge($data, $gcontacts);
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', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('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::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
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 = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
761 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
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::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
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::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
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 // Limit = 1 returns the row so no need for dba:inArray()
982 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
983 if (!DBM::is_result($r)) {
986 $data = array($r["photo"], $r["thumb"], $r["micro"]);
989 if (($r["avatar"] != $avatar) || $force) {
990 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
995 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
999 // Update the public contact (contact id = 0)
1001 $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
1002 if (DBM::is_result($pcontact)) {
1003 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1015 * @param integer $id contact id
1018 public static function update($id)
1021 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1022 This will reliably kill your communication with Friendica contacts.
1025 $r = dba::select('contact', ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'], ['id' => $id], ['limit' => 1]);
1026 if (!DBM::is_result($r)) {
1030 $ret = Probe::uri($r["url"]);
1032 // If Probe::uri fails the network code will be different
1033 if ($ret["network"] != $r["network"]) {
1039 // make sure to not overwrite existing values with blank entries
1040 foreach ($ret as $key => $val) {
1041 if (isset($r[$key]) && ($r[$key] != "") && ($val == ""))
1042 $ret[$key] = $r[$key];
1044 if (isset($r[$key]) && ($ret[$key] != $r[$key]))
1055 'url' => $ret['url'],
1056 'nurl' => normalise_link($ret['url']),
1057 'addr' => $ret['addr'],
1058 'alias' => $ret['alias'],
1059 'batch' => $ret['batch'],
1060 'notify' => $ret['notify'],
1061 'poll' => $ret['poll'],
1062 'poco' => $ret['poco']
1067 // Update the corresponding gcontact entry
1068 PortableContact::lastUpdated($ret["url"]);
1074 * Takes a $uid and a url/handle and adds a new contact
1075 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1076 * dfrn_request page.
1078 * Otherwise this can be used to bulk add statusnet contacts, twitter contacts, etc.
1081 * $return['success'] boolean true if successful
1082 * $return['message'] error text if success is false.
1084 * @brief Takes a $uid and a url/handle and adds a new contact
1086 * @param string $url
1087 * @param bool $interactive
1088 * @param string $network
1089 * @return boolean|string
1091 public static function add($uid, $url, $interactive = false, $network = '')
1093 $result = array('cid' => -1, 'success' => false, 'message' => '');
1097 // remove ajax junk, e.g. Twitter
1098 $url = str_replace('/#!/', '/', $url);
1100 if (!allowed_url($url)) {
1101 $result['message'] = t('Disallowed profile URL.');
1105 if (blocked_url($url)) {
1106 $result['message'] = t('Blocked domain');
1111 $result['message'] = t('Connect URL missing.');
1115 $arr = array('url' => $url, 'contact' => array());
1117 call_hooks('follow', $arr);
1119 if (x($arr['contact'], 'name')) {
1120 $ret = $arr['contact'];
1122 $ret = Probe::uri($url, $network, $uid, false);
1125 if (($network != '') && ($ret['network'] != $network)) {
1126 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1130 if ($ret['network'] === NETWORK_DFRN) {
1132 if (strlen($a->path)) {
1133 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1135 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1138 goaway($ret['request'] . "&addr=$myaddr");
1142 } elseif (Config::get('system', 'dfrn_only')) {
1143 $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1144 $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1148 // This extra param just confuses things, remove it
1149 if ($ret['network'] === NETWORK_DIASPORA) {
1150 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1153 // do we have enough information?
1155 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1156 $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1157 if (!x($ret, 'poll')) {
1158 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1160 if (!x($ret, 'name')) {
1161 $result['message'] .= t('An author or name was not found.') . EOL;
1163 if (!x($ret, 'url')) {
1164 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1166 if (strpos($url, '@') !== false) {
1167 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1168 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1173 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1174 $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1175 $ret['notify'] = '';
1178 if (!$ret['notify']) {
1179 $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1182 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1184 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1186 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1188 if (in_array($ret['network'], array(NETWORK_MAIL, NETWORK_DIASPORA))) {
1192 // check if we already have a contact
1193 // the poll url is more reliable than the profile url, as we may have
1194 // indirect links or webfinger links
1196 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1198 dbesc($ret['poll']),
1199 dbesc(normalise_link($ret['poll'])),
1200 dbesc($ret['network'])
1203 if (!DBM::is_result($r)) {
1204 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1205 intval($uid), dbesc(normalise_link($url)), dbesc($ret['network'])
1209 if (DBM::is_result($r)) {
1211 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1213 $fields = array('rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false);
1214 dba::update('contact', $fields, array('id' => $r[0]['id']));
1216 $new_relation = ((in_array($ret['network'], array(NETWORK_MAIL))) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1218 // create contact record
1223 'created' => datetime_convert(),
1224 'url' => $ret['url'],
1225 'nurl' => normalise_link($ret['url']),
1226 'addr' => $ret['addr'],
1227 'alias' => $ret['alias'],
1228 'batch' => $ret['batch'],
1229 `notify` => $ret['notify'],
1230 `poll` => $ret['poll'],
1231 `poco` => $ret['poco'],
1232 `name` => $ret['name'],
1233 `nick` => $ret['nick'],
1234 `network` => $ret['network'],
1235 `pubkey` => $ret['pubkey'],
1236 `rel` => $new_relation,
1237 `priority` => $ret['priority'],
1238 `writable` => $writeable,
1239 `hidden` => $hidden,
1248 $r = dba::select('contact', ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid], ['limit' => 1]);
1250 if (!DBM::is_result($r)) {
1251 $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1256 $contact_id = $r['id'];
1257 $result['cid'] = $contact_id;
1259 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1261 // Update the avatar
1262 Contact::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;