]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge pull request #8388 from annando/fetch
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * This is the POST destination for most all locally posted
21  * text stuff. This function handles status, wall-to-wall status,
22  * local comments, and remote coments that are posted on this site
23  * (as opposed to being delivered in a feed).
24  * Also processed here are posts and comments coming through the
25  * statusnet/twitter API.
26  *
27  * All of these become an "item" which is our basic unit of
28  * information.
29  */
30
31 use Friendica\App;
32 use Friendica\Content\Pager;
33 use Friendica\Content\Text\BBCode;
34 use Friendica\Core\Hook;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Protocol;
37 use Friendica\Core\Session;
38 use Friendica\Core\System;
39 use Friendica\Core\Worker;
40 use Friendica\Database\DBA;
41 use Friendica\DI;
42 use Friendica\Model\Attach;
43 use Friendica\Model\Contact;
44 use Friendica\Model\Conversation;
45 use Friendica\Model\FileTag;
46 use Friendica\Model\Item;
47 use Friendica\Model\Notify\Type;
48 use Friendica\Model\Photo;
49 use Friendica\Model\Term;
50 use Friendica\Network\HTTPException;
51 use Friendica\Object\EMail\ItemCCEMail;
52 use Friendica\Protocol\Activity;
53 use Friendica\Protocol\Diaspora;
54 use Friendica\Util\DateTimeFormat;
55 use Friendica\Util\Security;
56 use Friendica\Util\Strings;
57 use Friendica\Worker\Delivery;
58
59 require_once __DIR__ . '/../include/items.php';
60
61 function item_post(App $a) {
62         if (!Session::isAuthenticated()) {
63                 throw new HTTPException\ForbiddenException();
64         }
65
66         $uid = local_user();
67
68         if (!empty($_REQUEST['dropitems'])) {
69                 $arr_drop = explode(',', $_REQUEST['dropitems']);
70                 drop_items($arr_drop);
71                 $json = ['success' => 1];
72                 System::jsonExit($json);
73         }
74
75         Hook::callAll('post_local_start', $_REQUEST);
76
77         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
78
79         $api_source = $_REQUEST['api_source'] ?? false;
80
81         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
82
83         $return_path = $_REQUEST['return'] ?? '';
84         $preview = intval($_REQUEST['preview'] ?? 0);
85
86         /*
87          * Check for doubly-submitted posts, and reject duplicates
88          * Note that we have to ignore previews, otherwise nothing will post
89          * after it's been previewed
90          */
91         if (!$preview && !empty($_REQUEST['post_id_random'])) {
92                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
93                         Logger::info('item post: duplicate post');
94                         item_post_return(DI::baseUrl(), $api_source, $return_path);
95                 } else {
96                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
97                 }
98         }
99
100         // Is this a reply to something?
101         $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
102         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
103
104         $thread_parent_id = 0;
105         $thread_parent_contact = null;
106
107         $toplevel_item = null;
108         $parent_user = null;
109
110         $parent_contact = null;
111
112         $objecttype = null;
113         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
114         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
115
116         if ($toplevel_item_id || $thr_parent_uri) {
117                 if ($toplevel_item_id) {
118                         $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
119                 } elseif ($thr_parent_uri) {
120                         $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
121                 }
122
123                 // if this isn't the top-level parent of the conversation, find it
124                 if (DBA::isResult($toplevel_item)) {
125                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
126                         $thread_parent_id = $toplevel_item['id'];
127                         $thr_parent_uri = $toplevel_item['uri'];
128                         $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
129
130                         if ($toplevel_item['id'] != $toplevel_item['parent']) {
131                                 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
132                         }
133                 }
134
135                 if (!DBA::isResult($toplevel_item)) {
136                         notice(DI::l10n()->t('Unable to locate original post.'));
137                         if ($return_path) {
138                                 DI::baseUrl()->redirect($return_path);
139                         }
140                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
141                 }
142
143                 $toplevel_item_id = $toplevel_item['id'];
144                 $parent_user = $toplevel_item['uid'];
145
146                 $objecttype = Activity\ObjectType::COMMENT;
147         }
148
149         if ($toplevel_item_id) {
150                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
151         }
152
153         $post_id     = intval($_REQUEST['post_id'] ?? 0);
154         $app         = strip_tags($_REQUEST['source'] ?? '');
155         $extid       = strip_tags($_REQUEST['extid'] ?? '');
156         $object      = $_REQUEST['object'] ?? '';
157
158         // Don't use "defaults" here. It would turn 0 to 1
159         if (!isset($_REQUEST['wall'])) {
160                 $wall = 1;
161         } else {
162                 $wall = $_REQUEST['wall'];
163         }
164
165         // Ensure that the user id in a thread always stay the same
166         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
167                 $profile_uid = $parent_user;
168         }
169
170         // Check for multiple posts with the same message id (when the post was created via API)
171         if (($message_id != '') && ($profile_uid != 0)) {
172                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
173                         Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
174                         return 0;
175                 }
176         }
177
178         // Allow commenting if it is an answer to a public post
179         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
180
181         // Now check that valid personal details have been provided
182         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
183                 notice(DI::l10n()->t('Permission denied.'));
184                 if ($return_path) {
185                         DI::baseUrl()->redirect($return_path);
186                 }
187
188                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
189         }
190
191         // Init post instance
192         $orig_post = null;
193
194         // is this an edited post?
195         if ($post_id > 0) {
196                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
197         }
198
199         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
200
201         if (!DBA::isResult($user) && !$toplevel_item_id) {
202                 return 0;
203         }
204
205         $categories = '';
206         $postopts = '';
207         $emailcc = '';
208         $body = $_REQUEST['body'] ?? '';
209         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
210
211         // If we have a speparate attachment, we need to add it to the body.
212         if (!empty($has_attachment)) {
213                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
214                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
215                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
216
217                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
218                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
219
220                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
221                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
222                 $attachment = [
223                         'type'   => $attachment_type,
224                         'title'  => $attachment_title,
225                         'text'   => $attachment_text,
226                         'url'    => $attachment_url,
227                 ];
228
229                 if (!empty($attachment_img_src)) {
230                         $attachment['images'] = [
231                                 0 => [
232                                         'src'    => $attachment_img_src,
233                                         'width'  => $attachment_img_width,
234                                         'height' => $attachment_img_height
235                                 ]
236                         ];
237                 }
238
239                 $att_bbcode = add_page_info_data($attachment);
240                 $body .= $att_bbcode;
241         }
242
243         // Convert links with empty descriptions to links without an explicit description
244         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
245
246         if (!empty($orig_post)) {
247                 $str_group_allow   = $orig_post['allow_gid'];
248                 $str_contact_allow = $orig_post['allow_cid'];
249                 $str_group_deny    = $orig_post['deny_gid'];
250                 $str_contact_deny  = $orig_post['deny_cid'];
251                 $location          = $orig_post['location'];
252                 $coord             = $orig_post['coord'];
253                 $verb              = $orig_post['verb'];
254                 $objecttype        = $orig_post['object-type'];
255                 $app               = $orig_post['app'];
256                 $categories        = $orig_post['file'];
257                 $title             = Strings::escapeTags(trim($_REQUEST['title']));
258                 $body              = trim($body);
259                 $private           = $orig_post['private'];
260                 $pubmail_enabled   = $orig_post['pubmail'];
261                 $network           = $orig_post['network'];
262                 $guid              = $orig_post['guid'];
263                 $extid             = $orig_post['extid'];
264
265         } else {
266
267                 /*
268                  * if coming from the API and no privacy settings are set,
269                  * use the user default permissions - as they won't have
270                  * been supplied via a form.
271                  */
272                 if ($api_source
273                         && !array_key_exists('contact_allow', $_REQUEST)
274                         && !array_key_exists('group_allow', $_REQUEST)
275                         && !array_key_exists('contact_deny', $_REQUEST)
276                         && !array_key_exists('group_deny', $_REQUEST)) {
277                         $str_group_allow   = $user['allow_gid'];
278                         $str_contact_allow = $user['allow_cid'];
279                         $str_group_deny    = $user['deny_gid'];
280                         $str_contact_deny  = $user['deny_cid'];
281                 } else {
282                         // use the posted permissions
283
284                         $aclFormatter = DI::aclFormatter();
285
286                         $str_group_allow   = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
287                         $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
288                         $str_group_deny    = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
289                         $str_contact_deny  = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
290                 }
291
292                 $title             = Strings::escapeTags(trim($_REQUEST['title']    ?? ''));
293                 $location          = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
294                 $coord             = Strings::escapeTags(trim($_REQUEST['coord']    ?? ''));
295                 $verb              = Strings::escapeTags(trim($_REQUEST['verb']     ?? ''));
296                 $emailcc           = Strings::escapeTags(trim($_REQUEST['emailcc']  ?? ''));
297                 $body              = trim($body);
298                 $network           = Strings::escapeTags(trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN));
299                 $guid              = System::createUUID();
300
301                 $postopts = $_REQUEST['postopts'] ?? '';
302
303                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
304                         $private = Item::PRIVATE;
305                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
306                         $private = Item::UNLISTED;
307                 } else {
308                         $private = Item::PUBLIC;
309                 }
310
311                 // If this is a comment, set the permissions from the parent.
312
313                 if ($toplevel_item) {
314                         // for non native networks use the network of the original post as network of the item
315                         if (($toplevel_item['network'] != Protocol::DIASPORA)
316                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
317                                 && ($network == "")) {
318                                 $network = $toplevel_item['network'];
319                         }
320
321                         $str_contact_allow = $toplevel_item['allow_cid'];
322                         $str_group_allow   = $toplevel_item['allow_gid'];
323                         $str_contact_deny  = $toplevel_item['deny_cid'];
324                         $str_group_deny    = $toplevel_item['deny_gid'];
325                         $private           = $toplevel_item['private'];
326
327                         $wall              = $toplevel_item['wall'];
328                 }
329
330                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
331
332                 // if using the API, we won't see pubmail_enable - figure out if it should be set
333                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
334                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
335                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
336                         }
337                 }
338
339                 if (!strlen($body)) {
340                         if ($preview) {
341                                 System::jsonExit(['preview' => '']);
342                         }
343
344                         info(DI::l10n()->t('Empty post discarded.'));
345                         if ($return_path) {
346                                 DI::baseUrl()->redirect($return_path);
347                         }
348
349                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
350                 }
351         }
352
353         if (!empty($categories)) {
354                 // get the "fileas" tags for this post
355                 $filedas = FileTag::fileToArray($categories);
356         }
357
358         // save old and new categories, so we can determine what needs to be deleted from pconfig
359         $categories_old = $categories;
360         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
361         $categories_new = $categories;
362
363         if (!empty($filedas) && is_array($filedas)) {
364                 // append the fileas stuff to the new categories list
365                 $categories .= FileTag::arrayToFile($filedas);
366         }
367
368         // get contact info for poster
369
370         $author = null;
371         $self   = false;
372         $contact_id = 0;
373
374         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
375                 $self = true;
376                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
377         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
378                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
379         }
380
381         if (DBA::isResult($author)) {
382                 $contact_id = $author['id'];
383         }
384
385         // get contact info for owner
386         if ($profile_uid == local_user() || $allow_comment) {
387                 $contact_record = $author;
388         } else {
389                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
390         }
391
392         // Look for any tags and linkify them
393         $str_tags = '';
394         $inform   = '';
395
396         $tags = BBCode::getTags($body);
397
398         if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
399                 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
400         }
401
402         $tagged = [];
403
404         $private_forum = false;
405         $only_to_forum = false;
406         $forum_contact = [];
407
408         if (count($tags)) {
409                 foreach ($tags as $tag) {
410                         $tag_type = substr($tag, 0, 1);
411
412                         if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
413                                 continue;
414                         }
415
416                         /*
417                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
418                          * Robert Johnson should be first in the $tags array
419                          */
420                         $fullnametagged = false;
421                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
422                         foreach ($tagged as $nextTag) {
423                                 if (stristr($nextTag, $tag . ' ')) {
424                                         $fullnametagged = true;
425                                         break;
426                                 }
427                         }
428                         if ($fullnametagged) {
429                                 continue;
430                         }
431
432                         $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
433                         if ($success['replaced']) {
434                                 $tagged[] = $tag;
435                         }
436                         // When the forum is private or the forum is addressed with a "!" make the post private
437                         if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
438                                 $private_forum = $success['contact']['prv'];
439                                 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
440                                 $private_id = $success['contact']['id'];
441                                 $forum_contact = $success['contact'];
442                         } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
443                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
444                                 $private_forum = false;
445                                 $only_to_forum = true;
446                                 $private_id = $success['contact']['id'];
447                                 $forum_contact = $success['contact'];
448                         }
449                 }
450         }
451
452         $original_contact_id = $contact_id;
453
454         if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
455                 // we tagged a forum in a top level post. Now we change the post
456                 $private = $private_forum;
457
458                 $str_group_allow = '';
459                 $str_contact_deny = '';
460                 $str_group_deny = '';
461                 if ($private_forum) {
462                         $str_contact_allow = '<' . $private_id . '>';
463                 } else {
464                         $str_contact_allow = '';
465                 }
466                 $contact_id = $private_id;
467                 $contact_record = $forum_contact;
468                 $_REQUEST['origin'] = false;
469                 $wall = 0;
470         }
471
472         /*
473          * When a photo was uploaded into the message using the (profile wall) ajax
474          * uploader, The permissions are initially set to disallow anybody but the
475          * owner from seeing it. This is because the permissions may not yet have been
476          * set for the post. If it's private, the photo permissions should be set
477          * appropriately. But we didn't know the final permissions on the post until
478          * now. So now we'll look for links of uploaded messages that are in the
479          * post and set them to the same permissions as the post itself.
480          */
481
482         $match = null;
483
484         if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
485                 $objecttype = Activity\ObjectType::IMAGE;
486         }
487
488         /*
489          * Next link in any attachment references we find in the post.
490          */
491         $match = false;
492
493         /// @todo these lines should be moved to Model/Attach (Once it exists)
494         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
495                 $attaches = $match[1];
496                 if (count($attaches)) {
497                         foreach ($attaches as $attach) {
498                                 // Ensure to only modify attachments that you own
499                                 $srch = '<' . intval($original_contact_id) . '>';
500
501                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
502                                                 'id' => $attach];
503                                 if (!Attach::exists($condition)) {
504                                         continue;
505                                 }
506
507                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
508                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
509                                 $condition = ['id' => $attach];
510                                 Attach::update($fields, $condition);
511                         }
512                 }
513         }
514
515         // embedded bookmark or attachment in post? set bookmark flag
516
517         $data = BBCode::getAttachmentData($body);
518         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
519                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
520                 $posttype = Item::PT_PAGE;
521                 $objecttype =  Activity\ObjectType::BOOKMARK;
522         }
523
524         $body = DI::bbCodeVideo()->transform($body);
525
526         $body = BBCode::scaleExternalImages($body);
527
528         // Setting the object type if not defined before
529         if (!$objecttype) {
530                 $objecttype = Activity\ObjectType::NOTE; // Default value
531                 $objectdata = BBCode::getAttachedData($body);
532
533                 if ($objectdata["type"] == "link") {
534                         $objecttype = Activity\ObjectType::BOOKMARK;
535                 } elseif ($objectdata["type"] == "video") {
536                         $objecttype = Activity\ObjectType::VIDEO;
537                 } elseif ($objectdata["type"] == "photo") {
538                         $objecttype = Activity\ObjectType::IMAGE;
539                 }
540
541         }
542
543         $attachments = '';
544         $match = false;
545
546         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
547                 foreach ($match[2] as $mtch) {
548                         $fields = ['id', 'filename', 'filesize', 'filetype'];
549                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
550                         if ($attachment !== false) {
551                                 if (strlen($attachments)) {
552                                         $attachments .= ',';
553                                 }
554                                 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
555                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
556                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
557                         }
558                         $body = str_replace($match[1],'',$body);
559                 }
560         }
561
562         if (!strlen($verb)) {
563                 $verb = Activity::POST;
564         }
565
566         if ($network == "") {
567                 $network = Protocol::DFRN;
568         }
569
570         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
571
572         // even if the post arrived via API we are considering that it
573         // originated on this site by default for determining relayability.
574
575         // Don't use "defaults" here. It would turn 0 to 1
576         if (!isset($_REQUEST['origin'])) {
577                 $origin = 1;
578         } else {
579                 $origin = $_REQUEST['origin'];
580         }
581
582         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
583
584         // Fallback so that we alway have a parent uri
585         if (!$thr_parent_uri || !$toplevel_item_id) {
586                 $thr_parent_uri = $uri;
587         }
588
589         $datarray = [];
590         $datarray['uid']           = $profile_uid;
591         $datarray['wall']          = $wall;
592         $datarray['gravity']       = $gravity;
593         $datarray['network']       = $network;
594         $datarray['contact-id']    = $contact_id;
595         $datarray['owner-name']    = $contact_record['name'];
596         $datarray['owner-link']    = $contact_record['url'];
597         $datarray['owner-avatar']  = $contact_record['thumb'];
598         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
599         $datarray['author-name']   = $author['name'];
600         $datarray['author-link']   = $author['url'];
601         $datarray['author-avatar'] = $author['thumb'];
602         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
603         $datarray['created']       = DateTimeFormat::utcNow();
604         $datarray['edited']        = DateTimeFormat::utcNow();
605         $datarray['commented']     = DateTimeFormat::utcNow();
606         $datarray['received']      = DateTimeFormat::utcNow();
607         $datarray['changed']       = DateTimeFormat::utcNow();
608         $datarray['extid']         = $extid;
609         $datarray['guid']          = $guid;
610         $datarray['uri']           = $uri;
611         $datarray['title']         = $title;
612         $datarray['body']          = $body;
613         $datarray['app']           = $app;
614         $datarray['location']      = $location;
615         $datarray['coord']         = $coord;
616         $datarray['tag']           = $str_tags;
617         $datarray['file']          = $categories;
618         $datarray['inform']        = $inform;
619         $datarray['verb']          = $verb;
620         $datarray['post-type']     = $posttype;
621         $datarray['object-type']   = $objecttype;
622         $datarray['allow_cid']     = $str_contact_allow;
623         $datarray['allow_gid']     = $str_group_allow;
624         $datarray['deny_cid']      = $str_contact_deny;
625         $datarray['deny_gid']      = $str_group_deny;
626         $datarray['private']       = $private;
627         $datarray['pubmail']       = $pubmail_enabled;
628         $datarray['attach']        = $attachments;
629
630         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
631         $datarray['parent-uri']    = $thr_parent_uri;
632
633         $datarray['postopts']      = $postopts;
634         $datarray['origin']        = $origin;
635         $datarray['moderated']     = false;
636         $datarray['object']        = $object;
637
638         /*
639          * These fields are for the convenience of addons...
640          * 'self' if true indicates the owner is posting on their own wall
641          * If parent is 0 it is a top-level post.
642          */
643         $datarray['parent']        = $toplevel_item_id;
644         $datarray['self']          = $self;
645
646         // This triggers posts via API and the mirror functions
647         $datarray['api_source'] = $api_source;
648
649         // This field is for storing the raw conversation data
650         $datarray['protocol'] = Conversation::PARCEL_DFRN;
651
652         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
653         if (DBA::isResult($conversation)) {
654                 if ($conversation['conversation-uri'] != '') {
655                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
656                 }
657                 if ($conversation['conversation-href'] != '') {
658                         $datarray['conversation-href'] = $conversation['conversation-href'];
659                 }
660         }
661
662         if ($orig_post) {
663                 $datarray['edit'] = true;
664         } else {
665                 // If this was a share, add missing data here
666                 $datarray = Item::addShareDataFromOriginal($datarray);
667
668                 $datarray['edit'] = false;
669         }
670
671         // Check for hashtags in the body and repair or add hashtag links
672         if ($preview || $orig_post) {
673                 Item::setHashtags($datarray);
674         }
675
676         // preview mode - prepare the body for display and send it via json
677         if ($preview) {
678                 // We set the datarray ID to -1 because in preview mode the dataray
679                 // doesn't have an ID.
680                 $datarray["id"] = -1;
681                 $datarray["item_id"] = -1;
682                 $datarray["author-network"] = Protocol::DFRN;
683
684                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
685
686                 System::jsonExit(['preview' => $o]);
687         }
688
689         Hook::callAll('post_local',$datarray);
690
691         if (!empty($datarray['cancel'])) {
692                 Logger::info('mod_item: post cancelled by addon.');
693                 if ($return_path) {
694                         DI::baseUrl()->redirect($return_path);
695                 }
696
697                 $json = ['cancel' => 1];
698                 if (!empty($_REQUEST['jsreload'])) {
699                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
700                 }
701
702                 System::jsonExit($json);
703         }
704
705         if ($orig_post) {
706                 // Fill the cache field
707                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
708                 Item::putInCache($datarray);
709
710                 $fields = [
711                         'title' => $datarray['title'],
712                         'body' => $datarray['body'],
713                         'tag' => $datarray['tag'],
714                         'attach' => $datarray['attach'],
715                         'file' => $datarray['file'],
716                         'rendered-html' => $datarray['rendered-html'],
717                         'rendered-hash' => $datarray['rendered-hash'],
718                         'edited' => DateTimeFormat::utcNow(),
719                         'changed' => DateTimeFormat::utcNow()];
720
721                 Item::update($fields, ['id' => $post_id]);
722
723                 // update filetags in pconfig
724                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
725
726                 info(DI::l10n()->t('Post updated.'));
727                 if ($return_path) {
728                         DI::baseUrl()->redirect($return_path);
729                 }
730
731                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
732         }
733
734         unset($datarray['edit']);
735         unset($datarray['self']);
736         unset($datarray['api_source']);
737
738         if ($origin) {
739                 $signed = Diaspora::createCommentSignature($uid, $datarray);
740                 if (!empty($signed)) {
741                         $datarray['diaspora_signed_text'] = json_encode($signed);
742                 }
743         }
744
745         $post_id = Item::insert($datarray);
746
747         if (!$post_id) {
748                 info(DI::l10n()->t('Item wasn\'t stored.'));
749                 if ($return_path) {
750                         DI::baseUrl()->redirect($return_path);
751                 }
752
753                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
754         }
755
756         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
757
758         if (!DBA::isResult($datarray)) {
759                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
760                 if ($return_path) {
761                         DI::baseUrl()->redirect($return_path);
762                 }
763
764                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
765         }
766
767         // update filetags in pconfig
768         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
769
770         // These notifications are sent if someone else is commenting other your wall
771         if ($toplevel_item_id) {
772                 if ($contact_record != $author) {
773                         notification([
774                                 'type'         => Type::COMMENT,
775                                 'notify_flags' => $user['notify-flags'],
776                                 'language'     => $user['language'],
777                                 'to_name'      => $user['username'],
778                                 'to_email'     => $user['email'],
779                                 'uid'          => $user['uid'],
780                                 'item'         => $datarray,
781                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
782                                 'source_name'  => $datarray['author-name'],
783                                 'source_link'  => $datarray['author-link'],
784                                 'source_photo' => $datarray['author-avatar'],
785                                 'verb'         => Activity::POST,
786                                 'otype'        => 'item',
787                                 'parent'       => $toplevel_item_id,
788                                 'parent_uri'   => $toplevel_item['uri']
789                         ]);
790                 }
791         } else {
792                 if (($contact_record != $author) && !count($forum_contact)) {
793                         notification([
794                                 'type'         => Type::WALL,
795                                 'notify_flags' => $user['notify-flags'],
796                                 'language'     => $user['language'],
797                                 'to_name'      => $user['username'],
798                                 'to_email'     => $user['email'],
799                                 'uid'          => $user['uid'],
800                                 'item'         => $datarray,
801                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
802                                 'source_name'  => $datarray['author-name'],
803                                 'source_link'  => $datarray['author-link'],
804                                 'source_photo' => $datarray['author-avatar'],
805                                 'verb'         => Activity::POST,
806                                 'otype'        => 'item'
807                         ]);
808                 }
809         }
810
811         Hook::callAll('post_local_end', $datarray);
812
813         if (strlen($emailcc) && $profile_uid == local_user()) {
814                 $recipients = explode(',', $emailcc);
815                 if (count($recipients)) {
816                         foreach ($recipients as $recipient) {
817                                 $address = trim($recipient);
818                                 if (!strlen($address)) {
819                                         continue;
820                                 }
821                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
822                                         $datarray, $address, $author['thumb'] ?? ''));
823                         }
824                 }
825         }
826
827         // Insert an item entry for UID=0 for global entries.
828         // We now do it in the background to save some time.
829         // This is important in interactive environments like the frontend or the API.
830         // We don't fork a new process since this is done anyway with the following command
831         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
832
833         // When we are doing some forum posting via ! we have to start the notifier manually.
834         // These kind of posts don't initiate the notifier call in the item class.
835         if ($only_to_forum) {
836                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
837         }
838
839         Logger::info('post_complete');
840
841         if ($api_source) {
842                 return $post_id;
843         }
844
845         info(DI::l10n()->t('Post published.'));
846         item_post_return(DI::baseUrl(), $api_source, $return_path);
847         // NOTREACHED
848 }
849
850 function item_post_return($baseurl, $api_source, $return_path)
851 {
852         if ($api_source) {
853                 return;
854         }
855
856         if ($return_path) {
857                 DI::baseUrl()->redirect($return_path);
858         }
859
860         $json = ['success' => 1];
861         if (!empty($_REQUEST['jsreload'])) {
862                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
863         }
864
865         Logger::info('post_json', ['json' => $json]);
866
867         System::jsonExit($json);
868 }
869
870 function item_content(App $a)
871 {
872         if (!Session::isAuthenticated()) {
873                 return;
874         }
875
876         $o = '';
877
878         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
879                 if (DI::mode()->isAjax()) {
880                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
881                 } else {
882                         if (!empty($a->argv[3])) {
883                                 $o = drop_item($a->argv[2], $a->argv[3]);
884                         }
885                         else {
886                                 $o = drop_item($a->argv[2]);
887                         }
888                 }
889
890                 if (DI::mode()->isAjax()) {
891                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
892                         System::jsonExit([intval($a->argv[2]), intval($o)]);
893                 }
894         }
895
896         return $o;
897 }
898
899 /**
900  * This function removes the tag $tag from the text $body and replaces it with
901  * the appropriate link.
902  *
903  * @param App     $a
904  * @param string  $body     the text to replace the tag in
905  * @param string  $inform   a comma-seperated string containing everybody to inform
906  * @param string  $str_tags string to add the tag to
907  * @param integer $profile_uid
908  * @param string  $tag      the tag to replace
909  * @param string  $network  The network of the post
910  *
911  * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
912  * @throws ImagickException
913  * @throws HTTPException\InternalServerErrorException
914  */
915 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
916 {
917         $replaced = false;
918         $r = null;
919
920         //is it a person tag?
921         if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
922                 $tag_type = substr($tag, 0, 1);
923                 //is it already replaced?
924                 if (strpos($tag, '[url=')) {
925                         //append tag to str_tags
926                         if (!stristr($str_tags, $tag)) {
927                                 if (strlen($str_tags)) {
928                                         $str_tags .= ',';
929                                 }
930                                 $str_tags .= $tag;
931                         }
932
933                         // Checking for the alias that is used for OStatus
934                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
935                         if (preg_match($pattern, $tag, $matches)) {
936                                 $data = Contact::getDetailsByURL($matches[1]);
937
938                                 if ($data["alias"] != "") {
939                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
940
941                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
942                                                 if (strlen($str_tags)) {
943                                                         $str_tags .= ',';
944                                                 }
945
946                                                 $str_tags .= $newtag;
947                                         }
948                                 }
949                         }
950
951                         return $replaced;
952                 }
953
954                 //get the person's name
955                 $name = substr($tag, 1);
956
957                 // Sometimes the tag detection doesn't seem to work right
958                 // This is some workaround
959                 $nameparts = explode(" ", $name);
960                 $name = $nameparts[0];
961
962                 // Try to detect the contact in various ways
963                 if (strpos($name, 'http://')) {
964                         // At first we have to ensure that the contact exists
965                         Contact::getIdForURL($name);
966
967                         // Now we should have something
968                         $contact = Contact::getDetailsByURL($name);
969                 } elseif (strpos($name, '@')) {
970                         // This function automatically probes when no entry was found
971                         $contact = Contact::getDetailsByAddr($name);
972                 } else {
973                         $contact = false;
974                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
975
976                         if (strrpos($name, '+')) {
977                                 // Is it in format @nick+number?
978                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
979                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
980                         }
981
982                         // select someone by nick or attag in the current network
983                         if (!DBA::isResult($contact) && ($network != "")) {
984                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
985                                                 $name, $name, $network, $profile_uid];
986                                 $contact = DBA::selectFirst('contact', $fields, $condition);
987                         }
988
989                         //select someone by name in the current network
990                         if (!DBA::isResult($contact) && ($network != "")) {
991                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
992                                 $contact = DBA::selectFirst('contact', $fields, $condition);
993                         }
994
995                         // select someone by nick or attag in any network
996                         if (!DBA::isResult($contact)) {
997                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
998                                 $contact = DBA::selectFirst('contact', $fields, $condition);
999                         }
1000
1001                         // select someone by name in any network
1002                         if (!DBA::isResult($contact)) {
1003                                 $condition = ['name' => $name, 'uid' => $profile_uid];
1004                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1005                         }
1006                 }
1007
1008                 // Check if $contact has been successfully loaded
1009                 if (DBA::isResult($contact)) {
1010                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1011                                 $inform .= ',';
1012                         }
1013
1014                         if (isset($contact["id"])) {
1015                                 $inform .= 'cid:' . $contact["id"];
1016                         } elseif (isset($contact["notify"])) {
1017                                 $inform  .= $contact["notify"];
1018                         }
1019
1020                         $profile = $contact["url"];
1021                         $alias   = $contact["alias"];
1022                         $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1023                 }
1024
1025                 //if there is an url for this persons profile
1026                 if (isset($profile) && ($newname != "")) {
1027                         $replaced = true;
1028                         // create profile link
1029                         $profile = str_replace(',', '%2c', $profile);
1030                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1031                         $body = str_replace($tag_type . $name, $newtag, $body);
1032                         // append tag to str_tags
1033                         if (!stristr($str_tags, $newtag)) {
1034                                 if (strlen($str_tags)) {
1035                                         $str_tags .= ',';
1036                                 }
1037                                 $str_tags .= $newtag;
1038                         }
1039
1040                         /*
1041                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1042                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1043                          */
1044                         if (!empty($alias)) {
1045                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1046                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1047                                         if (strlen($str_tags)) {
1048                                                 $str_tags .= ',';
1049                                         }
1050                                         $str_tags .= $newtag;
1051                                 }
1052                         }
1053                 }
1054         }
1055
1056         return ['replaced' => $replaced, 'contact' => $contact];
1057 }
1058
1059 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1060 {
1061         if (DI::config()->get('system', 'disable_implicit_mentions')) {
1062                 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1063                 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1064                         $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1065                         if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1066                                 $tags[] = $contact;
1067                         }
1068                 }
1069         } else {
1070                 $implicit_mentions = [
1071                         $thread_parent_contact['url'] => $thread_parent_contact['nick']
1072                 ];
1073
1074                 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1075
1076                 foreach ($parent_terms as $parent_term) {
1077                         $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1078                 }
1079
1080                 foreach ($implicit_mentions as $url => $label) {
1081                         if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1082                                 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';
1083                         }
1084                 }
1085         }
1086
1087         return $tags;
1088 }