]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Escape user names in notifications
[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\Item as ItemHelper;
33 use Friendica\Content\PageInfo;
34 use Friendica\Content\Text\BBCode;
35 use Friendica\Core\Hook;
36 use Friendica\Core\Logger;
37 use Friendica\Core\Protocol;
38 use Friendica\Core\Session;
39 use Friendica\Core\System;
40 use Friendica\Core\Worker;
41 use Friendica\Database\DBA;
42 use Friendica\DI;
43 use Friendica\Model\Attach;
44 use Friendica\Model\Contact;
45 use Friendica\Model\Conversation;
46 use Friendica\Model\FileTag;
47 use Friendica\Model\Item;
48 use Friendica\Model\Notify\Type;
49 use Friendica\Model\Photo;
50 use Friendica\Model\Post;
51 use Friendica\Model\Tag;
52 use Friendica\Network\HTTPException;
53 use Friendica\Object\EMail\ItemCCEMail;
54 use Friendica\Protocol\Activity;
55 use Friendica\Protocol\Diaspora;
56 use Friendica\Util\DateTimeFormat;
57 use Friendica\Security\Security;
58 use Friendica\Worker\Delivery;
59
60 function item_post(App $a) {
61         if (!Session::isAuthenticated()) {
62                 throw new HTTPException\ForbiddenException();
63         }
64
65         $uid = local_user();
66
67         if (!empty($_REQUEST['dropitems'])) {
68                 $arr_drop = explode(',', $_REQUEST['dropitems']);
69                 foreach ($arr_drop as $item) {
70                         Item::deleteForUser(['id' => $item], $uid);
71                 }
72
73                 $json = ['success' => 1];
74                 System::jsonExit($json);
75         }
76
77         Hook::callAll('post_local_start', $_REQUEST);
78
79         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
80
81         $api_source = $_REQUEST['api_source'] ?? false;
82
83         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
84
85         $return_path = $_REQUEST['return'] ?? '';
86         $preview = intval($_REQUEST['preview'] ?? 0);
87
88         /*
89          * Check for doubly-submitted posts, and reject duplicates
90          * Note that we have to ignore previews, otherwise nothing will post
91          * after it's been previewed
92          */
93         if (!$preview && !empty($_REQUEST['post_id_random'])) {
94                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
95                         Logger::info('item post: duplicate post');
96                         item_post_return(DI::baseUrl(), $api_source, $return_path);
97                 } else {
98                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
99                 }
100         }
101
102         // Is this a reply to something?
103         $parent_item_id = intval($_REQUEST['parent'] ?? 0);
104         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
105
106         $parent_item = null;
107         $toplevel_item = null;
108         $toplevel_item_id = 0;
109         $toplevel_user_id = null;
110
111         $objecttype = null;
112         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
113         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
114
115         if ($parent_item_id || $thr_parent_uri) {
116                 if ($parent_item_id) {
117                         $parent_item = Item::selectFirst([], ['id' => $parent_item_id]);
118                 } elseif ($thr_parent_uri) {
119                         $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
120                 }
121
122                 // if this isn't the top-level parent of the conversation, find it
123                 if (DBA::isResult($parent_item)) {
124                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
125                         $thr_parent_uri = $parent_item['uri'];
126                         $toplevel_item = $parent_item;
127
128                         if ($parent_item['gravity'] != GRAVITY_PARENT) {
129                                 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
130                         }
131                 }
132
133                 if (!DBA::isResult($toplevel_item)) {
134                         notice(DI::l10n()->t('Unable to locate original post.'));
135                         if ($return_path) {
136                                 DI::baseUrl()->redirect($return_path);
137                         }
138                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
139                 }
140
141                 // When commenting on a public post then store the post for the current user
142                 // This enables interaction like starring and saving into folders
143                 if ($toplevel_item['uid'] == 0) {
144                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user());
145                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
146                         if ($stored) {
147                                 $toplevel_item = Item::selectFirst([], ['id' => $stored]);
148                         }
149                 }
150
151                 $toplevel_item_id = $toplevel_item['id'];
152                 $toplevel_user_id = $toplevel_item['uid'];
153
154                 $objecttype = Activity\ObjectType::COMMENT;
155         }
156
157         if ($toplevel_item_id) {
158                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
159         }
160
161         $post_id     = intval($_REQUEST['post_id'] ?? 0);
162         $app         = strip_tags($_REQUEST['source'] ?? '');
163         $extid       = strip_tags($_REQUEST['extid'] ?? '');
164         $object      = $_REQUEST['object'] ?? '';
165
166         // Don't use "defaults" here. It would turn 0 to 1
167         if (!isset($_REQUEST['wall'])) {
168                 $wall = 1;
169         } else {
170                 $wall = $_REQUEST['wall'];
171         }
172
173         // Ensure that the user id in a thread always stay the same
174         if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [local_user(), 0])) {
175                 $profile_uid = $toplevel_user_id;
176         }
177
178         // Check for multiple posts with the same message id (when the post was created via API)
179         if (($message_id != '') && ($profile_uid != 0)) {
180                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
181                         Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
182                         return 0;
183                 }
184         }
185
186         // Allow commenting if it is an answer to a public post
187         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
188
189         // Now check that valid personal details have been provided
190         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
191                 notice(DI::l10n()->t('Permission denied.'));
192                 if ($return_path) {
193                         DI::baseUrl()->redirect($return_path);
194                 }
195
196                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
197         }
198
199         // Init post instance
200         $orig_post = null;
201
202         // is this an edited post?
203         if ($post_id > 0) {
204                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
205         }
206
207         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
208
209         if (!DBA::isResult($user) && !$toplevel_item_id) {
210                 return 0;
211         }
212
213         $categories = '';
214         $postopts = '';
215         $emailcc = '';
216         $body = $_REQUEST['body'] ?? '';
217         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
218
219         // If we have a speparate attachment, we need to add it to the body.
220         if (!empty($has_attachment)) {
221                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
222                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
223                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
224
225                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
226                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
227
228                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
229                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
230                 $attachment = [
231                         'type'   => $attachment_type,
232                         'title'  => $attachment_title,
233                         'text'   => $attachment_text,
234                         'url'    => $attachment_url,
235                 ];
236
237                 if (!empty($attachment_img_src)) {
238                         $attachment['images'] = [
239                                 0 => [
240                                         'src'    => $attachment_img_src,
241                                         'width'  => $attachment_img_width,
242                                         'height' => $attachment_img_height
243                                 ]
244                         ];
245                 }
246
247                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
248                 $body .= $att_bbcode;
249         }
250
251         // Convert links with empty descriptions to links without an explicit description
252         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
253
254         if (!empty($orig_post)) {
255                 $str_group_allow   = $orig_post['allow_gid'];
256                 $str_contact_allow = $orig_post['allow_cid'];
257                 $str_group_deny    = $orig_post['deny_gid'];
258                 $str_contact_deny  = $orig_post['deny_cid'];
259                 $location          = $orig_post['location'];
260                 $coord             = $orig_post['coord'];
261                 $verb              = $orig_post['verb'];
262                 $objecttype        = $orig_post['object-type'];
263                 $app               = $orig_post['app'];
264                 $categories        = $orig_post['file'] ?? '';
265                 $title             = trim($_REQUEST['title'] ?? '');
266                 $body              = trim($body);
267                 $private           = $orig_post['private'];
268                 $pubmail_enabled   = $orig_post['pubmail'];
269                 $network           = $orig_post['network'];
270                 $guid              = $orig_post['guid'];
271                 $extid             = $orig_post['extid'];
272         } else {
273                 $str_contact_allow = '';
274                 $str_group_allow   = '';
275                 $str_contact_deny  = '';
276                 $str_group_deny    = '';
277
278                 if (($_REQUEST['visibility'] ?? '') !== 'public') {
279                         $aclFormatter = DI::aclFormatter();
280                         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
281                         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
282                         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
283                         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
284                 }
285
286                 $title             = trim($_REQUEST['title']    ?? '');
287                 $location          = trim($_REQUEST['location'] ?? '');
288                 $coord             = trim($_REQUEST['coord']    ?? '');
289                 $verb              = trim($_REQUEST['verb']     ?? '');
290                 $emailcc           = trim($_REQUEST['emailcc']  ?? '');
291                 $body              = trim($body);
292                 $network           = trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN);
293                 $guid              = System::createUUID();
294
295                 $postopts = $_REQUEST['postopts'] ?? '';
296
297                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
298                         $private = Item::PRIVATE;
299                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
300                         $private = Item::UNLISTED;
301                 } else {
302                         $private = Item::PUBLIC;
303                 }
304
305                 // If this is a comment, set the permissions from the parent.
306
307                 if ($toplevel_item) {
308                         // for non native networks use the network of the original post as network of the item
309                         if (($toplevel_item['network'] != Protocol::DIASPORA)
310                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
311                                 && ($network == "")) {
312                                 $network = $toplevel_item['network'];
313                         }
314
315                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
316                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
317                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
318                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
319                         $private           = $toplevel_item['private'];
320
321                         $wall              = $toplevel_item['wall'];
322                 }
323
324                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
325
326                 // if using the API, we won't see pubmail_enable - figure out if it should be set
327                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
328                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
329                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
330                         }
331                 }
332
333                 if (!strlen($body)) {
334                         if ($preview) {
335                                 System::jsonExit(['preview' => '']);
336                         }
337
338                         notice(DI::l10n()->t('Empty post discarded.'));
339                         if ($return_path) {
340                                 DI::baseUrl()->redirect($return_path);
341                         }
342
343                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
344                 }
345         }
346
347         if (!empty($categories)) {
348                 // get the "fileas" tags for this post
349                 $filedas = FileTag::fileToArray($categories);
350         }
351
352         // save old and new categories, so we can determine what needs to be deleted from pconfig
353         $categories_old = $categories;
354         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
355         $categories_new = $categories;
356
357         if (!empty($filedas) && is_array($filedas)) {
358                 // append the fileas stuff to the new categories list
359                 $categories .= FileTag::arrayToFile($filedas);
360         }
361
362         // get contact info for poster
363
364         $author = null;
365         $self   = false;
366         $contact_id = 0;
367
368         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
369                 $self = true;
370                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
371         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
372                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
373         }
374
375         if (DBA::isResult($author)) {
376                 $contact_id = $author['id'];
377         }
378
379         // get contact info for owner
380         if ($profile_uid == local_user() || $allow_comment) {
381                 $contact_record = $author ?: [];
382         } else {
383                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
384         }
385
386         // Look for any tags and linkify them
387         $inform   = '';
388         $private_forum = false;
389         $private_id = null;
390         $only_to_forum = false;
391         $forum_contact = [];
392
393         $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network, $str_contact_allow, &$inform, &$private_forum, &$private_id, &$only_to_forum, &$forum_contact) {
394                 $tags = BBCode::getTags($body);
395
396                 $tagged = [];
397
398                 foreach ($tags as $tag) {
399                         $tag_type = substr($tag, 0, 1);
400
401                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
402                                 continue;
403                         }
404
405                         /* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
406                          * Robert Johnson should be first in the $tags array
407                          */
408                         foreach ($tagged as $nextTag) {
409                                 if (stristr($nextTag, $tag . ' ')) {
410                                         continue 2;
411                                 }
412                         }
413
414                         $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
415                         if ($success['replaced']) {
416                                 $tagged[] = $tag;
417                         }
418                         // When the forum is private or the forum is addressed with a "!" make the post private
419                         if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
420                                 $private_forum = $success['contact']['prv'];
421                                 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
422                                 $private_id = $success['contact']['id'];
423                                 $forum_contact = $success['contact'];
424                         } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
425                                 $private_forum = false;
426                                 $only_to_forum = true;
427                                 $private_id = $success['contact']['id'];
428                                 $forum_contact = $success['contact'];
429                         }
430                 }
431
432                 return $body;
433         });
434
435         $original_contact_id = $contact_id;
436
437         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
438                 // we tagged a forum in a top level post. Now we change the post
439                 $private = $private_forum;
440
441                 $str_group_allow = '';
442                 $str_contact_deny = '';
443                 $str_group_deny = '';
444                 if ($private_forum) {
445                         $str_contact_allow = '<' . $private_id . '>';
446                 } else {
447                         $str_contact_allow = '';
448                 }
449                 $contact_id = $private_id;
450                 $contact_record = $forum_contact;
451                 $_REQUEST['origin'] = false;
452                 $wall = 0;
453         }
454
455         /*
456          * When a photo was uploaded into the message using the (profile wall) ajax
457          * uploader, The permissions are initially set to disallow anybody but the
458          * owner from seeing it. This is because the permissions may not yet have been
459          * set for the post. If it's private, the photo permissions should be set
460          * appropriately. But we didn't know the final permissions on the post until
461          * now. So now we'll look for links of uploaded messages that are in the
462          * post and set them to the same permissions as the post itself.
463          */
464
465         $match = null;
466
467         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
468                 $objecttype = Activity\ObjectType::IMAGE;
469         }
470
471         /*
472          * Next link in any attachment references we find in the post.
473          */
474         $match = false;
475
476         /// @todo these lines should be moved to Model/Attach (Once it exists)
477         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
478                 $attaches = $match[1];
479                 if (count($attaches)) {
480                         foreach ($attaches as $attach) {
481                                 // Ensure to only modify attachments that you own
482                                 $srch = '<' . intval($original_contact_id) . '>';
483
484                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
485                                                 'id' => $attach];
486                                 if (!Attach::exists($condition)) {
487                                         continue;
488                                 }
489
490                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
491                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
492                                 $condition = ['id' => $attach];
493                                 Attach::update($fields, $condition);
494                         }
495                 }
496         }
497
498         // embedded bookmark or attachment in post? set bookmark flag
499
500         $data = BBCode::getAttachmentData($body);
501         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
502                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
503                 $posttype = Item::PT_PAGE;
504                 $objecttype =  Activity\ObjectType::BOOKMARK;
505         }
506
507         $body = DI::bbCodeVideo()->transform($body);
508
509         $body = BBCode::scaleExternalImages($body);
510
511         // Setting the object type if not defined before
512         if (!$objecttype) {
513                 $objecttype = Activity\ObjectType::NOTE; // Default value
514                 $objectdata = BBCode::getAttachedData($body);
515
516                 if ($objectdata["type"] == "link") {
517                         $objecttype = Activity\ObjectType::BOOKMARK;
518                 } elseif ($objectdata["type"] == "video") {
519                         $objecttype = Activity\ObjectType::VIDEO;
520                 } elseif ($objectdata["type"] == "photo") {
521                         $objecttype = Activity\ObjectType::IMAGE;
522                 }
523
524         }
525
526         $attachments = '';
527         $match = false;
528
529         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
530                 foreach ($match[2] as $mtch) {
531                         $fields = ['id', 'filename', 'filesize', 'filetype'];
532                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
533                         if ($attachment !== false) {
534                                 if (strlen($attachments)) {
535                                         $attachments .= ',';
536                                 }
537                                 $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'],
538                                         $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? '');
539                         }
540                         $body = str_replace($match[1],'',$body);
541                 }
542         }
543
544         if (!strlen($verb)) {
545                 $verb = Activity::POST;
546         }
547
548         if ($network == "") {
549                 $network = Protocol::DFRN;
550         }
551
552         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
553
554         // even if the post arrived via API we are considering that it
555         // originated on this site by default for determining relayability.
556
557         // Don't use "defaults" here. It would turn 0 to 1
558         if (!isset($_REQUEST['origin'])) {
559                 $origin = 1;
560         } else {
561                 $origin = $_REQUEST['origin'];
562         }
563
564         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
565
566         // Fallback so that we alway have a parent uri
567         if (!$thr_parent_uri || !$toplevel_item_id) {
568                 $thr_parent_uri = $uri;
569         }
570
571         $datarray = [];
572         $datarray['uid']           = $profile_uid;
573         $datarray['wall']          = $wall;
574         $datarray['gravity']       = $gravity;
575         $datarray['network']       = $network;
576         $datarray['contact-id']    = $contact_id;
577         $datarray['owner-name']    = $contact_record['name'] ?? '';
578         $datarray['owner-link']    = $contact_record['url'] ?? '';
579         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
580         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
581         $datarray['author-name']   = $author['name'];
582         $datarray['author-link']   = $author['url'];
583         $datarray['author-avatar'] = $author['thumb'];
584         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
585         $datarray['created']       = DateTimeFormat::utcNow();
586         $datarray['edited']        = DateTimeFormat::utcNow();
587         $datarray['commented']     = DateTimeFormat::utcNow();
588         $datarray['received']      = DateTimeFormat::utcNow();
589         $datarray['changed']       = DateTimeFormat::utcNow();
590         $datarray['extid']         = $extid;
591         $datarray['guid']          = $guid;
592         $datarray['uri']           = $uri;
593         $datarray['title']         = $title;
594         $datarray['body']          = $body;
595         $datarray['app']           = $app;
596         $datarray['location']      = $location;
597         $datarray['coord']         = $coord;
598         $datarray['file']          = $categories;
599         $datarray['inform']        = $inform;
600         $datarray['verb']          = $verb;
601         $datarray['post-type']     = $posttype;
602         $datarray['object-type']   = $objecttype;
603         $datarray['allow_cid']     = $str_contact_allow;
604         $datarray['allow_gid']     = $str_group_allow;
605         $datarray['deny_cid']      = $str_contact_deny;
606         $datarray['deny_gid']      = $str_group_deny;
607         $datarray['private']       = $private;
608         $datarray['pubmail']       = $pubmail_enabled;
609         $datarray['attach']        = $attachments;
610
611         $datarray['thr-parent']    = $thr_parent_uri;
612
613         $datarray['postopts']      = $postopts;
614         $datarray['origin']        = $origin;
615         $datarray['moderated']     = false;
616         $datarray['object']        = $object;
617
618         /*
619          * These fields are for the convenience of addons...
620          * 'self' if true indicates the owner is posting on their own wall
621          * If parent is 0 it is a top-level post.
622          */
623         $datarray['parent']        = $toplevel_item_id;
624         $datarray['self']          = $self;
625
626         // This triggers posts via API and the mirror functions
627         $datarray['api_source'] = $api_source;
628
629         // This field is for storing the raw conversation data
630         $datarray['protocol'] = Conversation::PARCEL_DFRN;
631
632         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['thr-parent']]);
633         if (DBA::isResult($conversation)) {
634                 if ($conversation['conversation-uri'] != '') {
635                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
636                 }
637                 if ($conversation['conversation-href'] != '') {
638                         $datarray['conversation-href'] = $conversation['conversation-href'];
639                 }
640         }
641
642         if ($orig_post) {
643                 $datarray['edit'] = true;
644         } else {
645                 // If this was a share, add missing data here
646                 $datarray = Item::addShareDataFromOriginal($datarray);
647
648                 $datarray['edit'] = false;
649         }
650
651         // Check for hashtags in the body and repair or add hashtag links
652         if ($preview || $orig_post) {
653                 $datarray['body'] = Item::setHashtags($datarray['body']);
654         }
655
656         // preview mode - prepare the body for display and send it via json
657         if ($preview) {
658                 // We set the datarray ID to -1 because in preview mode the dataray
659                 // doesn't have an ID.
660                 $datarray["id"] = -1;
661                 $datarray["uri-id"] = -1;
662                 $datarray["item_id"] = -1;
663                 $datarray["author-network"] = Protocol::DFRN;
664
665                 $o = conversation($a, [array_merge($contact_record, $datarray)], 'search', false, true);
666
667                 System::jsonExit(['preview' => $o]);
668         }
669
670         Hook::callAll('post_local',$datarray);
671
672         if (!empty($datarray['cancel'])) {
673                 Logger::info('mod_item: post cancelled by addon.');
674                 if ($return_path) {
675                         DI::baseUrl()->redirect($return_path);
676                 }
677
678                 $json = ['cancel' => 1];
679                 if (!empty($_REQUEST['jsreload'])) {
680                         $json['reload'] = DI::baseUrl() . '/' . $_REQUEST['jsreload'];
681                 }
682
683                 System::jsonExit($json);
684         }
685
686         if ($orig_post) {
687                 // Fill the cache field
688                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
689                 Item::putInCache($datarray);
690
691                 $fields = [
692                         'title' => $datarray['title'],
693                         'body' => $datarray['body'],
694                         'attach' => $datarray['attach'],
695                         'file' => $datarray['file'],
696                         'rendered-html' => $datarray['rendered-html'],
697                         'rendered-hash' => $datarray['rendered-hash'],
698                         'edited' => DateTimeFormat::utcNow(),
699                         'changed' => DateTimeFormat::utcNow()];
700
701                 Item::update($fields, ['id' => $post_id]);
702
703                 // update filetags in pconfig
704                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
705
706                 if ($return_path) {
707                         DI::baseUrl()->redirect($return_path);
708                 }
709
710                 throw new HTTPException\OKException(DI::l10n()->t('Post updated.'));
711         }
712
713         unset($datarray['edit']);
714         unset($datarray['self']);
715         unset($datarray['api_source']);
716
717         if ($origin) {
718                 $signed = Diaspora::createCommentSignature($uid, $datarray);
719                 if (!empty($signed)) {
720                         $datarray['diaspora_signed_text'] = json_encode($signed);
721                 }
722         }
723
724         $post_id = Item::insert($datarray);
725
726         if (!$post_id) {
727                 notice(DI::l10n()->t('Item wasn\'t stored.'));
728                 if ($return_path) {
729                         DI::baseUrl()->redirect($return_path);
730                 }
731
732                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.'));
733         }
734
735         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
736
737         if (!DBA::isResult($datarray)) {
738                 Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
739                 if ($return_path) {
740                         DI::baseUrl()->redirect($return_path);
741                 }
742
743                 throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.'));
744         }
745
746         Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
747
748         if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == GRAVITY_COMMENT)) {
749                 Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']);
750         }
751
752         // update filetags in pconfig
753         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
754
755         // These notifications are sent if someone else is commenting other your wall
756         if ($contact_record != $author) {
757                 if ($toplevel_item_id) {
758                         notification([
759                                 'type'         => Type::COMMENT,
760                                 'notify_flags' => $user['notify-flags'],
761                                 'language'     => $user['language'],
762                                 'to_name'      => $user['username'],
763                                 'to_email'     => $user['email'],
764                                 'uid'          => $user['uid'],
765                                 'item'         => $datarray,
766                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
767                                 'source_name'  => $datarray['author-name'],
768                                 'source_link'  => $datarray['author-link'],
769                                 'source_photo' => $datarray['author-avatar'],
770                                 'verb'         => Activity::POST,
771                                 'otype'        => 'item',
772                                 'parent'       => $toplevel_item_id,
773                                 'parent_uri'   => $toplevel_item['uri']
774                         ]);
775                 } elseif (empty($forum_contact)) {
776                         notification([
777                                 'type'         => Type::WALL,
778                                 'notify_flags' => $user['notify-flags'],
779                                 'language'     => $user['language'],
780                                 'to_name'      => $user['username'],
781                                 'to_email'     => $user['email'],
782                                 'uid'          => $user['uid'],
783                                 'item'         => $datarray,
784                                 'link'         => DI::baseUrl().'/display/'.urlencode($datarray['guid']),
785                                 'source_name'  => $datarray['author-name'],
786                                 'source_link'  => $datarray['author-link'],
787                                 'source_photo' => $datarray['author-avatar'],
788                                 'verb'         => Activity::POST,
789                                 'otype'        => 'item'
790                         ]);
791                 }
792         }
793
794         Hook::callAll('post_local_end', $datarray);
795
796         if (strlen($emailcc) && $profile_uid == local_user()) {
797                 $recipients = explode(',', $emailcc);
798                 if (count($recipients)) {
799                         foreach ($recipients as $recipient) {
800                                 $address = trim($recipient);
801                                 if (!strlen($address)) {
802                                         continue;
803                                 }
804                                 DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(),
805                                         $datarray, $address, $author['thumb'] ?? ''));
806                         }
807                 }
808         }
809
810         // When we are doing some forum posting via ! we have to start the notifier manually.
811         // These kind of posts don't initiate the notifier call in the item class.
812         if ($only_to_forum) {
813                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
814         }
815
816         Logger::info('post_complete');
817
818         if ($api_source) {
819                 return $post_id;
820         }
821
822         item_post_return(DI::baseUrl(), $api_source, $return_path);
823         // NOTREACHED
824 }
825
826 function item_post_return($baseurl, $api_source, $return_path)
827 {
828         if ($api_source) {
829                 return;
830         }
831
832         if ($return_path) {
833                 DI::baseUrl()->redirect($return_path);
834         }
835
836         $json = ['success' => 1];
837         if (!empty($_REQUEST['jsreload'])) {
838                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
839         }
840
841         Logger::info('post_json', ['json' => $json]);
842
843         System::jsonExit($json);
844 }
845
846 function item_content(App $a)
847 {
848         if (!Session::isAuthenticated()) {
849                 return;
850         }
851
852         $o = '';
853
854         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
855                 if (DI::mode()->isAjax()) {
856                         Item::deleteForUser(['id' => $a->argv[2]], local_user());
857                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
858                         System::jsonExit([intval($a->argv[2]), local_user()]);
859                 } else {
860                         if (!empty($a->argv[3])) {
861                                 $o = drop_item($a->argv[2], $a->argv[3]);
862                         }
863                         else {
864                                 $o = drop_item($a->argv[2]);
865                         }
866                 }
867         }
868
869         return $o;
870 }
871
872 /**
873  * @param int    $id
874  * @param string $return
875  * @return string
876  * @throws HTTPException\InternalServerErrorException
877  */
878 function drop_item(int $id, string $return = '')
879 {
880         // locate item to be deleted
881         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
882         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
883
884         if (!DBA::isResult($item)) {
885                 notice(DI::l10n()->t('Item not found.'));
886                 DI::baseUrl()->redirect('network');
887         }
888
889         if ($item['deleted']) {
890                 return '';
891         }
892
893         $contact_id = 0;
894
895         // check if logged in user is either the author or owner of this item
896         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
897                 $contact_id = $item['contact-id'];
898         }
899
900         if ((local_user() == $item['uid']) || $contact_id) {
901                 if (!empty($item['parent'])) {
902                         $parentitem = Item::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
903                 }
904
905                 // delete the item
906                 Item::deleteForUser(['id' => $item['id']], local_user());
907
908                 $return_url = hex2bin($return);
909
910                 // removes update_* from return_url to ignore Ajax refresh
911                 $return_url = str_replace("update_", "", $return_url);
912
913                 // Check if delete a comment
914                 if ($item['gravity'] == GRAVITY_COMMENT) {
915                         // Return to parent guid
916                         if (!empty($parentitem)) {
917                                 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
918                                 //NOTREACHED
919                         } // In case something goes wrong
920                         else {
921                                 DI::baseUrl()->redirect('network');
922                                 //NOTREACHED
923                         }
924                 } else {
925                         // if unknown location or deleting top level post called from display
926                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
927                                 DI::baseUrl()->redirect('network');
928                                 //NOTREACHED
929                         } else {
930                                 DI::baseUrl()->redirect($return_url);
931                                 //NOTREACHED
932                         }
933                 }
934         } else {
935                 notice(DI::l10n()->t('Permission denied.'));
936                 DI::baseUrl()->redirect('display/' . $item['guid']);
937                 //NOTREACHED
938         }
939
940         return '';
941 }