]> git.mxchange.org Git - friendica.git/blob - include/items.php
Don't try to build form for "None" backend.
[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\Logger;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Item;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\Feed;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\ParseUrl;
24 use Friendica\Util\Strings;
25 use Friendica\Util\Temporal;
26
27 require_once 'mod/share.php';
28 function add_page_info_data(array $data, $no_photos = false)
29 {
30         Addon::callHooks('page_info_data', $data);
31
32         if (empty($data['type'])) {
33                 return '';
34         }
35
36         // It maybe is a rich content, but if it does have everything that a link has,
37         // then treat it that way
38         if (($data["type"] == "rich") && is_string($data["title"]) &&
39                 is_string($data["text"]) && !empty($data["images"])) {
40                 $data["type"] = "link";
41         }
42
43         $data["title"] = defaults($data, "title", "");
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 (empty($data["text"])) {
60                 $data["text"] = $data["title"];
61         }
62
63         if (empty($data["text"])) {
64                 $data["text"] = $data["url"];
65         }
66
67         if (!empty($data["url"])) {
68                 $text .= " url='".$data["url"]."'";
69         }
70
71         if (!empty($data["title"])) {
72                 $text .= " title='".$data["title"]."'";
73         }
74
75         // Only embedd a picture link when it seems to be a valid picture ("width" is set)
76         if (!empty($data["images"]) && !empty($data["images"][0]["width"])) {
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=" . $hashtag . "]" . $hashtag . "[/url] ";
98                 }
99         }
100
101         return "\n".$text.$hashtags;
102 }
103
104 function query_page_info($url, $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::log('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
121                 foreach ($list as $keyword) {
122                         $keyword = trim($keyword);
123
124                         $index = array_search($keyword, $data["keywords"]);
125                         if ($index !== false) {
126                                 unset($data["keywords"][$index]);
127                         }
128                 }
129         }
130
131         return $data;
132 }
133
134 function add_page_keywords($url, $photo = "", $keywords = false, $keyword_blacklist = "")
135 {
136         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
137
138         $tags = "";
139         if (isset($data["keywords"]) && count($data["keywords"])) {
140                 foreach ($data["keywords"] as $keyword) {
141                         $hashtag = str_replace([" ", "+", "/", ".", "#", "'"],
142                                 ["", "", "", "", "", ""], $keyword);
143
144                         if ($tags != "") {
145                                 $tags .= ", ";
146                         }
147
148                         $tags .= "#[url=" . System::baseUrl() . "/search?tag=" . $hashtag . "]" . $hashtag . "[/url]";
149                 }
150         }
151
152         return $tags;
153 }
154
155 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "")
156 {
157         $data = query_page_info($url, $photo, $keywords, $keyword_blacklist);
158
159         $text = '';
160
161         if (is_array($data)) {
162                 $text = add_page_info_data($data, $no_photos);
163         }
164
165         return $text;
166 }
167
168 function add_page_info_to_body($body, $texturl = false, $no_photos = false)
169 {
170         Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
171
172         $URLSearchString = "^\[\]";
173
174         // Fix for Mastodon where the mentions are in a different format
175         $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#!@])(.*?)\[\/url\]/ism",
176                 '$2[url=$1]$3[/url]', $body);
177
178         // Adding these spaces is a quick hack due to my problems with regular expressions :)
179         preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " " . $body, $matches);
180
181         if (!$matches) {
182                 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " " . $body, $matches);
183         }
184
185         // Convert urls without bbcode elements
186         if (!$matches && $texturl) {
187                 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
188
189                 // Yeah, a hack. I really hate regular expressions :)
190                 if ($matches) {
191                         $matches[1] = $matches[2];
192                 }
193         }
194
195         if ($matches) {
196                 $footer = add_page_info($matches[1], $no_photos);
197         }
198
199         // Remove the link from the body if the link is attached at the end of the post
200         if (isset($footer) && (trim($footer) != "") && (strpos($footer, $matches[1]))) {
201                 $removedlink = trim(str_replace($matches[1], "", $body));
202                 if (($removedlink == "") || strstr($body, $removedlink)) {
203                         $body = $removedlink;
204                 }
205
206                 $removedlink = preg_replace("/\[url\=" . preg_quote($matches[1], '/') . "\](.*?)\[\/url\]/ism", '', $body);
207                 if (($removedlink == "") || strstr($body, $removedlink)) {
208                         $body = $removedlink;
209                 }
210         }
211
212         // Add the page information to the bottom
213         if (isset($footer) && (trim($footer) != "")) {
214                 $body .= $footer;
215         }
216
217         return $body;
218 }
219
220 /**
221  *
222  * consume_feed - process atom feed and update anything/everything we might need to update
223  *
224  * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
225  *
226  * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
227  *             It is this person's stuff that is going to be updated.
228  * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
229  *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
230  *             have a contact record.
231  * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
232  *        might not) try and subscribe to it.
233  * $datedir sorts in reverse order
234  * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
235  *      imported prior to its children being seen in the stream unless we are certain
236  *      of how the feed is arranged/ordered.
237  * With $pass = 1, we only pull parent items out of the stream.
238  * With $pass = 2, we only pull children (comments/likes).
239  *
240  * So running this twice, first with pass 1 and then with pass 2 will do the right
241  * thing regardless of feed ordering. This won't be adequate in a fully-threaded
242  * model where comments can have sub-threads. That would require some massive sorting
243  * to get all the feed items into a mostly linear ordering, and might still require
244  * recursion.
245  */
246 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
247 {
248         if ($contact['network'] === Protocol::OSTATUS) {
249                 if ($pass < 2) {
250                         // Test - remove before flight
251                         //$tempfile = tempnam(get_temppath(), "ostatus2");
252                         //file_put_contents($tempfile, $xml);
253                         Logger::log("Consume OStatus messages ", Logger::DEBUG);
254                         OStatus::import($xml, $importer, $contact, $hub);
255                 }
256
257                 return;
258         }
259
260         if ($contact['network'] === Protocol::FEED) {
261                 if ($pass < 2) {
262                         Logger::log("Consume feeds", Logger::DEBUG);
263                         Feed::import($xml, $importer, $contact, $hub);
264                 }
265
266                 return;
267         }
268
269         if ($contact['network'] === Protocol::DFRN) {
270                 Logger::log("Consume DFRN messages", Logger::DEBUG);
271                 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
272                 if (!empty($dfrn_importer)) {
273                         Logger::log("Now import the DFRN feed");
274                         DFRN::import($xml, $dfrn_importer, true);
275                         return;
276                 }
277         }
278 }
279
280 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
281 {
282         /*
283          * Diaspora has different message-ids in feeds than they do
284          * through the direct Diaspora protocol. If we try and use
285          * the feed, we'll get duplicates. So don't.
286          */
287         if ($contact['network'] === Protocol::DIASPORA) {
288                 return;
289         }
290
291         // Without an importer we don't have a user id - so we quit
292         if (empty($importer)) {
293                 return;
294         }
295
296         $a = BaseObject::getApp();
297
298         $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
299
300         // No user, no nickname, we quit
301         if (!DBA::isResult($user)) {
302                 return;
303         }
304
305         $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
306
307         // Use a single verify token, even if multiple hubs
308         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
309
310         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
311
312         Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
313
314         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
315                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
316         }
317
318         $postResult = Network::post($url, $params);
319
320         Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
321
322         return;
323
324 }
325
326 function drop_items(array $items)
327 {
328         $uid = 0;
329
330         if (!local_user() && !remote_user()) {
331                 return;
332         }
333
334         if (!empty($items)) {
335                 foreach ($items as $item) {
336                         $owner = Item::deleteForUser(['id' => $item], local_user());
337
338                         if ($owner && !$uid) {
339                                 $uid = $owner;
340                         }
341                 }
342         }
343 }
344
345 function drop_item($id, $return = '')
346 {
347         $a = BaseObject::getApp();
348
349         // locate item to be deleted
350
351         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
352         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
353
354         if (!DBA::isResult($item)) {
355                 notice(L10n::t('Item not found.') . EOL);
356                 $a->internalRedirect('network');
357         }
358
359         if ($item['deleted']) {
360                 return 0;
361         }
362
363         $contact_id = 0;
364
365         // check if logged in user is either the author or owner of this item
366
367         if (!empty($_SESSION['remote'])) {
368                 foreach ($_SESSION['remote'] as $visitor) {
369                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
370                                 $contact_id = $visitor['cid'];
371                                 break;
372                         }
373                 }
374         }
375
376         if ((local_user() == $item['uid']) || $contact_id) {
377                 // Check if we should do HTML-based delete confirmation
378                 if (!empty($_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
384                         foreach ($query['args'] as $arg) {
385                                 if (strpos($arg, 'confirm=') === false) {
386                                         $arg_parts = explode('=', $arg);
387                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
388                                 }
389                         }
390
391                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
392                                 '$method' => 'get',
393                                 '$message' => L10n::t('Do you really want to delete this item?'),
394                                 '$extra_inputs' => $inputs,
395                                 '$confirm' => L10n::t('Yes'),
396                                 '$confirm_url' => $query['base'],
397                                 '$confirm_name' => 'confirmed',
398                                 '$cancel' => L10n::t('Cancel'),
399                         ]);
400                 }
401                 // Now check how the user responded to the confirmation query
402                 if (!empty($_REQUEST['canceled'])) {
403                         $a->internalRedirect('display/' . $item['guid']);
404                 }
405
406                 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
407                 $parentitem = null;
408                 if (!empty($item['parent'])){
409                         $fields = ['guid'];
410                         $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
411                 }
412
413                 // delete the item
414                 Item::deleteForUser(['id' => $item['id']], local_user());
415
416                 $return_url = hex2bin($return);
417
418                 // removes update_* from return_url to ignore Ajax refresh
419                 $return_url = str_replace("update_", "", $return_url);
420
421                 // Check if delete a comment
422                 if ($is_comment) {
423                         // Return to parent guid
424                         if (!empty($parentitem)) {
425                                 $a->internalRedirect('display/' . $parentitem['guid']);
426                                 //NOTREACHED
427                         }
428                         // In case something goes wrong
429                         else {
430                                 $a->internalRedirect('network');
431                                 //NOTREACHED
432                         }
433                 }
434                 else {
435                         // if unknown location or deleting top level post called from display
436                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
437                                 $a->internalRedirect('network');
438                                 //NOTREACHED
439                         } else {
440                                 $a->internalRedirect($return_url);
441                                 //NOTREACHED
442                         }
443                 }
444         } else {
445                 notice(L10n::t('Permission denied.') . EOL);
446                 $a->internalRedirect('display/' . $item['guid']);
447                 //NOTREACHED
448         }
449 }
450
451 /* arrange the list in years */
452 function list_post_dates($uid, $wall)
453 {
454         $dnow = DateTimeFormat::localNow('Y-m-d');
455
456         $dthen = Item::firstPostDate($uid, $wall);
457         if (!$dthen) {
458                 return [];
459         }
460
461         // Set the start and end date to the beginning of the month
462         $dnow = substr($dnow, 0, 8) . '01';
463         $dthen = substr($dthen, 0, 8) . '01';
464
465         $ret = [];
466
467         /*
468          * Starting with the current month, get the first and last days of every
469          * month down to and including the month of the first post
470          */
471         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
472                 $dyear = intval(substr($dnow, 0, 4));
473                 $dstart = substr($dnow, 0, 8) . '01';
474                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
475                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
476                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
477                 $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
478
479                 if (empty($ret[$dyear])) {
480                         $ret[$dyear] = [];
481                 }
482
483                 $ret[$dyear][] = [$str, $end_month, $start_month];
484                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
485         }
486         return $ret;
487 }
488
489 function posted_date_widget($url, $uid, $wall)
490 {
491         $o = '';
492
493         if (!Feature::isEnabled($uid, 'archives')) {
494                 return $o;
495         }
496
497         // For former Facebook folks that left because of "timeline"
498         /*
499          * @TODO old-lost code?
500         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
501                 return $o;
502         */
503
504         $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
505
506         $ret = list_post_dates($uid, $wall);
507
508         if (!DBA::isResult($ret)) {
509                 return $o;
510         }
511
512         $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
513         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
514
515         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
516                 '$title' => L10n::t('Archives'),
517                 '$size' => $visible_years,
518                 '$cutoff_year' => $cutoff_year,
519                 '$cutoff' => $cutoff,
520                 '$url' => $url,
521                 '$dates' => $ret,
522                 '$showmore' => L10n::t('show more')
523
524         ]);
525         return $o;
526 }