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