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.

2126 lines
69 KiB

11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. <?php
  2. require_once('include/bbcode.php');
  3. require_once('include/oembed.php');
  4. require_once('include/salmon.php');
  5. require_once('include/crypto.php');
  6. require_once('include/Photo.php');
  7. require_once('include/tags.php');
  8. require_once('include/files.php');
  9. require_once('include/text.php');
  10. require_once('include/email.php');
  11. require_once('include/threads.php');
  12. require_once('include/socgraph.php');
  13. require_once('include/plaintext.php');
  14. require_once('include/ostatus.php');
  15. require_once('include/feed.php');
  16. require_once('include/Contact.php');
  17. require_once('mod/share.php');
  18. require_once('include/enotify.php');
  19. require_once('include/dfrn.php');
  20. require_once('include/group.php');
  21. require_once('library/defuse/php-encryption-1.2.1/Crypto.php');
  22. function construct_verb($item) {
  23. if($item['verb'])
  24. return $item['verb'];
  25. return ACTIVITY_POST;
  26. }
  27. /* limit_body_size()
  28. *
  29. * The purpose of this function is to apply system message length limits to
  30. * imported messages without including any embedded photos in the length
  31. */
  32. if(! function_exists('limit_body_size')) {
  33. function limit_body_size($body) {
  34. // logger('limit_body_size: start', LOGGER_DEBUG);
  35. $maxlen = get_max_import_size();
  36. // If the length of the body, including the embedded images, is smaller
  37. // than the maximum, then don't waste time looking for the images
  38. if($maxlen && (strlen($body) > $maxlen)) {
  39. logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
  40. $orig_body = $body;
  41. $new_body = '';
  42. $textlen = 0;
  43. $max_found = false;
  44. $img_start = strpos($orig_body, '[img');
  45. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  46. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  47. while(($img_st_close !== false) && ($img_end !== false)) {
  48. $img_st_close++; // make it point to AFTER the closing bracket
  49. $img_end += $img_start;
  50. $img_end += strlen('[/img]');
  51. if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  52. // This is an embedded image
  53. if( ($textlen + $img_start) > $maxlen ) {
  54. if($textlen < $maxlen) {
  55. logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
  56. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  57. $textlen = $maxlen;
  58. }
  59. }
  60. else {
  61. $new_body = $new_body . substr($orig_body, 0, $img_start);
  62. $textlen += $img_start;
  63. }
  64. $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
  65. }
  66. else {
  67. if( ($textlen + $img_end) > $maxlen ) {
  68. if($textlen < $maxlen) {
  69. logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
  70. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  71. $textlen = $maxlen;
  72. }
  73. }
  74. else {
  75. $new_body = $new_body . substr($orig_body, 0, $img_end);
  76. $textlen += $img_end;
  77. }
  78. }
  79. $orig_body = substr($orig_body, $img_end);
  80. if($orig_body === false) // in case the body ends on a closing image tag
  81. $orig_body = '';
  82. $img_start = strpos($orig_body, '[img');
  83. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  84. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  85. }
  86. if( ($textlen + strlen($orig_body)) > $maxlen) {
  87. if($textlen < $maxlen) {
  88. logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
  89. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  90. $textlen = $maxlen;
  91. }
  92. }
  93. else {
  94. logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
  95. $new_body = $new_body . $orig_body;
  96. $textlen += strlen($orig_body);
  97. }
  98. return $new_body;
  99. }
  100. else
  101. return $body;
  102. }}
  103. function title_is_body($title, $body) {
  104. $title = strip_tags($title);
  105. $title = trim($title);
  106. $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
  107. $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
  108. $body = strip_tags($body);
  109. $body = trim($body);
  110. $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
  111. $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
  112. if (strlen($title) < strlen($body))
  113. $body = substr($body, 0, strlen($title));
  114. if (($title != $body) and (substr($title, -3) == "...")) {
  115. $pos = strrpos($title, "...");
  116. if ($pos > 0) {
  117. $title = substr($title, 0, $pos);
  118. $body = substr($body, 0, $pos);
  119. }
  120. }
  121. return($title == $body);
  122. }
  123. function add_page_info_data($data) {
  124. call_hooks('page_info_data', $data);
  125. // It maybe is a rich content, but if it does have everything that a link has,
  126. // then treat it that way
  127. if (($data["type"] == "rich") AND is_string($data["title"]) AND
  128. is_string($data["text"]) AND (sizeof($data["images"]) > 0))
  129. $data["type"] = "link";
  130. if ((($data["type"] != "link") AND ($data["type"] != "video") AND ($data["type"] != "photo")) OR ($data["title"] == $url))
  131. return("");
  132. if ($no_photos AND ($data["type"] == "photo"))
  133. return("");
  134. if (sizeof($data["images"]) > 0)
  135. $preview = $data["images"][0];
  136. else
  137. $preview = "";
  138. // Escape some bad characters
  139. $data["url"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
  140. $data["title"] = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
  141. $text = "[attachment type='".$data["type"]."'";
  142. if ($data["url"] != "")
  143. $text .= " url='".$data["url"]."'";
  144. if ($data["title"] != "")
  145. $text .= " title='".$data["title"]."'";
  146. if (sizeof($data["images"]) > 0) {
  147. $preview = str_replace(array("[", "]"), array("&#91;", "&#93;"), htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
  148. // if the preview picture is larger than 500 pixels then show it in a larger mode
  149. // But only, if the picture isn't higher than large (To prevent huge posts)
  150. if (($data["images"][0]["width"] >= 500) AND ($data["images"][0]["width"] >= $data["images"][0]["height"]))
  151. $text .= " image='".$preview."'";
  152. else
  153. $text .= " preview='".$preview."'";
  154. }
  155. $text .= "]".$data["text"]."[/attachment]";
  156. $hashtags = "";
  157. if (isset($data["keywords"]) AND count($data["keywords"])) {
  158. $a = get_app();
  159. $hashtags = "\n";
  160. foreach ($data["keywords"] AS $keyword) {
  161. /// @todo make a positive list of allowed characters
  162. $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'", "", "`", "(", ")", "", ""),
  163. array("","", "", "", "", "", "", "", "", "", "", ""), $keyword);
  164. $hashtags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url] ";
  165. }
  166. }
  167. return "\n".$text.$hashtags;
  168. }
  169. function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  170. require_once("mod/parse_url.php");
  171. $data = parseurl_getsiteinfo_cached($url, true);
  172. if ($photo != "")
  173. $data["images"][0]["src"] = $photo;
  174. logger('fetch page info for '.$url.' '.print_r($data, true), LOGGER_DEBUG);
  175. if (!$keywords AND isset($data["keywords"]))
  176. unset($data["keywords"]);
  177. if (($keyword_blacklist != "") AND isset($data["keywords"])) {
  178. $list = explode(",", $keyword_blacklist);
  179. foreach ($list AS $keyword) {
  180. $keyword = trim($keyword);
  181. $index = array_search($keyword, $data["keywords"]);
  182. if ($index !== false)
  183. unset($data["keywords"][$index]);
  184. }
  185. }
  186. return($data);
  187. }
  188. function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  189. $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
  190. $tags = "";
  191. if (isset($data["keywords"]) AND count($data["keywords"])) {
  192. $a = get_app();
  193. foreach ($data["keywords"] AS $keyword) {
  194. $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
  195. array("","", "", "", "", ""), $keyword);
  196. if ($tags != "")
  197. $tags .= ",";
  198. $tags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url]";
  199. }
  200. }
  201. return($tags);
  202. }
  203. function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
  204. $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
  205. $text = add_page_info_data($data);
  206. return($text);
  207. }
  208. function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
  209. logger('add_page_info_to_body: fetch page info for body '.$body, LOGGER_DEBUG);
  210. $URLSearchString = "^\[\]";
  211. // Adding these spaces is a quick hack due to my problems with regular expressions :)
  212. preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " ".$body, $matches);
  213. if (!$matches)
  214. preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " ".$body, $matches);
  215. // Convert urls without bbcode elements
  216. if (!$matches AND $texturl) {
  217. preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
  218. // Yeah, a hack. I really hate regular expressions :)
  219. if ($matches)
  220. $matches[1] = $matches[2];
  221. }
  222. if ($matches)
  223. $footer = add_page_info($matches[1], $no_photos);
  224. // Remove the link from the body if the link is attached at the end of the post
  225. if (isset($footer) AND (trim($footer) != "") AND (strpos($footer, $matches[1]))) {
  226. $removedlink = trim(str_replace($matches[1], "", $body));
  227. if (($removedlink == "") OR strstr($body, $removedlink))
  228. $body = $removedlink;
  229. $url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
  230. $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $body);
  231. if (($removedlink == "") OR strstr($body, $removedlink))
  232. $body = $removedlink;
  233. }
  234. // Add the page information to the bottom
  235. if (isset($footer) AND (trim($footer) != ""))
  236. $body .= $footer;
  237. return $body;
  238. }
  239. /**
  240. * Adds a "lang" specification in a "postopts" element of given $arr,
  241. * if possible and not already present.
  242. * Expects "body" element to exist in $arr.
  243. *
  244. * @todo Add a parameter to request forcing override
  245. */
  246. function item_add_language_opt(&$arr) {
  247. if (version_compare(PHP_VERSION, '5.3.0', '<')) return; // LanguageDetect.php not available ?
  248. if ( x($arr, 'postopts') )
  249. {
  250. if ( strstr($arr['postopts'], 'lang=') )
  251. {
  252. // do not override
  253. /// @TODO Add parameter to request overriding
  254. return;
  255. }
  256. $postopts = $arr['postopts'];
  257. }
  258. else
  259. {
  260. $postopts = "";
  261. }
  262. require_once('library/langdet/Text/LanguageDetect.php');
  263. $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
  264. $l = new Text_LanguageDetect;
  265. //$lng = $l->detectConfidence($naked_body);
  266. //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
  267. $lng = $l->detect($naked_body, 3);
  268. if (sizeof($lng) > 0) {
  269. if ($postopts != "") $postopts .= '&'; // arbitrary separator, to be reviewed
  270. $postopts .= 'lang=';
  271. $sep = "";
  272. foreach ($lng as $language => $score) {
  273. $postopts .= $sep . $language.";".$score;
  274. $sep = ':';
  275. }
  276. $arr['postopts'] = $postopts;
  277. }
  278. }
  279. /**
  280. * @brief Creates an unique guid out of a given uri
  281. *
  282. * @param string $uri uri of an item entry
  283. * @return string unique guid
  284. */
  285. function uri_to_guid($uri) {
  286. // Our regular guid routine is using this kind of prefix as well
  287. // We have to avoid that different routines could accidentally create the same value
  288. $parsed = parse_url($uri);
  289. $guid_prefix = hash("crc32", $parsed["host"]);
  290. // Remove the scheme to make sure that "https" and "http" doesn't make a difference
  291. unset($parsed["scheme"]);
  292. $host_id = implode("/", $parsed);
  293. // We could use any hash algorithm since it isn't a security issue
  294. $host_hash = hash("ripemd128", $host_id);
  295. return $guid_prefix.$host_hash;
  296. }
  297. function item_store($arr,$force_parent = false, $notify = false, $dontcache = false) {
  298. // If it is a posting where users should get notifications, then define it as wall posting
  299. if ($notify) {
  300. $arr['wall'] = 1;
  301. $arr['type'] = 'wall';
  302. $arr['origin'] = 1;
  303. $arr['last-child'] = 1;
  304. $arr['network'] = NETWORK_DFRN;
  305. }
  306. // If a Diaspora signature structure was passed in, pull it out of the
  307. // item array and set it aside for later storage.
  308. $dsprsig = null;
  309. if(x($arr,'dsprsig')) {
  310. $dsprsig = json_decode(base64_decode($arr['dsprsig']));
  311. unset($arr['dsprsig']);
  312. }
  313. // Converting the plink
  314. if ($arr['network'] == NETWORK_OSTATUS) {
  315. if (isset($arr['plink']))
  316. $arr['plink'] = ostatus::convert_href($arr['plink']);
  317. elseif (isset($arr['uri']))
  318. $arr['plink'] = ostatus::convert_href($arr['uri']);
  319. }
  320. if(x($arr, 'gravity'))
  321. $arr['gravity'] = intval($arr['gravity']);
  322. elseif($arr['parent-uri'] === $arr['uri'])
  323. $arr['gravity'] = 0;
  324. elseif(activity_match($arr['verb'],ACTIVITY_POST))
  325. $arr['gravity'] = 6;
  326. else
  327. $arr['gravity'] = 6; // extensible catchall
  328. if(! x($arr,'type'))
  329. $arr['type'] = 'remote';
  330. /* check for create date and expire time */
  331. $uid = intval($arr['uid']);
  332. $r = q("SELECT expire FROM user WHERE uid = %d", intval($uid));
  333. if(count($r)) {
  334. $expire_interval = $r[0]['expire'];
  335. if ($expire_interval>0) {
  336. $expire_date = new DateTime( '- '.$expire_interval.' days', new DateTimeZone('UTC'));
  337. $created_date = new DateTime($arr['created'], new DateTimeZone('UTC'));
  338. if ($created_date < $expire_date) {
  339. logger('item-store: item created ('.$arr['created'].') before expiration time ('.$expire_date->format(DateTime::W3C).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
  340. return 0;
  341. }
  342. }
  343. }
  344. // Do we already have this item?
  345. // We have to check several networks since Friendica posts could be repeated via OStatus (maybe Diasporsa as well)
  346. if (in_array(trim($arr['network']), array(NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""))) {
  347. $r = q("SELECT `id`, `network` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` IN ('%s', '%s', '%s') LIMIT 1",
  348. dbesc(trim($arr['uri'])),
  349. intval($uid),
  350. dbesc(NETWORK_DIASPORA),
  351. dbesc(NETWORK_DFRN),
  352. dbesc(NETWORK_OSTATUS)
  353. );
  354. if ($r) {
  355. // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
  356. if ($uid != 0)
  357. 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']);
  358. return($r[0]["id"]);
  359. }
  360. }
  361. // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
  362. // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
  363. //if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
  364. // $arr['body'] = strip_tags($arr['body']);
  365. item_add_language_opt($arr);
  366. if ($notify)
  367. $guid_prefix = "";
  368. elseif ((trim($arr['guid']) == "") AND (trim($arr['plink']) != ""))
  369. $arr['guid'] = uri_to_guid($arr['plink']);
  370. elseif ((trim($arr['guid']) == "") AND (trim($arr['uri']) != ""))
  371. $arr['guid'] = uri_to_guid($arr['uri']);
  372. else {
  373. $parsed = parse_url($arr["author-link"]);
  374. $guid_prefix = hash("crc32", $parsed["host"]);
  375. }
  376. $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
  377. $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid(32, $guid_prefix));
  378. $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : $arr['guid']);
  379. $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
  380. $arr['author-name'] = ((x($arr,'author-name')) ? trim($arr['author-name']) : '');
  381. $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
  382. $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
  383. $arr['owner-name'] = ((x($arr,'owner-name')) ? trim($arr['owner-name']) : '');
  384. $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
  385. $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
  386. $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
  387. $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
  388. $arr['commented'] = ((x($arr,'commented') !== false) ? datetime_convert('UTC','UTC',$arr['commented']) : datetime_convert());
  389. $arr['received'] = ((x($arr,'received') !== false) ? datetime_convert('UTC','UTC',$arr['received']) : datetime_convert());
  390. $arr['changed'] = ((x($arr,'changed') !== false) ? datetime_convert('UTC','UTC',$arr['changed']) : datetime_convert());
  391. $arr['title'] = ((x($arr,'title')) ? trim($arr['title']) : '');
  392. $arr['location'] = ((x($arr,'location')) ? trim($arr['location']) : '');
  393. $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
  394. $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
  395. $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
  396. $arr['deleted'] = 0;
  397. $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
  398. $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
  399. $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
  400. $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
  401. $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
  402. $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
  403. $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
  404. $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
  405. $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
  406. $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
  407. $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
  408. $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
  409. $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
  410. $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
  411. $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
  412. $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
  413. $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
  414. $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
  415. $arr['network'] = ((x($arr,'network')) ? trim($arr['network']) : '');
  416. $arr['postopts'] = ((x($arr,'postopts')) ? trim($arr['postopts']) : '');
  417. $arr['resource-id'] = ((x($arr,'resource-id')) ? trim($arr['resource-id']) : '');
  418. $arr['event-id'] = ((x($arr,'event-id')) ? intval($arr['event-id']) : 0 );
  419. $arr['inform'] = ((x($arr,'inform')) ? trim($arr['inform']) : '');
  420. $arr['file'] = ((x($arr,'file')) ? trim($arr['file']) : '');
  421. // Items cannot be stored before they happen ...
  422. if ($arr['created'] > datetime_convert())
  423. $arr['created'] = datetime_convert();
  424. // We haven't invented time travel by now.
  425. if ($arr['edited'] > datetime_convert())
  426. $arr['edited'] = datetime_convert();
  427. if (($arr['author-link'] == "") AND ($arr['owner-link'] == ""))
  428. logger("Both author-link and owner-link are empty. Called by: ".App::callstack(), LOGGER_DEBUG);
  429. if ($arr['plink'] == "") {
  430. $a = get_app();
  431. $arr['plink'] = $a->get_baseurl().'/display/'.urlencode($arr['guid']);
  432. }
  433. if ($arr['network'] == "") {
  434. $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  435. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
  436. dbesc(normalise_link($arr['author-link'])),
  437. intval($arr['uid'])
  438. );
  439. if(!count($r))
  440. $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
  441. dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
  442. dbesc(normalise_link($arr['author-link']))
  443. );
  444. if(!count($r))
  445. $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  446. intval($arr['contact-id']),
  447. intval($arr['uid'])
  448. );
  449. if(count($r))
  450. $arr['network'] = $r[0]["network"];
  451. // Fallback to friendica (why is it empty in some cases?)
  452. if ($arr['network'] == "")
  453. $arr['network'] = NETWORK_DFRN;
  454. logger("item_store: Set network to ".$arr["network"]." for ".$arr["uri"], LOGGER_DEBUG);
  455. }
  456. // The contact-id should be set before "item_store" was called - but there seems to be some issues
  457. if ($arr["contact-id"] == 0) {
  458. // First we are looking for a suitable contact that matches with the author of the post
  459. // This is done only for comments (See below explanation at "gcontact-id")
  460. if($arr['parent-uri'] != $arr['uri'])
  461. $arr["contact-id"] = get_contact($arr['author-link'], $uid);
  462. // If not present then maybe the owner was found
  463. if ($arr["contact-id"] == 0)
  464. $arr["contact-id"] = get_contact($arr['owner-link'], $uid);
  465. // Still missing? Then use the "self" contact of the current user
  466. if ($arr["contact-id"] == 0) {
  467. $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid` = %d", intval($uid));
  468. if ($r)
  469. $arr["contact-id"] = $r[0]["id"];
  470. }
  471. logger("Contact-id was missing for post ".$arr["guid"]." from user id ".$uid." - now set to ".$arr["contact-id"], LOGGER_DEBUG);
  472. }
  473. if ($arr["gcontact-id"] == 0) {
  474. // The gcontact should mostly behave like the contact. But is is supposed to be global for the system.
  475. // This means that wall posts, repeated posts, etc. should have the gcontact id of the owner.
  476. // On comments the author is the better choice.
  477. if($arr['parent-uri'] === $arr['uri'])
  478. $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['owner-link'], "network" => $arr['network'],
  479. "photo" => $arr['owner-avatar'], "name" => $arr['owner-name']));
  480. else
  481. $arr["gcontact-id"] = get_gcontact_id(array("url" => $arr['author-link'], "network" => $arr['network'],
  482. "photo" => $arr['author-avatar'], "name" => $arr['author-name']));
  483. }
  484. if ($arr["author-id"] == 0)
  485. $arr["author-id"] = get_contact($arr["author-link"], 0);
  486. if ($arr["owner-id"] == 0)
  487. $arr["owner-id"] = get_contact($arr["owner-link"], 0);
  488. if ($arr['guid'] != "") {
  489. // Checking if there is already an item with the same guid
  490. logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
  491. $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
  492. dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
  493. if(count($r)) {
  494. logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
  495. return 0;
  496. }
  497. }
  498. // Check for hashtags in the body and repair or add hashtag links
  499. item_body_set_hashtags($arr);
  500. $arr['thr-parent'] = $arr['parent-uri'];
  501. if($arr['parent-uri'] === $arr['uri']) {
  502. $parent_id = 0;
  503. $parent_deleted = 0;
  504. $allow_cid = $arr['allow_cid'];
  505. $allow_gid = $arr['allow_gid'];
  506. $deny_cid = $arr['deny_cid'];
  507. $deny_gid = $arr['deny_gid'];
  508. $notify_type = 'wall-new';
  509. }
  510. else {
  511. // find the parent and snarf the item id and ACLs
  512. // and anything else we need to inherit
  513. $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
  514. dbesc($arr['parent-uri']),
  515. intval($arr['uid'])
  516. );
  517. if(count($r)) {
  518. // is the new message multi-level threaded?
  519. // even though we don't support it now, preserve the info
  520. // and re-attach to the conversation parent.
  521. if($r[0]['uri'] != $r[0]['parent-uri']) {
  522. $arr['parent-uri'] = $r[0]['parent-uri'];
  523. $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
  524. ORDER BY `id` ASC LIMIT 1",
  525. dbesc($r[0]['parent-uri']),
  526. dbesc($r[0]['parent-uri']),
  527. intval($arr['uid'])
  528. );
  529. if($z && count($z))
  530. $r = $z;
  531. }
  532. $parent_id = $r[0]['id'];
  533. $parent_deleted = $r[0]['deleted'];
  534. $allow_cid = $r[0]['allow_cid'];
  535. $allow_gid = $r[0]['allow_gid'];
  536. $deny_cid = $r[0]['deny_cid'];
  537. $deny_gid = $r[0]['deny_gid'];
  538. $arr['wall'] = $r[0]['wall'];
  539. $notify_type = 'comment-new';
  540. // if the parent is private, force privacy for the entire conversation
  541. // This differs from the above settings as it subtly allows comments from
  542. // email correspondents to be private even if the overall thread is not.
  543. if($r[0]['private'])
  544. $arr['private'] = $r[0]['private'];
  545. // Edge case. We host a public forum that was originally posted to privately.
  546. // The original author commented, but as this is a comment, the permissions
  547. // weren't fixed up so it will still show the comment as private unless we fix it here.
  548. if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
  549. $arr['private'] = 0;
  550. // If its a post from myself then tag the thread as "mention"
  551. logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
  552. $u = q("select * from user where uid = %d limit 1", intval($arr['uid']));
  553. if(count($u)) {
  554. $a = get_app();
  555. $self = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  556. logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
  557. if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
  558. q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
  559. logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
  560. }
  561. }
  562. }
  563. else {
  564. // Allow one to see reply tweets from status.net even when
  565. // we don't have or can't see the original post.
  566. if($force_parent) {
  567. logger('item_store: $force_parent=true, reply converted to top-level post.');
  568. $parent_id = 0;
  569. $arr['parent-uri'] = $arr['uri'];
  570. $arr['gravity'] = 0;
  571. }
  572. else {
  573. logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
  574. return 0;
  575. }
  576. $parent_deleted = 0;
  577. }
  578. }
  579. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` IN ('%s', '%s') AND `uid` = %d LIMIT 1",
  580. dbesc($arr['uri']),
  581. dbesc($arr['network']),
  582. dbesc(NETWORK_DFRN),
  583. intval($arr['uid'])
  584. );
  585. if($r && count($r)) {
  586. logger('duplicated item with the same uri found. ' . print_r($arr,true));
  587. return 0;
  588. }
  589. // Check for an existing post with the same content. There seems to be a problem with OStatus.
  590. $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
  591. dbesc($arr['body']),
  592. dbesc($arr['network']),
  593. dbesc($arr['created']),
  594. intval($arr['contact-id']),
  595. intval($arr['uid'])
  596. );
  597. if($r && count($r)) {
  598. logger('duplicated item with the same body found. ' . print_r($arr,true));
  599. return 0;
  600. }
  601. // Is this item available in the global items (with uid=0)?
  602. if ($arr["uid"] == 0) {
  603. $arr["global"] = true;
  604. q("UPDATE `item` SET `global` = 1 WHERE `uri` = '%s'", dbesc($arr["uri"]));
  605. } else {
  606. $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `uri` = '%s'", dbesc($arr["uri"]));
  607. $arr["global"] = (count($isglobal) > 0);
  608. }
  609. // Fill the cache field
  610. put_item_in_cache($arr);
  611. if ($notify)
  612. call_hooks('post_local',$arr);
  613. else
  614. call_hooks('post_remote',$arr);
  615. if(x($arr,'cancel')) {
  616. logger('item_store: post cancelled by plugin.');
  617. return 0;
  618. }
  619. // Store the unescaped version
  620. $unescaped = $arr;
  621. dbesc_array($arr);
  622. logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
  623. $r = dbq("INSERT INTO `item` (`"
  624. . implode("`, `", array_keys($arr))
  625. . "`) VALUES ('"
  626. . implode("', '", array_values($arr))
  627. . "')" );
  628. // And restore it
  629. $arr = $unescaped;
  630. // find the item that we just created
  631. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' ORDER BY `id` ASC",
  632. dbesc($arr['uri']),
  633. intval($arr['uid']),
  634. dbesc($arr['network'])
  635. );
  636. if(count($r) > 1) {
  637. // There are duplicates. Keep the oldest one, delete the others
  638. logger('item_store: duplicated post occurred. Removing newer duplicates. uri = '.$arr['uri'].' uid = '.$arr['uid']);
  639. q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' AND `id` > %d",
  640. dbesc($arr['uri']),
  641. intval($arr['uid']),
  642. dbesc($arr['network']),
  643. intval($r[0]["id"])
  644. );
  645. return 0;
  646. } elseif(count($r)) {
  647. $current_post = $r[0]['id'];
  648. logger('item_store: created item ' . $current_post);
  649. // Set "success_update" and "last-item" to the date of the last time we heard from this contact
  650. // This can be used to filter for inactive contacts.
  651. // Only do this for public postings to avoid privacy problems, since poco data is public.
  652. // Don't set this value if it isn't from the owner (could be an author that we don't know)
  653. $update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
  654. // Is it a forum? Then we don't care about the rules from above
  655. if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
  656. $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
  657. intval($arr['contact-id']));
  658. if ($isforum)
  659. $update = true;
  660. }
  661. if ($update)
  662. q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
  663. dbesc($arr['received']),
  664. dbesc($arr['received']),
  665. intval($arr['contact-id'])
  666. );
  667. } else {
  668. logger('item_store: could not locate created item');
  669. return 0;
  670. }
  671. if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
  672. $parent_id = $current_post;
  673. if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
  674. $private = 1;
  675. else
  676. $private = $arr['private'];
  677. // Set parent id - and also make sure to inherit the parent's ACLs.
  678. $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
  679. `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d",
  680. intval($parent_id),
  681. dbesc($allow_cid),
  682. dbesc($allow_gid),
  683. dbesc($deny_cid),
  684. dbesc($deny_gid),
  685. intval($private),
  686. intval($parent_deleted),
  687. intval($current_post)
  688. );
  689. $arr['id'] = $current_post;
  690. $arr['parent'] = $parent_id;
  691. $arr['allow_cid'] = $allow_cid;
  692. $arr['allow_gid'] = $allow_gid;
  693. $arr['deny_cid'] = $deny_cid;
  694. $arr['deny_gid'] = $deny_gid;
  695. $arr['private'] = $private;
  696. $arr['deleted'] = $parent_deleted;
  697. // update the commented timestamp on the parent
  698. // Only update "commented" if it is really a comment
  699. if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment"))
  700. q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
  701. dbesc(datetime_convert()),
  702. dbesc(datetime_convert()),
  703. intval($parent_id)
  704. );
  705. else
  706. q("UPDATE `item` SET `changed` = '%s' WHERE `id` = %d",
  707. dbesc(datetime_convert()),
  708. intval($parent_id)
  709. );
  710. if($dsprsig) {
  711. // Friendica servers lower than 3.4.3-2 had double encoded the signature ...
  712. // We can check for this condition when we decode and encode the stuff again.
  713. if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
  714. $dsprsig->signature = base64_decode($dsprsig->signature);
  715. logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
  716. }
  717. q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
  718. intval($current_post),
  719. dbesc($dsprsig->signed_text),
  720. dbesc($dsprsig->signature),
  721. dbesc($dsprsig->signer)
  722. );
  723. }
  724. /**
  725. * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
  726. */
  727. if($arr['last-child']) {
  728. $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
  729. dbesc($arr['uri']),
  730. intval($arr['uid']),
  731. intval($current_post)
  732. );
  733. }
  734. $deleted = tag_deliver($arr['uid'],$current_post);
  735. // current post can be deleted if is for a community page and no mention are
  736. // in it.
  737. if (!$deleted AND !$dontcache) {
  738. $r = q('SELECT * FROM `item` WHERE id = %d', intval($current_post));
  739. if (count($r) == 1) {
  740. if ($notify)
  741. call_hooks('post_local_end', $r[0]);
  742. else
  743. call_hooks('post_remote_end', $r[0]);
  744. } else
  745. logger('item_store: new item not found in DB, id ' . $current_post);
  746. }
  747. create_tags_from_item($current_post);
  748. create_files_from_item($current_post);
  749. // Only check for notifications on start posts
  750. if ($arr['parent-uri'] === $arr['uri'])
  751. add_thread($current_post);
  752. else {
  753. update_thread($parent_id);
  754. add_shadow_entry($arr);
  755. }
  756. check_item_notification($current_post, $uid);
  757. if ($notify)
  758. proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $current_post);
  759. return $current_post;
  760. }
  761. function item_body_set_hashtags(&$item) {
  762. $tags = get_tags($item["body"]);
  763. // No hashtags?
  764. if(!count($tags))
  765. return(false);
  766. // This sorting is important when there are hashtags that are part of other hashtags
  767. // Otherwise there could be problems with hashtags like #test and #test2
  768. rsort($tags);
  769. $a = get_app();
  770. $URLSearchString = "^\[\]";
  771. // All hashtags should point to the home server
  772. //$item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  773. // "#[url=".$a->get_baseurl()."/search?tag=$2]$2[/url]", $item["body"]);
  774. //$item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  775. // "#[url=".$a->get_baseurl()."/search?tag=$2]$2[/url]", $item["tag"]);
  776. // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
  777. $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  778. function ($match){
  779. return("[url=".str_replace("#", "&num;", $match[1])."]".str_replace("#", "&num;", $match[2])."[/url]");
  780. },$item["body"]);
  781. $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
  782. function ($match){
  783. return("[bookmark=".str_replace("#", "&num;", $match[1])."]".str_replace("#", "&num;", $match[2])."[/bookmark]");
  784. },$item["body"]);
  785. $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
  786. function ($match){
  787. return("[attachment ".str_replace("#", "&num;", $match[1])."]".$match[2]."[/attachment]");
  788. },$item["body"]);
  789. // Repair recursive urls
  790. $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
  791. "&num;$2", $item["body"]);
  792. foreach($tags as $tag) {
  793. if(strpos($tag,'#') !== 0)
  794. continue;
  795. if(strpos($tag,'[url='))
  796. continue;
  797. $basetag = str_replace('_',' ',substr($tag,1));
  798. $newtag = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($basetag).']'.$basetag.'[/url]';
  799. $item["body"] = str_replace($tag, $newtag, $item["body"]);
  800. if(!stristr($item["tag"],"/search?tag=".$basetag."]".$basetag."[/url]")) {
  801. if(strlen($item["tag"]))
  802. $item["tag"] = ','.$item["tag"];
  803. $item["tag"] = $newtag.$item["tag"];
  804. }
  805. }
  806. // Convert back the masked hashtags
  807. $item["body"] = str_replace("&num;", "#", $item["body"]);
  808. }
  809. function get_item_guid($id) {
  810. $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
  811. if (count($r))
  812. return($r[0]["guid"]);
  813. else
  814. return("");
  815. }
  816. function get_item_id($guid, $uid = 0) {
  817. $nick = "";
  818. $id = 0;
  819. if ($uid == 0)
  820. $uid == local_user();
  821. // Does the given user have this item?
  822. if ($uid) {
  823. $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
  824. WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
  825. AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
  826. if (count($r)) {
  827. $id = $r[0]["id"];
  828. $nick = $r[0]["nickname"];
  829. }
  830. }
  831. // Or is it anywhere on the server?
  832. if ($nick == "") {
  833. $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
  834. WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
  835. AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
  836. AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
  837. AND `item`.`private` = 0 AND `item`.`wall` = 1
  838. AND `item`.`guid` = '%s'", dbesc($guid));
  839. if (count($r)) {
  840. $id = $r[0]["id"];
  841. $nick = $r[0]["nickname"];
  842. }
  843. }
  844. return(array("nick" => $nick, "id" => $id));
  845. }
  846. // return - test
  847. function get_item_contact($item,$contacts) {
  848. if(! count($contacts) || (! is_array($item)))
  849. return false;
  850. foreach($contacts as $contact) {
  851. if($contact['id'] == $item['contact-id']) {
  852. return $contact;
  853. break; // NOTREACHED
  854. }
  855. }
  856. return false;
  857. }
  858. /**
  859. * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  860. * @param int $uid
  861. * @param int $item_id
  862. * @return bool true if item was deleted, else false
  863. */
  864. function tag_deliver($uid,$item_id) {
  865. //
  866. $a = get_app();
  867. $mention = false;
  868. $u = q("select * from user where uid = %d limit 1",
  869. intval($uid)
  870. );
  871. if(! count($u))
  872. return;
  873. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  874. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  875. $i = q("select * from item where id = %d and uid = %d limit 1",
  876. intval($item_id),
  877. intval($uid)
  878. );
  879. if(! count($i))
  880. return;
  881. $item = $i[0];
  882. $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  883. // Diaspora uses their own hardwired link URL in @-tags
  884. // instead of the one we supply with webfinger
  885. $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
  886. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
  887. if($cnt) {
  888. foreach($matches as $mtch) {
  889. if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
  890. $mention = true;
  891. logger('tag_deliver: mention found: ' . $mtch[2]);
  892. }
  893. }
  894. }
  895. if(! $mention){
  896. if ( ($community_page || $prvgroup) &&
  897. (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])){
  898. // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
  899. // delete it!
  900. logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
  901. q("DELETE FROM item WHERE id = %d and uid = %d",
  902. intval($item_id),
  903. intval($uid)
  904. );
  905. return true;
  906. }
  907. return;
  908. }
  909. $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
  910. call_hooks('tagged', $arr);
  911. if((! $community_page) && (! $prvgroup))
  912. return;
  913. // tgroup delivery - setup a second delivery chain
  914. // prevent delivery looping - only proceed
  915. // if the message originated elsewhere and is a top-level post
  916. if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
  917. return;
  918. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  919. $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
  920. intval($u[0]['uid'])
  921. );
  922. if(! count($c))
  923. return;
  924. // also reset all the privacy bits to the forum default permissions
  925. $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
  926. $forum_mode = (($prvgroup) ? 2 : 1);
  927. q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
  928. `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d",
  929. intval($forum_mode),
  930. dbesc($c[0]['name']),
  931. dbesc($c[0]['url']),
  932. dbesc($c[0]['thumb']),
  933. intval($private),
  934. dbesc($u[0]['allow_cid']),
  935. dbesc($u[0]['allow_gid']),
  936. dbesc($u[0]['deny_cid']),
  937. dbesc($u[0]['deny_gid']),
  938. intval($item_id)
  939. );
  940. update_thread($item_id);
  941. proc_run(PRIORITY_HIGH,'include/notifier.php', 'tgroup', $item_id);
  942. }
  943. function tgroup_check($uid,$item) {
  944. $a = get_app();
  945. $mention = false;
  946. // check that the message originated elsewhere and is a top-level post
  947. if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
  948. return false;
  949. $u = q("select * from user where uid = %d limit 1",
  950. intval($uid)
  951. );
  952. if(! count($u))
  953. return false;
  954. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  955. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  956. $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  957. // Diaspora uses their own hardwired link URL in @-tags
  958. // instead of the one we supply with webfinger
  959. $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
  960. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
  961. if($cnt) {
  962. foreach($matches as $mtch) {
  963. if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
  964. $mention = true;
  965. logger('tgroup_check: mention found: ' . $mtch[2]);
  966. }
  967. }
  968. }
  969. if(! $mention)
  970. return false;
  971. if((! $community_page) && (! $prvgroup))
  972. return false;
  973. return true;
  974. }
  975. /*
  976. This function returns true if $update has an edited timestamp newer
  977. than $existing, i.e. $update contains new data which should override
  978. what's already there. If there is no timestamp yet, the update is
  979. assumed to be newer. If the update has no timestamp, the existing
  980. item is assumed to be up-to-date. If the timestamps are equal it
  981. assumes the update has been seen before and should be ignored.
  982. */
  983. function edited_timestamp_is_newer($existing, $update) {
  984. if (!x($existing,'edited') || !$existing['edited']) {
  985. return true;
  986. }
  987. if (!x($update,'edited') || !$update['edited']) {
  988. return false;
  989. }
  990. $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
  991. $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
  992. return (strcmp($existing_edited, $update_edited) < 0);
  993. }
  994. /**
  995. *
  996. * consume_feed - process atom feed and update anything/everything we might need to update
  997. *
  998. * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
  999. *
  1000. * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
  1001. * It is this person's stuff that is going to be updated.
  1002. * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
  1003. * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
  1004. * have a contact record.
  1005. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
  1006. * might not) try and subscribe to it.
  1007. * $datedir sorts in reverse order
  1008. * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
  1009. * imported prior to its children being seen in the stream unless we are certain
  1010. * of how the feed is arranged/ordered.
  1011. * With $pass = 1, we only pull parent items out of the stream.
  1012. * With $pass = 2, we only pull children (comments/likes).
  1013. *
  1014. * So running this twice, first with pass 1 and then with pass 2 will do the right
  1015. * thing regardless of feed ordering. This won't be adequate in a fully-threaded
  1016. * model where comments can have sub-threads. That would require some massive sorting
  1017. * to get all the feed items into a mostly linear ordering, and might still require
  1018. * recursion.
  1019. */
  1020. function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
  1021. if ($contact['network'] === NETWORK_OSTATUS) {
  1022. if ($pass < 2) {
  1023. // Test - remove before flight
  1024. //$tempfile = tempnam(get_temppath(), "ostatus2");
  1025. //file_put_contents($tempfile, $xml);
  1026. logger("Consume OStatus messages ", LOGGER_DEBUG);
  1027. ostatus::import($xml,$importer,$contact, $hub);
  1028. }
  1029. return;
  1030. }
  1031. if ($contact['network'] === NETWORK_FEED) {
  1032. if ($pass < 2) {
  1033. logger("Consume feeds", LOGGER_DEBUG);
  1034. feed_import($xml,$importer,$contact, $hub);
  1035. }
  1036. return;
  1037. }
  1038. if ($contact['network'] === NETWORK_DFRN) {
  1039. logger("Consume DFRN messages", LOGGER_DEBUG);
  1040. $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
  1041. `contact`.`pubkey` AS `cpubkey`,
  1042. `contact`.`prvkey` AS `cprvkey`,
  1043. `contact`.`thumb` AS `thumb`,
  1044. `contact`.`url` as `url`,
  1045. `contact`.`name` as `senderName`,
  1046. `user`.*
  1047. FROM `contact`
  1048. LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
  1049. WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
  1050. dbesc($contact["id"]), dbesc($importer["uid"])
  1051. );
  1052. if ($r) {
  1053. logger("Now import the DFRN feed");
  1054. dfrn::import($xml,$r[0], true);
  1055. return;
  1056. }
  1057. }
  1058. }
  1059. function item_is_remote_self($contact, &$datarray) {
  1060. $a = get_app();
  1061. if (!$contact['remote_self'])
  1062. return false;
  1063. // Prevent the forwarding of posts that are forwarded
  1064. if ($datarray["extid"] == NETWORK_DFRN)
  1065. return false;
  1066. // Prevent to forward already forwarded posts
  1067. if ($datarray["app"] == $a->get_hostname())
  1068. return false;
  1069. // Only forward posts
  1070. if ($datarray["verb"] != ACTIVITY_POST)
  1071. return false;
  1072. if (($contact['network'] != NETWORK_FEED) AND $datarray['private'])
  1073. return false;
  1074. $datarray2 = $datarray;
  1075. logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
  1076. if ($contact['remote_self'] == 2) {
  1077. $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
  1078. intval($contact['uid']));
  1079. if (count($r)) {
  1080. $datarray['contact-id'] = $r[0]["id"];
  1081. $datarray['owner-name'] = $r[0]["name"];
  1082. $datarray['owner-link'] = $r[0]["url"];
  1083. $datarray['owner-avatar'] = $r[0]["thumb"];
  1084. $datarray['author-name'] = $datarray['owner-name'];
  1085. $datarray['author-link'] = $datarray['owner-link'];
  1086. $datarray['author-avatar'] = $datarray['owner-avatar'];
  1087. }
  1088. if ($contact['network'] != NETWORK_FEED) {
  1089. $datarray["guid"] = get_guid(32);
  1090. unset($datarray["plink"]);
  1091. $datarray["uri"] = item_new_uri($a->get_hostname(),$contact['uid'], $datarray["guid"]);
  1092. $datarray["parent-uri"] = $datarray["uri"];
  1093. $datarray["extid"] = $contact['network'];
  1094. $urlpart = parse_url($datarray2['author-link']);
  1095. $datarray["app"] = $urlpart["host"];
  1096. } else
  1097. $datarray['private'] = 0;
  1098. }
  1099. if ($contact['network'] != NETWORK_FEED) {
  1100. // Store the original post
  1101. $r = item_store($datarray2, false, false);
  1102. logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
  1103. } else
  1104. $datarray["app"] = "Feed";
  1105. return true;
  1106. }
  1107. function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
  1108. $url = notags(trim($datarray['author-link']));
  1109. $name = notags(trim($datarray['author-name']));
  1110. $photo = notags(trim($datarray['author-avatar']));
  1111. if (is_object($item)) {
  1112. $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
  1113. if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
  1114. $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
  1115. } else
  1116. $nick = $item;
  1117. if(is_array($contact)) {
  1118. if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
  1119. || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
  1120. $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
  1121. intval(CONTACT_IS_FRIEND),
  1122. intval($contact['id']),
  1123. intval($importer['uid'])
  1124. );
  1125. }
  1126. // send email notification to owner?
  1127. } else {
  1128. // create contact record
  1129. $r = q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
  1130. `blocked`, `readonly`, `pending`, `writable`)
  1131. VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
  1132. intval($importer['uid']),
  1133. dbesc(datetime_convert()),
  1134. dbesc($url),
  1135. dbesc(normalise_link($url)),
  1136. dbesc($name),
  1137. dbesc($nick),
  1138. dbesc($photo),
  1139. dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
  1140. intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
  1141. );
  1142. $r = q("SELECT `id`, `network` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
  1143. intval($importer['uid']),
  1144. dbesc($url)
  1145. );
  1146. if(count($r)) {
  1147. $contact_record = $r[0];
  1148. update_contact_avatar($photo, $importer["uid"], $contact_record["id"], true);
  1149. }
  1150. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  1151. intval($importer['uid'])
  1152. );
  1153. $a = get_app();
  1154. if(count($r) AND !in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
  1155. // create notification
  1156. $hash = random_string();
  1157. if(is_array($contact_record)) {
  1158. $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
  1159. VALUES ( %d, %d, 0, 0, '%s', '%s' )",
  1160. intval($importer['uid']),
  1161. intval($contact_record['id']),
  1162. dbesc($hash),
  1163. dbesc(datetime_convert())
  1164. );
  1165. }
  1166. $def_gid = get_default_group($importer['uid'], $contact_record["network"]);
  1167. if(intval($def_gid))
  1168. group_add_member($importer['uid'],'',$contact_record['id'],$def_gid);
  1169. if(($r[0]['notify-flags'] & NOTIFY_INTRO) &&
  1170. in_array($r[0]['page-flags'], array(PAGE_NORMAL))) {
  1171. notification(array(
  1172. 'type' => NOTIFY_INTRO,
  1173. 'notify_flags' => $r[0]['notify-flags'],
  1174. 'language' => $r[0]['language'],
  1175. 'to_name' => $r[0]['username'],
  1176. 'to_email' => $r[0]['email'],
  1177. 'uid' => $r[0]['uid'],
  1178. 'link' => $a->get_baseurl() . '/notifications/intro',
  1179. 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
  1180. 'source_link' => $contact_record['url'],
  1181. 'source_photo' => $contact_record['photo'],
  1182. 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
  1183. 'otype' => 'intro'
  1184. ));
  1185. }
  1186. } elseif (count($r) AND in_array($r[0]['page-flags'], array(PAGE_SOAPBOX, PAGE_FREELOVE))) {
  1187. $r = q("UPDATE `contact` SET `pending` = 0 WHERE `uid` = %d AND `url` = '%s' AND `pending` LIMIT 1",
  1188. intval($importer['uid']),
  1189. dbesc($url)
  1190. );
  1191. }
  1192. }
  1193. }
  1194. function lose_follower($importer,$contact,$datarray = array(),$item = "") {
  1195. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
  1196. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
  1197. intval(CONTACT_IS_SHARING),
  1198. intval($contact['id'])
  1199. );
  1200. }
  1201. else {
  1202. contact_remove($contact['id']);
  1203. }
  1204. }
  1205. function lose_sharer($importer,$contact,$datarray = array(),$item = "") {
  1206. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
  1207. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
  1208. intval(CONTACT_IS_FOLLOWER),
  1209. intval($contact['id'])
  1210. );
  1211. }
  1212. else {
  1213. contact_remove($contact['id']);
  1214. }
  1215. }
  1216. function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
  1217. $a = get_app();
  1218. if(is_array($importer)) {
  1219. $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
  1220. intval($importer['uid'])
  1221. );
  1222. }
  1223. // Diaspora has different message-ids in feeds than they do
  1224. // through the direct Diaspora protocol. If we try and use
  1225. // the feed, we'll get duplicates. So don't.
  1226. if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
  1227. return;
  1228. $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
  1229. // Use a single verify token, even if multiple hubs
  1230. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
  1231. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  1232. logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  1233. if(!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
  1234. $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
  1235. dbesc($verify_token),
  1236. intval($contact['id'])
  1237. );
  1238. }
  1239. post_url($url,$params);
  1240. logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
  1241. return;
  1242. }
  1243. function fix_private_photos($s, $uid, $item = null, $cid = 0) {
  1244. if(get_config('system','disable_embedded'))
  1245. return $s;
  1246. $a = get_app();
  1247. logger('fix_private_photos: check for photos', LOGGER_DEBUG);
  1248. $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
  1249. $orig_body = $s;
  1250. $new_body = '';
  1251. $img_start = strpos($orig_body, '[img');
  1252. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  1253. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  1254. while( ($img_st_close !== false) && ($img_len !== false) ) {
  1255. $img_st_close++; // make it point to AFTER the closing bracket
  1256. $image = substr($orig_body, $img_start + $img_st_close, $img_len);
  1257. logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
  1258. if(stristr($image , $site . '/photo/')) {
  1259. // Only embed locally hosted photos
  1260. $replace = false;
  1261. $i = basename($image);
  1262. $i = str_replace(array('.jpg','.png','.gif'),array('','',''),$i);
  1263. $x = strpos($i,'-');
  1264. if($x) {
  1265. $res = substr($i,$x+1);
  1266. $i = substr($i,0,$x);
  1267. $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
  1268. dbesc($i),
  1269. intval($res),
  1270. intval($uid)
  1271. );
  1272. if($r) {
  1273. // Check to see if we should replace this photo link with an embedded image
  1274. // 1. No need to do so if the photo is public
  1275. // 2. If there's a contact-id provided, see if they're in the access list
  1276. // for the photo. If so, embed it.
  1277. // 3. Otherwise, if we have an item, see if the item permissions match the photo
  1278. // permissions, regardless of order but first check to see if they're an exact
  1279. // match to save some processing overhead.
  1280. if(has_permissions($r[0])) {
  1281. if($cid) {
  1282. $recips = enumerate_permissions($r[0]);
  1283. if(in_array($cid, $recips)) {
  1284. $replace = true;
  1285. }
  1286. }
  1287. elseif($item) {
  1288. if(compare_permissions($item,$r[0]))
  1289. $replace = true;
  1290. }
  1291. }
  1292. if($replace) {
  1293. $data = $r[0]['data'];
  1294. $type = $r[0]['type'];
  1295. // If a custom width and height were specified, apply before embedding
  1296. if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
  1297. logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
  1298. $width = intval($match[1]);
  1299. $height = intval($match[2]);
  1300. $ph = new Photo($data, $type);
  1301. if($ph->is_valid()) {
  1302. $ph->scaleImage(max($width, $height));
  1303. $data = $ph->imageString();
  1304. $type = $ph->getType();
  1305. }
  1306. }
  1307. logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
  1308. $image = 'data:' . $type . ';base64,' . base64_encode($data);
  1309. logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
  1310. }
  1311. }
  1312. }
  1313. }
  1314. $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
  1315. $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
  1316. if($orig_body === false)
  1317. $orig_body = '';
  1318. $img_start = strpos($orig_body, '[img');
  1319. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  1320. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  1321. }
  1322. $new_body = $new_body . $orig_body;
  1323. return($new_body);
  1324. }
  1325. function has_permissions($obj) {
  1326. if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
  1327. return true;
  1328. return false;
  1329. }
  1330. function compare_permissions($obj1,$obj2) {
  1331. // first part is easy. Check that these are exactly the same.
  1332. if(($obj1['allow_cid'] == $obj2['allow_cid'])
  1333. && ($obj1['allow_gid'] == $obj2['allow_gid'])
  1334. && ($obj1['deny_cid'] == $obj2['deny_cid'])
  1335. && ($obj1['deny_gid'] == $obj2['deny_gid']))
  1336. return true;
  1337. // This is harder. Parse all the permissions and compare the resulting set.
  1338. $recipients1 = enumerate_permissions($obj1);
  1339. $recipients2 = enumerate_permissions($obj2);
  1340. sort($recipients1);
  1341. sort($recipients2);
  1342. if($recipients1 == $recipients2)
  1343. return true;
  1344. return false;
  1345. }
  1346. // returns an array of contact-ids that are allowed to see this object
  1347. function enumerate_permissions($obj) {
  1348. $allow_people = expand_acl($obj['allow_cid']);
  1349. $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
  1350. $deny_people = expand_acl($obj['deny_cid']);
  1351. $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
  1352. $recipients = array_unique(array_merge($allow_people,$allow_groups));
  1353. $deny = array_unique(array_merge($deny_people,$deny_groups));
  1354. $recipients = array_diff($recipients,$deny);
  1355. return $recipients;
  1356. }
  1357. function item_getfeedtags($item) {
  1358. $ret = array();
  1359. $matches = false;
  1360. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  1361. if($cnt) {
  1362. for($x = 0; $x < $cnt; $x ++) {
  1363. if($matches[1][$x])
  1364. $ret[$matches[2][$x]] = array('#',$matches[1][$x], $matches[2][$x]);
  1365. }
  1366. }
  1367. $matches = false;
  1368. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  1369. if($cnt) {
  1370. for($x = 0; $x < $cnt; $x ++) {
  1371. if($matches[1][$x])
  1372. $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
  1373. }
  1374. }
  1375. return $ret;
  1376. }
  1377. function item_expire($uid, $days, $network = "", $force = false) {
  1378. if((! $uid) || ($days < 1))
  1379. return;
  1380. // $expire_network_only = save your own wall posts
  1381. // and just expire conversations started by others
  1382. $expire_network_only = get_pconfig($uid,'expire','network_only');
  1383. $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
  1384. if ($network != "") {
  1385. $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
  1386. // There is an index "uid_network_received" but not "uid_network_created"
  1387. // This avoids the creation of another index just for one purpose.
  1388. // And it doesn't really matter wether to look at "received" or "created"
  1389. $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
  1390. } else
  1391. $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
  1392. $r = q("SELECT `file`, `resource-id`, `starred`, `type`, `id` FROM `item`
  1393. WHERE `uid` = %d $range
  1394. AND `id` = `parent`
  1395. $sql_extra
  1396. AND `deleted` = 0",
  1397. intval($uid),
  1398. intval($days)
  1399. );
  1400. if(! count($r))
  1401. return;
  1402. $expire_items = get_pconfig($uid, 'expire','items');
  1403. $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
  1404. // Forcing expiring of items - but not notes and marked items
  1405. if ($force)
  1406. $expire_items = true;
  1407. $expire_notes = get_pconfig($uid, 'expire','notes');
  1408. $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
  1409. $expire_starred = get_pconfig($uid, 'expire','starred');
  1410. $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
  1411. $expire_photos = get_pconfig($uid, 'expire','photos');
  1412. $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
  1413. logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  1414. foreach($r as $item) {
  1415. // don't expire filed items
  1416. if(strpos($item['file'],'[') !== false)
  1417. continue;
  1418. // Only expire posts, not photos and photo comments
  1419. if($expire_photos==0 && strlen($item['resource-id']))
  1420. continue;
  1421. if($expire_starred==0 && intval($item['starred']))
  1422. continue;
  1423. if($expire_notes==0 && $item['type']=='note')
  1424. continue;
  1425. if($expire_items==0 && $item['type']!='note')
  1426. continue;
  1427. drop_item($item['id'],false);
  1428. }
  1429. proc_run(PRIORITY_HIGH,"include/notifier.php", "expire", $uid);
  1430. }
  1431. function drop_items($items) {
  1432. $uid = 0;
  1433. if(! local_user() && ! remote_user())
  1434. return;
  1435. if(count($items)) {
  1436. foreach($items as $item) {
  1437. $owner = drop_item($item,false);
  1438. if($owner && ! $uid)
  1439. $uid = $owner;
  1440. }
  1441. }
  1442. // multiple threads may have been deleted, send an expire notification
  1443. if($uid)
  1444. proc_run(PRIORITY_HIGH,"include/notifier.php", "expire", $uid);
  1445. }
  1446. function drop_item($id,$interactive = true) {
  1447. $a = get_app();
  1448. // locate item to be deleted
  1449. $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
  1450. intval($id)
  1451. );
  1452. if(! count($r)) {
  1453. if(! $interactive)
  1454. return 0;
  1455. notice( t('Item not found.') . EOL);
  1456. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  1457. }
  1458. $item = $r[0];
  1459. $owner = $item['uid'];
  1460. $cid = 0;
  1461. // check if logged in user is either the author or owner of this item
  1462. if(is_array($_SESSION['remote'])) {
  1463. foreach($_SESSION['remote'] as $visitor) {
  1464. if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
  1465. $cid = $visitor['cid'];
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
  1471. // Check if we should do HTML-based delete confirmation
  1472. if($_REQUEST['confirm']) {
  1473. // <form> can't take arguments in its "action" parameter
  1474. // so add any arguments as hidden inputs
  1475. $query = explode_querystring($a->query_string);
  1476. $inputs = array();
  1477. foreach($query['args'] as $arg) {
  1478. if(strpos($arg, 'confirm=') === false) {
  1479. $arg_parts = explode('=', $arg);
  1480. $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
  1481. }
  1482. }
  1483. return replace_macros(get_markup_template('confirm.tpl'), array(
  1484. '$method' => 'get',
  1485. '$message' => t('Do you really want to delete this item?'),
  1486. '$extra_inputs' => $inputs,
  1487. '$confirm' => t('Yes'),
  1488. '$confirm_url' => $query['base'],
  1489. '$confirm_name' => 'confirmed',
  1490. '$cancel' => t('Cancel'),
  1491. ));
  1492. }
  1493. // Now check how the user responded to the confirmation query
  1494. if($_REQUEST['canceled']) {
  1495. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  1496. }
  1497. logger('delete item: ' . $item['id'], LOGGER_DEBUG);
  1498. // delete the item
  1499. $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
  1500. dbesc(datetime_convert()),
  1501. dbesc(datetime_convert()),
  1502. intval($item['id'])
  1503. );
  1504. create_tags_from_item($item['id']);
  1505. create_files_from_item($item['id']);
  1506. delete_thread($item['id'], $item['parent-uri']);
  1507. // clean up categories and tags so they don't end up as orphans
  1508. $matches = false;
  1509. $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
  1510. if($cnt) {
  1511. foreach($matches as $mtch) {
  1512. file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
  1513. }
  1514. }
  1515. $matches = false;
  1516. $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
  1517. if($cnt) {
  1518. foreach($matches as $mtch) {
  1519. file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
  1520. }
  1521. }
  1522. // If item is a link to a photo resource, nuke all the associated photos
  1523. // (visitors will not have photo resources)
  1524. // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  1525. // generate a resource-id and therefore aren't intimately linked to the item.
  1526. if(strlen($item['resource-id'])) {
  1527. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
  1528. dbesc($item['resource-id']),
  1529. intval($item['uid'])
  1530. );
  1531. // ignore the result
  1532. }
  1533. // If item is a link to an event, nuke the event record.
  1534. if(intval($item['event-id'])) {
  1535. q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
  1536. intval($item['event-id']),
  1537. intval($item['uid'])
  1538. );
  1539. // ignore the result
  1540. }
  1541. // If item has attachments, drop them
  1542. foreach(explode(",",$item['attach']) as $attach){
  1543. preg_match("|attach/(\d+)|", $attach, $matches);
  1544. q("DELETE FROM `attach` WHERE