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