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/text.php';
26 * @brief functions for interacting with a contact
28 class Contact extends BaseObject
31 * @brief Returns a list of contacts belonging in a group
36 public static function getByGroupId($gid)
40 $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
42 INNER JOIN `group_member`
43 ON `contact`.`id` = `group_member`.`contact-id`
45 AND `group_member`.`uid` = ?
46 AND NOT `contact`.`self`
47 AND NOT `contact`.`blocked`
48 AND NOT `contact`.`pending`
49 ORDER BY `contact`.`name` ASC',
53 if (DBM::is_result($stmt)) {
54 $return = dba::inArray($stmt);
62 * @brief Returns the count of OStatus contacts in a group
67 public static function getOStatusCountByGroupId($gid)
71 $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
73 INNER JOIN `group_member`
74 ON `contact`.`id` = `group_member`.`contact-id`
76 AND `group_member`.`uid` = ?
77 AND `contact`.`network` = ?
78 AND `contact`.`notify` != ""',
83 $return = $contacts['count'];
91 * Creates the self-contact for the provided user id
94 * @return bool Operation success
96 public static function createSelfFromUserId($uid)
98 // Only create the entry if it doesn't exist yet
99 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
103 $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]);
104 if (!DBM::is_result($user)) {
108 $return = dba::insert('contact', [
109 'uid' => $user['uid'],
110 'created' => datetime_convert(),
112 'name' => $user['username'],
113 'nick' => $user['nickname'],
114 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
115 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
116 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
119 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
120 'nurl' => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
121 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
122 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
123 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
124 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
125 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
126 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
127 'name-date' => datetime_convert(),
128 'uri-date' => datetime_convert(),
129 'avatar-date' => datetime_convert(),
137 * @brief Marks a contact for removal
139 * @param int $id contact id
142 public static function remove($id)
144 // We want just to make sure that we don't delete our "self" contact
145 $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1));
147 if (!DBM::is_result($r) || !intval($r['uid'])) {
151 $archive = PConfig::get($r['uid'], 'system', 'archive_removed_contacts');
153 dba::update('contact', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
157 dba::delete('contact', array('id' => $id));
159 // Delete the rest in the background
160 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
164 * @brief Sends an unfriend message. Does not remove the contact
166 * @param array $user User unfriending
167 * @param array $contact Contact unfriended
170 public static function terminateFriendship(array $user, array $contact)
172 if ($contact['network'] === NETWORK_OSTATUS) {
173 // create an unfollow slap
175 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
176 $item['follow'] = $contact["url"];
177 $slap = OStatus::salmon($item, $user);
179 if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
180 Salmon::slapper($user, $contact['notify'], $slap);
182 } elseif ($contact['network'] === NETWORK_DIASPORA) {
183 Diaspora::sendUnshare($user, $contact);
184 } elseif ($contact['network'] === NETWORK_DFRN) {
185 DFRN::deliver($user, $contact, 'placeholder', 1);
190 * @brief Marks a contact for archival after a communication issue delay
192 * Contact has refused to recognise us as a friend. We will start a countdown.
193 * If they still don't recognise us in 32 days, the relationship is over,
194 * and we won't waste any more time trying to communicate with them.
195 * This provides for the possibility that their database is temporarily messed
196 * up or some other transient event and that there's a possibility we could recover from it.
198 * @param array $contact contact to mark for archival
201 public static function markForArchival(array $contact)
203 // Contact already archived or "self" contact? => nothing to do
204 if ($contact['archive'] || $contact['self']) {
208 if ($contact['term-date'] <= NULL_DATE) {
209 dba::update('contact', array('term-date' => datetime_convert()), array('id' => $contact['id']));
211 if ($contact['url'] != '') {
212 dba::update('contact', array('term-date' => datetime_convert()), array('`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE));
216 * We really should send a notification to the owner after 2-3 weeks
217 * so they won't be surprised when the contact vanishes and can take
218 * remedial action if this was a serious mistake or glitch
221 /// @todo Check for contact vitality via probing
222 $expiry = $contact['term-date'] . ' + 32 days ';
223 if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
224 /* Relationship is really truly dead. archive them rather than
225 * delete, though if the owner tries to unarchive them we'll start
226 * the whole process over again.
228 dba::update('contact', array('archive' => 1), array('id' => $contact['id']));
230 if ($contact['url'] != '') {
231 dba::update('contact', array('archive' => 1), array('nurl' => normalise_link($contact['url']), 'self' => false));
238 * @brief Cancels the archival countdown
240 * @see Contact::markForArchival()
242 * @param array $contact contact to be unmarked for archival
245 public static function unmarkForArchival(array $contact)
247 $condition = array('`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE);
248 $exists = dba::exists('contact', $condition);
250 // We don't need to update, we never marked this contact for archival
255 // It's a miracle. Our dead contact has inexplicably come back to life.
256 $fields = array('term-date' => NULL_DATE, 'archive' => false);
257 dba::update('contact', $fields, array('id' => $contact['id']));
259 if ($contact['url'] != '') {
260 dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
265 * @brief Get contact data for a given profile link
267 * The function looks at several places (contact table and gcontact table) for the contact
268 * It caches its result for the same script execution to prevent duplicate calls
270 * @param string $url The profile link
271 * @param int $uid User id
272 * @param array $default If not data was found take this data as default value
274 * @return array Contact data
276 public static function getDetailsByURL($url, $uid = -1, array $default = [])
278 static $cache = array();
288 if (isset($cache[$url][$uid])) {
289 return $cache[$url][$uid];
292 $ssl_url = str_replace('http://', 'https://', $url);
294 // Fetch contact data from the contact table for the given user
295 $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`,
296 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
297 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
298 $r = dba::inArray($s);
300 // Fetch contact data from the contact table for the given user, checking with the alias
301 if (!DBM::is_result($r)) {
302 $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`,
303 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
304 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
305 $r = dba::inArray($s);
308 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
309 if (!DBM::is_result($r)) {
310 $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`,
311 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
312 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
313 $r = dba::inArray($s);
316 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
317 if (!DBM::is_result($r)) {
318 $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`,
319 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
320 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
321 $r = dba::inArray($s);
324 // Fetch the data from the gcontact table
325 if (!DBM::is_result($r)) {
326 $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`,
327 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
328 FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
329 $r = dba::inArray($s);
332 if (DBM::is_result($r)) {
333 // If there is more than one entry we filter out the connector networks
335 foreach ($r as $id => $result) {
336 if ($result["network"] == NETWORK_STATUSNET) {
342 $profile = array_shift($r);
344 // "bd" always contains the upcoming birthday of a contact.
345 // "birthday" might contain the birthday including the year of birth.
346 if ($profile["birthday"] > '0001-01-01') {
347 $bd_timestamp = strtotime($profile["birthday"]);
348 $month = date("m", $bd_timestamp);
349 $day = date("d", $bd_timestamp);
351 $current_timestamp = time();
352 $current_year = date("Y", $current_timestamp);
353 $current_month = date("m", $current_timestamp);
354 $current_day = date("d", $current_timestamp);
356 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
357 $current = $current_year . "-" . $current_month . "-" . $current_day;
359 if ($profile["bd"] < $current) {
360 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
363 $profile["bd"] = '0001-01-01';
369 if (($profile["photo"] == "") && isset($default["photo"])) {
370 $profile["photo"] = $default["photo"];
373 if (($profile["name"] == "") && isset($default["name"])) {
374 $profile["name"] = $default["name"];
377 if (($profile["network"] == "") && isset($default["network"])) {
378 $profile["network"] = $default["network"];
381 if (($profile["thumb"] == "") && isset($profile["photo"])) {
382 $profile["thumb"] = $profile["photo"];
385 if (($profile["micro"] == "") && isset($profile["thumb"])) {
386 $profile["micro"] = $profile["thumb"];
389 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
390 && in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))
392 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
395 // Show contact details of Diaspora contacts only if connected
396 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
397 $profile["location"] = "";
398 $profile["about"] = "";
399 $profile["gender"] = "";
400 $profile["birthday"] = '0001-01-01';
403 $cache[$url][$uid] = $profile;
409 * @brief Get contact data for a given address
411 * The function looks at several places (contact table and gcontact table) for the contact
413 * @param string $addr The profile link
414 * @param int $uid User id
416 * @return array Contact data
418 public static function getDetailsByAddr($addr, $uid = -1)
420 static $cache = array();
430 // Fetch contact data from the contact table for the given user
431 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
432 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
433 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d", dbesc($addr), intval($uid));
435 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
436 if (!DBM::is_result($r))
437 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
438 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
439 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
441 // Fetch the data from the gcontact table
442 if (!DBM::is_result($r))
443 $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`,
444 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
445 FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
447 if (!DBM::is_result($r)) {
448 $data = Probe::uri($addr);
450 $profile = self::getDetailsByURL($data['url'], $uid);
459 * @brief Returns the data array for the photo menu of a given contact
461 * @param array $contact contact
462 * @param int $uid optional, default 0
465 public static function photoMenu(array $contact, $uid = 0)
467 // @todo Unused, to be removed
475 $contact_drop_link = '';
482 if ($contact['uid'] != $uid) {
484 $profile_link = zrl($contact['url']);
485 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
490 $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1));
492 return self::photoMenu($r, $uid);
494 $profile_link = zrl($contact['url']);
495 $connlnk = 'follow/?url=' . $contact['url'];
497 'profile' => array(t('View Profile'), $profile_link, true),
498 'follow' => array(t('Connect/Follow'), $connlnk, true)
506 if ($contact['network'] === NETWORK_DFRN) {
508 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
510 $profile_link = $contact['url'];
513 if ($profile_link === 'mailbox') {
518 $status_link = $profile_link . '?url=status';
519 $photos_link = $profile_link . '?url=photos';
520 $profile_link = $profile_link . '?url=profile';
523 if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
524 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
527 if ($contact['network'] == NETWORK_DFRN) {
528 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
531 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
533 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
534 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
538 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
541 'status' => array(t("View Status"), $status_link, true),
542 'profile' => array(t("View Profile"), $profile_link, true),
543 'photos' => array(t("View Photos"), $photos_link, true),
544 'network' => array(t("Network Posts"), $posts_link, false),
545 'edit' => array(t("View Contact"), $contact_url, false),
546 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
547 'pm' => array(t("Send PM"), $pm_url, false),
548 'poke' => array(t("Poke"), $poke_link, false),
552 $args = array('contact' => $contact, 'menu' => &$menu);
554 call_hooks('contact_photo_menu', $args);
556 $menucondensed = array();
558 foreach ($menu as $menuname => $menuitem) {
559 if ($menuitem[1] != '') {
560 $menucondensed[$menuname] = $menuitem;
564 return $menucondensed;
568 * @brief Returns ungrouped contact count or list for user
570 * Returns either the total number of ungrouped contacts for the given user
571 * id or a paginated list of ungrouped contacts.
573 * @param int $uid uid
574 * @param int $start optional, default 0
575 * @param int $count optional, default 0
579 public static function getUngroupedList($uid, $start = 0, $count = 0)
583 "SELECT COUNT(*) AS `total`
590 SELECT DISTINCT(`contact-id`)
593 )", intval($uid), intval($uid)
607 SELECT DISTINCT(`contact-id`)
608 FROM `group_member` WHERE `uid` = %d
610 LIMIT %d, %d", intval($uid), intval($uid), intval($start), intval($count)
616 * @brief Fetch the contact id for a given url and user
618 * First lookup in the contact table to find a record matching either `url`, `nurl`,
621 * If there's no record and we aren't looking for a public contact, we quit.
622 * If there's one, we check that it isn't time to update the picture else we
623 * directly return the found contact id.
625 * Second, we probe the provided $url wether it's http://server.tld/profile or
626 * nick@server.tld. We quit if we can't get any info back.
628 * Third, we create the contact record if it doesn't exist
630 * Fourth, we update the existing record with the new data (avatar, alias, nick)
631 * if there's any updates
633 * @param string $url Contact URL
634 * @param integer $uid The user id for the contact (0 = public contact)
635 * @param boolean $no_update Don't update the contact
637 * @return integer Contact ID
639 public static function getIdForURL($url, $uid = 0, $no_update = false)
641 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
649 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
650 // We first try the nurl (http://server.tld/nick), most common case
651 $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
653 // Then the addr (nick@server.tld)
654 if (!DBM::is_result($contact)) {
655 $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
658 // Then the alias (which could be anything)
659 if (!DBM::is_result($contact)) {
660 // The link could be provided as http although we stored it as https
661 $ssl_url = str_replace('http://', 'https://', $url);
662 $r = dba::select('contact', array('id', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1));
663 $contact = dba::fetch($r);
667 if (DBM::is_result($contact)) {
668 $contact_id = $contact["id"];
670 // Update the contact every 7 days
671 $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
673 // We force the update if the avatar is empty
674 if ($contact['avatar'] == '') {
675 $update_contact = true;
678 if (!$update_contact || $no_update) {
681 } elseif ($uid != 0) {
682 // Non-existing user-specific contact, exiting
686 $data = Probe::uri($url, "", $uid);
688 // Last try in gcontact for unsupported networks
689 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
694 // Get data from the gcontact table
695 $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1));
696 if (!DBM::is_result($gcontacts)) {
700 $data = array_merge($data, $gcontacts);
703 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
704 $contact_id = self::getIdForURL($data["alias"], $uid, true);
710 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
711 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
712 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
713 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
714 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
715 'network' => $data["network"], 'pubkey' => $data["pubkey"],
716 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
717 'batch' => $data["batch"], 'request' => $data["request"],
718 'confirm' => $data["confirm"], 'poco' => $data["poco"],
719 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
720 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
721 'readonly' => 0, 'pending' => 0)
724 $s = dba::select('contact', array('id'), array('nurl' => normalise_link($data["url"]), 'uid' => $uid), array('order' => array('id'), 'limit' => 2));
725 $contacts = dba::inArray($s);
726 if (!DBM::is_result($contacts)) {
730 $contact_id = $contacts[0]["id"];
732 // Update the newly created contact from data in the gcontact table
733 $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1));
734 if (DBM::is_result($gcontact)) {
735 // Only use the information when the probing hadn't fetched these values
736 if ($data['keywords'] != '') {
737 unset($gcontact['keywords']);
739 if ($data['location'] != '') {
740 unset($gcontact['location']);
742 if ($data['about'] != '') {
743 unset($gcontact['about']);
745 dba::update('contact', $gcontact, array('id' => $contact_id));
748 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
749 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
750 normalise_link($data["url"]), $contact_id));
754 self::updateAvatar($data["photo"], $uid, $contact_id);
756 $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey');
757 $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1));
759 // This condition should always be true
760 if (!DBM::is_result($contact)) {
764 $updated = array('addr' => $data['addr'],
765 'alias' => $data['alias'],
766 'url' => $data['url'],
767 'nurl' => normalise_link($data['url']),
768 'name' => $data['name'],
769 'nick' => $data['nick']);
771 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
772 if (!empty($contact['pubkey'])) {
773 unset($contact['pubkey']);
775 $updated['pubkey'] = $data['pubkey'];
778 if ($data['keywords'] != '') {
779 $updated['keywords'] = $data['keywords'];
781 if ($data['location'] != '') {
782 $updated['location'] = $data['location'];
784 if ($data['about'] != '') {
785 $updated['about'] = $data['about'];
788 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
789 $updated['uri-date'] = datetime_convert();
791 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
792 $updated['name-date'] = datetime_convert();
795 $updated['avatar-date'] = datetime_convert();
797 dba::update('contact', $updated, array('id' => $contact_id), $contact);
803 * @brief Checks if the contact is blocked
805 * @param int $cid contact id
807 * @return boolean Is the contact blocked?
809 public static function isBlocked($cid)
815 $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
816 if (!DBM::is_result($blocked)) {
819 return (bool) $blocked['blocked'];
823 * @brief Checks if the contact is hidden
825 * @param int $cid contact id
827 * @return boolean Is the contact hidden?
829 public static function isHidden($cid)
835 $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
836 if (!DBM::is_result($hidden)) {
839 return (bool) $hidden['hidden'];
843 * @brief Returns posts from a given contact url
845 * @param string $contact_url Contact URL
847 * @return string posts in HTML
849 public static function getPostsFromUrl($contact_url)
853 require_once 'include/conversation.php';
855 // There are no posts with "uid = 0" with connector networks
856 // This speeds up the query a lot
857 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
858 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
860 if (!DBM::is_result($r)) {
864 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
865 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
867 $sql = "`item`.`uid` = %d";
870 $author_id = intval($r[0]["author-id"]);
872 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
874 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
875 " ORDER BY `item`.`created` DESC LIMIT %d, %d", intval($author_id), intval(local_user()), intval($a->pager['start']), intval($a->pager['itemspage'])
879 $o = conversation($a, $r, 'community', false);
881 $o .= alt_pager($a, count($r));
887 * @brief Returns the account type name
889 * The function can be called with either the user or the contact array
891 * @param array $contact contact or user array
894 public static function getAccountType(array $contact)
896 // There are several fields that indicate that the contact or user is a forum
897 // "page-flags" is a field in the user table,
898 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
899 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
900 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
901 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
902 || (isset($contact['forum']) && intval($contact['forum']))
903 || (isset($contact['prv']) && intval($contact['prv']))
904 || (isset($contact['community']) && intval($contact['community']))
906 $type = ACCOUNT_TYPE_COMMUNITY;
908 $type = ACCOUNT_TYPE_PERSON;
911 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
912 if (isset($contact["contact-type"])) {
913 $type = $contact["contact-type"];
915 if (isset($contact["account-type"])) {
916 $type = $contact["account-type"];
920 case ACCOUNT_TYPE_ORGANISATION:
921 $account_type = t("Organisation");
923 case ACCOUNT_TYPE_NEWS:
924 $account_type = t('News');
926 case ACCOUNT_TYPE_COMMUNITY:
927 $account_type = t("Forum");
934 return $account_type;
938 * @brief Blocks a contact
943 public static function block($uid)
945 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
951 * @brief Unblocks a contact
956 public static function unblock($uid)
958 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
964 * @brief Updates the avatar links in a contact only if needed
966 * @param string $avatar Link to avatar picture
967 * @param int $uid User id of contact owner
968 * @param int $cid Contact id
969 * @param bool $force force picture update
971 * @return array Returns array of the different avatar sizes
973 public static function updateAvatar($avatar, $uid, $cid, $force = false)
975 // Limit = 1 returns the row so no need for dba:inArray()
976 $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1));
977 if (!DBM::is_result($r)) {
980 $data = array($r["photo"], $r["thumb"], $r["micro"]);
983 if (($r["avatar"] != $avatar) || $force) {
984 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
989 array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
993 // Update the public contact (contact id = 0)
995 $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1));
996 if (DBM::is_result($pcontact)) {
997 self::updateAvatar($avatar, 0, $pcontact['id'], $force);