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