]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Merge remote-tracking branch 'upstream/develop' into write-tags
[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\Text\BBCode;
33 use Friendica\Core\Hook;
34 use Friendica\Core\Logger;
35 use Friendica\Core\Protocol;
36 use Friendica\Core\Session;
37 use Friendica\Core\System;
38 use Friendica\Core\Worker;
39 use Friendica\Database\DBA;
40 use Friendica\DI;
41 use Friendica\Model\Attach;
42 use Friendica\Model\Contact;
43 use Friendica\Model\Conversation;
44 use Friendica\Model\FileTag;
45 use Friendica\Model\Item;
46 use Friendica\Model\Notify\Type;
47 use Friendica\Model\Photo;
48 use Friendica\Model\Tag;
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([], ['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         } else {
265                 $str_contact_allow = '';
266                 $str_group_allow   = '';
267                 $str_contact_deny  = '';
268                 $str_group_deny    = '';
269
270                 if (($_REQUEST['visibility'] ?? '') !== 'public') {
271                         $aclFormatter = DI::aclFormatter();
272                         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
273                         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
274                         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
275                         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
276                 }
277
278                 $title             = Strings::escapeTags(trim($_REQUEST['title']    ?? ''));
279                 $location          = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
280                 $coord             = Strings::escapeTags(trim($_REQUEST['coord']    ?? ''));
281                 $verb              = Strings::escapeTags(trim($_REQUEST['verb']     ?? ''));
282                 $emailcc           = Strings::escapeTags(trim($_REQUEST['emailcc']  ?? ''));
283                 $body              = trim($body);
284                 $network           = Strings::escapeTags(trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN));
285                 $guid              = System::createUUID();
286
287                 $postopts = $_REQUEST['postopts'] ?? '';
288
289                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
290                         $private = Item::PRIVATE;
291                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
292                         $private = Item::UNLISTED;
293                 } else {
294                         $private = Item::PUBLIC;
295                 }
296
297                 // If this is a comment, set the permissions from the parent.
298
299                 if ($toplevel_item) {
300                         // for non native networks use the network of the original post as network of the item
301                         if (($toplevel_item['network'] != Protocol::DIASPORA)
302                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
303                                 && ($network == "")) {
304                                 $network = $toplevel_item['network'];
305                         }
306
307                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
308                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
309                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
310                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
311                         $private           = $toplevel_item['private'];
312
313                         $wall              = $toplevel_item['wall'];
314                 }
315
316                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
317
318                 // if using the API, we won't see pubmail_enable - figure out if it should be set
319                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
320                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
321                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
322                         }
323                 }
324
325                 if (!strlen($body)) {
326                         if ($preview) {
327                                 System::jsonExit(['preview' => '']);
328                         }
329
330                         info(DI::l10n()->t('Empty post discarded.'));
331                         if ($return_path) {
332                                 DI::baseUrl()->redirect($return_path);
333                         }
334
335                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
336                 }
337         }
338
339         if (!empty($categories)) {
340                 // get the "fileas" tags for this post
341                 $filedas = FileTag::fileToArray($categories);
342         }
343
344         // save old and new categories, so we can determine what needs to be deleted from pconfig
345         $categories_old = $categories;
346         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
347         $categories_new = $categories;
348
349         if (!empty($filedas) && is_array($filedas)) {
350                 // append the fileas stuff to the new categories list
351                 $categories .= FileTag::arrayToFile($filedas);
352         }
353
354         // get contact info for poster
355
356         $author = null;
357         $self   = false;
358         $contact_id = 0;
359
360         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
361                 $self = true;
362                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
363         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
364                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
365         }
366
367         if (DBA::isResult($author)) {
368                 $contact_id = $author['id'];
369         }
370
371         // get contact info for owner
372         if ($profile_uid == local_user() || $allow_comment) {
373                 $contact_record = $author;
374         } else {
375                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
376         }
377
378         // Look for any tags and linkify them
379         $str_tags = '';
380         $inform   = '';
381
382         $tags = BBCode::getTags($body);
383
384         if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
385                 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
386         }
387
388         $tagged = [];
389
390         $private_forum = false;
391         $only_to_forum = false;
392         $forum_contact = [];
393
394         if (count($tags)) {
395                 foreach ($tags as $tag) {
396                         $tag_type = substr($tag, 0, 1);
397
398                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
399                                 continue;
400                         }
401
402                         /*
403                          * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
404                          * Robert Johnson should be first in the $tags array
405                          */
406                         $fullnametagged = false;
407                         /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
408                         foreach ($tagged as $nextTag) {
409                                 if (stristr($nextTag, $tag . ' ')) {
410                                         $fullnametagged = true;
411                                         break;
412                                 }
413                         }
414                         if ($fullnametagged) {
415                                 continue;
416                         }
417
418                         $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
419                         if ($success['replaced']) {
420                                 $tagged[] = $tag;
421                         }
422                         // When the forum is private or the forum is addressed with a "!" make the post private
423                         if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]))) {
424                                 $private_forum = $success['contact']['prv'];
425                                 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
426                                 $private_id = $success['contact']['id'];
427                                 $forum_contact = $success['contact'];
428                         } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
429                                 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
430                                 $private_forum = false;
431                                 $only_to_forum = true;
432                                 $private_id = $success['contact']['id'];
433                                 $forum_contact = $success['contact'];
434                         }
435                 }
436         }
437
438         $original_contact_id = $contact_id;
439
440         if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
441                 // we tagged a forum in a top level post. Now we change the post
442                 $private = $private_forum;
443
444                 $str_group_allow = '';
445                 $str_contact_deny = '';
446                 $str_group_deny = '';
447                 if ($private_forum) {
448                         $str_contact_allow = '<' . $private_id . '>';
449                 } else {
450                         $str_contact_allow = '';
451                 }
452                 $contact_id = $private_id;
453                 $contact_record = $forum_contact;
454                 $_REQUEST['origin'] = false;
455                 $wall = 0;
456         }
457
458         /*
459          * When a photo was uploaded into the message using the (profile wall) ajax
460          * uploader, The permissions are initially set to disallow anybody but the
461          * owner from seeing it. This is because the permissions may not yet have been
462          * set for the post. If it's private, the photo permissions should be set
463          * appropriately. But we didn't know the final permissions on the post until
464          * now. So now we'll look for links of uploaded messages that are in the
465          * post and set them to the same permissions as the post itself.
466          */
467
468         $match = null;
469
470         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
471                 $objecttype = Activity\ObjectType::IMAGE;
472         }
473
474         /*
475          * Next link in any attachment references we find in the post.
476          */
477         $match = false;
478
479         /// @todo these lines should be moved to Model/Attach (Once it exists)
480         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
481                 $attaches = $match[1];
482                 if (count($attaches)) {
483                         foreach ($attaches as $attach) {
484                                 // Ensure to only modify attachments that you own
485                                 $srch = '<' . intval($original_contact_id) . '>';
486
487                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
488                                                 'id' => $attach];
489                                 if (!Attach::exists($condition)) {
490                                         continue;
491                                 }
492
493                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
494                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
495                                 $condition = ['id' => $attach];
496                                 Attach::update($fields, $condition);
497                         }
498                 }
499         }
500
501         // embedded bookmark or attachment in post? set bookmark flag
502
503         $data = BBCode::getAttachmentData($body);
504         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
505                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
506                 $posttype = Item::PT_PAGE;
507                 $objecttype =  Activity\ObjectType::BOOKMARK;
508         }
509
510         $body = DI::bbCodeVideo()->transform($body);
511
512         $body = BBCode::scaleExternalImages($body);
513
514         // Setting the object type if not defined before
515         if (!$objecttype) {
516                 $objecttype = Activity\ObjectType::NOTE; // Default value
517                 $objectdata = BBCode::getAttachedData($body);
518
519                 if ($objectdata["type"] == "link") {
520                         $objecttype = Activity\ObjectType::BOOKMARK;
521                 } elseif ($objectdata["type"] == "video") {
522                         $objecttype = Activity\ObjectType::VIDEO;
523                 } elseif ($objectdata["type"] == "photo") {
524                         $objecttype = Activity\ObjectType::IMAGE;
525                 }
526
527         }
528
529         $attachments = '';
530         $match = false;
531
532         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
533                 foreach ($match[2] as $mtch) {
534                         $fields = ['id', 'filename', 'filesize', 'filetype'];
535                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
536                         if ($attachment !== false) {
537                                 if (strlen($attachments)) {
538                                         $attachments .= ',';
539                                 }
540                                 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
541                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
542                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
543                         }
544                         $body = str_replace($match[1],'',$body);
545                 }
546         }
547
548         if (!strlen($verb)) {
549                 $verb = Activity::POST;
550         }
551
552         if ($network == "") {
553                 $network = Protocol::DFRN;
554         }
555
556         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
557
558         // even if the post arrived via API we are considering that it
559         // originated on this site by default for determining relayability.
560
561         // Don't use "defaults" here. It would turn 0 to 1
562         if (!isset($_REQUEST['origin'])) {
563                 $origin = 1;
564         } else {
565                 $origin = $_REQUEST['origin'];
566         }
567
568         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
569
570         // Fallback so that we alway have a parent uri
571         if (!$thr_parent_uri || !$toplevel_item_id) {
572                 $thr_parent_uri = $uri;
573         }
574
575         $datarray = [];
576         $datarray['uid']           = $profile_uid;
577         $datarray['wall']          = $wall;
578         $datarray['gravity']       = $gravity;
579         $datarray['network']       = $network;
580         $datarray['contact-id']    = $contact_id;
581         $datarray['owner-name']    = $contact_record['name'];
582         $datarray['owner-link']    = $contact_record['url'];
583         $datarray['owner-avatar']  = $contact_record['thumb'];
584         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
585         $datarray['author-name']   = $author['name'];
586         $datarray['author-link']   = $author['url'];
587         $datarray['author-avatar'] = $author['thumb'];
588         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
589         $datarray['created']       = DateTimeFormat::utcNow();
590         $datarray['edited']        = DateTimeFormat::utcNow();
591         $datarray['commented']     = DateTimeFormat::utcNow();
592         $datarray['received']      = DateTimeFormat::utcNow();
593         $datarray['changed']       = DateTimeFormat::utcNow();
594         $datarray['extid']         = $extid;
595         $datarray['guid']          = $guid;
596         $datarray['uri']           = $uri;
597         $datarray['title']         = $title;
598         $datarray['body']          = $body;
599         $datarray['app']           = $app;
600         $datarray['location']      = $location;
601         $datarray['coord']         = $coord;
602         $datarray['tag']           = $str_tags;
603         $datarray['file']          = $categories;
604         $datarray['inform']        = $inform;
605         $datarray['verb']          = $verb;
606         $datarray['post-type']     = $posttype;
607         $datarray['object-type']   = $objecttype;
608         $datarray['allow_cid']     = $str_contact_allow;
609         $datarray['allow_gid']     = $str_group_allow;
610         $datarray['deny_cid']      = $str_contact_deny;
611         $datarray['deny_gid']      = $str_group_deny;
612         $datarray['private']       = $private;
613         $datarray['pubmail']       = $pubmail_enabled;
614         $datarray['attach']        = $attachments;
615
616         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
617         $datarray['parent-uri']    = $thr_parent_uri;
618
619         $datarray['postopts']      = $postopts;
620         $datarray['origin']        = $origin;
621         $datarray['moderated']     = false;
622         $datarray['object']        = $object;
623
624         /*
625          * These fields are for the convenience of addons...
626          * 'self' if true indicates the owner is posting on their own wall
627          * If parent is 0 it is a top-level post.
628          */
629         $datarray['parent']        = $toplevel_item_id;
630         $datarray['self']          = $self;
631
632         // This triggers posts via API and the mirror functions
633         $datarray['api_source'] = $api_source;
634
635         // This field is for storing the raw conversation data
636         $datarray['protocol'] = Conversation::PARCEL_DFRN;
637
638         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
639         if (DBA::isResult($conversation)) {
640                 if ($conversation['conversation-uri'] != '') {
641                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
642                 }
643                 if ($conversation['conversation-href'] != '') {
644                         $datarray['conversation-href'] = $conversation['conversation-href'];
645                 }
646         }
647
648         if ($orig_post) {
649                 $datarray['edit'] = true;
650         } else {
651                 // If this was a share, add missing data here
652                 $datarray = Item::addShareDataFromOriginal($datarray);
653
654                 $datarray['edit'] = false;
655         }
656
657         // Check for hashtags in the body and repair or add hashtag links
658         if ($preview || $orig_post) {
659                 Item::setHashtags($datarray);
660         }
661
662         // preview mode - prepare the body for display and send it via json
663         if ($preview) {
664                 // We set the datarray ID to -1 because in preview mode the dataray
665                 // doesn't have an ID.
666                 $datarray["id"] = -1;
667                 $datarray["item_id"] = -1;
668                 $datarray["author-network"] = Protocol::DFRN;
669
670                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
671
672                 System::jsonExit(['preview' => $o]);
673         }
674
675         Hook::callAll('post_local',$datarray);
676
677         if (!empty($datarray['cancel'])) {
678                 Logger::info('mod_item: post cancelled by addon.');
679                 if ($return_path) {
680                         DI::baseUrl()->redirect($return_path);
681                 }
682
683                 $json = ['cancel' => 1];
684                 if (!empty($_REQUEST['jsreload'])) {
685                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
686                 }
687
688                 System::jsonExit($json);
689         }
690
691         if ($orig_post) {
692                 // Fill the cache field
693                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
694                 Item::putInCache($datarray);
695
696                 $fields = [
697                         'title' => $datarray['title'],
698                         'body' => $datarray['body'],
699                         'tag' => $datarray['tag'],
700                         'attach' => $datarray['attach'],
701                         'file' => $datarray['file'],
702                         'rendered-html' => $datarray['rendered-html'],
703                         'rendered-hash' => $datarray['rendered-hash'],
704                         'edited' => DateTimeFormat::utcNow(),
705                         'changed' => DateTimeFormat::utcNow()];
706
707                 Item::update($fields, ['id' => $post_id]);
708
709                 // update filetags in pconfig
710                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
711
712                 info(DI::l10n()->t('Post updated.'));
713                 if ($return_path) {
714                         DI::baseUrl()->redirect($return_path);
715                 }
716
717                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
718         }
719
720         unset($datarray['edit']);
721         unset($datarray['self']);
722         unset($datarray['api_source']);
723
724         if ($origin) {
725                 $signed = Diaspora::createCommentSignature($uid, $datarray);
726                 if (!empty($signed)) {
727                         $datarray['diaspora_signed_text'] = json_encode($signed);
728                 }
729         }
730
731         $post_id = Item::insert($datarray);
732
733         if (!$post_id) {
734                 info(DI::l10n()->t('Item wasn\'t stored.'));
735                 if ($return_path) {
736                         DI::baseUrl()->redirect($return_path);
737                 }
738
739                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
740         }
741
742         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
743
744         if (!DBA::isResult($datarray)) {
745                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
746                 if ($return_path) {
747                         DI::baseUrl()->redirect($return_path);
748                 }
749
750                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
751         }
752
753         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
754
755         // update filetags in pconfig
756         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
757
758         // These notifications are sent if someone else is commenting other your wall
759         if ($toplevel_item_id) {
760                 if ($contact_record != $author) {
761                         notification([
762                                 'type'         => Type::COMMENT,
763                                 'notify_flags' => $user['notify-flags'],
764                                 'language'     => $user['language'],
765                                 'to_name'      => $user['username'],
766                                 'to_email'     => $user['email'],
767                                 'uid'          => $user['uid'],
768                                 'item'         => $datarray,
769                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
770                                 'source_name'  => $datarray['author-name'],
771                                 'source_link'  => $datarray['author-link'],
772                                 'source_photo' => $datarray['author-avatar'],
773                                 'verb'         => Activity::POST,
774                                 'otype'        => 'item',
775                                 'parent'       => $toplevel_item_id,
776                                 'parent_uri'   => $toplevel_item['uri']
777                         ]);
778                 }
779         } else {
780                 if (($contact_record != $author) && !count($forum_contact)) {
781                         notification([
782                                 'type'         => Type::WALL,
783                                 'notify_flags' => $user['notify-flags'],
784                                 'language'     => $user['language'],
785                                 'to_name'      => $user['username'],
786                                 'to_email'     => $user['email'],
787                                 'uid'          => $user['uid'],
788                                 'item'         => $datarray,
789                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
790                                 'source_name'  => $datarray['author-name'],
791                                 'source_link'  => $datarray['author-link'],
792                                 'source_photo' => $datarray['author-avatar'],
793                                 'verb'         => Activity::POST,
794                                 'otype'        => 'item'
795                         ]);
796                 }
797         }
798
799         Hook::callAll('post_local_end', $datarray);
800
801         if (strlen($emailcc) && $profile_uid == local_user()) {
802                 $recipients = explode(',', $emailcc);
803                 if (count($recipients)) {
804                         foreach ($recipients as $recipient) {
805                                 $address = trim($recipient);
806                                 if (!strlen($address)) {
807                                         continue;
808                                 }
809                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
810                                         $datarray, $address, $author['thumb'] ?? ''));
811                         }
812                 }
813         }
814
815         // Insert an item entry for UID=0 for global entries.
816         // We now do it in the background to save some time.
817         // This is important in interactive environments like the frontend or the API.
818         // We don't fork a new process since this is done anyway with the following command
819         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
820
821         // When we are doing some forum posting via ! we have to start the notifier manually.
822         // These kind of posts don't initiate the notifier call in the item class.
823         if ($only_to_forum) {
824                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
825         }
826
827         Logger::info('post_complete');
828
829         if ($api_source) {
830                 return $post_id;
831         }
832
833         info(DI::l10n()->t('Post published.'));
834         item_post_return(DI::baseUrl(), $api_source, $return_path);
835         // NOTREACHED
836 }
837
838 function item_post_return($baseurl, $api_source, $return_path)
839 {
840         if ($api_source) {
841                 return;
842         }
843
844         if ($return_path) {
845                 DI::baseUrl()->redirect($return_path);
846         }
847
848         $json = ['success' => 1];
849         if (!empty($_REQUEST['jsreload'])) {
850                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
851         }
852
853         Logger::info('post_json', ['json' => $json]);
854
855         System::jsonExit($json);
856 }
857
858 function item_content(App $a)
859 {
860         if (!Session::isAuthenticated()) {
861                 return;
862         }
863
864         $o = '';
865
866         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
867                 if (DI::mode()->isAjax()) {
868                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
869                 } else {
870                         if (!empty($a->argv[3])) {
871                                 $o = drop_item($a->argv[2], $a->argv[3]);
872                         }
873                         else {
874                                 $o = drop_item($a->argv[2]);
875                         }
876                 }
877
878                 if (DI::mode()->isAjax()) {
879                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
880                         System::jsonExit([intval($a->argv[2]), intval($o)]);
881                 }
882         }
883
884         return $o;
885 }
886
887 /**
888  * This function removes the tag $tag from the text $body and replaces it with
889  * the appropriate link.
890  *
891  * @param App     $a
892  * @param string  $body     the text to replace the tag in
893  * @param string  $inform   a comma-seperated string containing everybody to inform
894  * @param string  $str_tags string to add the tag to
895  * @param integer $profile_uid
896  * @param string  $tag      the tag to replace
897  * @param string  $network  The network of the post
898  *
899  * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
900  * @throws ImagickException
901  * @throws HTTPException\InternalServerErrorException
902  */
903 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
904 {
905         $replaced = false;
906         $r = null;
907
908         //is it a person tag?
909         if (Term::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
910                 $tag_type = substr($tag, 0, 1);
911                 //is it already replaced?
912                 if (strpos($tag, '[url=')) {
913                         //append tag to str_tags
914                         if (!stristr($str_tags, $tag)) {
915                                 if (strlen($str_tags)) {
916                                         $str_tags .= ',';
917                                 }
918                                 $str_tags .= $tag;
919                         }
920
921                         // Checking for the alias that is used for OStatus
922                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
923                         if (preg_match($pattern, $tag, $matches)) {
924                                 $data = Contact::getDetailsByURL($matches[1]);
925
926                                 if ($data["alias"] != "") {
927                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
928
929                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
930                                                 if (strlen($str_tags)) {
931                                                         $str_tags .= ',';
932                                                 }
933
934                                                 $str_tags .= $newtag;
935                                         }
936                                 }
937                         }
938
939                         return $replaced;
940                 }
941
942                 //get the person's name
943                 $name = substr($tag, 1);
944
945                 // Sometimes the tag detection doesn't seem to work right
946                 // This is some workaround
947                 $nameparts = explode(" ", $name);
948                 $name = $nameparts[0];
949
950                 // Try to detect the contact in various ways
951                 if (strpos($name, 'http://')) {
952                         // At first we have to ensure that the contact exists
953                         Contact::getIdForURL($name);
954
955                         // Now we should have something
956                         $contact = Contact::getDetailsByURL($name);
957                 } elseif (strpos($name, '@')) {
958                         // This function automatically probes when no entry was found
959                         $contact = Contact::getDetailsByAddr($name);
960                 } else {
961                         $contact = false;
962                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
963
964                         if (strrpos($name, '+')) {
965                                 // Is it in format @nick+number?
966                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
967                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
968                         }
969
970                         // select someone by nick or attag in the current network
971                         if (!DBA::isResult($contact) && ($network != "")) {
972                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
973                                                 $name, $name, $network, $profile_uid];
974                                 $contact = DBA::selectFirst('contact', $fields, $condition);
975                         }
976
977                         //select someone by name in the current network
978                         if (!DBA::isResult($contact) && ($network != "")) {
979                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
980                                 $contact = DBA::selectFirst('contact', $fields, $condition);
981                         }
982
983                         // select someone by nick or attag in any network
984                         if (!DBA::isResult($contact)) {
985                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
986                                 $contact = DBA::selectFirst('contact', $fields, $condition);
987                         }
988
989                         // select someone by name in any network
990                         if (!DBA::isResult($contact)) {
991                                 $condition = ['name' => $name, 'uid' => $profile_uid];
992                                 $contact = DBA::selectFirst('contact', $fields, $condition);
993                         }
994                 }
995
996                 // Check if $contact has been successfully loaded
997                 if (DBA::isResult($contact)) {
998                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
999                                 $inform .= ',';
1000                         }
1001
1002                         if (isset($contact["id"])) {
1003                                 $inform .= 'cid:' . $contact["id"];
1004                         } elseif (isset($contact["notify"])) {
1005                                 $inform  .= $contact["notify"];
1006                         }
1007
1008                         $profile = $contact["url"];
1009                         $alias   = $contact["alias"];
1010                         $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1011                 }
1012
1013                 //if there is an url for this persons profile
1014                 if (isset($profile) && ($newname != "")) {
1015                         $replaced = true;
1016                         // create profile link
1017                         $profile = str_replace(',', '%2c', $profile);
1018                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1019                         $body = str_replace($tag_type . $name, $newtag, $body);
1020                         // append tag to str_tags
1021                         if (!stristr($str_tags, $newtag)) {
1022                                 if (strlen($str_tags)) {
1023                                         $str_tags .= ',';
1024                                 }
1025                                 $str_tags .= $newtag;
1026                         }
1027
1028                         /*
1029                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1030                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1031                          */
1032                         if (!empty($alias)) {
1033                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1034                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1035                                         if (strlen($str_tags)) {
1036                                                 $str_tags .= ',';
1037                                         }
1038                                         $str_tags .= $newtag;
1039                                 }
1040                         }
1041                 }
1042         }
1043
1044         return ['replaced' => $replaced, 'contact' => $contact];
1045 }
1046
1047 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1048 {
1049         if (DI::config()->get('system', 'disable_implicit_mentions')) {
1050                 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1051                 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1052                         $contact = Tag::TAG_CHARACTER[Tag::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1053                         if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1054                                 $tags[] = $contact;
1055                         }
1056                 }
1057         } else {
1058                 $implicit_mentions = [
1059                         $thread_parent_contact['url'] => $thread_parent_contact['nick']
1060                 ];
1061
1062                 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Tag::MENTION, Tag::IMPLICIT_MENTION]);
1063
1064                 foreach ($parent_terms as $parent_term) {
1065                         $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1066                 }
1067
1068                 foreach ($implicit_mentions as $url => $label) {
1069                         if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1070                                 $tags[] = Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';
1071                         }
1072                 }
1073         }
1074
1075         return $tags;
1076 }