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