Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

901 lines
27KB

  1. <?php
  2. use Friendica\App;
  3. use Friendica\Core\PConfig;
  4. use Friendica\Core\System;
  5. use Friendica\Core\Worker;
  6. use Friendica\Database\DBM;
  7. use Friendica\Network\Probe;
  8. use Friendica\Protocol\Diaspora;
  9. use Friendica\Protocol\DFRN;
  10. // Included here for completeness, but this is a very dangerous operation.
  11. // It is the caller's responsibility to confirm the requestor's intent and
  12. // authorisation to do this.
  13. function user_remove($uid) {
  14. if (!$uid) {
  15. return;
  16. }
  17. logger('Removing user: ' . $uid);
  18. $r = dba::select('user', array(), array('uid' => $uid), array("limit" => 1));
  19. call_hooks('remove_user',$r);
  20. // save username (actually the nickname as it is guaranteed
  21. // unique), so it cannot be re-registered in the future.
  22. dba::insert('userd', array('username' => $r['nickname']));
  23. // The user and related data will be deleted in "cron_expire_and_remove_users" (cronjobs.php)
  24. q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid));
  25. Worker::add(PRIORITY_HIGH, "notifier", "removeme", $uid);
  26. // Send an update to the directory
  27. Worker::add(PRIORITY_LOW, "directory", $r['url']);
  28. if($uid == local_user()) {
  29. unset($_SESSION['authenticated']);
  30. unset($_SESSION['uid']);
  31. goaway(System::baseUrl());
  32. }
  33. }
  34. function contact_remove($id) {
  35. // We want just to make sure that we don't delete our "self" contact
  36. $r = q("SELECT `uid` FROM `contact` WHERE `id` = %d AND NOT `self` LIMIT 1",
  37. intval($id)
  38. );
  39. if (!DBM::is_result($r) || !intval($r[0]['uid'])) {
  40. return;
  41. }
  42. $archive = PConfig::get($r[0]['uid'], 'system','archive_removed_contacts');
  43. if ($archive) {
  44. q("update contact set `archive` = 1, `network` = 'none', `writable` = 0 where id = %d",
  45. intval($id)
  46. );
  47. return;
  48. }
  49. dba::delete('contact', array('id' => $id));
  50. // Delete the rest in the background
  51. Worker::add(PRIORITY_LOW, 'remove_contact', $id);
  52. }
  53. // sends an unfriend message. Does not remove the contact
  54. function terminate_friendship($user,$self,$contact) {
  55. /// @TODO Get rid of this, include/datetime.php should care about it by itself
  56. $a = get_app();
  57. require_once 'include/datetime.php';
  58. if ($contact['network'] === NETWORK_OSTATUS) {
  59. require_once 'include/ostatus.php';
  60. // create an unfollow slap
  61. $item = array();
  62. $item['verb'] = NAMESPACE_OSTATUS."/unfollow";
  63. $item['follow'] = $contact["url"];
  64. $slap = ostatus::salmon($item, $user);
  65. if ((x($contact,'notify')) && (strlen($contact['notify']))) {
  66. require_once 'include/salmon.php';
  67. slapper($user,$contact['notify'],$slap);
  68. }
  69. } elseif ($contact['network'] === NETWORK_DIASPORA) {
  70. Diaspora::send_unshare($user,$contact);
  71. } elseif ($contact['network'] === NETWORK_DFRN) {
  72. DFRN::deliver($user,$contact,'placeholder', 1);
  73. }
  74. }
  75. // Contact has refused to recognise us as a friend. We will start a countdown.
  76. // If they still don't recognise us in 32 days, the relationship is over,
  77. // and we won't waste any more time trying to communicate with them.
  78. // This provides for the possibility that their database is temporarily messed
  79. // up or some other transient event and that there's a possibility we could recover from it.
  80. function mark_for_death($contact) {
  81. if($contact['archive'])
  82. return;
  83. if ($contact['term-date'] <= NULL_DATE) {
  84. q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
  85. dbesc(datetime_convert()),
  86. intval($contact['id'])
  87. );
  88. if ($contact['url'] != '') {
  89. q("UPDATE `contact` SET `term-date` = '%s'
  90. WHERE `nurl` = '%s' AND `term-date` <= '1000-00-00'",
  91. dbesc(datetime_convert()),
  92. dbesc(normalise_link($contact['url']))
  93. );
  94. }
  95. } else {
  96. /// @todo
  97. /// We really should send a notification to the owner after 2-3 weeks
  98. /// so they won't be surprised when the contact vanishes and can take
  99. /// remedial action if this was a serious mistake or glitch
  100. /// @todo
  101. /// Check for contact vitality via probing
  102. $expiry = $contact['term-date'] . ' + 32 days ';
  103. if(datetime_convert() > datetime_convert('UTC','UTC',$expiry)) {
  104. // relationship is really truly dead.
  105. // archive them rather than delete
  106. // though if the owner tries to unarchive them we'll start the whole process over again
  107. q("UPDATE `contact` SET `archive` = 1 WHERE `id` = %d",
  108. intval($contact['id'])
  109. );
  110. if ($contact['url'] != '') {
  111. q("UPDATE `contact` SET `archive` = 1 WHERE `nurl` = '%s'",
  112. dbesc(normalise_link($contact['url']))
  113. );
  114. }
  115. }
  116. }
  117. }
  118. function unmark_for_death($contact) {
  119. $r = q("SELECT `term-date` FROM `contact` WHERE `id` = %d AND (`term-date` > '%s' OR `archive`)",
  120. intval($contact['id']),
  121. dbesc('1000-00-00 00:00:00')
  122. );
  123. // We don't need to update, we never marked this contact as dead
  124. if (!DBM::is_result($r)) {
  125. return;
  126. }
  127. // It's a miracle. Our dead contact has inexplicably come back to life.
  128. $fields = array('term-date' => NULL_DATE, 'archive' => false);
  129. dba::update('contact', $fields, array('id' => $contact['id']));
  130. if ($contact['url'] != '') {
  131. dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
  132. }
  133. }
  134. /**
  135. * @brief Get contact data for a given profile link
  136. *
  137. * The function looks at several places (contact table and gcontact table) for the contact
  138. * It caches its result for the same script execution to prevent duplicate calls
  139. *
  140. * @param string $url The profile link
  141. * @param int $uid User id
  142. * @param array $default If not data was found take this data as default value
  143. *
  144. * @return array Contact data
  145. */
  146. function get_contact_details_by_url($url, $uid = -1, $default = array()) {
  147. static $cache = array();
  148. if ($url == '') {
  149. return $default;
  150. }
  151. if ($uid == -1) {
  152. $uid = local_user();
  153. }
  154. if (isset($cache[$url][$uid])) {
  155. return $cache[$url][$uid];
  156. }
  157. $ssl_url = str_replace('http://', 'https://', $url);
  158. // Fetch contact data from the contact table for the given user
  159. $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`,
  160. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  161. FROM `contact` WHERE `nurl` = ? AND `uid` = ?",
  162. normalise_link($url), $uid);
  163. $r = dba::inArray($s);
  164. // Fetch contact data from the contact table for the given user, checking with the alias
  165. if (!DBM::is_result($r)) {
  166. $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`,
  167. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  168. FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?",
  169. normalise_link($url), $url, $ssl_url, $uid);
  170. $r = dba::inArray($s);
  171. }
  172. // Fetch the data from the contact table with "uid=0" (which is filled automatically)
  173. if (!DBM::is_result($r)) {
  174. $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`,
  175. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  176. FROM `contact` WHERE `nurl` = ? AND `uid` = 0",
  177. normalise_link($url));
  178. $r = dba::inArray($s);
  179. }
  180. // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
  181. if (!DBM::is_result($r)) {
  182. $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`,
  183. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  184. FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0",
  185. normalise_link($url), $url, $ssl_url);
  186. $r = dba::inArray($s);
  187. }
  188. // Fetch the data from the gcontact table
  189. if (!DBM::is_result($r)) {
  190. $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`,
  191. `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
  192. FROM `gcontact` WHERE `nurl` = ?",
  193. normalise_link($url));
  194. $r = dba::inArray($s);
  195. }
  196. if (DBM::is_result($r)) {
  197. // If there is more than one entry we filter out the connector networks
  198. if (count($r) > 1) {
  199. foreach ($r AS $id => $result) {
  200. if ($result["network"] == NETWORK_STATUSNET) {
  201. unset($r[$id]);
  202. }
  203. }
  204. }
  205. $profile = array_shift($r);
  206. // "bd" always contains the upcoming birthday of a contact.
  207. // "birthday" might contain the birthday including the year of birth.
  208. if ($profile["birthday"] > '0001-01-01') {
  209. $bd_timestamp = strtotime($profile["birthday"]);
  210. $month = date("m", $bd_timestamp);
  211. $day = date("d", $bd_timestamp);
  212. $current_timestamp = time();
  213. $current_year = date("Y", $current_timestamp);
  214. $current_month = date("m", $current_timestamp);
  215. $current_day = date("d", $current_timestamp);
  216. $profile["bd"] = $current_year."-".$month."-".$day;
  217. $current = $current_year."-".$current_month."-".$current_day;
  218. if ($profile["bd"] < $current) {
  219. $profile["bd"] = (++$current_year)."-".$month."-".$day;
  220. }
  221. } else {
  222. $profile["bd"] = '0001-01-01';
  223. }
  224. } else {
  225. $profile = $default;
  226. }
  227. if (($profile["photo"] == "") && isset($default["photo"])) {
  228. $profile["photo"] = $default["photo"];
  229. }
  230. if (($profile["name"] == "") && isset($default["name"])) {
  231. $profile["name"] = $default["name"];
  232. }
  233. if (($profile["network"] == "") && isset($default["network"])) {
  234. $profile["network"] = $default["network"];
  235. }
  236. if (($profile["thumb"] == "") && isset($profile["photo"])) {
  237. $profile["thumb"] = $profile["photo"];
  238. }
  239. if (($profile["micro"] == "") && isset($profile["thumb"])) {
  240. $profile["micro"] = $profile["thumb"];
  241. }
  242. if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0) &&
  243. in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
  244. Worker::add(PRIORITY_LOW, "update_gcontact", $profile["gid"]);
  245. }
  246. // Show contact details of Diaspora contacts only if connected
  247. if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
  248. $profile["location"] = "";
  249. $profile["about"] = "";
  250. $profile["gender"] = "";
  251. $profile["birthday"] = '0001-01-01';
  252. }
  253. $cache[$url][$uid] = $profile;
  254. return $profile;
  255. }
  256. /**
  257. * @brief Get contact data for a given address
  258. *
  259. * The function looks at several places (contact table and gcontact table) for the contact
  260. *
  261. * @param string $addr The profile link
  262. * @param int $uid User id
  263. *
  264. * @return array Contact data
  265. */
  266. function get_contact_details_by_addr($addr, $uid = -1) {
  267. static $cache = array();
  268. if ($addr == '') {
  269. return array();
  270. }
  271. if ($uid == -1) {
  272. $uid = local_user();
  273. }
  274. // Fetch contact data from the contact table for the given user
  275. $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  276. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
  277. FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
  278. dbesc($addr), intval($uid));
  279. // Fetch the data from the contact table with "uid=0" (which is filled automatically)
  280. if (!DBM::is_result($r))
  281. $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
  282. `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
  283. FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
  284. dbesc($addr));
  285. // Fetch the data from the gcontact table
  286. if (!DBM::is_result($r))
  287. $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`,
  288. `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
  289. FROM `gcontact` WHERE `addr` = '%s'",
  290. dbesc($addr));
  291. if (!DBM::is_result($r)) {
  292. $data = Probe::uri($addr);
  293. $profile = get_contact_details_by_url($data['url'], $uid);
  294. } else {
  295. $profile = $r[0];
  296. }
  297. return $profile;
  298. }
  299. if (! function_exists('contact_photo_menu')) {
  300. function contact_photo_menu($contact, $uid = 0)
  301. {
  302. $a = get_app();
  303. $contact_url = '';
  304. $pm_url = '';
  305. $status_link = '';
  306. $photos_link = '';
  307. $posts_link = '';
  308. $contact_drop_link = '';
  309. $poke_link = '';
  310. if ($uid == 0) {
  311. $uid = local_user();
  312. }
  313. if ($contact['uid'] != $uid) {
  314. if ($uid == 0) {
  315. $profile_link = zrl($contact['url']);
  316. $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
  317. return $menu;
  318. }
  319. $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
  320. dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
  321. if ($r) {
  322. return contact_photo_menu($r[0], $uid);
  323. } else {
  324. $profile_link = zrl($contact['url']);
  325. $connlnk = 'follow/?url='.$contact['url'];
  326. $menu = array(
  327. 'profile' => array(t('View Profile'), $profile_link, true),
  328. 'follow' => array(t('Connect/Follow'), $connlnk, true)
  329. );
  330. return $menu;
  331. }
  332. }
  333. $sparkle = false;
  334. if ($contact['network'] === NETWORK_DFRN) {
  335. $sparkle = true;
  336. $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
  337. } else {
  338. $profile_link = $contact['url'];
  339. }
  340. if ($profile_link === 'mailbox') {
  341. $profile_link = '';
  342. }
  343. if ($sparkle) {
  344. $status_link = $profile_link . '?url=status';
  345. $photos_link = $profile_link . '?url=photos';
  346. $profile_link = $profile_link . '?url=profile';
  347. }
  348. if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
  349. $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
  350. }
  351. if ($contact['network'] == NETWORK_DFRN) {
  352. $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
  353. }
  354. $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
  355. $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
  356. $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
  357. /**
  358. * menu array:
  359. * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
  360. */
  361. $menu = array(
  362. 'status' => array(t("View Status"), $status_link, true),
  363. 'profile' => array(t("View Profile"), $profile_link, true),
  364. 'photos' => array(t("View Photos"), $photos_link, true),
  365. 'network' => array(t("Network Posts"), $posts_link, false),
  366. 'edit' => array(t("View Contact"), $contact_url, false),
  367. 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
  368. 'pm' => array(t("Send PM"), $pm_url, false),
  369. 'poke' => array(t("Poke"), $poke_link, false),
  370. );
  371. $args = array('contact' => $contact, 'menu' => &$menu);
  372. call_hooks('contact_photo_menu', $args);
  373. $menucondensed = array();
  374. foreach ($menu AS $menuname => $menuitem) {
  375. if ($menuitem[1] != '') {
  376. $menucondensed[$menuname] = $menuitem;
  377. }
  378. }
  379. return $menucondensed;
  380. }}
  381. function random_profile() {
  382. $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
  383. AND `last_contact` >= `last_failure`
  384. AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
  385. ORDER BY rand() LIMIT 1",
  386. dbesc(NETWORK_DFRN));
  387. if (DBM::is_result($r))
  388. return dirname($r[0]['url']);
  389. return '';
  390. }
  391. function contacts_not_grouped($uid,$start = 0,$count = 0) {
  392. if(! $count) {
  393. $r = q("select count(*) as total from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) ",
  394. intval($uid),
  395. intval($uid)
  396. );
  397. return $r;
  398. }
  399. $r = q("select * from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) and blocked = 0 and pending = 0 limit %d, %d",
  400. intval($uid),
  401. intval($uid),
  402. intval($start),
  403. intval($count)
  404. );
  405. return $r;
  406. }
  407. /**
  408. * @brief Fetch the contact id for a given url and user
  409. *
  410. * First lookup in the contact table to find a record matching either `url`, `nurl`,
  411. * `addr` or `alias`.
  412. *
  413. * If there's no record and we aren't looking for a public contact, we quit.
  414. * If there's one, we check that it isn't time to update the picture else we
  415. * directly return the found contact id.
  416. *
  417. * Second, we probe the provided $url wether it's http://server.tld/profile or
  418. * nick@server.tld. We quit if we can't get any info back.
  419. *
  420. * Third, we create the contact record if it doesn't exist
  421. *
  422. * Fourth, we update the existing record with the new data (avatar, alias, nick)
  423. * if there's any updates
  424. *
  425. * @param string $url Contact URL
  426. * @param integer $uid The user id for the contact (0 = public contact)
  427. * @param boolean $no_update Don't update the contact
  428. *
  429. * @return integer Contact ID
  430. */
  431. function get_contact($url, $uid = 0, $no_update = false) {
  432. logger("Get contact data for url ".$url." and user ".$uid." - ".System::callstack(), LOGGER_DEBUG);
  433. $data = array();
  434. $contact_id = 0;
  435. if ($url == '') {
  436. return 0;
  437. }
  438. // We first try the nurl (http://server.tld/nick), most common case
  439. $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
  440. // Then the addr (nick@server.tld)
  441. if (!DBM::is_result($contact)) {
  442. $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
  443. }
  444. // Then the alias (which could be anything)
  445. if (!DBM::is_result($contact)) {
  446. // The link could be provided as http although we stored it as https
  447. $ssl_url = str_replace('http://', 'https://', $url);
  448. $r = dba::p("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ? LIMIT 1",
  449. $url, normalise_link($url), $ssl_url, $uid);
  450. $contact = dba::fetch($r);
  451. dba::close($r);
  452. }
  453. if (DBM::is_result($contact)) {
  454. $contact_id = $contact["id"];
  455. // Update the contact every 7 days
  456. $update_contact = ($contact['avatar-date'] < datetime_convert('','','now -7 days'));
  457. // We force the update if the avatar is empty
  458. if ($contact['avatar'] == '') {
  459. $update_contact = true;
  460. }
  461. if (!$update_contact || $no_update) {
  462. return $contact_id;
  463. }
  464. } elseif ($uid != 0) {
  465. // Non-existing user-specific contact, exiting
  466. return 0;
  467. }
  468. $data = Probe::uri($url, "", $uid);
  469. // Last try in gcontact for unsupported networks
  470. if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
  471. if ($uid != 0) {
  472. return 0;
  473. }
  474. // Get data from the gcontact table
  475. $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'),
  476. array('nurl' => normalise_link($url)), array('limit' => 1));
  477. if (!DBM::is_result($gcontacts)) {
  478. return 0;
  479. }
  480. $data = array_merge($data, $gcontacts);
  481. }
  482. if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
  483. $contact_id = get_contact($data["alias"], $uid, true);
  484. }
  485. $url = $data["url"];
  486. if (!$contact_id) {
  487. dba::insert('contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
  488. 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
  489. 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
  490. 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
  491. 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
  492. 'network' => $data["network"], 'pubkey' => $data["pubkey"],
  493. 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
  494. 'batch' => $data["batch"], 'request' => $data["request"],
  495. 'confirm' => $data["confirm"], 'poco' => $data["poco"],
  496. 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
  497. 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
  498. 'readonly' => 0, 'pending' => 0));
  499. $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
  500. dbesc(normalise_link($data["url"])),
  501. intval($uid));
  502. if (!DBM::is_result($contacts)) {
  503. return 0;
  504. }
  505. $contact_id = $contacts[0]["id"];
  506. // Update the newly created contact from data in the gcontact table
  507. $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'),
  508. array('nurl' => normalise_link($data["url"])), array('limit' => 1));
  509. if (DBM::is_result($gcontact)) {
  510. // Only use the information when the probing hadn't fetched these values
  511. if ($data['keywords'] != '') {
  512. unset($gcontact['keywords']);
  513. }
  514. if ($data['location'] != '') {
  515. unset($gcontact['location']);
  516. }
  517. if ($data['about'] != '') {
  518. unset($gcontact['about']);
  519. }
  520. dba::update('contact', $gcontact, array('id' => $contact_id));
  521. }
  522. if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
  523. dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
  524. normalise_link($data["url"]), $contact_id));
  525. }
  526. }
  527. require_once "Photo.php";
  528. update_contact_avatar($data["photo"], $uid, $contact_id);
  529. $contact = dba::select('contact', array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date'),
  530. array('id' => $contact_id), array('limit' => 1));
  531. // This condition should always be true
  532. if (!DBM::is_result($contact)) {
  533. return $contact_id;
  534. }
  535. $updated = array('addr' => $data['addr'],
  536. 'alias' => $data['alias'],
  537. 'url' => $data['url'],
  538. 'nurl' => normalise_link($data['url']),
  539. 'name' => $data['name'],
  540. 'nick' => $data['nick']);
  541. if ($data['keywords'] != '') {
  542. $updated['keywords'] = $data['keywords'];
  543. }
  544. if ($data['location'] != '') {
  545. $updated['location'] = $data['location'];
  546. }
  547. if ($data['about'] != '') {
  548. $updated['about'] = $data['about'];
  549. }
  550. if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
  551. $updated['uri-date'] = datetime_convert();
  552. }
  553. if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
  554. $updated['name-date'] = datetime_convert();
  555. }
  556. $updated['avatar-date'] = datetime_convert();
  557. dba::update('contact', $updated, array('id' => $contact_id), $contact);
  558. return $contact_id;
  559. }
  560. /**
  561. * @brief Checks if the contact is blocked
  562. *
  563. * @param int $cid contact id
  564. *
  565. * @return boolean Is the contact blocked?
  566. */
  567. function blockedContact($cid) {
  568. if ($cid == 0) {
  569. return false;
  570. }
  571. $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
  572. if (!DBM::is_result($blocked)) {
  573. return false;
  574. }
  575. return (bool)$blocked['blocked'];
  576. }
  577. /**
  578. * @brief Checks if the contact is hidden
  579. *
  580. * @param int $cid contact id
  581. *
  582. * @return boolean Is the contact hidden?
  583. */
  584. function hiddenContact($cid) {
  585. if ($cid == 0) {
  586. return false;
  587. }
  588. $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
  589. if (!DBM::is_result($hidden)) {
  590. return false;
  591. }
  592. return (bool)$hidden['hidden'];
  593. }
  594. /**
  595. * @brief Returns posts from a given gcontact
  596. *
  597. * @param App $a argv application class
  598. * @param int $gcontact_id Global contact
  599. *
  600. * @return string posts in HTML
  601. */
  602. function posts_from_gcontact(App $a, $gcontact_id) {
  603. require_once 'include/conversation.php';
  604. // There are no posts with "uid = 0" with connector networks
  605. // This speeds up the query a lot
  606. $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
  607. if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
  608. $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
  609. else
  610. $sql = "`item`.`uid` = %d";
  611. $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
  612. `author-name` AS `name`, `owner-avatar` AS `photo`,
  613. `owner-link` AS `url`, `owner-avatar` AS `thumb`
  614. FROM `item`
  615. WHERE `gcontact-id` = %d AND $sql AND
  616. NOT `deleted` AND NOT `moderated` AND `visible`
  617. ORDER BY `item`.`created` DESC LIMIT %d, %d",
  618. intval($gcontact_id),
  619. intval(local_user()),
  620. intval($a->pager['start']),
  621. intval($a->pager['itemspage'])
  622. );
  623. $o = conversation($a, $r, 'community', false);
  624. $o .= alt_pager($a, count($r));
  625. return $o;
  626. }
  627. /**
  628. * @brief Returns posts from a given contact url
  629. *
  630. * @param App $a argv application class
  631. * @param string $contact_url Contact URL
  632. *
  633. * @return string posts in HTML
  634. */
  635. function posts_from_contact_url(App $a, $contact_url) {
  636. require_once 'include/conversation.php';
  637. // There are no posts with "uid = 0" with connector networks
  638. // This speeds up the query a lot
  639. $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
  640. WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
  641. dbesc(normalise_link($contact_url)));
  642. if (!DBM::is_result($r)) {
  643. return '';
  644. }
  645. if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  646. $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
  647. } else {
  648. $sql = "`item`.`uid` = %d";
  649. }
  650. $author_id = intval($r[0]["author-id"]);
  651. $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
  652. $r = q(item_query()." AND `item`.`".$contact."` = %d AND ".$sql.
  653. " ORDER BY `item`.`created` DESC LIMIT %d, %d",
  654. intval($author_id),
  655. intval(local_user()),
  656. intval($a->pager['start']),
  657. intval($a->pager['itemspage'])
  658. );
  659. $o = conversation($a, $r, 'community', false);
  660. $o .= alt_pager($a, count($r));
  661. return $o;
  662. }
  663. /**
  664. * @brief Returns a formatted location string from the given profile array
  665. *
  666. * @param array $profile Profile array (Generated from the "profile" table)
  667. *
  668. * @return string Location string
  669. */
  670. function formatted_location($profile) {
  671. $location = '';
  672. if($profile['locality'])
  673. $location .= $profile['locality'];
  674. if($profile['region'] && ($profile['locality'] != $profile['region'])) {
  675. if($location)
  676. $location .= ', ';
  677. $location .= $profile['region'];
  678. }
  679. if($profile['country-name']) {
  680. if($location)
  681. $location .= ', ';
  682. $location .= $profile['country-name'];
  683. }
  684. return $location;
  685. }
  686. /**
  687. * @brief Returns the account type name
  688. *
  689. * The function can be called with either the user or the contact array
  690. *
  691. * @param array $contact contact or user array
  692. */
  693. function account_type($contact) {
  694. // There are several fields that indicate that the contact or user is a forum
  695. // "page-flags" is a field in the user table,
  696. // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
  697. // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
  698. if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
  699. || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
  700. || (isset($contact['forum']) && intval($contact['forum']))
  701. || (isset($contact['prv']) && intval($contact['prv']))
  702. || (isset($contact['community']) && intval($contact['community'])))
  703. $type = ACCOUNT_TYPE_COMMUNITY;
  704. else
  705. $type = ACCOUNT_TYPE_PERSON;
  706. // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
  707. if (isset($contact["contact-type"]))
  708. $type = $contact["contact-type"];
  709. if (isset($contact["account-type"]))
  710. $type = $contact["account-type"];
  711. switch($type) {
  712. case ACCOUNT_TYPE_ORGANISATION:
  713. $account_type = t("Organisation");
  714. break;
  715. case ACCOUNT_TYPE_NEWS:
  716. $account_type = t('News');
  717. break;
  718. case ACCOUNT_TYPE_COMMUNITY:
  719. $account_type = t("Forum");
  720. break;
  721. default:
  722. $account_type = "";
  723. break;
  724. }
  725. return $account_type;
  726. }