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