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