]> git.mxchange.org Git - friendica.git/blob - include/items.php
Facebook and App.net is removed from nearly all places (#5581)
[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 = '';
154
155         if (is_array($data)) {
156                 $text = add_page_info_data($data, $no_photos);
157         }
158
159         return $text;
160 }
161
162 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
163 {
164         logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG);
165
166         $URLSearchString = "^\[\]";
167
168         // Fix for Mastodon where the mentions are in a different format
169         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
170                 '$2[url=$1]$3[/url]', $body);
171
172         // Adding these spaces is a quick hack due to my problems with regular expressions :)
173         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
174
175         if (!$matches) {
176                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
177         }
178
179         // Convert urls without bbcode elements
180         if (!$matches && $texturl) {
181                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
182
183                 // Yeah, a hack. I really hate regular expressions :)
184                 if ($matches) {
185                         $matches[1] = $matches[2];
186                 }
187         }
188
189         if ($matches) {
190                 $footer = add_page_info($matches[1], $no_photos);
191         }
192
193         // Remove the link from the body if the link is attached at the end of the post
194         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
195                 $removedlink = trim(str_replace($matches[1], "", $body));
196                 if (($removedlink == "") || strstr($body, $removedlink)) {
197                         $body = $removedlink;
198                 }
199
200                 $url = str_replace(['/', '.'], ['\/', '\.'], $matches[1]);
201                 $removedlink = preg_replace("/\[url\=" . $url . "\](.*?)\[\/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 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
242 {
243         if ($contact['network'] === NETWORK_OSTATUS) {
244                 if ($pass < 2) {
245                         // Test - remove before flight
246                         //$tempfile = tempnam(get_temppath(), "ostatus2");
247                         //file_put_contents($tempfile, $xml);
248                         logger("Consume OStatus messages ", LOGGER_DEBUG);
249                         OStatus::import($xml, $importer, $contact, $hub);
250                 }
251
252                 return;
253         }
254
255         if ($contact['network'] === NETWORK_FEED) {
256                 if ($pass < 2) {
257                         logger("Consume feeds", LOGGER_DEBUG);
258                         Feed::import($xml, $importer, $contact, $hub);
259                 }
260
261                 return;
262         }
263
264         if ($contact['network'] === NETWORK_DFRN) {
265                 logger("Consume DFRN messages", LOGGER_DEBUG);
266
267                 $r = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
268                                         `contact`.`pubkey` AS `cpubkey`,
269                                         `contact`.`prvkey` AS `cprvkey`,
270                                         `contact`.`thumb` AS `thumb`,
271                                         `contact`.`url` as `url`,
272                                         `contact`.`name` as `senderName`,
273                                         `user`.*
274                         FROM `contact`
275                         LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
276                         WHERE `contact`.`id` = %d AND `user`.`uid` = %d",
277                         DBA::escape($contact["id"]), DBA::escape($importer["uid"])
278                 );
279
280                 if (DBA::isResult($r)) {
281                         logger("Now import the DFRN feed");
282                         DFRN::import($xml, $r[0], true);
283                         return;
284                 }
285         }
286 }
287
288 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
289 {
290         $a = BaseObject::getApp();
291         $r = null;
292
293         if (!empty($importer)) {
294                 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
295                         intval($importer['uid'])
296                 );
297         }
298
299         /*
300          * Diaspora has different message-ids in feeds than they do
301          * through the direct Diaspora protocol. If we try and use
302          * the feed, we'll get duplicates. So don't.
303          */
304         if ((!DBA::isResult($r)) || $contact['network'] === NETWORK_DIASPORA) {
305                 return;
306         }
307
308         $push_url = System::baseUrl() . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
309
310         // Use a single verify token, even if multiple hubs
311         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
312
313         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
314
315         logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
316
317         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
318                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
319         }
320
321         Network::post($url, $params);
322
323         logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
324
325         return;
326
327 }
328
329 function drop_items(array $items)
330 {
331         $uid = 0;
332
333         if (!local_user() && !remote_user()) {
334                 return;
335         }
336
337         if (!empty($items)) {
338                 foreach ($items as $item) {
339                         $owner = Item::deleteForUser(['id' => $item], local_user());
340
341                         if ($owner && !$uid) {
342                                 $uid = $owner;
343                         }
344                 }
345         }
346 }
347
348 function drop_item($id)
349 {
350         $a = BaseObject::getApp();
351
352         // locate item to be deleted
353
354         $fields = ['id', 'uid', 'contact-id', 'deleted'];
355         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
356
357         if (!DBA::isResult($item)) {
358                 notice(L10n::t('Item not found.') . EOL);
359                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
360         }
361
362         if ($item['deleted']) {
363                 return 0;
364         }
365
366         $contact_id = 0;
367
368         // check if logged in user is either the author or owner of this item
369
370         if (!empty($_SESSION['remote'])) {
371                 foreach ($_SESSION['remote'] as $visitor) {
372                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
373                                 $contact_id = $visitor['cid'];
374                                 break;
375                         }
376                 }
377         }
378
379         if ((local_user() == $item['uid']) || $contact_id) {
380                 // Check if we should do HTML-based delete confirmation
381                 if ($_REQUEST['confirm']) {
382                         // <form> can't take arguments in its "action" parameter
383                         // so add any arguments as hidden inputs
384                         $query = explode_querystring($a->query_string);
385                         $inputs = [];
386
387                         foreach ($query['args'] as $arg) {
388                                 if (strpos($arg, 'confirm=') === false) {
389                                         $arg_parts = explode('=', $arg);
390                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
391                                 }
392                         }
393
394                         return replace_macros(get_markup_template('confirm.tpl'), [
395                                 '$method' => 'get',
396                                 '$message' => L10n::t('Do you really want to delete this item?'),
397                                 '$extra_inputs' => $inputs,
398                                 '$confirm' => L10n::t('Yes'),
399                                 '$confirm_url' => $query['base'],
400                                 '$confirm_name' => 'confirmed',
401                                 '$cancel' => L10n::t('Cancel'),
402                         ]);
403                 }
404                 // Now check how the user responded to the confirmation query
405                 if ($_REQUEST['canceled']) {
406                         goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
407                 }
408
409                 // delete the item
410                 Item::deleteForUser(['id' => $item['id']], local_user());
411
412                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
413                 //NOTREACHED
414         } else {
415                 notice(L10n::t('Permission denied.') . EOL);
416                 goaway(System::baseUrl() . '/' . $_SESSION['return_url']);
417                 //NOTREACHED
418         }
419 }
420
421 /* arrange the list in years */
422 function list_post_dates($uid, $wall)
423 {
424         $dnow = DateTimeFormat::localNow('Y-m-d');
425
426         $dthen = Item::firstPostDate($uid, $wall);
427         if (!$dthen) {
428                 return [];
429         }
430
431         // Set the start and end date to the beginning of the month
432         $dnow = substr($dnow, 0, 8) . '01';
433         $dthen = substr($dthen, 0, 8) . '01';
434
435         $ret = [];
436
437         /*
438          * Starting with the current month, get the first and last days of every
439          * month down to and including the month of the first post
440          */
441         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
442                 $dyear = intval(substr($dnow, 0, 4));
443                 $dstart = substr($dnow, 0, 8) . '01';
444                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
445                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
446                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
447                 $str = day_translate(DateTimeFormat::utc($dnow, 'F'));
448
449                 if (empty($ret[$dyear])) {
450                         $ret[$dyear] = [];
451                 }
452
453                 $ret[$dyear][] = [$str, $end_month, $start_month];
454                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
455         }
456         return $ret;
457 }
458
459 function posted_date_widget($url, $uid, $wall)
460 {
461         $o = '';
462
463         if (!Feature::isEnabled($uid, 'archives')) {
464                 return $o;
465         }
466
467         // For former Facebook folks that left because of "timeline"
468         /*
469          * @TODO old-lost code?
470         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
471                 return $o;
472         */
473
474         $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
475
476         $ret = list_post_dates($uid, $wall);
477
478         if (!DBA::isResult($ret)) {
479                 return $o;
480         }
481
482         $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
483         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
484
485         $o = replace_macros(get_markup_template('posted_date_widget.tpl'),[
486                 '$title' => L10n::t('Archives'),
487                 '$size' => $visible_years,
488                 '$cutoff_year' => $cutoff_year,
489                 '$cutoff' => $cutoff,
490                 '$url' => $url,
491                 '$dates' => $ret,
492                 '$showmore' => L10n::t('show more')
493
494         ]);
495         return $o;
496 }