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.

1004 lines
30 KiB

  1. <?php
  2. /**
  3. * @file src/Model/GlobalContact.php
  4. * @brief This file includes the GlobalContact class with directory related functions
  5. */
  6. namespace Friendica\Model;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\System;
  9. use Friendica\Core\Worker;
  10. use Friendica\Database\DBM;
  11. use Friendica\Network\Probe;
  12. use Friendica\Protocol\PortableContact;
  13. use dba;
  14. use Exception;
  15. require_once 'include/datetime.php';
  16. require_once 'include/network.php';
  17. require_once 'include/html2bbcode.php';
  18. require_once 'include/Contact.php';
  19. require_once 'include/Photo.php';
  20. /**
  21. * @brief This class handles GlobalContact related functions
  22. */
  23. class GlobalContact
  24. {
  25. /**
  26. * @brief Search global contact table by nick or name
  27. *
  28. * @param string $search Name or nick
  29. * @param string $mode Search mode (e.g. "community")
  30. *
  31. * @return array with search results
  32. */
  33. public static function searchByName($search, $mode = '')
  34. {
  35. if ($search) {
  36. // check supported networks
  37. if (Config::get('system', 'diaspora_enabled')) {
  38. $diaspora = NETWORK_DIASPORA;
  39. } else {
  40. $diaspora = NETWORK_DFRN;
  41. }
  42. if (!Config::get('system', 'ostatus_disabled')) {
  43. $ostatus = NETWORK_OSTATUS;
  44. } else {
  45. $ostatus = NETWORK_DFRN;
  46. }
  47. // check if we search only communities or every contact
  48. if ($mode === "community") {
  49. $extra_sql = " AND `community`";
  50. } else {
  51. $extra_sql = "";
  52. }
  53. $search .= "%";
  54. $results = q(
  55. "SELECT `contact`.`id` AS `cid`, `gcontact`.`url`, `gcontact`.`name`, `gcontact`.`nick`, `gcontact`.`photo`,
  56. `gcontact`.`network`, `gcontact`.`keywords`, `gcontact`.`addr`, `gcontact`.`community`
  57. FROM `gcontact`
  58. LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl`
  59. AND `contact`.`uid` = %d AND NOT `contact`.`blocked`
  60. AND NOT `contact`.`pending` AND `contact`.`rel` IN ('%s', '%s')
  61. WHERE (`contact`.`id` > 0 OR (NOT `gcontact`.`hide` AND `gcontact`.`network` IN ('%s', '%s', '%s') AND
  62. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
  63. (`gcontact`.`updated` >= `gcontact`.`last_failure`)))) AND
  64. (`gcontact`.`addr` LIKE '%s' OR `gcontact`.`name` LIKE '%s' OR `gcontact`.`nick` LIKE '%s') $extra_sql
  65. GROUP BY `gcontact`.`nurl`
  66. ORDER BY `gcontact`.`nurl` DESC
  67. LIMIT 1000",
  68. intval(local_user()),
  69. dbesc(CONTACT_IS_SHARING),
  70. dbesc(CONTACT_IS_FRIEND),
  71. dbesc(NETWORK_DFRN),
  72. dbesc($ostatus),
  73. dbesc($diaspora),
  74. dbesc(escape_tags($search)),
  75. dbesc(escape_tags($search)),
  76. dbesc(escape_tags($search))
  77. );
  78. return $results;
  79. }
  80. }
  81. /**
  82. * @brief Link the gcontact entry with user, contact and global contact
  83. *
  84. * @param integer $gcid Global contact ID
  85. * @param integer $uid User ID
  86. * @param integer $cid Contact ID
  87. * @param integer $zcid Global Contact ID
  88. */
  89. public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
  90. {
  91. if ($gcid <= 0) {
  92. return;
  93. }
  94. $r = q(
  95. "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
  96. intval($cid),
  97. intval($uid),
  98. intval($gcid),
  99. intval($zcid)
  100. );
  101. if (!DBM::is_result($r)) {
  102. q(
  103. "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
  104. intval($cid),
  105. intval($uid),
  106. intval($gcid),
  107. intval($zcid),
  108. dbesc(datetime_convert())
  109. );
  110. } else {
  111. q(
  112. "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
  113. dbesc(datetime_convert()),
  114. intval($cid),
  115. intval($uid),
  116. intval($gcid),
  117. intval($zcid)
  118. );
  119. }
  120. }
  121. /**
  122. * @brief Sanitize the given gcontact data
  123. *
  124. * @param array $gcontact array with gcontact data
  125. * @throw Exception
  126. *
  127. * Generation:
  128. * 0: No definition
  129. * 1: Profiles on this server
  130. * 2: Contacts of profiles on this server
  131. * 3: Contacts of contacts of profiles on this server
  132. * 4: ...
  133. */
  134. public static function sanitize($gcontact)
  135. {
  136. if ($gcontact['url'] == "") {
  137. throw new Exception('URL is empty');
  138. }
  139. $urlparts = parse_url($gcontact['url']);
  140. if (!isset($urlparts["scheme"])) {
  141. throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
  142. }
  143. if (in_array($urlparts["host"], array("www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"))) {
  144. throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
  145. }
  146. // Don't store the statusnet connector as network
  147. // We can't simply set this to NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
  148. if ($gcontact['network'] == NETWORK_STATUSNET) {
  149. $gcontact['network'] = "";
  150. }
  151. // Assure that there are no parameter fragments in the profile url
  152. if (in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  153. $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
  154. }
  155. $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
  156. // The global contacts should contain the original picture, not the cached one
  157. if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
  158. $gcontact['photo'] = "";
  159. }
  160. if (!isset($gcontact['network'])) {
  161. $r = q(
  162. "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
  163. dbesc(normalise_link($gcontact['url'])),
  164. dbesc(NETWORK_STATUSNET)
  165. );
  166. if (DBM::is_result($r)) {
  167. $gcontact['network'] = $r[0]["network"];
  168. }
  169. if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
  170. $r = q(
  171. "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
  172. dbesc($gcontact['url']),
  173. dbesc(normalise_link($gcontact['url'])),
  174. dbesc(NETWORK_STATUSNET)
  175. );
  176. if (DBM::is_result($r)) {
  177. $gcontact['network'] = $r[0]["network"];
  178. }
  179. }
  180. }
  181. $gcontact['server_url'] = '';
  182. $gcontact['network'] = '';
  183. $x = q(
  184. "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
  185. dbesc(normalise_link($gcontact['url']))
  186. );
  187. if (DBM::is_result($x)) {
  188. if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_STATUSNET)) {
  189. $gcontact['network'] = $x[0]["network"];
  190. }
  191. if ($gcontact['updated'] <= NULL_DATE) {
  192. $gcontact['updated'] = $x[0]["updated"];
  193. }
  194. if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
  195. $gcontact['server_url'] = $x[0]["server_url"];
  196. }
  197. if (!isset($gcontact['addr'])) {
  198. $gcontact['addr'] = $x[0]["addr"];
  199. }
  200. }
  201. if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
  202. && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
  203. ) {
  204. $data = Probe::uri($gcontact['url']);
  205. if ($data["network"] == NETWORK_PHANTOM) {
  206. throw new Exception('Probing for URL '.$gcontact['url'].' failed');
  207. }
  208. $orig_profile = $gcontact['url'];
  209. $gcontact["server_url"] = $data["baseurl"];
  210. $gcontact = array_merge($gcontact, $data);
  211. if ($alternate && ($gcontact['network'] == NETWORK_OSTATUS)) {
  212. // Delete the old entry - if it exists
  213. $r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  214. if (DBM::is_result($r)) {
  215. q("DELETE FROM `gcontact` WHERE `nurl` = '%s'", dbesc(normalise_link($orig_profile)));
  216. q("DELETE FROM `glink` WHERE `gcid` = %d", intval($r[0]["id"]));
  217. }
  218. }
  219. }
  220. if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
  221. throw new Exception('No name and photo for URL '.$gcontact['url']);
  222. }
  223. if (!in_array($gcontact['network'], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
  224. throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
  225. }
  226. if (!isset($gcontact['server_url'])) {
  227. // We check the server url to be sure that it is a real one
  228. $server_url = PortableContact::detectServer($gcontact['url']);
  229. // We are now sure that it is a correct URL. So we use it in the future
  230. if ($server_url != "") {
  231. $gcontact['server_url'] = $server_url;
  232. }
  233. }
  234. // The server URL doesn't seem to be valid, so we don't store it.
  235. if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
  236. $gcontact['server_url'] = "";
  237. }
  238. return $gcontact;
  239. }
  240. public static function countCommonFriends($uid, $cid)
  241. {
  242. $r = q(
  243. "SELECT count(*) as `total`
  244. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  245. WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
  246. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
  247. (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  248. AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
  249. intval($cid),
  250. intval($uid),
  251. intval($uid),
  252. intval($cid)
  253. );
  254. // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
  255. if (DBM::is_result($r)) {
  256. return $r[0]['total'];
  257. }
  258. return 0;
  259. }
  260. public static function countCommonFriendsZcid($uid, $zcid)
  261. {
  262. $r = q(
  263. "SELECT count(*) as `total`
  264. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  265. where `glink`.`zcid` = %d
  266. and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
  267. intval($zcid),
  268. intval($uid)
  269. );
  270. if (DBM::is_result($r)) {
  271. return $r[0]['total'];
  272. }
  273. return 0;
  274. }
  275. public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
  276. {
  277. if ($shuffle) {
  278. $sql_extra = " order by rand() ";
  279. } else {
  280. $sql_extra = " order by `gcontact`.`name` asc ";
  281. }
  282. $r = q(
  283. "SELECT `gcontact`.*, `contact`.`id` AS `cid`
  284. FROM `glink`
  285. INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
  286. INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
  287. WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
  288. AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
  289. AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
  290. AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  291. $sql_extra LIMIT %d, %d",
  292. intval($cid),
  293. intval($uid),
  294. intval($uid),
  295. intval($cid),
  296. intval($start),
  297. intval($limit)
  298. );
  299. /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
  300. return $r;
  301. }
  302. function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
  303. {
  304. if ($shuffle) {
  305. $sql_extra = " order by rand() ";
  306. } else {
  307. $sql_extra = " order by `gcontact`.`name` asc ";
  308. }
  309. $r = q(
  310. "SELECT `gcontact`.*
  311. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  312. where `glink`.`zcid` = %d
  313. and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
  314. $sql_extra limit %d, %d",
  315. intval($zcid),
  316. intval($uid),
  317. intval($start),
  318. intval($limit)
  319. );
  320. /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
  321. return $r;
  322. }
  323. public static function countAllFriends($uid, $cid)
  324. {
  325. $r = q(
  326. "SELECT count(*) as `total`
  327. FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  328. where `glink`.`cid` = %d and `glink`.`uid` = %d AND
  329. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
  330. intval($cid),
  331. intval($uid)
  332. );
  333. if (DBM::is_result($r)) {
  334. return $r[0]['total'];
  335. }
  336. return 0;
  337. }
  338. public static function allFriends($uid, $cid, $start = 0, $limit = 80)
  339. {
  340. $r = q(
  341. "SELECT `gcontact`.*, `contact`.`id` AS `cid`
  342. FROM `glink`
  343. INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
  344. LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
  345. WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
  346. ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
  347. ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
  348. intval($uid),
  349. intval($cid),
  350. intval($uid),
  351. intval($start),
  352. intval($limit)
  353. );
  354. /// @TODO Check all calling-findings of this function if they properly use DBM::is_result()
  355. return $r;
  356. }
  357. public static function suggestionQuery($uid, $start = 0, $limit = 80)
  358. {
  359. if (!$uid) {
  360. return array();
  361. }
  362. /*
  363. * Uncommented because the result of the queries are to big to store it in the cache.
  364. * We need to decide if we want to change the db column type or if we want to delete it.
  365. */
  366. //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
  367. //if (!is_null($list)) {
  368. // return $list;
  369. //}
  370. $network = array(NETWORK_DFRN);
  371. if (Config::get('system', 'diaspora_enabled')) {
  372. $network[] = NETWORK_DIASPORA;
  373. }
  374. if (!Config::get('system', 'ostatus_disabled')) {
  375. $network[] = NETWORK_OSTATUS;
  376. }
  377. $sql_network = implode("', '", $network);
  378. $sql_network = "'".$sql_network."'";
  379. /// @todo This query is really slow
  380. // By now we cache the data for five minutes
  381. $r = q(
  382. "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
  383. INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
  384. where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
  385. AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
  386. AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
  387. AND `gcontact`.`updated` >= '%s'
  388. AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
  389. AND `gcontact`.`network` IN (%s)
  390. GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
  391. intval($uid),
  392. intval($uid),
  393. intval($uid),
  394. intval($uid),
  395. dbesc(NULL_DATE),
  396. $sql_network,
  397. intval($start),
  398. intval($limit)
  399. );
  400. if (DBM::is_result($r) && count($r) >= ($limit -1)) {
  401. /*
  402. * Uncommented because the result of the queries are to big to store it in the cache.
  403. * We need to decide if we want to change the db column type or if we want to delete it.
  404. */
  405. //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
  406. return $r;
  407. }
  408. $r2 = q(
  409. "SELECT gcontact.* FROM gcontact
  410. INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
  411. WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
  412. AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
  413. AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
  414. AND `gcontact`.`updated` >= '%s'
  415. AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
  416. AND `gcontact`.`network` IN (%s)
  417. ORDER BY rand() LIMIT %d, %d",
  418. intval($uid),
  419. intval($uid),
  420. intval($uid),
  421. dbesc(NULL_DATE),
  422. $sql_network,
  423. intval($start),
  424. intval($limit)
  425. );
  426. $list = array();
  427. foreach ($r2 as $suggestion) {
  428. $list[$suggestion["nurl"]] = $suggestion;
  429. }
  430. foreach ($r as $suggestion) {
  431. $list[$suggestion["nurl"]] = $suggestion;
  432. }
  433. while (sizeof($list) > ($limit)) {
  434. array_pop($list);
  435. }
  436. /*
  437. * Uncommented because the result of the queries are to big to store it in the cache.
  438. * We need to decide if we want to change the db column type or if we want to delete it.
  439. */
  440. //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
  441. return $list;
  442. }
  443. public static function updateSuggestions()
  444. {
  445. $a = get_app();
  446. $done = array();
  447. /// @TODO Check if it is really neccessary to poll the own server
  448. PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
  449. $done[] = System::baseUrl() . '/poco';
  450. if (strlen(Config::get('system', 'directory'))) {
  451. $x = fetch_url(get_server()."/pubsites");
  452. if ($x) {
  453. $j = json_decode($x);
  454. if ($j->entries) {
  455. foreach ($j->entries as $entry) {
  456. PortableContact::checkServer($entry->url);
  457. $url = $entry->url . '/poco';
  458. if (! in_array($url, $done)) {
  459. PortableContact::loadWorker(0, 0, 0, $entry->url . '/poco');
  460. }
  461. }
  462. }
  463. }
  464. }
  465. // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
  466. $r = q(
  467. "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
  468. dbesc(NETWORK_DFRN),
  469. dbesc(NETWORK_DIASPORA)
  470. );
  471. if (DBM::is_result($r)) {
  472. foreach ($r as $rr) {
  473. $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
  474. if (! in_array($base, $done)) {
  475. PortableContact::loadWorker(0, 0, 0, $base);
  476. }
  477. }
  478. }
  479. }
  480. /**
  481. * @brief Removes unwanted parts from a contact url
  482. *
  483. * @param string $url Contact url
  484. *
  485. * @return string Contact url with the wanted parts
  486. */
  487. public static function cleanContactUrl($url)
  488. {
  489. $parts = parse_url($url);
  490. if (!isset($parts["scheme"]) || !isset($parts["host"])) {
  491. return $url;
  492. }
  493. $new_url = $parts["scheme"]."://".$parts["host"];
  494. if (isset($parts["port"])) {
  495. $new_url .= ":".$parts["port"];
  496. }
  497. if (isset($parts["path"])) {
  498. $new_url .= $parts["path"];
  499. }
  500. if ($new_url != $url) {
  501. logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
  502. }
  503. return $new_url;
  504. }
  505. /**
  506. * @brief Replace alternate OStatus user format with the primary one
  507. *
  508. * @param arr $contact contact array (called by reference)
  509. */
  510. public static function fixAlternateContactAddress(&$contact)
  511. {
  512. if (($contact["network"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
  513. $data = Probe::uri($contact["url"]);
  514. if ($contact["network"] == NETWORK_OSTATUS) {
  515. logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
  516. $contact["url"] = $data["url"];
  517. $contact["addr"] = $data["addr"];
  518. $contact["alias"] = $data["alias"];
  519. $contact["server_url"] = $data["baseurl"];
  520. }
  521. }
  522. }
  523. /**
  524. * @brief Fetch the gcontact id, add an entry if not existed
  525. *
  526. * @param arr $contact contact array
  527. *
  528. * @return bool|int Returns false if not found, integer if contact was found
  529. */
  530. public static function getId($contact)
  531. {
  532. $gcontact_id = 0;
  533. $doprobing = false;
  534. if (in_array($contact["network"], array(NETWORK_PHANTOM))) {
  535. logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
  536. return false;
  537. }
  538. if ($contact["network"] == NETWORK_STATUSNET) {
  539. $contact["network"] = NETWORK_OSTATUS;
  540. }
  541. // All new contacts are hidden by default
  542. if (!isset($contact["hide"])) {
  543. $contact["hide"] = true;
  544. }
  545. // Replace alternate OStatus user format with the primary one
  546. self::fixAlternateContactAddress($contact);
  547. // Remove unwanted parts from the contact url (e.g. "?zrl=...")
  548. if (in_array($contact["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
  549. $contact["url"] = self::cleanContactUrl($contact["url"]);
  550. }
  551. dba::lock('gcontact');
  552. $r = q(
  553. "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
  554. dbesc(normalise_link($contact["url"]))
  555. );
  556. if (DBM::is_result($r)) {
  557. $gcontact_id = $r[0]["id"];
  558. // Update every 90 days
  559. if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
  560. $last_failure_str = $r[0]["last_failure"];
  561. $last_failure = strtotime($r[0]["last_failure"]);
  562. $last_contact_str = $r[0]["last_contact"];
  563. $last_contact = strtotime($r[0]["last_contact"]);
  564. $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
  565. }
  566. } else {
  567. q(
  568. "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
  569. VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
  570. dbesc($contact["name"]),
  571. dbesc($contact["nick"]),
  572. dbesc($contact["addr"]),
  573. dbesc($contact["network"]),
  574. dbesc($contact["url"]),
  575. dbesc(normalise_link($contact["url"])),
  576. dbesc($contact["photo"]),
  577. dbesc(datetime_convert()),
  578. dbesc(datetime_convert()),
  579. dbesc($contact["location"]),
  580. dbesc($contact["about"]),
  581. intval($contact["hide"]),
  582. intval($contact["generation"])
  583. );
  584. $r = q(
  585. "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
  586. dbesc(normalise_link($contact["url"]))
  587. );
  588. if (DBM::is_result($r)) {
  589. $gcontact_id = $r[0]["id"];
  590. $doprobing = in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""));
  591. }
  592. }
  593. dba::unlock();
  594. if ($doprobing) {
  595. logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
  596. Worker::add(PRIORITY_LOW, 'gprobe', $contact["url"]);
  597. }
  598. return $gcontact_id;
  599. }
  600. /**
  601. * @brief Updates the gcontact table from a given array
  602. *
  603. * @param arr $contact contact array
  604. *
  605. * @return bool|int Returns false if not found, integer if contact was found
  606. */
  607. public static function update($contact)
  608. {
  609. // Check for invalid "contact-type" value
  610. if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
  611. $contact['contact-type'] = 0;
  612. }
  613. /// @todo update contact table as well
  614. $gcontact_id = self::getId($contact);
  615. if (!$gcontact_id) {
  616. return false;
  617. }
  618. $r = q(
  619. "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
  620. `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
  621. FROM `gcontact` WHERE `id` = %d LIMIT 1",
  622. intval($gcontact_id)
  623. );
  624. // Get all field names
  625. $fields = array();
  626. foreach ($r[0] as $field => $data) {
  627. $fields[$field] = $data;
  628. }
  629. unset($fields["url"]);
  630. unset($fields["updated"]);
  631. unset($fields["hide"]);
  632. // Bugfix: We had an error in the storing of keywords which lead to the "0"
  633. // This value is still transmitted via poco.
  634. if ($contact["keywords"] == "0") {
  635. unset($contact["keywords"]);
  636. }
  637. if ($r[0]["keywords"] == "0") {
  638. $r[0]["keywords"] = "";
  639. }
  640. // assign all unassigned fields from the database entry
  641. foreach ($fields as $field => $data) {
  642. if (!isset($contact[$field]) || ($contact[$field] == "")) {
  643. $contact[$field] = $r[0][$field];
  644. }
  645. }
  646. if (!isset($contact["hide"])) {
  647. $contact["hide"] = $r[0]["hide"];
  648. }
  649. $fields["hide"] = $r[0]["hide"];
  650. if ($contact["network"] == NETWORK_STATUSNET) {
  651. $contact["network"] = NETWORK_OSTATUS;
  652. }
  653. // Replace alternate OStatus user format with the primary one
  654. self::fixAlternateContactAddress($contact);
  655. if (!isset($contact["updated"])) {
  656. $contact["updated"] = DBM::date();
  657. }
  658. if ($contact["network"] == NETWORK_TWITTER) {
  659. $contact["server_url"] = 'http://twitter.com';
  660. }
  661. if ($contact["server_url"] == "") {
  662. $data = Probe::uri($contact["url"]);
  663. if ($data["network"] != NETWORK_PHANTOM) {
  664. $contact["server_url"] = $data['baseurl'];
  665. }
  666. } else {
  667. $contact["server_url"] = normalise_link($contact["server_url"]);
  668. }
  669. if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
  670. $hostname = str_replace("http://", "", $contact["server_url"]);
  671. $contact["addr"] = $contact["nick"]."@".$hostname;
  672. }
  673. // Check if any field changed
  674. $update = false;
  675. unset($fields["generation"]);
  676. if ((($contact["generation"] > 0) && ($contact["generation"] <= $r[0]["generation"])) || ($r[0]["generation"] == 0)) {
  677. foreach ($fields as $field => $data) {
  678. if ($contact[$field] != $r[0][$field]) {
  679. logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
  680. $update = true;
  681. }
  682. }
  683. if ($contact["generation"] < $r[0]["generation"]) {
  684. logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$r[0]["generation"]."'", LOGGER_DEBUG);
  685. $update = true;
  686. }
  687. }
  688. if ($update) {
  689. logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
  690. $condition = array('`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
  691. normalise_link($contact["url"]), $contact["generation"]);
  692. $contact["updated"] = DBM::date($contact["updated"]);
  693. $updated = array('photo' => $contact['photo'], 'name' => $contact['name'],
  694. 'nick' => $contact['nick'], 'addr' => $contact['addr'],
  695. 'network' => $contact['network'], 'birthday' => $contact['birthday'],
  696. 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
  697. 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
  698. 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
  699. 'notify' => $contact['notify'], 'url' => $contact['url'],
  700. 'location' => $contact['location'], 'about' => $contact['about'],
  701. 'generation' => $contact['generation'], 'updated' => $contact['updated'],
  702. 'server_url' => $contact['server_url'], 'connect' => $contact['connect']);
  703. dba::update('gcontact', $updated, $condition, $fields);
  704. // Now update the contact entry with the user id "0" as well.
  705. // This is used for the shadow copies of public items.
  706. $r = q(
  707. "SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0 ORDER BY `id` LIMIT 1",
  708. dbesc(normalise_link($contact["url"]))
  709. );
  710. if (DBM::is_result($r)) {
  711. logger("Update public contact ".$r[0]["id"], LOGGER_DEBUG);
  712. update_contact_avatar($contact["photo"], 0, $r[0]["id"]);
  713. $fields = array('name', 'nick', 'addr',
  714. 'network', 'bd', 'gender',
  715. 'keywords', 'alias', 'contact-type',
  716. 'url', 'location', 'about');
  717. $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1));
  718. // Update it with the current values
  719. $fields = array('name' => $contact['name'], 'nick' => $contact['nick'],
  720. 'addr' => $contact['addr'], 'network' => $contact['network'],
  721. 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
  722. 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
  723. 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
  724. 'location' => $contact['location'], 'about' => $contact['about']);
  725. dba::update('contact', $fields, array('id' => $r[0]["id"]), $old_contact);
  726. }
  727. }
  728. return $gcontact_id;
  729. }
  730. /**
  731. * @brief Updates the gcontact entry from probe
  732. *
  733. * @param str $url profile link
  734. */
  735. public static function updateFromProbe($url)
  736. {
  737. $data = Probe::uri($url);
  738. if (in_array($data["network"], array(NETWORK_PHANTOM))) {
  739. logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
  740. return;
  741. }
  742. $data["server_url"] = $data["baseurl"];
  743. self::update($data);
  744. }
  745. /**
  746. * @brief Update the gcontact entry for a given user id
  747. *
  748. * @param int $uid User ID
  749. */
  750. public static function updateForUser($uid)
  751. {
  752. $r = q(
  753. "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
  754. `profile`.`name`, `profile`.`about`, `profile`.`gender`,
  755. `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
  756. `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
  757. `contact`.`notify`, `contact`.`url`, `contact`.`addr`
  758. FROM `profile`
  759. INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  760. INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
  761. WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
  762. intval($uid)
  763. );
  764. $location = formatted_location(
  765. array("locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"])
  766. );
  767. // The "addr" field was added in 3.4.3 so it can be empty for older users
  768. if ($r[0]["addr"] != "") {
  769. $addr = $r[0]["nickname"].'@'.str_replace(array("http://", "https://"), "", System::baseUrl());
  770. } else {
  771. $addr = $r[0]["addr"];
  772. }
  773. $gcontact = array("name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
  774. "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
  775. "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
  776. "notify" => $r[0]["notify"], "url" => $r[0]["url"],
  777. "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
  778. "nick" => $r[0]["nickname"], "addr" => $addr,
  779. "connect" => $addr, "server_url" => System::baseUrl(),
  780. "generation" => 1, "network" => NETWORK_DFRN);
  781. self::update($gcontact);
  782. }
  783. /**
  784. * @brief Fetches users of given GNU Social server
  785. *
  786. * If the "Statistics" plugin is enabled (See http://gstools.org/ for details) we query user data with this.
  787. *
  788. * @param str $server Server address
  789. */
  790. public static function gsFetchUsers($server)
  791. {
  792. logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
  793. $url = $server."/main/statistics";
  794. $result = z_fetch_url($url);
  795. if (!$result["success"]) {
  796. return false;
  797. }
  798. $statistics = json_decode($result["body"]);
  799. if (is_object($statistics->config)) {
  800. if ($statistics->config->instance_with_ssl) {
  801. $server = "https://";
  802. } else {
  803. $server = "http://";
  804. }
  805. $server .= $statistics->config->instance_address;
  806. $hostname = $statistics->config->instance_address;
  807. } else {
  808. /// @TODO is_object() above means here no object, still $statistics is being used as object
  809. if ($statistics->instance_with_ssl) {
  810. $server = "https://";
  811. } else {
  812. $server = "http://";
  813. }
  814. $server .= $statistics->instance_address;
  815. $hostname = $statistics->instance_address;
  816. }
  817. if (is_object($statistics->users)) {
  818. foreach ($statistics->users as $nick => $user) {
  819. $profile_url = $server."/".$user->nickname;
  820. $contact = array("url" => $profile_url,
  821. "name" => $user->fullname,
  822. "addr" => $user->nickname."@".$hostname,
  823. "nick" => $user->nickname,
  824. "about" => $user->bio,
  825. "network" => NETWORK_OSTATUS,
  826. "photo" => System::baseUrl()."/images/person-175.jpg");
  827. self::getId($contact);
  828. }
  829. }
  830. }
  831. /**
  832. * @brief Asking GNU Social server on a regular base for their user data
  833. *
  834. */
  835. public static function gsDiscover()
  836. {
  837. $requery_days = intval(Config::get("system", "poco_requery_days"));
  838. $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
  839. $r = q(
  840. "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
  841. dbesc(NETWORK_OSTATUS),
  842. dbesc($last_update)
  843. );
  844. if (!DBM::is_result($r)) {
  845. return;
  846. }
  847. foreach ($r as $server) {
  848. self::gsFetchUsers($server["url"]);
  849. q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(datetime_convert()), dbesc($server["nurl"]));
  850. }
  851. }
  852. }