]> git.mxchange.org Git - friendica.git/blob - include/items.php
Use appropriate redirect in dfrn_poll
[friendica.git] / include / items.php
1 <?php
2 /**
3  * @file include/items.php
4  */
5
6 use Friendica\BaseObject;
7 use Friendica\Content\Feature;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\Logger;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
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
27 require_once 'include/text.php';
28 require_once 'mod/share.php';
29 require_once 'include/enotify.php';
30
31 function add_page_info_data(array $data, $no_photos = false)
32 {
33         Addon::callHooks('page_info_data', $data);
34
35         if (empty($data['type'])) {
36                 return '';
37         }
38
39         // It maybe is a rich content, but if it does have everything that a link has,
40         // then treat it that way
41         if (($data["type"] == "rich") && is_string($data["title"]) &&
42                 is_string($data["text"]) && !empty($data["images"])) {
43                 $data["type"] = "link";
44         }
45
46         $data["title"] = defaults($data, "title", "");
47
48         if ((($data["type"] != "link") && ($data["type"] != "video") && ($data["type"] != "photo")) || ($data["title"] == $data["url"])) {
49                 return "";
50         }
51
52         if ($no_photos && ($data["type"] == "photo")) {
53                 return "";
54         }
55
56         // Escape some bad characters
57         $data["url"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["url"], ENT_QUOTES, 'UTF-8', false));
58         $data["title"] = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["title"], ENT_QUOTES, 'UTF-8', false));
59
60         $text = "[attachment type='".$data["type"]."'";
61
62         if (empty($data["text"])) {
63                 $data["text"] = $data["title"];
64         }
65
66         if (empty($data["text"])) {
67                 $data["text"] = $data["url"];
68         }
69
70         if (!empty($data["url"])) {
71                 $text .= " url='".$data["url"]."'";
72         }
73
74         if (!empty($data["title"])) {
75                 $text .= " title='".$data["title"]."'";
76         }
77
78         // Only embedd a picture link when it seems to be a valid picture ("width" is set)
79         if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
80                 $preview = str_replace(["[", "]"], ["&#91;", "&#93;"], htmlentities($data["images"][0]["src"], ENT_QUOTES, 'UTF-8', false));
81                 // if the preview picture is larger than 500 pixels then show it in a larger mode
82                 // But only, if the picture isn't higher than large (To prevent huge posts)
83                 if (!Config::get('system', 'always_show_preview') && ($data["images"][0]["width"] >= 500)
84                         && ($data["images"][0]["width"] >= $data["images"][0]["height"])) {
85                         $text .= " image='".$preview."'";
86                 } else {
87                         $text .= " preview='".$preview."'";
88                 }
89         }
90
91         $text .= "]".$data["text"]."[/attachment]";
92
93         $hashtags = "";
94         if (isset($data["keywords"]) && count($data["keywords"])) {
95                 $hashtags = "\n";
96                 foreach ($data["keywords"] as $keyword) {
97                         /// @TODO make a positive list of allowed characters
98                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'", "’", "`", "(", ")", "„", "“"],
99                                                 ["", "", "", "", "", "", "", "", "", "", "", ""], $keyword);
100                         $hashtags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url] ";
101                 }
102         }
103
104         return "\n".$text.$hashtags;
105 }
106
107 function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklist = "")
108 {
109         $data = ParseUrl::getSiteinfoCached($url, true);
110
111         if ($photo != "") {
112                 $data["images"][0]["src"] = $photo;
113         }
114
115         Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
116
117         if (!$keywords && isset($data["keywords"])) {
118                 unset($data["keywords"]);
119         }
120
121         if (($keyword_blacklist != "") && isset($data["keywords"])) {
122                 $list = explode(", ", $keyword_blacklist);
123
124                 foreach ($list as $keyword) {
125                         $keyword = trim($keyword);
126
127                         $index = array_search($keyword, $data["keywords"]);
128                         if ($index !== false) {
129                                 unset($data["keywords"][$index]);
130                         }
131                 }
132         }
133
134         return $data;
135 }
136
137 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
138 {
139         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
140
141         $tags = "";
142         if (isset($data["keywords"]) && count($data["keywords"])) {
143                 foreach ($data["keywords"] as $keyword) {
144                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
145                                 ["", "", "", "", "", ""], $keyword);
146
147                         if ($tags != "") {
148                                 $tags .= ", ";
149                         }
150
151                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . rawurlencode($hashtag) . "]" . $hashtag . "[/url]";
152                 }
153         }
154
155         return $tags;
156 }
157
158 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
159 {
160         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
161
162         $text = '';
163
164         if (is_array($data)) {
165                 $text = add_page_info_data($data, $no_photos);
166         }
167
168         return $text;
169 }
170
171 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
172 {
173         Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
174
175         $URLSearchString = "^\[\]";
176
177         // Fix for Mastodon where the mentions are in a different format
178         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
179                 '$2[url=$1]$3[/url]', $body);
180
181         // Adding these spaces is a quick hack due to my problems with regular expressions :)
182         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
183
184         if (!$matches) {
185                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
186         }
187
188         // Convert urls without bbcode elements
189         if (!$matches && $texturl) {
190                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
191
192                 // Yeah, a hack. I really hate regular expressions :)
193                 if ($matches) {
194                         $matches[1] = $matches[2];
195                 }
196         }
197
198         if ($matches) {
199                 $footer = add_page_info($matches[1], $no_photos);
200         }
201
202         // Remove the link from the body if the link is attached at the end of the post
203         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
204                 $removedlink = trim(str_replace($matches[1], "", $body));
205                 if (($removedlink == "") || strstr($body, $removedlink)) {
206                         $body = $removedlink;
207                 }
208
209                 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
210                 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/url\]/ism", '', $body);
211                 if (($removedlink == "") || strstr($body, $removedlink)) {
212                         $body = $removedlink;
213                 }
214         }
215
216         // Add the page information to the bottom
217         if (isset($footer) && (trim($footer) != "")) {
218                 $body .= $footer;
219         }
220
221         return $body;
222 }
223
224 /**
225  *
226  * consume_feed - process atom feed and update anything/everything we might need to update
227  *
228  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
229  *
230  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
231  *             It is this person's stuff that is going to be updated.
232  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
233  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
234  *             have a contact record.
235  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
236  *        might not) try and subscribe to it.
237  * $datedir sorts in reverse order
238  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
239  *      imported prior to its children being seen in the stream unless we are certain
240  *      of how the feed is arranged/ordered.
241  * With $pass = 1, we only pull parent items out of the stream.
242  * With $pass = 2, we only pull children (comments/likes).
243  *
244  * So running this twice, first with pass 1 and then with pass 2 will do the right
245  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
246  * model where comments can have sub-threads. That would require some massive sorting
247  * to get all the feed items into a mostly linear ordering, and might still require
248  * recursion.
249  */
250 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
251 {
252         if ($contact['network'] === Protocol::OSTATUS) {
253                 if ($pass < 2) {
254                         // Test - remove before flight
255                         //$tempfile = tempnam(get_temppath(), "ostatus2");
256                         //file_put_contents($tempfile, $xml);
257                         Logger::log("Consume OStatus messages ", Logger::DEBUG);
258                         OStatus::import($xml, $importer, $contact, $hub);
259                 }
260
261                 return;
262         }
263
264         if ($contact['network'] === Protocol::FEED) {
265                 if ($pass < 2) {
266                         Logger::log("Consume feeds", Logger::DEBUG);
267                         Feed::import($xml, $importer, $contact, $hub);
268                 }
269
270                 return;
271         }
272
273         if ($contact['network'] === Protocol::DFRN) {
274                 Logger::log("Consume DFRN messages", Logger::DEBUG);
275                 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
276                 if (!empty($dfrn_importer)) {
277                         Logger::log("Now import the DFRN feed");
278                         DFRN::import($xml, $dfrn_importer, true);
279                         return;
280                 }
281         }
282 }
283
284 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
285 {
286         /*
287          * Diaspora has different message-ids in feeds than they do
288          * through the direct Diaspora protocol. If we try and use
289          * the feed, we'll get duplicates. So don't.
290          */
291         if ($contact['network'] === Protocol::DIASPORA) {
292                 return;
293         }
294
295         // Without an importer we don't have a user id - so we quit
296         if (empty($importer)) {
297                 return;
298         }
299
300         $a = BaseObject::getApp();
301
302         $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
303
304         // No user, no nickname, we quit
305         if (!DBA::isResult($user)) {
306                 return;
307         }
308
309         $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
310
311         // Use a single verify token, even if multiple hubs
312         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
313
314         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
315
316         Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
317
318         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
319                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
320         }
321
322         $postResult = Network::post($url, $params);
323
324         Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
325
326         return;
327
328 }
329
330 function drop_items(array $items)
331 {
332         $uid = 0;
333
334         if (!local_user() && !remote_user()) {
335                 return;
336         }
337
338         if (!empty($items)) {
339                 foreach ($items as $item) {
340                         $owner = Item::deleteForUser(['id' => $item], local_user());
341
342                         if ($owner && !$uid) {
343                                 $uid = $owner;
344                         }
345                 }
346         }
347 }
348
349 function drop_item($id, $return = '')
350 {
351         $a = BaseObject::getApp();
352
353         // locate item to be deleted
354
355         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity'];
356         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
357
358         if (!DBA::isResult($item)) {
359                 notice(L10n::t('Item not found.') . EOL);
360                 $a->internalRedirect('network');
361         }
362
363         if ($item['deleted']) {
364                 return 0;
365         }
366
367         $contact_id = 0;
368
369         // check if logged in user is either the author or owner of this item
370
371         if (!empty($_SESSION['remote'])) {
372                 foreach ($_SESSION['remote'] as $visitor) {
373                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
374                                 $contact_id = $visitor['cid'];
375                                 break;
376                         }
377                 }
378         }
379
380         if ((local_user() == $item['uid']) || $contact_id) {
381                 // Check if we should do HTML-based delete confirmation
382                 if (!empty($_REQUEST['confirm'])) {
383                         // <form> can't take arguments in its "action" parameter
384                         // so add any arguments as hidden inputs
385                         $query = explode_querystring($a->query_string);
386                         $inputs = [];
387
388                         foreach ($query['args'] as $arg) {
389                                 if (strpos($arg, 'confirm=') === false) {
390                                         $arg_parts = explode('=', $arg);
391                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
392                                 }
393                         }
394
395                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
396                                 '$method' => 'get',
397                                 '$message' => L10n::t('Do you really want to delete this item?'),
398                                 '$extra_inputs' => $inputs,
399                                 '$confirm' => L10n::t('Yes'),
400                                 '$confirm_url' => $query['base'],
401                                 '$confirm_name' => 'confirmed',
402                                 '$cancel' => L10n::t('Cancel'),
403                         ]);
404                 }
405                 // Now check how the user responded to the confirmation query
406                 if (!empty($_REQUEST['canceled'])) {
407                         $a->internalRedirect('display/' . $item['guid']);
408                 }
409
410                 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
411
412                 // delete the item
413                 Item::deleteForUser(['id' => $item['id']], local_user());
414
415                 $return_url = hex2bin($return);
416
417                 // removes update_* from return_url to ignore Ajax refresh
418                 $return_url = str_replace("update_", "", $return_url);
419
420                 // if unknown location or top level post called from display
421                 if (empty($return_url) || ((strpos($return_url, 'display') !== false) AND (!$is_comment))) {
422                         $a->internalRedirect('network');
423                         //NOTREACHED
424                 }
425                 else {
426                         $a->internalRedirect($return_url);
427                         //NOTREACHED
428                 }
429         } else {
430                 notice(L10n::t('Permission denied.') . EOL);
431                 $a->internalRedirect('display/' . $item['guid']);
432                 //NOTREACHED
433         }
434 }
435
436 /* arrange the list in years */
437 function list_post_dates($uid, $wall)
438 {
439         $dnow = DateTimeFormat::localNow('Y-m-d');
440
441         $dthen = Item::firstPostDate($uid, $wall);
442         if (!$dthen) {
443                 return [];
444         }
445
446         // Set the start and end date to the beginning of the month
447         $dnow = substr($dnow, 0, 8) . '01';
448         $dthen = substr($dthen, 0, 8) . '01';
449
450         $ret = [];
451
452         /*
453          * Starting with the current month, get the first and last days of every
454          * month down to and including the month of the first post
455          */
456         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
457                 $dyear = intval(substr($dnow, 0, 4));
458                 $dstart = substr($dnow, 0, 8) . '01';
459                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
460                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
461                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
462                 $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
463
464                 if (empty($ret[$dyear])) {
465                         $ret[$dyear] = [];
466                 }
467
468                 $ret[$dyear][] = [$str, $end_month, $start_month];
469                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
470         }
471         return $ret;
472 }
473
474 function posted_date_widget($url, $uid, $wall)
475 {
476         $o = '';
477
478         if (!Feature::isEnabled($uid, 'archives')) {
479                 return $o;
480         }
481
482         // For former Facebook folks that left because of "timeline"
483         /*
484          * @TODO old-lost code?
485         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
486                 return $o;
487         */
488
489         $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
490
491         $ret = list_post_dates($uid, $wall);
492
493         if (!DBA::isResult($ret)) {
494                 return $o;
495         }
496
497         $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
498         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
499
500         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
501                 '$title' => L10n::t('Archives'),
502                 '$size' => $visible_years,
503                 '$cutoff_year' => $cutoff_year,
504                 '$cutoff' => $cutoff,
505                 '$url' => $url,
506                 '$dates' => $ret,
507                 '$showmore' => L10n::t('show more')
508
509         ]);
510         return $o;
511 }