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.

443 lines
13 KiB

11 years ago
5 years ago
2 years ago
10 years ago
  1. <?php
  2. /**
  3. * @file include/items.php
  4. */
  5. use Friendica\BaseObject;
  6. use Friendica\Content\Feature;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\Hook;
  9. use Friendica\Core\L10n;
  10. use Friendica\Core\Logger;
  11. use Friendica\Core\PConfig;
  12. use Friendica\Core\Protocol;
  13. use Friendica\Core\Renderer;
  14. use Friendica\Core\System;
  15. use Friendica\Core\Session;
  16. use Friendica\Database\DBA;
  17. use Friendica\Model\Item;
  18. use Friendica\Protocol\DFRN;
  19. use Friendica\Protocol\Feed;
  20. use Friendica\Protocol\OStatus;
  21. use Friendica\Util\DateTimeFormat;
  22. use Friendica\Util\Network;
  23. use Friendica\Util\ParseUrl;
  24. use Friendica\Util\Strings;
  25. use Friendica\Util\Temporal;
  26. require_once __DIR__ . '/../mod/share.php';
  27. function add_page_info_data(array $data, $no_photos = false)
  28. {
  29. Hook::callAll('page_info_data', $data);
  30. if (empty($data['type'])) {
  31. return '';
  32. }
  33. // It maybe is a rich content, but if it does have everything that a link has,
  34. // then treat it that way
  35. if (($data["type"] == "rich") && is_string($data["title"]) &&
  36. is_string($data["text"]) && !empty($data["images"])) {
  37. $data["type"] = "link";
  38. }
  39. $data["title"] = defaults($data, "title", "");
  40. if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
  41. return "";
  42. }
  43. if ($no_photos && ($data["type"] == "photo")) {
  44. return "";
  45. }
  46. // Escape some bad characters
  47. $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
  48. $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
  49. $text = "[attachment type='".$data["type"]."'";
  50. if (empty($data["text"])) {
  51. $data["text"] = $data["title"];
  52. }
  53. if (empty($data["text"])) {
  54. $data["text"] = $data["url"];
  55. }
  56. if (!empty($data["url"])) {
  57. $text .= " url='".$data["url"]."'";
  58. }
  59. if (!empty($data["title"])) {
  60. $text .= " title='".$data["title"]."'";
  61. }
  62. // Only embedd a picture link when it seems to be a valid picture ("width" is set)
  63. if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
  64. $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
  65. // if the preview picture is larger than 500 pixels then show it in a larger mode
  66. // But only, if the picture isn't higher than large (To prevent huge posts)
  67. if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
  68. && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
  69. $text .= " image='".$preview."'";
  70. } else {
  71. $text .= " preview='".$preview."'";
  72. }
  73. }
  74. $text .= "]".$data["text"]."[/attachment]";
  75. $hashtags = "";
  76. if (isset($data["keywords"]) && count($data["keywords"])) {
  77. $hashtags = "\n";
  78. foreach ($data["keywords"] as $keyword) {
  79. /// @TODO make a positive list of allowed characters
  80. $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "", "`", "(", ")", "", ""],
  81. ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
  82. $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
  83. }
  84. }
  85. return "\n".$text.$hashtags;
  86. }
  87. function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
  88. {
  89. $data = ParseUrl::getSiteinfoCached($url, true);
  90. if ($photo != "") {
  91. $data["images"][0]["src"] = $photo;
  92. }
  93. Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
  94. if (!$keywords && isset($data["keywords"])) {
  95. unset($data["keywords"]);
  96. }
  97. if (($keyword_blacklist != "") && isset($data["keywords"])) {
  98. $list = explode(", ", $keyword_blacklist);
  99. foreach ($list as $keyword) {
  100. $keyword = trim($keyword);
  101. $index = array_search($keyword, $data["keywords"]);
  102. if ($index !== false) {
  103. unset($data["keywords"][$index]);
  104. }
  105. }
  106. }
  107. return $data;
  108. }
  109. function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
  110. {
  111. $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
  112. $tags = "";
  113. if (isset($data["keywords"]) && count($data["keywords"])) {
  114. foreach ($data["keywords"] as $keyword) {
  115. $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
  116. ["", "", "", "", "", ""], $keyword);
  117. if ($tags != "") {
  118. $tags .= ", ";
  119. }
  120. $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
  121. }
  122. }
  123. return $tags;
  124. }
  125. function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
  126. {
  127. $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
  128. $text = '';
  129. if (is_array($data)) {
  130. $text = add_page_info_data($data, $no_photos);
  131. }
  132. return $text;
  133. }
  134. function add_page_info_to_body($body, $texturl = false, $no_photos = false)
  135. {
  136. Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
  137. $URLSearchString = "^\[\]";
  138. // Fix for Mastodon where the mentions are in a different format
  139. $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
  140. '$2[url=$1]$3[/url]', $body);
  141. // Adding these spaces is a quick hack due to my problems with regular expressions :)
  142. preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
  143. if (!$matches) {
  144. preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
  145. }
  146. // Convert urls without bbcode elements
  147. if (!$matches && $texturl) {
  148. preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
  149. // Yeah, a hack. I really hate regular expressions :)
  150. if ($matches) {
  151. $matches[1] = $matches[2];
  152. }
  153. }
  154. if ($matches) {
  155. $footer = add_page_info($matches[1], $no_photos);
  156. }
  157. // Remove the link from the body if the link is attached at the end of the post
  158. if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
  159. $removedlink = trim(str_replace($matches[1], "", $body));
  160. if (($removedlink == "") || strstr($body, $removedlink)) {
  161. $body = $removedlink;
  162. }
  163. $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
  164. if (($removedlink == "") || strstr($body, $removedlink)) {
  165. $body = $removedlink;
  166. }
  167. }
  168. // Add the page information to the bottom
  169. if (isset($footer) && (trim($footer) != "")) {
  170. $body .= $footer;
  171. }
  172. return $body;
  173. }
  174. /**
  175. *
  176. * consume_feed - process atom feed and update anything/everything we might need to update
  177. *
  178. * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
  179. *
  180. * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
  181. * It is this person's stuff that is going to be updated.
  182. * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
  183. * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
  184. * have a contact record.
  185. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
  186. * might not) try and subscribe to it.
  187. * $datedir sorts in reverse order
  188. * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
  189. * imported prior to its children being seen in the stream unless we are certain
  190. * of how the feed is arranged/ordered.
  191. * With $pass = 1, we only pull parent items out of the stream.
  192. * With $pass = 2, we only pull children (comments/likes).
  193. *
  194. * So running this twice, first with pass 1 and then with pass 2 will do the right
  195. * thing regardless of feed ordering. This won't be adequate in a fully-threaded
  196. * model where comments can have sub-threads. That would require some massive sorting
  197. * to get all the feed items into a mostly linear ordering, and might still require
  198. * recursion.
  199. *
  200. * @param $xml
  201. * @param array $importer
  202. * @param array $contact
  203. * @param $hub
  204. * @throws ImagickException
  205. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  206. */
  207. function consume_feed($xml, array $importer, array $contact, &$hub)
  208. {
  209. if ($contact['network'] === Protocol::OSTATUS) {
  210. Logger::log("Consume OStatus messages ", Logger::DEBUG);
  211. OStatus::import($xml, $importer, $contact, $hub);
  212. return;
  213. }
  214. if ($contact['network'] === Protocol::FEED) {
  215. Logger::log("Consume feeds", Logger::DEBUG);
  216. Feed::import($xml, $importer, $contact, $hub);
  217. return;
  218. }
  219. if ($contact['network'] === Protocol::DFRN) {
  220. Logger::log("Consume DFRN messages", Logger::DEBUG);
  221. $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
  222. if (!empty($dfrn_importer)) {
  223. Logger::log("Now import the DFRN feed");
  224. DFRN::import($xml, $dfrn_importer, true);
  225. return;
  226. }
  227. }
  228. }
  229. function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
  230. {
  231. /*
  232. * Diaspora has different message-ids in feeds than they do
  233. * through the direct Diaspora protocol. If we try and use
  234. * the feed, we'll get duplicates. So don't.
  235. */
  236. if ($contact['network'] === Protocol::DIASPORA) {
  237. return;
  238. }
  239. // Without an importer we don't have a user id - so we quit
  240. if (empty($importer)) {
  241. return;
  242. }
  243. $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
  244. // No user, no nickname, we quit
  245. if (!DBA::isResult($user)) {
  246. return;
  247. }
  248. $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
  249. // Use a single verify token, even if multiple hubs
  250. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
  251. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  252. Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  253. if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
  254. DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
  255. }
  256. $postResult = Network::post($url, $params);
  257. Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
  258. return;
  259. }
  260. function drop_items(array $items)
  261. {
  262. $uid = 0;
  263. if (!Session::isAuthenticated()) {
  264. return;
  265. }
  266. if (!empty($items)) {
  267. foreach ($items as $item) {
  268. $owner = Item::deleteForUser(['id' => $item], local_user());
  269. if ($owner && !$uid) {
  270. $uid = $owner;
  271. }
  272. }
  273. }
  274. }
  275. function drop_item($id, $return = '')
  276. {
  277. $a = BaseObject::getApp();
  278. // locate item to be deleted
  279. $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
  280. $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
  281. if (!DBA::isResult($item)) {
  282. notice(L10n::t('Item not found.') . EOL);
  283. $a->internalRedirect('network');
  284. }
  285. if ($item['deleted']) {
  286. return 0;
  287. }
  288. $contact_id = 0;
  289. // check if logged in user is either the author or owner of this item
  290. if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
  291. $contact_id = $item['contact-id'];
  292. }
  293. if ((local_user() == $item['uid']) || $contact_id) {
  294. // Check if we should do HTML-based delete confirmation
  295. if (!empty($_REQUEST['confirm'])) {
  296. // <form> can't take arguments in its "action" parameter
  297. // so add any arguments as hidden inputs
  298. $query = explode_querystring($a->query_string);
  299. $inputs = [];
  300. foreach ($query['args'] as $arg) {
  301. if (strpos($arg, 'confirm=') === false) {
  302. $arg_parts = explode('=', $arg);
  303. $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
  304. }
  305. }
  306. return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
  307. '$method' => 'get',
  308. '$message' => L10n::t('Do you really want to delete this item?'),
  309. '$extra_inputs' => $inputs,
  310. '$confirm' => L10n::t('Yes'),
  311. '$confirm_url' => $query['base'],
  312. '$confirm_name' => 'confirmed',
  313. '$cancel' => L10n::t('Cancel'),
  314. ]);
  315. }
  316. // Now check how the user responded to the confirmation query
  317. if (!empty($_REQUEST['canceled'])) {
  318. $a->internalRedirect('display/' . $item['guid']);
  319. }
  320. $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
  321. $parentitem = null;
  322. if (!empty($item['parent'])){
  323. $fields = ['guid'];
  324. $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
  325. }
  326. // delete the item
  327. Item::deleteForUser(['id' => $item['id']], local_user());
  328. $return_url = hex2bin($return);
  329. // removes update_* from return_url to ignore Ajax refresh
  330. $return_url = str_replace("update_", "", $return_url);
  331. // Check if delete a comment
  332. if ($is_comment) {
  333. // Return to parent guid
  334. if (!empty($parentitem)) {
  335. $a->internalRedirect('display/' . $parentitem['guid']);
  336. //NOTREACHED
  337. }
  338. // In case something goes wrong
  339. else {
  340. $a->internalRedirect('network');
  341. //NOTREACHED
  342. }
  343. }
  344. else {
  345. // if unknown location or deleting top level post called from display
  346. if (empty($return_url) || strpos($return_url, 'display') !== false) {
  347. $a->internalRedirect('network');
  348. //NOTREACHED
  349. } else {
  350. $a->internalRedirect($return_url);
  351. //NOTREACHED
  352. }
  353. }
  354. } else {
  355. notice(L10n::t('Permission denied.') . EOL);
  356. $a->internalRedirect('display/' . $item['guid']);
  357. //NOTREACHED
  358. }
  359. }