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