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'];
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::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
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 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
148 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
152 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
154 dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
158 dba::delete('contact', array('id' => $id));
160 // Delete the rest in the background
161 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
165 * @brief Sends an unfriend message. Does not remove the contact
167 * @param array $user User unfriending
168 * @param array $contact Contact unfriended
171 public static function terminateFriendship(array $user, array $contact)
173 if ($contact['network'] === NETWORK_OSTATUS) {
174 // create an unfollow slap
176 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
177 $item['follow'] = $contact["url"];
178 $slap = OStatus::salmon($item, $user);
180 if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
181 Salmon::slapper($user, $contact['notify'], $slap);
183 } elseif ($contact['network'] === NETWORK_DIASPORA) {
184 Diaspora::sendUnshare($user, $contact);
185 } elseif ($contact['network'] === NETWORK_DFRN) {
186 DFRN::deliver($user, $contact, 'placeholder', 1);
191 * @brief Marks a contact for archival after a communication issue delay
193 * Contact has refused to recognise us as a friend. We will start a countdown.
194 * If they still don't recognise us in 32 days, the relationship is over,
195 * and we won't waste any more time trying to communicate with them.
196 * This provides for the possibility that their database is temporarily messed
197 * up or some other transient event and that there's a possibility we could recover from it.
199 * @param array $contact contact to mark for archival
202 public static function markForArchival(array $contact)
204 // Contact already archived or "self" contact? => nothing to do
205 if ($contact['archive'] || $contact['self']) {
209 if ($contact['term-date'] <= NULL_DATE) {
210 dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
212 if ($contact['url'] != '') {
213 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE));
217 * We really should send a notification to the owner after 2-3 weeks
218 * so they won't be surprised when the contact vanishes and can take
219 * remedial action if this was a serious mistake or glitch
222 /// @todo Check for contact vitality via probing
223 $expiry = $contact['term-date'] . ' + 32 days ';
224 if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
225 /* Relationship is really truly dead. archive them rather than
226 * delete, though if the owner tries to unarchive them we'll start
227 * the whole process over again.
229 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
231 if ($contact['url'] != '') {
232 dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url']), 'self' => false));
239 * @brief Cancels the archival countdown
241 * @see Contact::markForArchival()
243 * @param array $contact contact to be unmarked for archival
246 public static function unmarkForArchival(array $contact)
248 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE);
249 $exists = dba::exists('contact', $condition);
251 // We don't need to update, we never marked this contact for archival
256 // It's a miracle. Our dead contact has inexplicably come back to life.
257 $fields = array('term-date' => NULL_DATE, 'archive' => false);
258 dba::update('contact', $fields, array('id' => $contact['id']));
260 if ($contact['url'] != '') {
261 dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
266 * @brief Get contact data for a given profile link
268 * The function looks at several places (contact table and gcontact table) for the contact
269 * It caches its result for the same script execution to prevent duplicate calls
271 * @param string $url The profile link
272 * @param int $uid User id
273 * @param array $default If not data was found take this data as default value
275 * @return array Contact data
277 public static function getDetailsByURL($url, $uid = -1, array $default = [])
279 static $cache = array();
289 if (isset($cache[$url][$uid])) {
290 return $cache[$url][$uid];
293 $ssl_url = str_replace('http://', 'https://', $url);
295 // Fetch contact data from the contact table for the given user
296 $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`,
297 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
298 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
299 $r = dba::inArray($s);
301 // Fetch contact data from the contact table for the given user, checking with the alias
302 if (!DBM::is_result($r)) {
303 $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`,
304 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
305 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
306 $r = dba::inArray($s);
309 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
310 if (!DBM::is_result($r)) {
311 $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`,
312 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
313 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
314 $r = dba::inArray($s);
317 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
318 if (!DBM::is_result($r)) {
319 $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`,
320 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
321 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
322 $r = dba::inArray($s);
325 // Fetch the data from the gcontact table
326 if (!DBM::is_result($r)) {
327 $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`,
328 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
329 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
330 $r = dba::inArray($s);
333 if (DBM::is_result($r)) {
334 // If there is more than one entry we filter out the connector networks
336 foreach ($r as $id => $result) {
337 if ($result["network"] == NETWORK_STATUSNET) {
343 $profile = array_shift($r);
345 // "bd" always contains the upcoming birthday of a contact.
346 // "birthday" might contain the birthday including the year of birth.
347 if ($profile["birthday"] > '0001-01-01') {
348 $bd_timestamp = strtotime($profile["birthday"]);
349 $month = date("m", $bd_timestamp);
350 $day = date("d", $bd_timestamp);
352 $current_timestamp = time();
353 $current_year = date("Y", $current_timestamp);
354 $current_month = date("m", $current_timestamp);
355 $current_day = date("d", $current_timestamp);
357 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
358 $current = $current_year . "-" . $current_month . "-" . $current_day;
360 if ($profile["bd"] < $current) {
361 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
364 $profile["bd"] = '0001-01-01';
370 if (($profile["photo"] == "") && isset($default["photo"])) {
371 $profile["photo"] = $default["photo"];
374 if (($profile["name"] == "") && isset($default["name"])) {
375 $profile["name"] = $default["name"];
378 if (($profile["network"] == "") && isset($default["network"])) {
379 $profile["network"] = $default["network"];
382 if (($profile["thumb"] == "") && isset($profile["photo"])) {
383 $profile["thumb"] = $profile["photo"];
386 if (($profile["micro"] == "") && isset($profile["thumb"])) {
387 $profile["micro"] = $profile["thumb"];
390 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
391 && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
393 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
396 // Show contact details of Diaspora contacts only if connected
397 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
398 $profile["location"] = "";
399 $profile["about"] = "";
400 $profile["gender"] = "";
401 $profile["birthday"] = '0001-01-01';
404 $cache[$url][$uid] = $profile;
410 * @brief Get contact data for a given address
412 * The function looks at several places (contact table and gcontact table) for the contact
414 * @param string $addr The profile link
415 * @param int $uid User id
417 * @return array Contact data
419 public static function getDetailsByAddr($addr, $uid = -1)
421 static $cache = array();
431 // Fetch contact data from the contact table for the given user
432 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
433 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
434 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
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",
447 // Fetch the data from the gcontact table
448 if (!DBM::is_result($r)) {
449 $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`,
450 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
451 FROM `gcontact` WHERE `addr` = '%s'",
456 if (!DBM::is_result($r)) {
457 $data = Probe::uri($addr);
459 $profile = self::getDetailsByURL($data['url'], $uid);
468 * @brief Returns the data array for the photo menu of a given contact
470 * @param array $contact contact
471 * @param int $uid optional, default 0
474 public static function photoMenu(array $contact, $uid = 0)
476 // @todo Unused, to be removed
484 $contact_drop_link = '';
491 if ($contact['uid'] != $uid) {
493 $profile_link = zrl($contact['url']);
494 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
499 // Look for our own contact if the uid doesn't match and isn't public
500 $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
501 if (DBM::is_result($contact_own)) {
502 return self::photoMenu($contact_own, $uid);
504 $profile_link = zrl($contact['url']);
505 $connlnk = 'follow/?url=' . $contact['url'];
507 'profile' => array(t('View Profile'), $profile_link, true),
508 'follow' => array(t('Connect/Follow'), $connlnk, true)
516 if ($contact['network'] === NETWORK_DFRN) {
518 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
520 $profile_link = $contact['url'];
523 if ($profile_link === 'mailbox') {
528 $status_link = $profile_link . '?url=status';
529 $photos_link = $profile_link . '?url=photos';
530 $profile_link = $profile_link . '?url=profile';
533 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
534 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
537 if ($contact['network'] == NETWORK_DFRN) {
538 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
541 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
543 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
544 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
548 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
551 'status' => [t("View Status") , $status_link , true],
552 'profile' => [t("View Profile") , $profile_link , true],
553 'photos' => [t("View Photos") , $photos_link , true],
554 'network' => [t("Network Posts"), $posts_link , false],
555 'edit' => [t("View Contact") , $contact_url , false],
556 'drop' => [t("Drop Contact") , $contact_drop_link, false],
557 'pm' => [t("Send PM") , $pm_url , false],
558 'poke' => [t("Poke") , $poke_link , false],
561 $args = ['contact' => $contact, 'menu' => &$menu];
563 call_hooks('contact_photo_menu', $args);
565 $menucondensed = array();
567 foreach ($menu as $menuname => $menuitem) {
568 if ($menuitem[1] != '') {
569 $menucondensed[$menuname] = $menuitem;
573 return $menucondensed;
577 * @brief Returns ungrouped contact count or list for user
579 * Returns either the total number of ungrouped contacts for the given user
580 * id or a paginated list of ungrouped contacts.
582 * @param int $uid uid
583 * @param int $start optional, default 0
584 * @param int $count optional, default 0
588 public static function getUngroupedList($uid, $start = 0, $count = 0)
592 "SELECT COUNT(*) AS `total`
599 SELECT DISTINCT(`contact-id`)
618 SELECT DISTINCT(`contact-id`)
620 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
621 WHERE `group`.`uid` = %d
634 * @brief Fetch the contact id for a given URL and user
636 * First lookup in the contact table to find a record matching either `url`, `nurl`,
639 * If there's no record and we aren't looking for a public contact, we quit.
640 * If there's one, we check that it isn't time to update the picture else we
641 * directly return the found contact id.
643 * Second, we probe the provided $url whether it's http://server.tld/profile or
644 * nick@server.tld. We quit if we can't get any info back.
646 * Third, we create the contact record if it doesn't exist
648 * Fourth, we update the existing record with the new data (avatar, alias, nick)
649 * if there's any updates
651 * @param string $url Contact URL
652 * @param integer $uid The user id for the contact (0 = public contact)
653 * @param boolean $no_update Don't update the contact
655 * @return integer Contact ID
657 public static function getIdForURL($url, $uid = 0, $no_update = false)
659 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
667 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
668 // We first try the nurl (http://server.tld/nick), most common case
669 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
671 // Then the addr (nick@server.tld)
672 if (!DBM::is_result($contact)) {
673 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
676 // Then the alias (which could be anything)
677 if (!DBM::is_result($contact)) {
678 // The link could be provided as http although we stored it as https
679 $ssl_url = str_replace('http://', 'https://', $url);
680 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
681 $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
684 if (DBM::is_result($contact)) {
685 $contact_id = $contact["id"];
687 // Update the contact every 7 days
688 $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
690 // We force the update if the avatar is empty
691 if (!x($contact, 'avatar')) {
692 $update_contact = true;
695 if (!$update_contact || $no_update) {
698 } elseif ($uid != 0) {
699 // Non-existing user-specific contact, exiting
703 $data = Probe::uri($url, "", $uid);
705 // Last try in gcontact for unsupported networks
706 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
711 // Get data from the gcontact table
712 $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
713 if (!DBM::is_result($gcontact)) {
717 $data = array_merge($data, $gcontact);
720 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
721 $contact_id = self::getIdForURL($data["alias"], $uid, true);
726 dba::insert('contact', [
728 'created' => datetime_convert(),
729 'url' => $data["url"],
730 'nurl' => normalise_link($data["url"]),
731 'addr' => $data["addr"],
732 'alias' => $data["alias"],
733 'notify' => $data["notify"],
734 'poll' => $data["poll"],
735 'name' => $data["name"],
736 'nick' => $data["nick"],
737 'photo' => $data["photo"],
738 'keywords' => $data["keywords"],
739 'location' => $data["location"],
740 'about' => $data["about"],
741 'network' => $data["network"],
742 'pubkey' => $data["pubkey"],
743 'rel' => CONTACT_IS_SHARING,
744 'priority' => $data["priority"],
745 'batch' => $data["batch"],
746 'request' => $data["request"],
747 'confirm' => $data["confirm"],
748 'poco' => $data["poco"],
749 'name-date' => datetime_convert(),
750 'uri-date' => datetime_convert(),
751 'avatar-date' => datetime_convert(),
758 $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
759 $contacts = dba::inArray($s);
760 if (!DBM::is_result($contacts)) {
764 $contact_id = $contacts[0]["id"];
766 // Update the newly created contact from data in the gcontact table
767 $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
768 if (DBM::is_result($gcontact)) {
769 // Only use the information when the probing hadn't fetched these values
770 if ($data['keywords'] != '') {
771 unset($gcontact['keywords']);
773 if ($data['location'] != '') {
774 unset($gcontact['location']);
776 if ($data['about'] != '') {
777 unset($gcontact['about']);
779 dba::update('contact', $gcontact, array('id' => $contact_id));
782 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
783 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
784 normalise_link($data["url"]), $contact_id]);
788 self::updateAvatar($data["photo"], $uid, $contact_id);
790 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
791 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
793 // This condition should always be true
794 if (!DBM::is_result($contact)) {
798 $updated = array('addr' => $data['addr'],
799 'alias' => $data['alias'],
800 'url' => $data['url'],
801 'nurl' => normalise_link($data['url']),
802 'name' => $data['name'],
803 'nick' => $data['nick']);
805 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
806 if (!empty($contact['pubkey'])) {
807 unset($contact['pubkey']);
809 $updated['pubkey'] = $data['pubkey'];
812 if ($data['keywords'] != '') {
813 $updated['keywords'] = $data['keywords'];
815 if ($data['location'] != '') {
816 $updated['location'] = $data['location'];
818 if ($data['about'] != '') {
819 $updated['about'] = $data['about'];
822 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
823 $updated['uri-date'] = datetime_convert();
825 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
826 $updated['name-date'] = datetime_convert();
829 $updated['avatar-date'] = datetime_convert();
831 dba::update('contact', $updated, array('id' => $contact_id), $contact);
837 * @brief Checks if the contact is blocked
839 * @param int $cid contact id
841 * @return boolean Is the contact blocked?
843 public static function isBlocked($cid)
849 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
850 if (!DBM::is_result($blocked)) {
853 return (bool) $blocked['blocked'];
857 * @brief Checks if the contact is hidden
859 * @param int $cid contact id
861 * @return boolean Is the contact hidden?
863 public static function isHidden($cid)
869 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
870 if (!DBM::is_result($hidden)) {
873 return (bool) $hidden['hidden'];
877 * @brief Returns posts from a given contact url
879 * @param string $contact_url Contact URL
881 * @return string posts in HTML
883 public static function getPostsFromUrl($contact_url)
887 require_once 'include/conversation.php';
889 // There are no posts with "uid = 0" with connector networks
890 // This speeds up the query a lot
891 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
892 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
893 dbesc(normalise_link($contact_url))
896 if (!DBM::is_result($r)) {
900 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
901 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
903 $sql = "`item`.`uid` = %d";
906 $author_id = intval($r[0]["author-id"]);
908 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
910 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
911 " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
912 intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
913 intval($a->pager['start']), intval($a->pager['itemspage'])
916 $o = conversation($a, $r, 'contact-posts', false);
918 $o .= alt_pager($a, count($r));
924 * @brief Returns the account type name
926 * The function can be called with either the user or the contact array
928 * @param array $contact contact or user array
931 public static function getAccountType(array $contact)
933 // There are several fields that indicate that the contact or user is a forum
934 // "page-flags" is a field in the user table,
935 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
936 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
937 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
938 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
939 || (isset($contact['forum']) && intval($contact['forum']))
940 || (isset($contact['prv']) && intval($contact['prv']))
941 || (isset($contact['community']) && intval($contact['community']))
943 $type = ACCOUNT_TYPE_COMMUNITY;
945 $type = ACCOUNT_TYPE_PERSON;
948 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
949 if (isset($contact["contact-type"])) {
950 $type = $contact["contact-type"];
953 if (isset($contact["account-type"])) {
954 $type = $contact["account-type"];
958 case ACCOUNT_TYPE_ORGANISATION:
959 $account_type = t("Organisation");
961 case ACCOUNT_TYPE_NEWS:
962 $account_type = t('News');
964 case ACCOUNT_TYPE_COMMUNITY:
965 $account_type = t("Forum");
972 return $account_type;
976 * @brief Blocks a contact
981 public static function block($uid)
983 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
989 * @brief Unblocks a contact
994 public static function unblock($uid)
996 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
1002 * @brief Updates the avatar links in a contact only if needed
1004 * @param string $avatar Link to avatar picture
1005 * @param int $uid User id of contact owner
1006 * @param int $cid Contact id
1007 * @param bool $force force picture update
1009 * @return array Returns array of the different avatar sizes
1011 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1013 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1014 if (!DBM::is_result($contact)) {
1017 $data = array($contact["photo"], $contact["thumb"], $contact["micro"]);
1020 if (($contact["avatar"] != $avatar) || $force) {
1021 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1026 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
1030 // Update the public contact (contact id = 0)
1032 $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1033 if (DBM::is_result($pcontact)) {
1034 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1046 * @param integer $id contact id
1049 public static function updateFromProbe($id)
1052 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1053 This will reliably kill your communication with Friendica contacts.
1056 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1057 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1058 if (!DBM::is_result($contact)) {
1062 $ret = Probe::uri($contact["url"]);
1064 // If Probe::uri fails the network code will be different
1065 if ($ret["network"] != $contact["network"]) {
1071 // make sure to not overwrite existing values with blank entries
1072 foreach ($ret as $key => $val) {
1073 if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1074 $ret[$key] = $contact[$key];
1077 if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1088 'url' => $ret['url'],
1089 'nurl' => normalise_link($ret['url']),
1090 'addr' => $ret['addr'],
1091 'alias' => $ret['alias'],
1092 'batch' => $ret['batch'],
1093 'notify' => $ret['notify'],
1094 'poll' => $ret['poll'],
1095 'poco' => $ret['poco']
1100 // Update the corresponding gcontact entry
1101 PortableContact::lastUpdated($ret["url"]);
1107 * Takes a $uid and a url/handle and adds a new contact
1108 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1109 * dfrn_request page.
1111 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1114 * $return['success'] boolean true if successful
1115 * $return['message'] error text if success is false.
1117 * @brief Takes a $uid and a url/handle and adds a new contact
1119 * @param string $url
1120 * @param bool $interactive
1121 * @param string $network
1122 * @return boolean|string
1124 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1126 $result = array('cid' => -1, 'success' => false, 'message' => '');
1130 // remove ajax junk, e.g. Twitter
1131 $url = str_replace('/#!/', '/', $url);
1133 if (!allowed_url($url)) {
1134 $result['message'] = t('Disallowed profile URL.');
1138 if (blocked_url($url)) {
1139 $result['message'] = t('Blocked domain');
1144 $result['message'] = t('Connect URL missing.');
1148 $arr = array('url' => $url, 'contact' => array());
1150 call_hooks('follow', $arr);
1152 if (x($arr['contact'], 'name')) {
1153 $ret = $arr['contact'];
1155 $ret = Probe::uri($url, $network, $uid, false);
1158 if (($network != '') && ($ret['network'] != $network)) {
1159 logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1163 if ($ret['network'] === NETWORK_DFRN) {
1165 if (strlen($a->path)) {
1166 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1168 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1171 goaway($ret['request'] . "&addr=$myaddr");
1175 } elseif (Config::get('system', 'dfrn_only')) {
1176 $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1177 $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1181 // This extra param just confuses things, remove it
1182 if ($ret['network'] === NETWORK_DIASPORA) {
1183 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1186 // do we have enough information?
1188 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1189 $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1190 if (!x($ret, 'poll')) {
1191 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1193 if (!x($ret, 'name')) {
1194 $result['message'] .= t('An author or name was not found.') . EOL;
1196 if (!x($ret, 'url')) {
1197 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1199 if (strpos($url, '@') !== false) {
1200 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1201 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1206 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1207 $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1208 $ret['notify'] = '';
1211 if (!$ret['notify']) {
1212 $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1215 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1217 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1219 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1221 if (in_array($ret['network'], array(NETWORK_MAIL, NETWORK_DIASPORA))) {
1225 // check if we already have a contact
1226 // the poll url is more reliable than the profile url, as we may have
1227 // indirect links or webfinger links
1229 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1231 dbesc($ret['poll']),
1232 dbesc(normalise_link($ret['poll'])),
1233 dbesc($ret['network'])
1236 if (!DBM::is_result($r)) {
1237 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1239 dbesc(normalise_link($url)),
1240 dbesc($ret['network'])
1244 if (DBM::is_result($r)) {
1246 $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1248 $fields = array('rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false);
1249 dba::update('contact', $fields, array('id' => $r[0]['id']));
1251 $new_relation = ((in_array($ret['network'], array(NETWORK_MAIL))) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1253 // create contact record
1254 dba::insert('contact', [
1256 'created' => datetime_convert(),
1257 'url' => $ret['url'],
1258 'nurl' => normalise_link($ret['url']),
1259 'addr' => $ret['addr'],
1260 'alias' => $ret['alias'],
1261 'batch' => $ret['batch'],
1262 'notify' => $ret['notify'],
1263 'poll' => $ret['poll'],
1264 'poco' => $ret['poco'],
1265 'name' => $ret['name'],
1266 'nick' => $ret['nick'],
1267 'network' => $ret['network'],
1268 'pubkey' => $ret['pubkey'],
1269 'rel' => $new_relation,
1270 'priority'=> $ret['priority'],
1271 'writable'=> $writeable,
1272 'hidden' => $hidden,
1280 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1281 if (!DBM::is_result($contact)) {
1282 $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1286 $contact_id = $contact['id'];
1287 $result['cid'] = $contact_id;
1289 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1291 // Update the avatar
1292 self::updateAvatar($ret['photo'], $uid, $contact_id);
1294 // pull feed and consume it, which should subscribe to the hub.
1296 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1298 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1299 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1303 if (DBM::is_result($r)) {
1304 if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1305 // create a follow slap
1307 $item['verb'] = ACTIVITY_FOLLOW;
1308 $item['follow'] = $contact["url"];
1309 $slap = OStatus::salmon($item, $r[0]);
1310 Salmon::slapper($r[0], $contact['notify'], $slap);
1313 if ($contact['network'] == NETWORK_DIASPORA) {
1314 $ret = Diaspora::sendShare($a->user, $contact);
1315 logger('share returns: ' . $ret);
1319 $result['success'] = true;