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