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