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.

2437 lines
78KB

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