Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

2455 satır
78 KiB

  1. <?php
  2. /**
  3. * @file include/items.php
  4. */
  5. use Friendica\ParseUrl;
  6. require_once 'include/bbcode.php';
  7. require_once 'include/oembed.php';
  8. require_once 'include/salmon.php';
  9. require_once 'include/crypto.php';
  10. require_once 'include/Photo.php';
  11. require_once 'include/tags.php';
  12. require_once 'include/files.php';
  13. require_once 'include/text.php';
  14. require_once 'include/email.php';
  15. require_once 'include/threads.php';
  16. require_once 'include/socgraph.php';
  17. require_once 'include/plaintext.php';
  18. require_once 'include/ostatus.php';
  19. require_once 'include/feed.php';
  20. require_once 'include/Contact.php';
  21. require_once 'mod/share.php';
  22. require_once 'include/enotify.php';
  23. require_once 'include/dfrn.php';
  24. require_once 'include/group.php';
  25. /// @TODO one day with composer autoloader no more needed
  26. require_once 'library/defuse/php-encryption-1.2.1/Crypto.php';
  27. function construct_verb($item) {
  28. if ($item['verb']) {
  29. return $item['verb'];
  30. }
  31. return ACTIVITY_POST;
  32. }
  33. /* limit_body_size()
  34. *
  35. * The purpose of this function is to apply system message length limits to
  36. * imported messages without including any embedded photos in the length
  37. */
  38. if (! function_exists('limit_body_size')) {
  39. function limit_body_size($body) {
  40. // logger('limit_body_size: start', LOGGER_DEBUG);
  41. $maxlen = get_max_import_size();
  42. // If the length of the body, including the embedded images, is smaller
  43. // than the maximum, then don't waste time looking for the images
  44. if ($maxlen && (strlen($body) > $maxlen)) {
  45. logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
  46. $orig_body = $body;
  47. $new_body = '';
  48. $textlen = 0;
  49. $max_found = false;
  50. $img_start = strpos($orig_body, '[img');
  51. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  52. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  53. while (($img_st_close !== false) && ($img_end !== false)) {
  54. $img_st_close++; // make it point to AFTER the closing bracket
  55. $img_end += $img_start;
  56. $img_end += strlen('[/img]');
  57. if (! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  58. // This is an embedded image
  59. if (($textlen + $img_start) > $maxlen ) {
  60. if ($textlen < $maxlen) {
  61. logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
  62. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  63. $textlen = $maxlen;
  64. }
  65. } else {
  66. $new_body = $new_body . substr($orig_body, 0, $img_start);
  67. $textlen += $img_start;
  68. }
  69. $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
  70. } else {
  71. if (($textlen + $img_end) > $maxlen ) {
  72. if ($textlen < $maxlen) {
  73. logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
  74. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  75. $textlen = $maxlen;
  76. }
  77. } else {
  78. $new_body = $new_body . substr($orig_body, 0, $img_end);
  79. $textlen += $img_end;
  80. }
  81. }
  82. $orig_body = substr($orig_body, $img_end);
  83. if ($orig_body === false) {
  84. // in case the body ends on a closing image tag
  85. $orig_body = '';
  86. }
  87. $img_start = strpos($orig_body, '[img');
  88. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  89. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  90. }
  91. if (($textlen + strlen($orig_body)) > $maxlen) {
  92. if ($textlen < $maxlen) {
  93. logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
  94. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  95. $textlen = $maxlen;
  96. }
  97. } else {
  98. logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
  99. $new_body = $new_body . $orig_body;
  100. $textlen += strlen($orig_body);
  101. }
  102. return $new_body;
  103. } else {
  104. return $body;
  105. }
  106. }}
  107. function title_is_body($title, $body) {
  108. $title = strip_tags($title);
  109. $title = trim($title);
  110. $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
  111. $title = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $title);
  112. $body = strip_tags($body);
  113. $body = trim($body);
  114. $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
  115. $body = str_replace(array("\n", "\r", "\t", " "), array("", "", "", ""), $body);
  116. if (strlen($title) < strlen($body)) {
  117. $body = substr($body, 0, strlen($title));
  118. }
  119. if (($title != $body) and (substr($title, -3) == "...")) {
  120. $pos = strrpos($title, "...");
  121. if ($pos > 0) {
  122. $title = substr($title, 0, $pos);
  123. $body = substr($body, 0, $pos);
  124. }
  125. }
  126. return ($title == $body);
  127. }
  128. function add_page_info_data($data) {
  129. call_hooks('page_info_data', $data);
  130. // It maybe is a rich content, but if it does have everything that a link has,
  131. // then treat it that way
  132. if (($data["type"] == "rich") AND is_string($data["title"]) AND
  133. is_string($data["text"]) AND (sizeof($data["images"]) > 0)) {
  134. $data["type"] = "link";
  135. }
  136. if ((($data["type"] != "link") AND ($data["type"] != "video") AND ($data["type"] != "photo")) OR ($data["title"] == $data["url"])) {
  137. return "";
  138. }
  139. if ($no_photos AND ($data["type"] == "photo")) {
  140. return "";
  141. }
  142. if (sizeof($data["images"]) > 0) {
  143. $preview = $data["images"][0];
  144. } else {
  145. $preview = "";
  146. }
  147. // Escape some bad characters
  148. $data["url"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
  149. $data["title"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
  150. $text = "[attachment type='".$data["type"]."'";
  151. if ($data["text"] == "") {
  152. $data["text"] = $data["title"];
  153. }
  154. if ($data["text"] == "") {
  155. $data["text"] = $data["url"];
  156. }
  157. if ($data["url"] != "") {
  158. $text .= " url='".$data["url"]."'";
  159. }
  160. if ($data["title"] != "") {
  161. $text .= " title='".$data["title"]."'";
  162. }
  163. if (sizeof($data["images"]) > 0) {
  164. $preview = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
  165. // if the preview picture is larger than 500 pixels then show it in a larger mode
  166. // But only, if the picture isn't higher than large (To prevent huge posts)
  167. if (($data["images"][0]["width"] >= 500) AND ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
  168. $text .= " image='".$preview."'";
  169. } else {
  170. $text .= " preview='".$preview."'";
  171. }
  172. }
  173. $text .= "]".$data["text"]."[/attachment]";
  174. $hashtags = "";
  175. if (isset($data["keywords"]) AND count($data["keywords"])) {
  176. $hashtags = "\n";
  177. foreach ($data["keywords"] AS $keyword) {
  178. /// @todo make a positive list of allowed characters
  179. $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"),
  180. array("", "", "", "", "", "", "", "", "", "", "", ""), $keyword);
  181. $hashtags .= "#[url=" . App::get_baseurl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
  182. }
  183. }
  184. return "\n".$text.$hashtags;
  185. }
  186. function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  187. $data = ParseUrl::getSiteinfoCached($url, true);
  188. if ($photo != "") {
  189. $data["images"][0]["src"] = $photo;
  190. }
  191. logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG);
  192. if (!$keywords AND isset($data["keywords"])) {
  193. unset($data["keywords"]);
  194. }
  195. if (($keyword_blacklist != "") AND isset($data["keywords"])) {
  196. $list = explode(", ", $keyword_blacklist);
  197. foreach ($list AS $keyword) {
  198. $keyword = trim($keyword);
  199. $index = array_search($keyword, $data["keywords"]);
  200. if ($index !== false) {
  201. unset($data["keywords"][$index]);
  202. }
  203. }
  204. }
  205. return $data;
  206. }
  207. function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  208. $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
  209. $tags = "";
  210. if (isset($data["keywords"]) AND count($data["keywords"])) {
  211. foreach ($data["keywords"] AS $keyword) {
  212. $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
  213. array("", "", "", "", "", ""), $keyword);
  214. if ($tags != "") {
  215. $tags .= ", ";
  216. }
  217. $tags .= "#[url=" . App::get_baseurl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
  218. }
  219. }
  220. return $tags;
  221. }
  222. function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  223. $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
  224. $text = add_page_info_data($data);
  225. return $text;
  226. }
  227. function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
  228. logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
  229. $URLSearchString = "^\[\]";
  230. // Fix for Mastodon where the mentions are in a different format
  231. $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
  232. '$2[url=$1]$3[/url]', $body);
  233. // Adding these spaces is a quick hack due to my problems with regular expressions :)
  234. preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
  235. if (!$matches) {
  236. preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
  237. }
  238. // Convert urls without bbcode elements
  239. if (!$matches AND $texturl) {
  240. preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
  241. // Yeah, a hack. I really hate regular expressions :)
  242. if ($matches) {
  243. $matches[1] = $matches[2];
  244. }
  245. }
  246. if ($matches) {
  247. $footer = add_page_info($matches[1], $no_photos);
  248. }
  249. // Remove the link from the body if the link is attached at the end of the post
  250. if (isset($footer) AND (trim($footer) != "") AND (strpos($footer, $matches[1]))) {
  251. $removedlink = trim(str_replace($matches[1], "", $body));
  252. if (($removedlink == "") OR strstr($body, $removedlink)) {
  253. $body = $removedlink;
  254. }
  255. $url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
  256. $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
  257. if (($removedlink == "") OR strstr($body, $removedlink)) {
  258. $body = $removedlink;
  259. }
  260. }
  261. // Add the page information to the bottom
  262. if (isset($footer) AND (trim($footer) != "")) {
  263. $body .= $footer;
  264. }
  265. return $body;
  266. }
  267. /**
  268. * Adds a "lang" specification in a "postopts" element of given $arr,
  269. * if possible and not already present.
  270. * Expects "body" element to exist in $arr.
  271. *
  272. * @todo Add a parameter to request forcing override
  273. */
  274. function item_add_language_opt(&$arr) {
  275. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  276. // LanguageDetect.php not available ?
  277. return;
  278. }
  279. if (x($arr, 'postopts') ) {
  280. if (strstr($arr['postopts'], 'lang=') ) {
  281. // do not override
  282. /// @TODO Add parameter to request overriding
  283. return;
  284. }
  285. $postopts = $arr['postopts'];
  286. } else {
  287. $postopts = "";
  288. }
  289. require_once('library/langdet/Text/LanguageDetect.php');
  290. $naked_body = preg_replace('/\[(.+?)\]/','', $arr['body']);
  291. $l = new Text_LanguageDetect();
  292. //$lng = $l->detectConfidence($naked_body);
  293. //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
  294. $lng = $l->detect($naked_body, 3);
  295. if (sizeof($lng) > 0) {
  296. if ($postopts != "") $postopts .= '&'; // arbitrary separator, to be reviewed
  297. $postopts .= 'lang=';
  298. $sep = "";
  299. foreach ($lng as $language => $score) {
  300. $postopts .= $sep . $language . ";" . $score;
  301. $sep = ':';
  302. }
  303. $arr['postopts'] = $postopts;
  304. }
  305. }
  306. /**
  307. * @brief Creates an unique guid out of a given uri
  308. *
  309. * @param string $uri uri of an item entry
  310. * @param string $host (Optional) hostname for the GUID prefix
  311. * @return string unique guid
  312. */
  313. function uri_to_guid($uri, $host = "") {
  314. // Our regular guid routine is using this kind of prefix as well
  315. // We have to avoid that different routines could accidentally create the same value
  316. $parsed = parse_url($uri);
  317. if ($host == "") {
  318. $host = $parsed["host"];
  319. }
  320. $guid_prefix = hash("crc32", $host);
  321. // Remove the scheme to make sure that "https" and "http" doesn't make a difference
  322. unset($parsed["scheme"]);
  323. $host_id = implode("/", $parsed);
  324. // We could use any hash algorithm since it isn't a security issue
  325. $host_hash = hash("ripemd128", $host_id);
  326. return $guid_prefix.$host_hash;
  327. }
  328. /**
  329. * @brief Store the conversation data
  330. *
  331. * @param array $arr Item array with conversation data
  332. * @return array Item array with removed conversation data
  333. */
  334. function store_conversation($arr) {
  335. if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
  336. $conversation = array('item-uri' => $arr['uri'], 'received' => dbm::date());
  337. if (isset($arr['parent-uri']) AND ($arr['parent-uri'] != $arr['uri'])) {
  338. $conversation['reply-to-uri'] = $arr['parent-uri'];
  339. }
  340. if (isset($arr['thr-parent']) AND ($arr['thr-parent'] != $arr['uri'])) {
  341. $conversation['reply-to-uri'] = $arr['thr-parent'];
  342. }
  343. if (isset($arr['conversation-uri'])) {
  344. $conversation['conversation-uri'] = $arr['conversation-uri'];
  345. }
  346. if (isset($arr['conversation-href'])) {
  347. $conversation['conversation-href'] = $arr['conversation-href'];
  348. }
  349. if (isset($arr['protocol'])) {
  350. $conversation['protocol'] = $arr['protocol'];
  351. }
  352. if (isset($arr['source'])) {
  353. $conversation['source'] = $arr['source'];
  354. }
  355. $old_conv = dba::fetch_first("SELECT `item-uri`, `reply-to-uri`, `conversation-uri`, `conversation-href`, `protocol`, `source`
  356. FROM `conversation` WHERE `item-uri` = ?", $conversation['item-uri']);
  357. if (dbm::is_result($old_conv)) {
  358. // Don't update when only the source has changed.
  359. // Only do this when there had been no source before.
  360. if ($old_conv['source'] != '') {
  361. unset($old_conv['source']);
  362. }
  363. // Update structure data all the time but the source only when its from a better protocol.
  364. if (($old_conv['protocol'] < $conversation['protocol']) AND ($old_conv['protocol'] != 0)) {
  365. unset($conversation['protocol']);
  366. unset($conversation['source']);
  367. }
  368. if (!dba::update('conversation', $conversation, array('item-uri' => $conversation['item-uri']), $old_conv)) {
  369. logger('Conversation: update for '.$conversation['item-uri'].' from '.$conv['protocol'].' to '.$conversation['protocol'].' failed', LOGGER_DEBUG);
  370. }
  371. } else {
  372. if (!dba::insert('conversation', $conversation)) {
  373. logger('Conversation: insert for '.$conversation['item-uri'].' (protocol '.$conversation['protocol'].') failed', LOGGER_DEBUG);
  374. }
  375. }
  376. }
  377. unset($arr['conversation-uri']);
  378. unset($arr['conversation-href']);
  379. unset($arr['protocol']);
  380. unset($arr['source']);
  381. return $arr;
  382. }
  383. /// @TODO add type-hint array
  384. function item_store($arr, $force_parent = false, $notify = false, $dontcache = false) {
  385. $a = get_app();
  386. // If it is a posting where users should get notifications, then define it as wall posting
  387. if ($notify) {
  388. $arr['wall'] = 1;
  389. $arr['type'] = 'wall';
  390. $arr['origin'] = 1;
  391. $arr['last-child'] = 1;
  392. $arr['network'] = NETWORK_DFRN;
  393. $arr['protocol'] = PROTOCOL_DFRN;
  394. // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
  395. // In difference to the call to "uri_to_guid" several lines below we add the hash of our own host.
  396. // This is done because our host is the original creator of the post.
  397. if (!isset($arr['guid'])) {
  398. if (isset($arr['plink'])) {
  399. $arr['guid'] = uri_to_guid($arr['plink'], $a->get_hostname());
  400. } elseif (isset($arr['uri'])) {
  401. $arr['guid'] = uri_to_guid($arr['uri'], $a->get_hostname());
  402. }
  403. }
  404. }
  405. // Store conversation data
  406. $arr = store_conversation($arr);
  407. /*
  408. * If a Diaspora signature structure was passed in, pull it out of the
  409. * item array and set it aside for later storage.
  410. */
  411. $dsprsig = null;
  412. if (x($arr, 'dsprsig')) {
  413. $encoded_signature = $arr['dsprsig'];
  414. $dsprsig = json_decode(base64_decode($arr['dsprsig']));
  415. unset($arr['dsprsig']);
  416. }
  417. // Converting the plink
  418. if ($arr['network'] == NETWORK_OSTATUS) {
  419. if (isset($arr['plink'])) {
  420. $arr['plink'] = ostatus::convert_href($arr['plink']);
  421. } elseif (isset($arr['uri'])) {
  422. $arr['plink'] = ostatus::convert_href($arr['uri']);
  423. }
  424. }
  425. if (x($arr, 'gravity')) {
  426. $arr['gravity'] = intval($arr['gravity']);
  427. } elseif ($arr['parent-uri'] === $arr['uri']) {
  428. $arr['gravity'] = 0;
  429. } elseif (activity_match($arr['verb'],ACTIVITY_POST)) {
  430. $arr['gravity'] = 6;
  431. } else {
  432. $arr['gravity'] = 6; // extensible catchall
  433. }
  434. if (! x($arr, 'type')) {
  435. $arr['type'] = 'remote';
  436. }
  437. // check for create date and expire time
  438. $uid = intval($arr['uid']);
  439. $r = q("SELECT expire FROM user WHERE uid = %d", intval($uid));
  440. if (dbm::is_result($r)) {
  441. $expire_interval = $r[0]['expire'];
  442. if ($expire_interval>0) {
  443. $expire_date = new DateTime( '- '.$expire_interval.' days', new DateTimeZone('UTC'));
  444. $created_date = new DateTime($arr['created'], new DateTimeZone('UTC'));
  445. if ($created_date < $expire_date) {
  446. logger('item-store: item created ('.$arr['created'].') before expiration time ('.$expire_date->format(DateTime::W3C).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
  447. return 0;
  448. }
  449. }
  450. }
  451. /*
  452. * Do we already have this item?
  453. * We have to check several networks since Friendica posts could be repeated
  454. * via OStatus (maybe Diasporsa as well)
  455. */
  456. if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
  457. $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
  458. dbesc(trim($arr['uri'])),
  459. intval($uid),
  460. dbesc(NETWORK_DIASPORA),
  461. dbesc(NETWORK_DFRN),
  462. dbesc(NETWORK_OSTATUS)
  463. );
  464. if (dbm::is_result($r)) {
  465. // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
  466. if ($uid != 0) {
  467. logger("Item with uri ".$arr['uri']." already existed for user ".$uid." with id ".$r[0]["id"]." target network ".$r[0]["network"]." - new network: ".$arr['network']);
  468. }
  469. return $r[0]["id"];
  470. }
  471. }
  472. /// @TODO old-lost code?
  473. // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
  474. // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
  475. //if ((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
  476. // $arr['body'] = strip_tags($arr['body']);
  477. item_add_language_opt($arr);
  478. if ($notify) {
  479. $guid_prefix = "";
  480. } elseif ((trim($arr['guid']) == "") AND (trim($arr['plink']) != "")) {
  481. $arr['guid'] = uri_to_guid($arr['plink']);
  482. } elseif ((trim($arr['guid']) == "") AND (trim($arr['uri']) != "")) {
  483. $arr['guid'] = uri_to_guid($arr['uri']);
  484. } else {
  485. $parsed = parse_url($arr["author-link"]);
  486. $guid_prefix = hash("crc32", $parsed["host"]);
  487. }
  488. $arr['wall'] = ((x($arr, 'wall')) ? intval($arr['wall']) : 0);
  489. $arr['guid'] = ((x($arr, 'guid')) ? notags(trim($arr['guid'])) : get_guid(32, $guid_prefix));
  490. $arr['uri'] = ((x($arr, 'uri')) ? notags(trim($arr['uri'])) : item_new_uri($a->get_hostname(), $uid, $arr['guid']));
  491. $arr['extid'] = ((x($arr, 'extid')) ? notags(trim($arr['extid'])) : '');
  492. $arr['author-name'] = ((x($arr, 'author-name')) ? trim($arr['author-name']) : '');
  493. $arr['author-link'] = ((x($arr, 'author-link')) ? notags(trim($arr['author-link'])) : '');
  494. $arr['author-avatar'] = ((x($arr, 'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
  495. $arr['owner-name'] = ((x($arr, 'owner-name')) ? trim($arr['owner-name']) : '');
  496. $arr['owner-link'] = ((x($arr, 'owner-link')) ? notags(trim($arr['owner-link'])) : '');
  497. $arr['owner-avatar'] = ((x($arr, 'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
  498. $arr['created'] = ((x($arr, 'created') !== false) ? datetime_convert('UTC','UTC', $arr['created']) : datetime_convert());
  499. $arr['edited'] = ((x($arr, 'edited') !== false) ? datetime_convert('UTC','UTC', $arr['edited']) : datetime_convert());
  500. $arr['commented'] = ((x($arr, 'commented') !== false) ? datetime_convert('UTC','UTC', $arr['commented']) : datetime_convert());
  501. $arr['received'] = ((x($arr, 'received') !== false) ? datetime_convert('UTC','UTC', $arr['received']) : datetime_convert());
  502. $arr['changed'] = ((x($arr, 'changed') !== false) ? datetime_convert('UTC','UTC', $arr['changed']) : datetime_convert());
  503. $arr['title'] = ((x($arr, 'title')) ? trim($arr['title']) : '');
  504. $arr['location'] = ((x($arr, 'location')) ? trim($arr['location']) : '');
  505. $arr['coord'] = ((x($arr, 'coord')) ? notags(trim($arr['coord'])) : '');
  506. $arr['last-child'] = ((x($arr, 'last-child')) ? intval($arr['last-child']) : 0 );
  507. $arr['visible'] = ((x($arr, 'visible') !== false) ? intval($arr['visible']) : 1 );
  508. $arr['deleted'] = 0;
  509. $arr['parent-uri'] = ((x($arr, 'parent-uri')) ? notags(trim($arr['parent-uri'])) : $arr['uri']);
  510. $arr['verb'] = ((x($arr, 'verb')) ? notags(trim($arr['verb'])) : '');
  511. $arr['object-type'] = ((x($arr, 'object-type')) ? notags(trim($arr['object-type'])) : '');
  512. $arr['object'] = ((x($arr, 'object')) ? trim($arr['object']) : '');
  513. $arr['target-type'] = ((x($arr, 'target-type')) ? notags(trim($arr['target-type'])) : '');
  514. $arr['target'] = ((x($arr, 'target')) ? trim($arr['target']) : '');
  515. $arr['plink'] = ((x($arr, 'plink')) ? notags(trim($arr['plink'])) : '');
  516. $arr['allow_cid'] = ((x($arr, 'allow_cid')) ? trim($arr['allow_cid']) : '');
  517. $arr['allow_gid'] = ((x($arr, 'allow_gid')) ? trim($arr['allow_gid']) : '');
  518. $arr['deny_cid'] = ((x($arr, 'deny_cid')) ? trim($arr['deny_cid']) : '');
  519. $arr['deny_gid'] = ((x($arr, 'deny_gid')) ? trim($arr['deny_gid']) : '');
  520. $arr['private'] = ((x($arr, 'private')) ? intval($arr['private']) : 0 );
  521. $arr['bookmark'] = ((x($arr, 'bookmark')) ? intval($arr['bookmark']) : 0 );
  522. $arr['body'] = ((x($arr, 'body')) ? trim($arr['body']) : '');
  523. $arr['tag'] = ((x($arr, 'tag')) ? notags(trim($arr['tag'])) : '');
  524. $arr['attach'] = ((x($arr, 'attach')) ? notags(trim($arr['attach'])) : '');
  525. $arr['app'] = ((x($arr, 'app')) ? notags(trim($arr['app'])) : '');
  526. $arr['origin'] = ((x($arr, 'origin')) ? intval($arr['origin']) : 0 );
  527. $arr['network'] = ((x($arr, 'network')) ? trim($arr['network']) : '');
  528. $arr['postopts'] = ((x($arr, 'postopts')) ? trim($arr['postopts']) : '');
  529. $arr['resource-id'] = ((x($arr, 'resource-id')) ? trim($arr['resource-id']) : '');
  530. $arr['event-id'] = ((x($arr, 'event-id')) ? intval($arr['event-id']) : 0 );
  531. $arr['inform'] = ((x($arr, 'inform')) ? trim($arr['inform']) : '');
  532. $arr['file'] = ((x($arr, 'file')) ? trim($arr['file']) : '');
  533. // Items cannot be stored before they happen ...
  534. if ($arr['created'] > datetime_convert()) {
  535. $arr['created'] = datetime_convert();
  536. }
  537. // We haven't invented time travel by now.
  538. if ($arr['edited'] > datetime_convert()) {
  539. $arr['edited'] = datetime_convert();
  540. }
  541. if (($arr['author-link'] == "") AND ($arr['owner-link'] == "")) {
  542. logger("Both author-link and owner-link are empty. Called by: " . App::callstack(), LOGGER_DEBUG);
  543. }
  544. if ($arr['plink'] == "") {
  545. $arr['plink'] = App::get_baseurl() . '/display/' . urlencode($arr['guid']);
  546. }
  547. if ($arr['network'] == "") {
  548. $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  549. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
  550. dbesc(normalise_link($arr['author-link'])),
  551. intval($arr['uid'])
  552. );
  553. if (!dbm::is_result($r))
  554. $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
  555. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
  556. dbesc(normalise_link($arr['author-link']))
  557. );
  558. if (!dbm::is_result($r)) {
  559. $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  560. intval($arr['contact-id']),
  561. intval($arr['uid'])
  562. );
  563. }
  564. if (dbm::is_result($r)) {
  565. $arr['network'] = $r[0]["network"];
  566. }
  567. // Fallback to friendica (why is it empty in some cases?)
  568. if ($arr['network'] == "") {
  569. $arr['network'] = NETWORK_DFRN;
  570. }
  571. logger("item_store: Set network to " . $arr["network"] . " for " . $arr["uri"], LOGGER_DEBUG);
  572. }
  573. // The contact-id should be set before "item_store" was called - but there seems to be some issues
  574. if ($arr["contact-id"] == 0) {
  575. /*
  576. * First we are looking for a suitable contact that matches with the author of the post
  577. * This is done only for comments (See below explanation at "gcontact-id")
  578. */
  579. if ($arr['parent-uri'] != $arr['uri']) {
  580. $arr["contact-id"] = get_contact($arr['author-link'], $uid);
  581. }
  582. // If not present then maybe the owner was found
  583. if ($arr["contact-id"] == 0) {
  584. $arr["contact-id"] = get_contact($arr['owner-link'], $uid);
  585. }
  586. // Still missing? Then use the "self" contact of the current user
  587. if ($arr["contact-id"] == 0) {
  588. $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
  589. if (dbm::is_result($r)) {
  590. $arr["contact-id"] = $r[0]["id"];
  591. }
  592. }
  593. logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
  594. }
  595. if ($arr["gcontact-id"] == 0) {
  596. /*
  597. * The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
  598. * This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
  599. * On comments the author is the better choice.
  600. */
  601. if ($arr['parent-uri'] === $arr['uri']) {
  602. $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['owner-link'], "network" => $arr['network'],
  603. "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']));
  604. } else {
  605. $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'],
  606. "photo" => $arr['author-avatar'], "name" => $arr['author-name']));
  607. }
  608. }
  609. if ($arr["author-id"] == 0) {
  610. $arr["author-id"] = get_contact($arr["author-link"], 0);
  611. }
  612. if ($arr["owner-id"] == 0) {
  613. $arr["owner-id"] = get_contact($arr["owner-link"], 0);
  614. }
  615. if ($arr['guid'] != "") {
  616. // Checking if there is already an item with the same guid
  617. logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
  618. $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
  619. dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
  620. if (dbm::is_result($r)) {
  621. logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
  622. return 0;
  623. }
  624. }
  625. // Check for hashtags in the body and repair or add hashtag links
  626. item_body_set_hashtags($arr);
  627. $arr['thr-parent'] = $arr['parent-uri'];
  628. if ($arr['parent-uri'] === $arr['uri']) {
  629. $parent_id = 0;
  630. $parent_deleted = 0;
  631. $allow_cid = $arr['allow_cid'];
  632. $allow_gid = $arr['allow_gid'];
  633. $deny_cid = $arr['deny_cid'];
  634. $deny_gid = $arr['deny_gid'];
  635. $notify_type = 'wall-new';
  636. } else {
  637. // find the parent and snarf the item id and ACLs
  638. // and anything else we need to inherit
  639. $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
  640. dbesc($arr['parent-uri']),
  641. intval($arr['uid'])
  642. );
  643. if (dbm::is_result($r)) {
  644. // is the new message multi-level threaded?
  645. // even though we don't support it now, preserve the info
  646. // and re-attach to the conversation parent.
  647. if ($r[0]['uri'] != $r[0]['parent-uri']) {
  648. $arr['parent-uri'] = $r[0]['parent-uri'];
  649. $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
  650. ORDER BY `id` ASC LIMIT 1",
  651. dbesc($r[0]['parent-uri']),
  652. dbesc($r[0]['parent-uri']),
  653. intval($arr['uid'])
  654. );
  655. if (dbm::is_result($z)) {
  656. $r = $z;
  657. }
  658. }
  659. $parent_id = $r[0]['id'];
  660. $parent_deleted = $r[0]['deleted'];
  661. $allow_cid = $r[0]['allow_cid'];
  662. $allow_gid = $r[0]['allow_gid'];
  663. $deny_cid = $r[0]['deny_cid'];
  664. $deny_gid = $r[0]['deny_gid'];
  665. $arr['wall'] = $r[0]['wall'];
  666. $notify_type = 'comment-new';
  667. /*
  668. * If the parent is private, force privacy for the entire conversation
  669. * This differs from the above settings as it subtly allows comments from
  670. * email correspondents to be private even if the overall thread is not.
  671. */
  672. if ($r[0]['private']) {
  673. $arr['private'] = $r[0]['private'];
  674. }
  675. /*
  676. * Edge case. We host a public forum that was originally posted to privately.
  677. * The original author commented, but as this is a comment, the permissions
  678. * weren't fixed up so it will still show the comment as private unless we fix it here.
  679. */
  680. if ((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private'])) {
  681. $arr['private'] = 0;
  682. }
  683. // If its a post from myself then tag the thread as "mention"
  684. logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
  685. $u = q("SELECT `nickname` FROM `user` WHERE `uid` = %d", intval($arr['uid']));
  686. if (dbm::is_result($u)) {
  687. $a = get_app();
  688. $self = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
  689. logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
  690. if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
  691. q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
  692. logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
  693. }
  694. }
  695. } else {
  696. /*
  697. * Allow one to see reply tweets from status.net even when
  698. * we don't have or can't see the original post.
  699. */
  700. if ($force_parent) {
  701. logger('item_store: $force_parent=true, reply converted to top-level post.');
  702. $parent_id = 0;
  703. $arr['parent-uri'] = $arr['uri'];
  704. $arr['gravity'] = 0;
  705. } else {
  706. logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
  707. return 0;
  708. }
  709. $parent_deleted = 0;
  710. }
  711. }
  712. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
  713. dbesc($arr['uri']),
  714. dbesc($arr['network']),
  715. dbesc(NETWORK_DFRN),
  716. intval($arr['uid'])
  717. );
  718. if (dbm::is_result($r)) {
  719. logger('duplicated item with the same uri found. '.print_r($arr,true));
  720. return 0;
  721. }
  722. // On Friendica and Diaspora the GUID is unique
  723. if (in_array($arr['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
  724. $r = q("SELECT `id` FROM `item` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
  725. dbesc($arr['guid']),
  726. intval($arr['uid'])
  727. );
  728. if (dbm::is_result($r)) {
  729. logger('duplicated item with the same guid found. '.print_r($arr,true));
  730. return 0;
  731. }
  732. } else {
  733. // Check for an existing post with the same content. There seems to be a problem with OStatus.
  734. $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
  735. dbesc($arr['body']),
  736. dbesc($arr['network']),
  737. dbesc($arr['created']),
  738. intval($arr['contact-id']),
  739. intval($arr['uid'])
  740. );
  741. if (dbm::is_result($r)) {
  742. logger('duplicated item with the same body found. '.print_r($arr,true));
  743. return 0;
  744. }
  745. }
  746. // Is this item available in the global items (with uid=0)?
  747. if ($arr["uid"] == 0) {
  748. $arr["global"] = true;
  749. // Set the global flag on all items if this was a global item entry
  750. q("UPDATE `item` SET `global` = 1 WHERE `uri` = '%s'", dbesc($arr["uri"]));
  751. } else {
  752. $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
  753. $arr["global"] = (dbm::is_result($isglobal) && count($isglobal) > 0);
  754. }
  755. // ACL settings
  756. if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
  757. $private = 1;
  758. } else {
  759. $private = $arr['private'];
  760. }
  761. $arr["allow_cid"] = $allow_cid;
  762. $arr["allow_gid"] = $allow_gid;
  763. $arr["deny_cid"] = $deny_cid;
  764. $arr["deny_gid"] = $deny_gid;
  765. $arr["private"] = $private;
  766. $arr["deleted"] = $parent_deleted;
  767. // Fill the cache field
  768. put_item_in_cache($arr);
  769. if ($notify) {
  770. call_hooks('post_local', $arr);
  771. } else {
  772. call_hooks('post_remote', $arr);
  773. }
  774. if (x($arr, 'cancel')) {
  775. logger('item_store: post cancelled by plugin.');
  776. return 0;
  777. }
  778. /*
  779. * Check for already added items.
  780. * There is a timing issue here that sometimes creates double postings.
  781. * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
  782. */
  783. if ($arr["uid"] == 0) {
  784. $r = qu("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = 0 LIMIT 1", dbesc(trim($arr['uri'])));
  785. if (dbm::is_result($r)) {
  786. logger('Global item already stored. URI: '.$arr['uri'].' on network '.$arr['network'], LOGGER_DEBUG);
  787. return 0;
  788. }
  789. }
  790. // Store the unescaped version
  791. $unescaped = $arr;
  792. dbm::esc_array($arr, true);
  793. logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
  794. q("COMMIT");
  795. q("START TRANSACTION;");
  796. $r = dbq("INSERT INTO `item` (`"
  797. . implode("`, `", array_keys($arr))
  798. . "`) VALUES ("
  799. . implode(", ", array_values($arr))
  800. . ")");
  801. // And restore it
  802. $arr = $unescaped;
  803. // When the item was successfully stored we fetch the ID of the item.
  804. if (dbm::is_result($r)) {
  805. $r = q("SELECT LAST_INSERT_ID() AS `item-id`");
  806. if (dbm::is_result($r)) {
  807. $current_post = $r[0]['item-id'];
  808. } else {
  809. // This shouldn't happen
  810. $current_post = 0;
  811. }
  812. } else {
  813. // This can happen - for example - if there are locking timeouts.
  814. q("ROLLBACK");
  815. // Store the data into a spool file so that we can try again later.
  816. // At first we restore the Diaspora signature that we removed above.
  817. if (isset($encoded_signature)) {
  818. $arr['dsprsig'] = $encoded_signature;
  819. }
  820. // Now we store the data in the spool directory
  821. // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
  822. $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
  823. $spoolpath = get_spoolpath();
  824. if ($spoolpath != "") {
  825. $spool = $spoolpath.'/'.$file;
  826. file_put_contents($spool, json_encode($arr));
  827. logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
  828. }
  829. return 0;
  830. }
  831. if ($current_post == 0) {
  832. // This is one of these error messages that never should occur.
  833. logger("couldn't find created item - we better quit now.");
  834. q("ROLLBACK");
  835. return 0;
  836. }
  837. // How much entries have we created?
  838. // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
  839. $r = q("SELECT COUNT(*) AS `entries` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s'",
  840. dbesc($arr['uri']),
  841. intval($arr['uid']),
  842. dbesc($arr['network'])
  843. );
  844. if (!dbm::is_result($r)) {
  845. // This shouldn't happen, since COUNT always works when the database connection is there.
  846. logger("We couldn't count the stored entries. Very strange ...");
  847. q("ROLLBACK");
  848. return 0;
  849. }
  850. if ($r[0]["entries"] > 1) {
  851. // There are duplicates. We delete our just created entry.
  852. logger('Duplicated post occurred. uri = ' . $arr['uri'] . ' uid = ' . $arr['uid']);
  853. // Yes, we could do a rollback here - but we are having many users with MyISAM.
  854. q("DELETE FROM `item` WHERE `id` = %d", intval($current_post));
  855. q("COMMIT");
  856. return 0;
  857. } elseif ($r[0]["entries"] == 0) {
  858. // This really should never happen since we quit earlier if there were problems.
  859. logger("Something is terribly wrong. We haven't found our created entry.");
  860. q("ROLLBACK");
  861. return 0;
  862. }
  863. logger('item_store: created item '.$current_post);
  864. item_set_last_item($arr);
  865. if (!$parent_id || ($arr['parent-uri'] === $arr['uri'])) {
  866. $parent_id = $current_post;
  867. }
  868. // Set parent id
  869. $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
  870. intval($parent_id),
  871. intval($current_post)
  872. );
  873. $arr['id'] = $current_post;
  874. $arr['parent'] = $parent_id;
  875. // update the commented timestamp on the parent
  876. // Only update "commented" if it is really a comment
  877. if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment")) {
  878. q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
  879. dbesc(datetime_convert()),
  880. dbesc(datetime_convert()),
  881. intval($parent_id)
  882. );
  883. } else {
  884. q("UPDATE `item` SET `changed` = '%s' WHERE `id` = %d",
  885. dbesc(datetime_convert()),
  886. intval($parent_id)
  887. );
  888. }
  889. if ($dsprsig) {
  890. /*
  891. * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
  892. * We can check for this condition when we decode and encode the stuff again.
  893. */
  894. if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
  895. $dsprsig->signature = base64_decode($dsprsig->signature);
  896. logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
  897. }
  898. q("INSERT INTO `sign` (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
  899. intval($current_post),
  900. dbesc($dsprsig->signed_text),
  901. dbesc($dsprsig->signature),
  902. dbesc($dsprsig->signer)
  903. );
  904. }
  905. $deleted = tag_deliver($arr['uid'], $current_post);
  906. /*
  907. * current post can be deleted if is for a community page and no mention are
  908. * in it.
  909. */
  910. if (!$deleted AND !$dontcache) {
  911. $r = q('SELECT * FROM `item` WHERE `id` = %d', intval($current_post));
  912. if ((dbm::is_result($r)) && (count($r) == 1)) {
  913. if ($notify) {
  914. call_hooks('post_local_end', $r[0]);
  915. } else {
  916. call_hooks('post_remote_end', $r[0]);
  917. }
  918. } else {
  919. logger('item_store: new item not found in DB, id ' . $current_post);
  920. }
  921. }
  922. if ($arr['parent-uri'] === $arr['uri']) {
  923. add_thread($current_post);
  924. } else {
  925. update_thread($parent_id);
  926. }
  927. q("COMMIT");
  928. /*
  929. * Due to deadlock issues with the "term" table we are doing these steps after the commit.
  930. * This is not perfect - but a workable solution until we found the reason for the problem.
  931. */
  932. create_tags_from_item($current_post);
  933. create_files_from_item($current_post);
  934. /*
  935. * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
  936. * It is done after the transaction to avoid dead locks.
  937. */
  938. if ($arr['last-child']) {
  939. $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
  940. dbesc($arr['uri']),
  941. intval($arr['uid']),
  942. intval($current_post)
  943. );
  944. }
  945. if ($arr['parent-uri'] === $arr['uri']) {
  946. add_shadow_thread($current_post);
  947. } else {
  948. add_shadow_entry($current_post);
  949. }
  950. check_item_notification($current_post, $uid);
  951. if ($notify) {
  952. proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $current_post);
  953. }
  954. return $current_post;
  955. }
  956. /**
  957. * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
  958. *
  959. * This can be used to filter for inactive contacts.
  960. * Only do this for public postings to avoid privacy problems, since poco data is public.
  961. * Don't set this value if it isn't from the owner (could be an author that we don't know)
  962. *
  963. * @param array $arr Contains the just posted item record
  964. */
  965. function item_set_last_item($arr) {
  966. $update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
  967. // Is it a forum? Then we don't care about the rules from above
  968. if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
  969. $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
  970. intval($arr['contact-id']));
  971. if (dbm::is_result($isforum)) {
  972. $update = true;
  973. }
  974. }
  975. if ($update) {
  976. q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
  977. dbesc($arr['received']),
  978. dbesc($arr['received']),
  979. intval($arr['contact-id'])
  980. );
  981. }
  982. // Now do the same for the system wide contacts with uid=0
  983. if (!$arr['private']) {
  984. q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
  985. dbesc($arr['received']),
  986. dbesc($arr['received']),
  987. intval($arr['owner-id'])
  988. );
  989. if ($arr['owner-id'] != $arr['author-id']) {
  990. q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
  991. dbesc($arr['received']),
  992. dbesc($arr['received']),
  993. intval($arr['author-id'])
  994. );
  995. }
  996. }
  997. }
  998. function item_body_set_hashtags(&$item) {
  999. $tags = get_tags($item["body"]);
  1000. // No hashtags?
  1001. if (!count($tags)) {
  1002. return false;
  1003. }
  1004. // This sorting is important when there are hashtags that are part of other hashtags
  1005. // Otherwise there could be problems with hashtags like #test and #test2
  1006. rsort($tags);
  1007. $a = get_app();
  1008. $URLSearchString = "^\[\]";
  1009. /// @TODO old-lost code?
  1010. // All hashtags should point to the home server
  1011. //$item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1012. // "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["body"]);
  1013. //$item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1014. // "#[url=".App::get_baseurl()."/search?tag=$2]$2[/url]", $item["tag"]);
  1015. // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
  1016. $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1017. function ($match) {
  1018. return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
  1019. }, $item["body"]);
  1020. $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
  1021. function ($match) {
  1022. return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
  1023. }, $item["body"]);
  1024. $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
  1025. function ($match) {
  1026. return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
  1027. }, $item["body"]);
  1028. // Repair recursive urls
  1029. $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  1030. "&num;$2", $item["body"]);
  1031. foreach ($tags as $tag) {
  1032. if ((strpos($tag, '#') !== 0) || (strpos($tag, '[url='))) {
  1033. continue;
  1034. }
  1035. $basetag = str_replace('_',' ',substr($tag,1));
  1036. $newtag = '#[url=' . App::get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
  1037. $item["body"] = str_replace($tag, $newtag, $item["body"]);
  1038. if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
  1039. if (strlen($item["tag"])) {
  1040. $item["tag"] = ','.$item["tag"];
  1041. }
  1042. $item["tag"] = $newtag.$item["tag"];
  1043. }
  1044. }
  1045. // Convert back the masked hashtags
  1046. $item["body"] = str_replace("&num;", "#", $item["body"]);
  1047. }
  1048. function get_item_guid($id) {
  1049. $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
  1050. if (dbm::is_result($r)) {
  1051. return $r[0]["guid"];
  1052. } else {
  1053. /// @TODO This else-block can be elimited again
  1054. return "";
  1055. }
  1056. }
  1057. function get_item_id($guid, $uid = 0) {
  1058. $nick = "";
  1059. $id = 0;
  1060. if ($uid == 0) {
  1061. $uid == local_user();
  1062. }
  1063. // Does the given user have this item?
  1064. if ($uid) {
  1065. $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
  1066. WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
  1067. AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
  1068. if (dbm::is_result($r)) {
  1069. $id = $r[0]["id"];
  1070. $nick = $r[0]["nickname"];
  1071. }
  1072. }
  1073. // Or is it anywhere on the server?
  1074. if ($nick == "") {
  1075. $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
  1076. WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
  1077. AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
  1078. AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
  1079. AND `item`.`private` = 0 AND `item`.`wall` = 1
  1080. AND `item`.`guid` = '%s'", dbesc($guid));
  1081. if (dbm::is_result($r)) {
  1082. $id = $r[0]["id"];
  1083. $nick = $r[0]["nickname"];
  1084. }
  1085. }
  1086. return array("nick" => $nick, "id" => $id);
  1087. }
  1088. // return - test
  1089. function get_item_contact($item, $contacts) {
  1090. if (! count($contacts) || (! is_array($item))) {
  1091. return false;
  1092. }
  1093. foreach ($contacts as $contact) {
  1094. if ($contact['id'] == $item['contact-id']) {
  1095. return $contact;
  1096. break; // NOTREACHED
  1097. }
  1098. }
  1099. return false;
  1100. }
  1101. /**
  1102. * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  1103. * @param int $uid
  1104. * @param int $item_id
  1105. * @return bool true if item was deleted, else false
  1106. */
  1107. function tag_deliver($uid, $item_id) {
  1108. $a = get_app();
  1109. $mention = false;
  1110. $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  1111. intval($uid)
  1112. );
  1113. if (! dbm::is_result($u)) {
  1114. return;
  1115. }
  1116. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  1117. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  1118. $i = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  1119. intval($item_id),
  1120. intval($uid)
  1121. );
  1122. if (! dbm::is_result($i)) {
  1123. return;
  1124. }
  1125. $item = $i[0];
  1126. $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
  1127. /*
  1128. * Diaspora uses their own hardwired link URL in @-tags
  1129. * instead of the one we supply with webfinger
  1130. */
  1131. $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
  1132. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
  1133. if ($cnt) {
  1134. foreach ($matches as $mtch) {
  1135. if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
  1136. $mention = true;
  1137. logger('tag_deliver: mention found: ' . $mtch[2]);
  1138. }
  1139. }
  1140. }
  1141. if (! $mention) {
  1142. if (($community_page || $prvgroup) &&
  1143. (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])) {
  1144. // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
  1145. // delete it!
  1146. logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
  1147. q("DELETE FROM item WHERE id = %d and uid = %d",
  1148. intval($item_id),
  1149. intval($uid)
  1150. );
  1151. return true;
  1152. }
  1153. return;
  1154. }
  1155. $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
  1156. call_hooks('tagged', $arr);
  1157. if ((! $community_page) && (! $prvgroup)) {
  1158. return;
  1159. }
  1160. /*
  1161. * tgroup delivery - setup a second delivery chain
  1162. * prevent delivery looping - only proceed
  1163. * if the message originated elsewhere and is a top-level post
  1164. */
  1165. if (($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent'])) {
  1166. return;
  1167. }
  1168. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  1169. $c = q("SELECT `name`, `url`, `thumb` FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
  1170. intval($u[0]['uid'])
  1171. );
  1172. if (! dbm::is_result($c)) {
  1173. return;
  1174. }
  1175. // also reset all the privacy bits to the forum default permissions
  1176. $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
  1177. $forum_mode = (($prvgroup) ? 2 : 1);
  1178. q("UPDATE `item` SET `wall` = 1, `origin` = 1, `forum_mode` = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
  1179. `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d",
  1180. intval($forum_mode),
  1181. dbesc($c[0]['name']),
  1182. dbesc($c[0]['url']),
  1183. dbesc($c[0]['thumb']),
  1184. intval($private),
  1185. dbesc($u[0]['allow_cid']),
  1186. dbesc($u[0]['allow_gid']),
  1187. dbesc($u[0]['deny_cid']),
  1188. dbesc($u[0]['deny_gid']),
  1189. intval($item_id)
  1190. );
  1191. update_thread($item_id);
  1192. proc_run(PRIORITY_HIGH,'include/notifier.php', 'tgroup', $item_id);
  1193. }
  1194. function tgroup_check($uid, $item) {
  1195. $mention = false;
  1196. // check that the message originated elsewhere and is a top-level post
  1197. if (($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri'])) {
  1198. return false;
  1199. }
  1200. /// @TODO Encapsulate this or find it encapsulated and replace all occurrances
  1201. $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  1202. intval($uid)
  1203. );
  1204. if (! dbm::is_result($u)) {
  1205. return false;
  1206. }
  1207. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  1208. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  1209. $link = normalise_link(App::get_baseurl() . '/profile/' . $u[0]['nickname']);
  1210. /*
  1211. * Diaspora uses their own hardwired link URL in @-tags
  1212. * instead of the one we supply with webfinger
  1213. */
  1214. $dlink = normalise_link(App::get_baseurl() . '/u/' . $u[0]['nickname']);
  1215. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
  1216. if ($cnt) {
  1217. foreach ($matches as $mtch) {
  1218. if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
  1219. $mention = true;
  1220. logger('tgroup_check: mention found: ' . $mtch[2]);
  1221. }
  1222. }
  1223. }
  1224. if (! $mention) {
  1225. return false;
  1226. }
  1227. /// @TODO Combine both return statements into one
  1228. return (($community_page) || ($prvgroup));
  1229. }
  1230. /**
  1231. * This function returns true if $update has an edited timestamp newer
  1232. * than $existing, i.e. $update contains new data which should override
  1233. * what's already there. If there is no timestamp yet, the update is
  1234. * assumed to be newer. If the update has no timestamp, the existing
  1235. * item is assumed to be up-to-date. If the timestamps are equal it
  1236. * assumes the update has been seen before and should be ignored.
  1237. *
  1238. * @todo fix type-hints (both array)
  1239. */
  1240. function edited_timestamp_is_newer ($existing, $update) {
  1241. if (!x($existing, 'edited') || !$existing['edited']) {
  1242. return true;
  1243. }
  1244. if (!x($update, 'edited') || !$update['edited']) {
  1245. return false;
  1246. }
  1247. $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
  1248. $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
  1249. return (strcmp($existing_edited, $update_edited) < 0);
  1250. }
  1251. /**
  1252. *
  1253. * consume_feed - process atom feed and update anything/everything we might need to update
  1254. *
  1255. * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
  1256. *
  1257. * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
  1258. * It is this person's stuff that is going to be updated.
  1259. * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
  1260. * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
  1261. * have a contact record.
  1262. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
  1263. * might not) try and subscribe to it.
  1264. * $datedir sorts in reverse order
  1265. * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
  1266. * imported prior to its children being seen in the stream unless we are certain
  1267. * of how the feed is arranged/ordered.
  1268. * With $pass = 1, we only pull parent items out of the stream.
  1269. * With $pass = 2, we only pull children (comments/likes).
  1270. *
  1271. * So running this twice, first with pass 1 and then with pass 2 will do the right
  1272. * thing regardless of feed ordering. This won't be adequate in a fully-threaded
  1273. * model where comments can have sub-threads. That would require some massive sorting
  1274. * to get all the feed items into a mostly linear ordering, and might still require
  1275. * recursion.
  1276. *
  1277. * @todo find proper type-hints
  1278. */
  1279. function consume_feed($xml, $importer, &$contact, &$hub, $datedir = 0, $pass = 0) {
  1280. if ($contact['network'] === NETWORK_OSTATUS) {
  1281. if ($pass < 2) {
  1282. // Test - remove before flight
  1283. //$tempfile = tempnam(get_temppath(), "ostatus2");
  1284. //file_put_contents($tempfile, $xml);
  1285. logger("Consume OStatus messages ", LOGGER_DEBUG);
  1286. ostatus::import($xml, $importer, $contact, $hub);
  1287. }
  1288. return;
  1289. }
  1290. if ($contact['network'] === NETWORK_FEED) {
  1291. if ($pass < 2) {
  1292. logger("Consume feeds", LOGGER_DEBUG);
  1293. feed_import($xml, $importer, $contact, $hub);
  1294. }
  1295. return;
  1296. }
  1297. if ($contact['network'] === NETWORK_DFRN) {
  1298. logger("Consume DFRN messages", LOGGER_DEBUG);
  1299. $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
  1300. `contact`.`pubkey` AS `cpubkey`,
  1301. `contact`.`prvkey` AS `cprvkey`,
  1302. `contact`.`thumb` AS `thumb`,
  1303. `contact`.`url` as `url`,
  1304. `contact`.`name` as `senderName`,
  1305. `user`.*
  1306. FROM `contact`
  1307. LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
  1308. WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
  1309. dbesc($contact["id"]), dbesc($importer["uid"])
  1310. );
  1311. if (dbm::is_result($r)) {
  1312. logger("Now import the DFRN feed");
  1313. dfrn::import($xml, $r[0], true);
  1314. return;
  1315. }
  1316. }
  1317. }
  1318. /// @TODO type-hint is array
  1319. function item_is_remote_self($contact, &$datarray) {
  1320. $a = get_app();
  1321. if (!$contact['remote_self']) {
  1322. return false;
  1323. }
  1324. // Prevent the forwarding of posts that are forwarded
  1325. if ($datarray["extid"] == NETWORK_DFRN) {
  1326. return false;
  1327. }
  1328. // Prevent to forward already forwarded posts
  1329. if ($datarray["app"] == $a->get_hostname()) {
  1330. return false;
  1331. }
  1332. // Only forward posts
  1333. if ($datarray["verb"] != ACTIVITY_POST) {
  1334. return false;
  1335. }
  1336. if (($contact['network'] != NETWORK_FEED) AND $datarray['private']) {
  1337. return false;
  1338. }
  1339. $datarray2 = $datarray;
  1340. logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
  1341. if ($contact['remote_self'] == 2) {
  1342. $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
  1343. intval($contact['uid']));
  1344. if (dbm::is_result($r)) {
  1345. $datarray['contact-id'] = $r[0]["id"];
  1346. $datarray['owner-name'] = $r[0]["name"];
  1347. $datarray['owner-link'] = $r[0]["url"];
  1348. $datarray['owner-avatar'] = $r[0]["thumb"];
  1349. $datarray['author-name'] = $datarray['owner-name'];
  1350. $datarray['author-link'] = $datarray['owner-link'];
  1351. $datarray['author-avatar'] = $datarray['owner-avatar'];
  1352. }
  1353. if ($contact['network'] != NETWORK_FEED) {
  1354. $datarray["guid"] = get_guid(32);
  1355. unset($datarray["plink"]);
  1356. $datarray["uri"] = item_new_uri($a->get_hostname(), $contact['uid'], $datarray["guid"]);
  1357. $datarray["parent-uri"] = $datarray["uri"];
  1358. $datarray["extid"] = $contact['network'];
  1359. $urlpart = parse_url($datarray2['author-link']);
  1360. $datarray["app"] = $urlpart["host"];
  1361. } else {
  1362. $datarray['private'] = 0;
  1363. }
  1364. }
  1365. if ($contact['network'] != NETWORK_FEED) {
  1366. // Store the original post
  1367. $r = item_store($datarray2, false, false);
  1368. logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
  1369. } else {
  1370. $datarray["app"] = "Feed";
  1371. }
  1372. return true;
  1373. }
  1374. /// @TODO find proper type-hints
  1375. function new_follower($importer, $contact, $datarray, $item, $sharing = false) {
  1376. $url = notags(trim($datarray['author-link']));
  1377. $name = notags(trim($datarray['author-name']));
  1378. $photo = notags(trim($datarray['author-avatar']));
  1379. if (is_object($item)) {
  1380. $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
  1381. if ($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data']) {
  1382. $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
  1383. }
  1384. } else {
  1385. $nick = $item;
  1386. }
  1387. if (is_array($contact)) {
  1388. if (($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
  1389. || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
  1390. $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
  1391. intval(CONTACT_IS_FRIEND),
  1392. intval($contact['id']),
  1393. intval($importer['uid'])
  1394. );
  1395. }
  1396. // send email notification to owner?
  1397. } else {
  1398. // create contact record
  1399. $r = q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
  1400. `blocked`, `readonly`, `pending`, `writable`)
  1401. VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
  1402. intval($importer['uid']),
  1403. dbesc(datetime_convert()),
  1404. dbesc($url),
  1405. dbesc(normalise_link($url)),
  1406. dbesc($name),
  1407. dbesc($nick),
  1408. dbesc($photo),
  1409. dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
  1410. intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
  1411. );
  1412. $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
  1413. intval($importer['uid']),
  1414. dbesc($url)
  1415. );
  1416. if (dbm::is_result($r)) {
  1417. $contact_record = $r[0];
  1418. update_contact_avatar($photo, $importer["uid"], $contact_record["id"], true);
  1419. }
  1420. /// @TODO Encapsulate this into a function/method
  1421. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  1422. intval($importer['uid'])
  1423. );
  1424. if (dbm::is_result($r) AND !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
  1425. // create notification
  1426. $hash = random_string();
  1427. if (is_array($contact_record)) {
  1428. $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
  1429. VALUES ( %d, %d, 0, 0, '%s', '%s' )",
  1430. intval($importer['uid']),
  1431. intval($contact_record['id']),
  1432. dbesc($hash),
  1433. dbesc(datetime_convert())
  1434. );
  1435. }
  1436. $def_gid = get_default_group($importer['uid'], $contact_record["network"]);
  1437. if (intval($def_gid)) {
  1438. group_add_member($importer['uid'], '', $contact_record['id'], $def_gid);
  1439. }
  1440. if (($r[0]['notify-flags'] & NOTIFY_INTRO) &&
  1441. in_array($r[0]['page-flags'], array(PAGE_NORMAL))) {
  1442. notification(array(
  1443. 'type' => NOTIFY_INTRO,
  1444. 'notify_flags' => $r[0]['notify-flags'],
  1445. 'language' => $r[0]['language'],
  1446. 'to_name' => $r[0]['username'],
  1447. 'to_email' => $r[0]['email'],
  1448. 'uid' => $r[0]['uid'],
  1449. 'link' => App::get_baseurl() . '/notifications/intro',
  1450. 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
  1451. 'source_link' => $contact_record['url'],
  1452. 'source_photo' => $contact_record['photo'],
  1453. 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
  1454. 'otype' => 'intro'
  1455. ));
  1456. }
  1457. } elseif (dbm::is_result($r) AND in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
  1458. $r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
  1459. intval($importer['uid']),
  1460. dbesc($url)
  1461. );
  1462. }
  1463. }
  1464. }
  1465. function lose_follower($importer, $contact, array $datarray = array(), $item = "") {
  1466. if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
  1467. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
  1468. intval(CONTACT_IS_SHARING),
  1469. intval($contact['id'])
  1470. );
  1471. } else {
  1472. contact_remove($contact['id']);
  1473. }
  1474. }
  1475. function lose_sharer($importer, $contact, array $datarray = array(), $item = "") {
  1476. if (($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
  1477. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
  1478. intval(CONTACT_IS_FOLLOWER),
  1479. intval($contact['id'])
  1480. );
  1481. } else {
  1482. contact_remove($contact['id']);
  1483. }
  1484. }
  1485. function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
  1486. $a = get_app();
  1487. if (is_array($importer)) {
  1488. $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
  1489. intval($importer['uid'])
  1490. );
  1491. }
  1492. /*
  1493. * Diaspora has different message-ids in feeds than they do
  1494. * through the direct Diaspora protocol. If we try and use
  1495. * the feed, we'll get duplicates. So don't.
  1496. */
  1497. if ((! dbm::is_result($r)) || $contact['network'] === NETWORK_DIASPORA) {
  1498. return;
  1499. }
  1500. $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
  1501. // Use a single verify token, even if multiple hubs
  1502. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
  1503. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  1504. logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  1505. if (!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
  1506. $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
  1507. dbesc($verify_token),
  1508. intval($contact['id'])
  1509. );
  1510. }
  1511. post_url($url, $params);
  1512. logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
  1513. return;
  1514. }
  1515. function fix_private_photos($s, $uid, $item = null, $cid = 0) {
  1516. if (get_config('system','disable_embedded')) {
  1517. return $s;
  1518. }
  1519. $a = get_app();
  1520. logger('fix_private_photos: check for photos', LOGGER_DEBUG);
  1521. $site = substr(App::get_baseurl(),strpos(App::get_baseurl(),'://'));
  1522. $orig_body = $s;
  1523. $new_body = '';
  1524. $img_start = strpos($orig_body, '[img');
  1525. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  1526. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  1527. while ( ($img_st_close !== false) && ($img_len !== false) ) {
  1528. $img_st_close++; // make it point to AFTER the closing bracket
  1529. $image = substr($orig_body, $img_start + $img_st_close, $img_len);
  1530. logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
  1531. if (stristr($image , $site . '/photo/')) {
  1532. // Only embed locally hosted photos
  1533. $replace = false;
  1534. $i = basename($image);
  1535. $i = str_replace(array('.jpg', '.png', '.gif'),array('', '',''), $i);
  1536. $x = strpos($i, '-');
  1537. if ($x) {
  1538. $res = substr($i, $x + 1);
  1539. $i = substr($i, 0, $x);
  1540. $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
  1541. dbesc($i),
  1542. intval($res),
  1543. intval($uid)
  1544. );
  1545. if (dbm::is_result($r)) {
  1546. /*
  1547. * Check to see if we should replace this photo link with an embedded image
  1548. * 1. No need to do so if the photo is public
  1549. * 2. If there's a contact-id provided, see if they're in the access list
  1550. * for the photo. If so, embed it.
  1551. * 3. Otherwise, if we have an item, see if the item permissions match the photo
  1552. * permissions, regardless of order but first check to see if they're an exact
  1553. * match to save some processing overhead.
  1554. */
  1555. if (has_permissions($r[0])) {
  1556. if ($cid) {
  1557. $recips = enumerate_permissions($r[0]);
  1558. if (in_array($cid, $recips)) {
  1559. $replace = true;
  1560. }
  1561. } elseif ($item) {
  1562. if (compare_permissions($item, $r[0])) {
  1563. $replace = true;
  1564. }
  1565. }
  1566. }
  1567. if ($replace) {
  1568. $data = $r[0]['data'];
  1569. $type = $r[0]['type'];
  1570. // If a custom width and height were specified, apply before embedding
  1571. if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
  1572. logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
  1573. $width = intval($match[1]);
  1574. $height = intval($match[2]);
  1575. $ph = new Photo($data, $type);
  1576. if ($ph->is_valid()) {
  1577. $ph->scaleImage(max($width, $height));
  1578. $data = $ph->imageString();
  1579. $type = $ph->getType();
  1580. }
  1581. }
  1582. logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
  1583. $image = 'data:' . $type . ';base64,' . base64_encode($data);
  1584. logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
  1585. }
  1586. }
  1587. }
  1588. }
  1589. $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
  1590. $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
  1591. if ($orig_body === false) {
  1592. $orig_body = '';
  1593. }
  1594. $img_start = strpos($orig_body, '[img');
  1595. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  1596. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  1597. }
  1598. $new_body = $new_body . $orig_body;
  1599. return $new_body;
  1600. }
  1601. /// @TODO type-hint is array
  1602. function has_permissions($obj) {
  1603. return (
  1604. (
  1605. x($obj, 'allow_cid')
  1606. ) || (
  1607. x($obj, 'allow_gid')
  1608. ) || (
  1609. x($obj, 'deny_cid')
  1610. ) || (
  1611. x($obj, 'deny_gid')
  1612. )
  1613. );
  1614. }
  1615. /// @TODO type-hint is array
  1616. function compare_permissions($obj1, $obj2) {
  1617. // first part is easy. Check that these are exactly the same.
  1618. if (($obj1['allow_cid'] == $obj2['allow_cid'])
  1619. && ($obj1['allow_gid'] == $obj2['allow_gid'])
  1620. && ($obj1['deny_cid'] == $obj2['deny_cid'])
  1621. && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
  1622. return true;
  1623. }
  1624. // This is harder. Parse all the permissions and compare the resulting set.
  1625. $recipients1 = enumerate_permissions($obj1);
  1626. $recipients2 = enumerate_permissions($obj2);
  1627. sort($recipients1);
  1628. sort($recipients2);
  1629. /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
  1630. return ($recipients1 == $recipients2);
  1631. }
  1632. // returns an array of contact-ids that are allowed to see this object
  1633. /// @TODO type-hint is array
  1634. function enumerate_permissions($obj) {
  1635. $allow_people = expand_acl($obj['allow_cid']);
  1636. $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
  1637. $deny_people = expand_acl($obj['deny_cid']);
  1638. $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
  1639. $recipients = array_unique(array_merge($allow_people, $allow_groups));
  1640. $deny = array_unique(array_merge($deny_people, $deny_groups));
  1641. $recipients = array_diff($recipients, $deny);
  1642. return $recipients;
  1643. }
  1644. function item_getfeedtags($item) {
  1645. $ret = array();
  1646. $matches = false;
  1647. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  1648. if ($cnt) {
  1649. for ($x = 0; $x < $cnt; $x ++) {
  1650. if ($matches[1][$x]) {
  1651. $ret[$matches[2][$x]] = array('#', $matches[1][$x], $matches[2][$x]);
  1652. }
  1653. }
  1654. }
  1655. $matches = false;
  1656. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
  1657. if ($cnt) {
  1658. for ($x = 0; $x < $cnt; $x ++) {
  1659. if ($matches[1][$x]) {
  1660. $ret[] = array('@', $matches[1][$x], $matches[2][$x]);
  1661. }
  1662. }
  1663. }
  1664. return $ret;
  1665. }
  1666. function item_expire($uid, $days, $network = "", $force = false) {
  1667. if ((! $uid) || ($days < 1)) {
  1668. return;
  1669. }
  1670. /*
  1671. * $expire_network_only = save your own wall posts
  1672. * and just expire conversations started by others
  1673. */
  1674. $expire_network_only = get_pconfig($uid,'expire', 'network_only');
  1675. $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
  1676. if ($network != "") {
  1677. $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
  1678. /*
  1679. * There is an index "uid_network_received" but not "uid_network_created"
  1680. * This avoids the creation of another index just for one purpose.
  1681. * And it doesn't really matter wether to look at "received" or "created"
  1682. */
  1683. $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
  1684. } else {
  1685. $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
  1686. }
  1687. $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
  1688. WHERE `uid` = %d $range
  1689. AND `id` = `parent`
  1690. $sql_extra
  1691. AND `deleted` = 0",
  1692. intval($uid),
  1693. intval($days)
  1694. );
  1695. if (! dbm::is_result($r)) {
  1696. return;
  1697. }
  1698. $expire_items = get_pconfig($uid, 'expire', 'items');
  1699. $expire_items = (($expire_items === false) ? 1 : intval($expire_items)); // default if not set: 1
  1700. // Forcing expiring of items - but not notes and marked items
  1701. if ($force) {
  1702. $expire_items = true;
  1703. }
  1704. $expire_notes = get_pconfig($uid, 'expire', 'notes');
  1705. $expire_notes = (($expire_notes === false) ? 1 : intval($expire_notes)); // default if not set: 1
  1706. $expire_starred = get_pconfig($uid, 'expire', 'starred');
  1707. $expire_starred = (($expire_starred === false) ? 1 : intval($expire_starred)); // default if not set: 1
  1708. $expire_photos = get_pconfig($uid, 'expire', 'photos');
  1709. $expire_photos = (($expire_photos === false) ? 0 : intval($expire_photos)); // default if not set: 0
  1710. logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  1711. foreach ($r as $item) {
  1712. // don't expire filed items
  1713. if (strpos($item['file'],'[') !== false) {
  1714. continue;
  1715. }
  1716. // Only expire posts, not photos and photo comments
  1717. if ($expire_photos == 0 && strlen($item['resource-id'])) {
  1718. continue;
  1719. } elseif ($expire_starred == 0 && intval($item['starred'])) {
  1720. continue;
  1721. } elseif ($expire_notes == 0 && $item['type'] == 'note') {
  1722. continue;
  1723. } elseif ($expire_items == 0 && $item['type'] != 'note') {
  1724. continue;
  1725. }
  1726. drop_item($item['id'], false);
  1727. }
  1728. proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
  1729. }
  1730. /// @TODO type-hint is array
  1731. function drop_items($items) {
  1732. $uid = 0;
  1733. if (! local_user() && ! remote_user()) {
  1734. return;
  1735. }
  1736. if (count($items)) {
  1737. foreach ($items as $item) {
  1738. $owner = drop_item($item,false);
  1739. if ($owner && ! $uid)
  1740. $uid = $owner;
  1741. }
  1742. }
  1743. // multiple threads may have been deleted, send an expire notification
  1744. if ($uid) {
  1745. proc_run(PRIORITY_HIGH, "include/notifier.php", "expire", $uid);
  1746. }
  1747. }
  1748. function drop_item($id, $interactive = true) {
  1749. $a = get_app();
  1750. // locate item to be deleted
  1751. $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
  1752. intval($id)
  1753. );
  1754. if (! dbm::is_result($r)) {
  1755. if (! $interactive) {
  1756. return 0;
  1757. }
  1758. notice( t('Item not found.') . EOL);
  1759. goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
  1760. }
  1761. $item = $r[0];
  1762. $owner = $item['uid'];
  1763. $contact_id = 0;
  1764. // check if logged in user is either the author or owner of this item
  1765. if (is_array($_SESSION['remote'])) {
  1766. foreach ($_SESSION['remote'] as $visitor) {
  1767. if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
  1768. $contact_id = $visitor['cid'];
  1769. break;
  1770. }
  1771. }
  1772. }
  1773. if ((local_user() == $item['uid']) || ($contact_id) || (! $interactive)) {
  1774. // Check if we should do HTML-based delete confirmation
  1775. if ($_REQUEST['confirm']) {
  1776. // <form> can't take arguments in its "action" parameter
  1777. // so add any arguments as hidden inputs
  1778. $query = explode_querystring($a->query_string);
  1779. $inputs = array();
  1780. foreach ($query['args'] as $arg) {
  1781. if (strpos($arg, 'confirm=') === false) {
  1782. $arg_parts = explode('=', $arg);
  1783. $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
  1784. }
  1785. }
  1786. return replace_macros(get_markup_template('confirm.tpl'), array(
  1787. '$method' => 'get',
  1788. '$message' => t('Do you really want to delete this item?'),
  1789. '$extra_inputs' => $inputs,
  1790. '$confirm' => t('Yes'),
  1791. '$confirm_url' => $query['base'],
  1792. '$confirm_name' => 'confirmed',
  1793. '$cancel' => t('Cancel'),
  1794. ));
  1795. }
  1796. // Now check how the user responded to the confirmation query
  1797. if ($_REQUEST['canceled']) {
  1798. goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
  1799. }
  1800. logger('delete item: ' . $item['id'], LOGGER_DEBUG);
  1801. // delete the item
  1802. $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
  1803. dbesc(datetime_convert()),
  1804. dbesc(datetime_convert()),
  1805. intval($item['id'])
  1806. );
  1807. create_tags_from_item($item['id']);
  1808. create_files_from_item($item['id']);
  1809. delete_thread($item['id'], $item['parent-uri']);
  1810. // clean up categories and tags so they don't end up as orphans
  1811. $matches = false;
  1812. $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
  1813. if ($cnt) {
  1814. foreach ($matches as $mtch) {
  1815. file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
  1816. }
  1817. }
  1818. $matches = false;
  1819. $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
  1820. if ($cnt) {
  1821. foreach ($matches as $mtch) {
  1822. file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
  1823. }
  1824. }
  1825. /*
  1826. * If item is a link to a photo resource, nuke all the associated photos
  1827. * (visitors will not have photo resources)
  1828. * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  1829. * generate a resource-id and therefore aren't intimately linked to the item.
  1830. */
  1831. if (strlen($item['resource-id'])) {
  1832. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
  1833. dbesc($item['resource-id']),
  1834. intval($item['uid'])
  1835. );
  1836. // ignore the result
  1837. }
  1838. // If item is a link to an event, nuke the event record.
  1839. if (intval($item['event-id'])) {
  1840. q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
  1841. intval($item['event-id']),
  1842. intval($item['uid'])
  1843. );
  1844. // ignore the result
  1845. }
  1846. // If item has attachments, drop them
  1847. foreach (explode(", ", $item['attach']) as $attach) {
  1848. preg_match("|attach/(\d+)|", $attach, $matches);
  1849. q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
  1850. intval($matches[1]),
  1851. local_user()
  1852. );
  1853. // ignore the result
  1854. }
  1855. // clean up item_id and sign meta-data tables
  1856. /*
  1857. /// @TODO Old code - caused very long queries and warning entries in the mysql logfiles:
  1858. $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
  1859. intval($item['id']),
  1860. intval($item['uid'])
  1861. );
  1862. $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
  1863. intval($item['id']),
  1864. intval($item['uid'])
  1865. );
  1866. */
  1867. // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
  1868. // Creating list of parents
  1869. $r = q("SELECT `id` FROM `item` WHERE `parent` = %d AND `uid` = %d",
  1870. intval($item['id']),
  1871. intval($item['uid'])
  1872. );
  1873. $parentid = "";
  1874. foreach ($r as $row) {
  1875. if ($parentid != "") {
  1876. $parentid .= ", ";
  1877. }
  1878. $parentid .= $row["id"];
  1879. }
  1880. // Now delete them
  1881. if ($parentid != "") {
  1882. $r = q("DELETE FROM `item_id` WHERE `iid` IN (%s)", dbesc($parentid));
  1883. $r = q("DELETE FROM `sign` WHERE `iid` IN (%s)", dbesc($parentid));
  1884. }
  1885. // If it's the parent of a comment thread, kill all the kids
  1886. if ($item['uri'] == $item['parent-uri']) {
  1887. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
  1888. WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1889. dbesc(datetime_convert()),
  1890. dbesc(datetime_convert()),
  1891. dbesc($item['parent-uri']),
  1892. intval($item['uid'])
  1893. );
  1894. create_tags_from_itemuri($item['parent-uri'], $item['uid']);
  1895. create_files_from_itemuri($item['parent-uri'], $item['uid']);
  1896. delete_thread_uri($item['parent-uri'], $item['uid']);
  1897. // ignore the result
  1898. } else {
  1899. // ensure that last-child is set in case the comment that had it just got wiped.
  1900. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1901. dbesc(datetime_convert()),
  1902. dbesc($item['parent-uri']),
  1903. intval($item['uid'])
  1904. );
  1905. // who is the last child now?
  1906. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
  1907. dbesc($item['parent-uri']),
  1908. intval($item['uid'])
  1909. );
  1910. if (dbm::is_result($r)) {
  1911. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
  1912. intval($r[0]['id'])
  1913. );
  1914. }
  1915. }
  1916. $drop_id = intval($item['id']);
  1917. // send the notification upstream/downstream as the case may be
  1918. proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
  1919. if (! $interactive) {
  1920. return $owner;
  1921. }
  1922. goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
  1923. //NOTREACHED
  1924. } else {
  1925. if (! $interactive) {
  1926. return 0;
  1927. }
  1928. notice( t('Permission denied.') . EOL);
  1929. goaway(App::get_baseurl() . '/' . $_SESSION['return_url']);
  1930. //NOTREACHED
  1931. }
  1932. }
  1933. function first_post_date($uid, $wall = false) {
  1934. $r = q("SELECT `id`, `created` FROM `item`
  1935. WHERE `uid` = %d AND `wall` = %d AND `deleted` = 0 AND `visible` = 1 AND `moderated` = 0
  1936. AND `id` = `parent`
  1937. ORDER BY `created` ASC LIMIT 1",
  1938. intval($uid),
  1939. intval($wall ? 1 : 0)
  1940. );
  1941. if (dbm::is_result($r)) {
  1942. // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
  1943. return substr(datetime_convert('',date_default_timezone_get(), $r[0]['created']),0,10);
  1944. }
  1945. return false;
  1946. }
  1947. /* modified posted_dates() {below} to arrange the list in years */
  1948. function list_post_dates($uid, $wall) {
  1949. $dnow = datetime_convert('',date_default_timezone_get(), 'now','Y-m-d');
  1950. $dthen = first_post_date($uid, $wall);
  1951. if (! $dthen) {
  1952. return array();
  1953. }
  1954. // Set the start and end date to the beginning of the month
  1955. $dnow = substr($dnow, 0, 8) . '01';
  1956. $dthen = substr($dthen, 0, 8) . '01';
  1957. $ret = array();
  1958. /*
  1959. * Starting with the current month, get the first and last days of every
  1960. * month down to and including the month of the first post
  1961. */
  1962. while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
  1963. $dyear = intval(substr($dnow, 0, 4));
  1964. $dstart = substr($dnow, 0, 8) . '01';
  1965. $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
  1966. $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
  1967. $end_month = datetime_convert('', '', $dend, 'Y-m-d');
  1968. $str = day_translate(datetime_convert('', '', $dnow, 'F'));
  1969. if (!$ret[$dyear]) {
  1970. $ret[$dyear] = array();
  1971. }
  1972. $ret[$dyear][] = array($str, $end_month, $start_month);
  1973. $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
  1974. }
  1975. return $ret;
  1976. }
  1977. function posted_dates($uid, $wall) {
  1978. $dnow = datetime_convert('', date_default_timezone_get(), 'now', 'Y-m-d');
  1979. $dthen = first_post_date($uid, $wall);
  1980. if (! $dthen) {
  1981. return array();
  1982. }
  1983. // Set the start and end date to the beginning of the month
  1984. $dnow = substr($dnow, 0, 8) . '01';
  1985. $dthen = substr($dthen, 0, 8) . '01';
  1986. $ret = array();
  1987. /*
  1988. * Starting with the current month, get the first and last days of every
  1989. * month down to and including the month of the first post
  1990. */
  1991. while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
  1992. $dstart = substr($dnow, 0, 8) . '01';
  1993. $dend = substr($dnow, 0, 8) . get_dim(intval($dnow), intval(substr($dnow, 5)));
  1994. $start_month = datetime_convert('', '', $dstart, 'Y-m-d');
  1995. $end_month = datetime_convert('', '', $dend, 'Y-m-d');
  1996. $str = day_translate(datetime_convert('', '', $dnow, 'F Y'));
  1997. $ret[] = array($str, $end_month, $start_month);
  1998. $dnow = datetime_convert('', '', $dnow . ' -1 month', 'Y-m-d');
  1999. }
  2000. return $ret;
  2001. }
  2002. function posted_date_widget($url, $uid, $wall) {
  2003. $o = '';
  2004. if (! feature_enabled($uid, 'archives')) {
  2005. return $o;
  2006. }
  2007. // For former Facebook folks that left because of "timeline"
  2008. /*
  2009. * @TODO old-lost code?
  2010. if ($wall && intval(get_pconfig($uid, 'system', 'no_wall_archive_widget')))
  2011. return $o;
  2012. */
  2013. $visible_years = get_pconfig($uid,'system','archive_visible_years');
  2014. if (! $visible_years) {
  2015. $visible_years = 5;
  2016. }
  2017. $ret = list_post_dates($uid, $wall);
  2018. if (! dbm::is_result($ret)) {
  2019. return $o;
  2020. }
  2021. $cutoff_year = intval(datetime_convert('',date_default_timezone_get(), 'now', 'Y')) - $visible_years;
  2022. $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
  2023. $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
  2024. '$title' => t('Archives'),
  2025. '$size' => $visible_years,
  2026. '$cutoff_year' => $cutoff_year,
  2027. '$cutoff' => $cutoff,
  2028. '$url' => $url,
  2029. '$dates' => $ret,
  2030. '$showmore' => t('show more')
  2031. ));
  2032. return $o;
  2033. }