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