]> git.mxchange.org Git - friendica.git/blob - include/items.php
Update more PHPDoc, including in include/
[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\Config;
9 use Friendica\Core\Hook;
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         Hook::callAll('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  * @param       $xml
247  * @param array $importer
248  * @param array $contact
249  * @param       $hub
250  * @param int   $datedir
251  * @param int   $pass
252  * @throws ImagickException
253  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254  */
255 function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0, $pass = 0)
256 {
257         if ($contact['network'] === Protocol::OSTATUS) {
258                 if ($pass < 2) {
259                         // Test - remove before flight
260                         //$tempfile = tempnam(get_temppath(), "ostatus2");
261                         //file_put_contents($tempfile, $xml);
262                         Logger::log("Consume OStatus messages ", Logger::DEBUG);
263                         OStatus::import($xml, $importer, $contact, $hub);
264                 }
265
266                 return;
267         }
268
269         if ($contact['network'] === Protocol::FEED) {
270                 if ($pass < 2) {
271                         Logger::log("Consume feeds", Logger::DEBUG);
272                         Feed::import($xml, $importer, $contact, $hub);
273                 }
274
275                 return;
276         }
277
278         if ($contact['network'] === Protocol::DFRN) {
279                 Logger::log("Consume DFRN messages", Logger::DEBUG);
280                 $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
281                 if (!empty($dfrn_importer)) {
282                         Logger::log("Now import the DFRN feed");
283                         DFRN::import($xml, $dfrn_importer, true);
284                         return;
285                 }
286         }
287 }
288
289 function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'subscribe')
290 {
291         /*
292          * Diaspora has different message-ids in feeds than they do
293          * through the direct Diaspora protocol. If we try and use
294          * the feed, we'll get duplicates. So don't.
295          */
296         if ($contact['network'] === Protocol::DIASPORA) {
297                 return;
298         }
299
300         // Without an importer we don't have a user id - so we quit
301         if (empty($importer)) {
302                 return;
303         }
304
305         $a = BaseObject::getApp();
306
307         $user = DBA::selectFirst('user', ['nickname'], ['uid' => $importer['uid']]);
308
309         // No user, no nickname, we quit
310         if (!DBA::isResult($user)) {
311                 return;
312         }
313
314         $push_url = System::baseUrl() . '/pubsub/' . $user['nickname'] . '/' . $contact['id'];
315
316         // Use a single verify token, even if multiple hubs
317         $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : Strings::getRandomHex());
318
319         $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
320
321         Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: '  . $push_url . ' with verifier ' . $verify_token);
322
323         if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
324                 DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
325         }
326
327         $postResult = Network::post($url, $params);
328
329         Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
330
331         return;
332
333 }
334
335 function drop_items(array $items)
336 {
337         $uid = 0;
338
339         if (!local_user() && !remote_user()) {
340                 return;
341         }
342
343         if (!empty($items)) {
344                 foreach ($items as $item) {
345                         $owner = Item::deleteForUser(['id' => $item], local_user());
346
347                         if ($owner && !$uid) {
348                                 $uid = $owner;
349                         }
350                 }
351         }
352 }
353
354 function drop_item($id, $return = '')
355 {
356         $a = BaseObject::getApp();
357
358         // locate item to be deleted
359
360         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
361         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
362
363         if (!DBA::isResult($item)) {
364                 notice(L10n::t('Item not found.') . EOL);
365                 $a->internalRedirect('network');
366         }
367
368         if ($item['deleted']) {
369                 return 0;
370         }
371
372         $contact_id = 0;
373
374         // check if logged in user is either the author or owner of this item
375
376         if (!empty($_SESSION['remote'])) {
377                 foreach ($_SESSION['remote'] as $visitor) {
378                         if ($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
379                                 $contact_id = $visitor['cid'];
380                                 break;
381                         }
382                 }
383         }
384
385         if ((local_user() == $item['uid']) || $contact_id) {
386                 // Check if we should do HTML-based delete confirmation
387                 if (!empty($_REQUEST['confirm'])) {
388                         // <form> can't take arguments in its "action" parameter
389                         // so add any arguments as hidden inputs
390                         $query = explode_querystring($a->query_string);
391                         $inputs = [];
392
393                         foreach ($query['args'] as $arg) {
394                                 if (strpos($arg, 'confirm=') === false) {
395                                         $arg_parts = explode('=', $arg);
396                                         $inputs[] = ['name' => $arg_parts[0], 'value' => $arg_parts[1]];
397                                 }
398                         }
399
400                         return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [
401                                 '$method' => 'get',
402                                 '$message' => L10n::t('Do you really want to delete this item?'),
403                                 '$extra_inputs' => $inputs,
404                                 '$confirm' => L10n::t('Yes'),
405                                 '$confirm_url' => $query['base'],
406                                 '$confirm_name' => 'confirmed',
407                                 '$cancel' => L10n::t('Cancel'),
408                         ]);
409                 }
410                 // Now check how the user responded to the confirmation query
411                 if (!empty($_REQUEST['canceled'])) {
412                         $a->internalRedirect('display/' . $item['guid']);
413                 }
414
415                 $is_comment = ($item['gravity'] == GRAVITY_COMMENT) ? true : false;
416                 $parentitem = null;
417                 if (!empty($item['parent'])){
418                         $fields = ['guid'];
419                         $parentitem = Item::selectFirstForUser(local_user(), $fields, ['id' => $item['parent']]);
420                 }
421
422                 // delete the item
423                 Item::deleteForUser(['id' => $item['id']], local_user());
424
425                 $return_url = hex2bin($return);
426
427                 // removes update_* from return_url to ignore Ajax refresh
428                 $return_url = str_replace("update_", "", $return_url);
429
430                 // Check if delete a comment
431                 if ($is_comment) {
432                         // Return to parent guid
433                         if (!empty($parentitem)) {
434                                 $a->internalRedirect('display/' . $parentitem['guid']);
435                                 //NOTREACHED
436                         }
437                         // In case something goes wrong
438                         else {
439                                 $a->internalRedirect('network');
440                                 //NOTREACHED
441                         }
442                 }
443                 else {
444                         // if unknown location or deleting top level post called from display
445                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
446                                 $a->internalRedirect('network');
447                                 //NOTREACHED
448                         } else {
449                                 $a->internalRedirect($return_url);
450                                 //NOTREACHED
451                         }
452                 }
453         } else {
454                 notice(L10n::t('Permission denied.') . EOL);
455                 $a->internalRedirect('display/' . $item['guid']);
456                 //NOTREACHED
457         }
458 }
459
460 /* arrange the list in years */
461 function list_post_dates($uid, $wall)
462 {
463         $dnow = DateTimeFormat::localNow('Y-m-d');
464
465         $dthen = Item::firstPostDate($uid, $wall);
466         if (!$dthen) {
467                 return [];
468         }
469
470         // Set the start and end date to the beginning of the month
471         $dnow = substr($dnow, 0, 8) . '01';
472         $dthen = substr($dthen, 0, 8) . '01';
473
474         $ret = [];
475
476         /*
477          * Starting with the current month, get the first and last days of every
478          * month down to and including the month of the first post
479          */
480         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
481                 $dyear = intval(substr($dnow, 0, 4));
482                 $dstart = substr($dnow, 0, 8) . '01';
483                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
484                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
485                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
486                 $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
487
488                 if (empty($ret[$dyear])) {
489                         $ret[$dyear] = [];
490                 }
491
492                 $ret[$dyear][] = [$str, $end_month, $start_month];
493                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
494         }
495         return $ret;
496 }
497
498 function posted_date_widget($url, $uid, $wall)
499 {
500         $o = '';
501
502         if (!Feature::isEnabled($uid, 'archives')) {
503                 return $o;
504         }
505
506         // For former Facebook folks that left because of "timeline"
507         /*
508          * @TODO old-lost code?
509         if ($wall && intval(PConfig::get($uid, 'system', 'no_wall_archive_widget')))
510                 return $o;
511         */
512
513         $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
514
515         $ret = list_post_dates($uid, $wall);
516
517         if (!DBA::isResult($ret)) {
518                 return $o;
519         }
520
521         $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
522         $cutoff = ((array_key_exists($cutoff_year, $ret))? true : false);
523
524         $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('posted_date_widget.tpl'),[
525                 '$title' => L10n::t('Archives'),
526                 '$size' => $visible_years,
527                 '$cutoff_year' => $cutoff_year,
528                 '$cutoff' => $cutoff,
529                 '$url' => $url,
530                 '$dates' => $ret,
531                 '$showmore' => L10n::t('show more')
532
533         ]);
534         return $o;
535 }