Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

528 lignes
15KB

  1. <?php
  2. /**
  3. * @file include/items.php
  4. */
  5. use Friendica\BaseObject;
  6. use Friendica\Content\Feature;
  7. use Friendica\Core\Addon;
  8. use Friendica\Core\Config;
  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\Database\DBA;
  16. use Friendica\Model\Item;
  17. use Friendica\Protocol\DFRN;
  18. use Friendica\Protocol\Feed;
  19. use Friendica\Protocol\OStatus;
  20. use Friendica\Util\DateTimeFormat;
  21. use Friendica\Util\Network;
  22. use Friendica\Util\ParseUrl;
  23. use Friendica\Util\Strings;
  24. use Friendica\Util\Temporal;
  25. require_once 'mod/share.php';
  26. function add_page_info_data(array $data, $no_photos = false)
  27. {
  28. Addon::callHooks('page_info_data', $data);
  29. if (empty($data['type'])) {
  30. return '';
  31. }
  32. // It maybe is a rich content, but if it does have everything that a link has,
  33. // then treat it that way
  34. if (($data["type"] == "rich") && is_string($data["title"]) &&
  35. is_string($data["text"]) && !empty($data["images"])) {
  36. $data["type"] = "link";
  37. }
  38. $data["title"] = defaults($data, "title", "");
  39. if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
  40. return "";
  41. }
  42. if ($no_photos && ($data["type"] == "photo")) {
  43. return "";
  44. }
  45. // Escape some bad characters
  46. $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
  47. $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
  48. $text = "[attachment type='".$data["type"]."'";
  49. if (empty($data["text"])) {
  50. $data["text"] = $data["title"];
  51. }
  52. if (empty($data["text"])) {
  53. $data["text"] = $data["url"];
  54. }
  55. if (!empty($data["url"])) {
  56. $text .= " url='".$data["url"]."'";
  57. }
  58. if (!empty($data["title"])) {
  59. $text .= " title='".$data["title"]."'";
  60. }
  61. // Only embedd a picture link when it seems to be a valid picture ("width" is set)
  62. if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
  63. $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
  64. // if the preview picture is larger than 500 pixels then show it in a larger mode
  65. // But only, if the picture isn't higher than large (To prevent huge posts)
  66. if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
  67. && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
  68. $text .= " image='".$preview."'";
  69. } else {
  70. $text .= " preview='".$preview."'";
  71. }
  72. }
  73. $text .= "]".$data["text"]."[/attachment]";
  74. $hashtags = "";
  75. if (isset($data["keywords"]) && count($data["keywords"])) {
  76. $hashtags = "\n";
  77. foreach ($data["keywords"] as $keyword) {
  78. /// @TODO make a positive list of allowed characters
  79. $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
  80. ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
  81. $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url] ";
  82. }
  83. }
  84. return "\n".$text.$hashtags;
  85. }
  86. function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
  87. {
  88. $data = ParseUrl::getSiteinfoCached($url, true);
  89. if ($photo != "") {
  90. $data["images"][0]["src"] = $photo;
  91. }
  92. Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
  93. if (!$keywords && isset($data["keywords"])) {
  94. unset($data["keywords"]);
  95. }
  96. if (($keyword_blacklist != "") && isset($data["keywords"])) {
  97. $list = explode(", ", $keyword_blacklist);
  98. foreach ($list as $keyword) {
  99. $keyword = trim($keyword);
  100. $index = array_search($keyword, $data["keywords"]);
  101. if ($index !== false) {
  102. unset($data["keywords"][$index]);
  103. }
  104. }
  105. }
  106. return $data;
  107. }
  108. function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
  109. {
  110. $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
  111. $tags = "";
  112. if (isset($data["keywords"]) && count($data["keywords"])) {
  113. foreach ($data["keywords"] as $keyword) {
  114. $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
  115. ["", "", "", "", "", ""], $keyword);
  116. if ($tags != "") {
  117. $tags .= ", ";
  118. }
  119. $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
  120. }
  121. }
  122. return $tags;
  123. }
  124. function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
  125. {
  126. $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
  127. $text = '';
  128. if (is_array($data)) {
  129. $text = add_page_info_data($data, $no_photos);
  130. }
  131. return $text;
  132. }
  133. function add_page_info_to_body($body, $texturl = false, $no_photos = false)
  134. {
  135. Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
  136. $URLSearchString = "^\[\]";
  137. // Fix for Mastodon where the mentions are in a different format
  138. $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
  139. '$2[url=$1]$3[/url]', $body);
  140. // Adding these spaces is a quick hack due to my problems with regular expressions :)
  141. preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
  142. if (!$matches) {
  143. preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
  144. }
  145. // Convert urls without bbcode elements
  146. if (!$matches && $texturl) {
  147. preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
  148. // Yeah, a hack. I really hate regular expressions :)
  149. if ($matches) {
  150. $matches[1] = $matches[2];
  151. }
  152. }
  153. if ($matches) {
  154. $footer = add_page_info($matches[1], $no_photos);
  155. }
  156. // Remove the link from the body if the link is attached at the end of the post
  157. if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
  158. $removedlink = trim(str_replace($matches[1], "", $body));
  159. if (($removedlink == "") || strstr($body, $removedlink)) {
  160. $body = $removedlink;
  161. }
  162. $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
  163. $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/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. function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
  201. {
  202. if ($contact['network'] === Protocol::OSTATUS) {
  203. if ($pass < 2) {
  204. // Test - remove before flight
  205. //$tempfile = tempnam(get_temppath(), "ostatus2");
  206. //file_put_contents($tempfile, $xml);
  207. Logger::log("Consume OStatus messages ", Logger::DEBUG);
  208. OStatus::import($xml, $importer, $contact, $hub);
  209. }
  210. return;
  211. }
  212. if ($contact['network'] === Protocol::FEED) {
  213. if ($pass < 2) {
  214. Logger::log("Consume feeds", Logger::DEBUG);
  215. Feed::import($xml, $importer, $contact, $hub);
  216. }
  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. $a = BaseObject::getApp();
  244. $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
  245. // No user, no nickname, we quit
  246. if (!DBA::isResult($user)) {
  247. return;
  248. }
  249. $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
  250. // Use a single verify token, even if multiple hubs
  251. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
  252. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  253. Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  254. if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
  255. DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
  256. }
  257. $postResult = Network::post($url, $params);
  258. Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
  259. return;
  260. }
  261. function drop_items(array $items)
  262. {
  263. $uid = 0;
  264. if (!local_user() && !remote_user()) {
  265. return;
  266. }
  267. if (!empty($items)) {
  268. foreach ($items as $item) {
  269. $owner = Item::deleteForUser(['id' => $item], local_user());
  270. if ($owner && !$uid) {
  271. $uid = $owner;
  272. }
  273. }
  274. }
  275. }
  276. function drop_item($id, $return = '')
  277. {
  278. $a = BaseObject::getApp();
  279. // locate item to be deleted
  280. $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
  281. $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
  282. if (!DBA::isResult($item)) {
  283. notice(L10n::t('Item not found.') . EOL);
  284. $a->internalRedirect('network');
  285. }
  286. if ($item['deleted']) {
  287. return 0;
  288. }
  289. $contact_id = 0;
  290. // check if logged in user is either the author or owner of this item
  291. if (!empty($_SESSION['remote'])) {
  292. foreach ($_SESSION['remote'] as $visitor) {
  293. if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
  294. $contact_id = $visitor['cid'];
  295. break;
  296. }
  297. }
  298. }
  299. if ((local_user() == $item['uid']) || $contact_id) {
  300. // Check if we should do HTML-based delete confirmation
  301. if (!empty($_REQUEST['confirm'])) {
  302. // <form> can't take arguments in its "action" parameter
  303. // so add any arguments as hidden inputs
  304. $query = explode_querystring($a->query_string);
  305. $inputs = [];
  306. foreach ($query['args'] as $arg) {
  307. if (strpos($arg, 'confirm=') === false) {
  308. $arg_parts = explode('=', $arg);
  309. $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
  310. }
  311. }
  312. return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
  313. '$method' => 'get',
  314. '$message' => L10n::t('Do you really want to delete this item?'),
  315. '$extra_inputs' => $inputs,
  316. '$confirm' => L10n::t('Yes'),
  317. '$confirm_url' => $query['base'],
  318. '$confirm_name' => 'confirmed',
  319. '$cancel' => L10n::t('Cancel'),
  320. ]);
  321. }
  322. // Now check how the user responded to the confirmation query
  323. if (!empty($_REQUEST['canceled'])) {
  324. $a->internalRedirect('display/' . $item['guid']);
  325. }
  326. $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
  327. $parentitem = null;
  328. if (!empty($item['parent'])){
  329. $fields = ['guid'];
  330. $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
  331. }
  332. // delete the item
  333. Item::deleteForUser(['id' => $item['id']], local_user());
  334. $return_url = hex2bin($return);
  335. // removes update_* from return_url to ignore Ajax refresh
  336. $return_url = str_replace("update_", "", $return_url);
  337. // Check if delete a comment
  338. if ($is_comment) {
  339. // Return to parent guid
  340. if (!empty($parentitem)) {
  341. $a->internalRedirect('display/' . $parentitem['guid']);
  342. //NOTREACHED
  343. }
  344. // In case something goes wrong
  345. else {
  346. $a->internalRedirect('network');
  347. //NOTREACHED
  348. }
  349. }
  350. else {
  351. // if unknown location or deleting top level post called from display
  352. if (empty($return_url) || strpos($return_url, 'display') !== false) {
  353. $a->internalRedirect('network');
  354. //NOTREACHED
  355. } else {
  356. $a->internalRedirect($return_url);
  357. //NOTREACHED
  358. }
  359. }
  360. } else {
  361. notice(L10n::t('Permission denied.') . EOL);
  362. $a->internalRedirect('display/' . $item['guid']);
  363. //NOTREACHED
  364. }
  365. }
  366. /* arrange the list in years */
  367. function list_post_dates($uid, $wall)
  368. {
  369. $dnow = DateTimeFormat::localNow('Y-m-d');
  370. $dthen = Item::firstPostDate($uid, $wall);
  371. if (!$dthen) {
  372. return [];
  373. }
  374. // Set the start and end date to the beginning of the month
  375. $dnow = substr($dnow, 0, 8) . '01';
  376. $dthen = substr($dthen, 0, 8) . '01';
  377. $ret = [];
  378. /*
  379. * Starting with the current month, get the first and last days of every
  380. * month down to and including the month of the first post
  381. */
  382. while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
  383. $dyear = intval(substr($dnow, 0, 4));
  384. $dstart = substr($dnow, 0, 8) . '01';
  385. $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
  386. $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
  387. $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
  388. $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
  389. if (empty($ret[$dyear])) {
  390. $ret[$dyear] = [];
  391. }
  392. $ret[$dyear][] = [$str, $end_month, $start_month];
  393. $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
  394. }
  395. return $ret;
  396. }
  397. function posted_date_widget($url, $uid, $wall)
  398. {
  399. $o = '';
  400. if (!Feature::isEnabled($uid, 'archives')) {
  401. return $o;
  402. }
  403. // For former Facebook folks that left because of "timeline"
  404. /*
  405. * @TODO old-lost code?
  406. if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
  407. return $o;
  408. */
  409. $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
  410. $ret = list_post_dates($uid, $wall);
  411. if (!DBA::isResult($ret)) {
  412. return $o;
  413. }
  414. $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
  415. $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
  416. $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
  417. '$title' => L10n::t('Archives'),
  418. '$size' => $visible_years,
  419. '$cutoff_year' => $cutoff_year,
  420. '$cutoff' => $cutoff,
  421. '$url' => $url,
  422. '$dates' => $ret,
  423. '$showmore' => L10n::t('show more')
  424. ]);
  425. return $o;
  426. }