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