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