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\Salmon;
22 require_once 'boot.php';
23 require_once 'include/dba.php';
24 require_once 'include/text.php';
27 * @brief functions for interacting with a contact
29 class Contact extends BaseObject
32 * @brief Returns a list of contacts belonging in a group
37 public static function getByGroupId($gid)
41 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
43 INNER JOIN `group_member`
44 ON `contact`.`id` = `group_member`.`contact-id`
46 AND `contact`.`uid` = ?
47 AND NOT `contact`.`self`
48 AND NOT `contact`.`blocked`
49 AND NOT `contact`.`pending`
50 ORDER BY `contact`.`name` ASC',
54 if (DBM::is_result($stmt)) {
55 $return = dba::inArray($stmt);
63 * @brief Returns the count of OStatus contacts in a group
68 public static function getOStatusCountByGroupId($gid)
72 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
74 INNER JOIN `group_member`
75 ON `contact`.`id` = `group_member`.`contact-id`
77 AND `contact`.`uid` = ?
78 AND `contact`.`network` = ?
79 AND `contact`.`notify` != ""',
84 $return = $contacts['count'];
92 * Creates the self-contact for the provided user id
95 * @return bool Operation success
97 public static function createSelfFromUserId($uid)
99 // Only create the entry if it doesn't exist yet
100 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
104 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]);
105 if (!DBM::is_result($user)) {
109 $return = dba::insert('contact', [
110 'uid' => $user['uid'],
111 'created' => datetime_convert(),
113 'name' => $user['username'],
114 'nick' => $user['nickname'],
115 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
116 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
117 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
120 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
121 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
122 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
123 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
124 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
125 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
126 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
127 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
128 'name-date' => datetime_convert(),
129 'uri-date' => datetime_convert(),
130 'avatar-date' => datetime_convert(),
138 * @brief Marks a contact for removal
140 * @param int $id contact id
143 public static function remove($id)
145 // We want just to make sure that we don't delete our "self" contact
146 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
148 if (!DBM::is_result($r) || !intval($r['uid'])) {
152 $archive = PConfig::get($r['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", dbesc($addr), intval($uid));
436 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
437 if (!DBM::is_result($r))
438 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
439 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
440 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
442 // Fetch the data from the gcontact table
443 if (!DBM::is_result($r))
444 $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`,
445 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
446 FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
448 if (!DBM::is_result($r)) {
449 $data = Probe::uri($addr);
451 $profile = self::getDetailsByURL($data['url'], $uid);
460 * @brief Returns the data array for the photo menu of a given contact
462 * @param array $contact contact
463 * @param int $uid optional, default 0
466 public static function photoMenu(array $contact, $uid = 0)
468 // @todo Unused, to be removed
476 $contact_drop_link = '';
483 if ($contact['uid'] != $uid) {
485 $profile_link = zrl($contact['url']);
486 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
491 $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1));
493 return self::photoMenu($r, $uid);
495 $profile_link = zrl($contact['url']);
496 $connlnk = 'follow/?url=' . $contact['url'];
498 'profile' => array(t('View Profile'), $profile_link, true),
499 'follow' => array(t('Connect/Follow'), $connlnk, true)
507 if ($contact['network'] === NETWORK_DFRN) {
509 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
511 $profile_link = $contact['url'];
514 if ($profile_link === 'mailbox') {
519 $status_link = $profile_link . '?url=status';
520 $photos_link = $profile_link . '?url=photos';
521 $profile_link = $profile_link . '?url=profile';
524 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
525 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
528 if ($contact['network'] == NETWORK_DFRN) {
529 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
532 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
534 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
535 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
539 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
542 'status' => array(t("View Status"), $status_link, true),
543 'profile' => array(t("View Profile"), $profile_link, true),
544 'photos' => array(t("View Photos"), $photos_link, true),
545 'network' => array(t("Network Posts"), $posts_link, false),
546 'edit' => array(t("View Contact"), $contact_url, false),
547 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
548 'pm' => array(t("Send PM"), $pm_url, false),
549 'poke' => array(t("Poke"), $poke_link, false),
553 $args = array('contact' => $contact, 'menu' => &$menu);
555 call_hooks('contact_photo_menu', $args);
557 $menucondensed = array();
559 foreach ($menu as $menuname => $menuitem) {
560 if ($menuitem[1] != '') {
561 $menucondensed[$menuname] = $menuitem;
565 return $menucondensed;
569 * @brief Returns ungrouped contact count or list for user
571 * Returns either the total number of ungrouped contacts for the given user
572 * id or a paginated list of ungrouped contacts.
574 * @param int $uid uid
575 * @param int $start optional, default 0
576 * @param int $count optional, default 0
580 public static function getUngroupedList($uid, $start = 0, $count = 0)
584 "SELECT COUNT(*) AS `total`
591 SELECT DISTINCT(`contact-id`)
594 )", intval($uid), intval($uid)
608 SELECT DISTINCT(`contact-id`)
610 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
611 WHERE `group`.`uid` = %d
613 LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
619 * @brief Fetch the contact id for a given url and user
621 * First lookup in the contact table to find a record matching either `url`, `nurl`,
624 * If there's no record and we aren't looking for a public contact, we quit.
625 * If there's one, we check that it isn't time to update the picture else we
626 * directly return the found contact id.
628 * Second, we probe the provided $url wether it's http://server.tld/profile or
629 * nick@server.tld. We quit if we can't get any info back.
631 * Third, we create the contact record if it doesn't exist
633 * Fourth, we update the existing record with the new data (avatar, alias, nick)
634 * if there's any updates
636 * @param string $url Contact URL
637 * @param integer $uid The user id for the contact (0 = public contact)
638 * @param boolean $no_update Don't update the contact
640 * @return integer Contact ID
642 public static function getIdForURL($url, $uid = 0, $no_update = false)
644 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
652 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
653 // We first try the nurl (http://server.tld/nick), most common case
654 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
656 // Then the addr (nick@server.tld)
657 if (!DBM::is_result($contact)) {
658 $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
661 // Then the alias (which could be anything)
662 if (!DBM::is_result($contact)) {
663 // The link could be provided as http although we stored it as https
664 $ssl_url = str_replace('http://', 'https://', $url);
665 $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
666 $contact = dba::fetch($r);
670 if (DBM::is_result($contact)) {
671 $contact_id = $contact["id"];
673 // Update the contact every 7 days
674 $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
676 // We force the update if the avatar is empty
677 if ($contact['avatar'] == '') {
678 $update_contact = true;
681 if (!$update_contact || $no_update) {
684 } elseif ($uid != 0) {
685 // Non-existing user-specific contact, exiting
689 $data = Probe::uri($url, "", $uid);
691 // Last try in gcontact for unsupported networks
692 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
697 // Get data from the gcontact table
698 $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
699 if (!DBM::is_result($gcontacts)) {
703 $data = array_merge($data, $gcontacts);
706 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
707 $contact_id = self::getIdForURL($data["alias"], $uid, true);
713 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
714 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
715 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
716 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
717 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
718 'network' => $data["network"], 'pubkey' => $data["pubkey"],
719 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
720 'batch' => $data["batch"], 'request' => $data["request"],
721 'confirm' => $data["confirm"], 'poco' => $data["poco"],
722 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
723 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
724 'readonly' => 0, 'pending' => 0)
727 $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
728 $contacts = dba::inArray($s);
729 if (!DBM::is_result($contacts)) {
733 $contact_id = $contacts[0]["id"];
735 // Update the newly created contact from data in the gcontact table
736 $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
737 if (DBM::is_result($gcontact)) {
738 // Only use the information when the probing hadn't fetched these values
739 if ($data['keywords'] != '') {
740 unset($gcontact['keywords']);
742 if ($data['location'] != '') {
743 unset($gcontact['location']);
745 if ($data['about'] != '') {
746 unset($gcontact['about']);
748 dba::update('contact', $gcontact, array('id' => $contact_id));
751 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
752 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
753 normalise_link($data["url"]), $contact_id));
757 self::updateAvatar($data["photo"], $uid, $contact_id);
759 $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
760 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
762 // This condition should always be true
763 if (!DBM::is_result($contact)) {
767 $updated = array('addr' => $data['addr'],
768 'alias' => $data['alias'],
769 'url' => $data['url'],
770 'nurl' => normalise_link($data['url']),
771 'name' => $data['name'],
772 'nick' => $data['nick']);
774 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
775 if (!empty($contact['pubkey'])) {
776 unset($contact['pubkey']);
778 $updated['pubkey'] = $data['pubkey'];
781 if ($data['keywords'] != '') {
782 $updated['keywords'] = $data['keywords'];
784 if ($data['location'] != '') {
785 $updated['location'] = $data['location'];
787 if ($data['about'] != '') {
788 $updated['about'] = $data['about'];
791 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
792 $updated['uri-date'] = datetime_convert();
794 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
795 $updated['name-date'] = datetime_convert();
798 $updated['avatar-date'] = datetime_convert();
800 dba::update('contact', $updated, array('id' => $contact_id), $contact);
806 * @brief Checks if the contact is blocked
808 * @param int $cid contact id
810 * @return boolean Is the contact blocked?
812 public static function isBlocked($cid)
818 $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
819 if (!DBM::is_result($blocked)) {
822 return (bool) $blocked['blocked'];
826 * @brief Checks if the contact is hidden
828 * @param int $cid contact id
830 * @return boolean Is the contact hidden?
832 public static function isHidden($cid)
838 $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
839 if (!DBM::is_result($hidden)) {
842 return (bool) $hidden['hidden'];
846 * @brief Returns posts from a given contact url
848 * @param string $contact_url Contact URL
850 * @return string posts in HTML
852 public static function getPostsFromUrl($contact_url)
856 require_once 'include/conversation.php';
858 // There are no posts with "uid = 0" with connector networks
859 // This speeds up the query a lot
860 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
861 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
863 if (!DBM::is_result($r)) {
867 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
868 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
870 $sql = "`item`.`uid` = %d";
873 $author_id = intval($r[0]["author-id"]);
875 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
877 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
878 " ORDER BY `item`.`created` DESC LIMIT %d, %d", intval($author_id), intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage'])
882 $o = conversation($a, $r, 'community', false);
884 $o .= alt_pager($a, count($r));
890 * @brief Returns the account type name
892 * The function can be called with either the user or the contact array
894 * @param array $contact contact or user array
897 public static function getAccountType(array $contact)
899 // There are several fields that indicate that the contact or user is a forum
900 // "page-flags" is a field in the user table,
901 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
902 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
903 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
904 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
905 || (isset($contact['forum']) && intval($contact['forum']))
906 || (isset($contact['prv']) && intval($contact['prv']))
907 || (isset($contact['community']) && intval($contact['community']))
909 $type = ACCOUNT_TYPE_COMMUNITY;
911 $type = ACCOUNT_TYPE_PERSON;
914 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
915 if (isset($contact["contact-type"])) {
916 $type = $contact["contact-type"];
918 if (isset($contact["account-type"])) {
919 $type = $contact["account-type"];
923 case ACCOUNT_TYPE_ORGANISATION:
924 $account_type = t("Organisation");
926 case ACCOUNT_TYPE_NEWS:
927 $account_type = t('News');
929 case ACCOUNT_TYPE_COMMUNITY:
930 $account_type = t("Forum");
937 return $account_type;
941 * @brief Blocks a contact
946 public static function block($uid)
948 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
954 * @brief Unblocks a contact
959 public static function unblock($uid)
961 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
967 * @brief Updates the avatar links in a contact only if needed
969 * @param string $avatar Link to avatar picture
970 * @param int $uid User id of contact owner
971 * @param int $cid Contact id
972 * @param bool $force force picture update
974 * @return array Returns array of the different avatar sizes
976 public static function updateAvatar($avatar, $uid, $cid, $force = false)
978 // Limit = 1 returns the row so no need for dba:inArray()
979 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
980 if (!DBM::is_result($r)) {
983 $data = array($r["photo"], $r["thumb"], $r["micro"]);
986 if (($r["avatar"] != $avatar) || $force) {
987 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
992 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
996 // Update the public contact (contact id = 0)
998 $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
999 if (DBM::is_result($pcontact)) {
1000 self::updateAvatar($avatar, 0, $pcontact['id'], $force);