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