Move ExAuth, FKOAuth1 & FKOAuthDataStore to own namespace `Friendica\Security`
[friendica.git/.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\Renderer;
39 use Friendica\Core\Session;
40 use Friendica\Core\System;
41 use Friendica\Core\Worker;
42 use Friendica\Database\DBA;
43 use Friendica\DI;
44 use Friendica\Model\Attach;
45 use Friendica\Model\Contact;
46 use Friendica\Model\Conversation;
47 use Friendica\Model\FileTag;
48 use Friendica\Model\Item;
49 use Friendica\Model\Notify\Type;
50 use Friendica\Model\Photo;
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\Util\Strings;
59 use Friendica\Worker\Delivery;
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                 foreach ($arr_drop as $item) {
71                         Item::deleteForUser(['id' => $item], $uid);
72                 }
73
74                 $json = ['success' => 1];
75                 System::jsonExit($json);
76         }
77
78         Hook::callAll('post_local_start', $_REQUEST);
79
80         Logger::debug('postvars', ['_REQUEST' => $_REQUEST]);
81
82         $api_source = $_REQUEST['api_source'] ?? false;
83
84         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
85
86         $return_path = $_REQUEST['return'] ?? '';
87         $preview = intval($_REQUEST['preview'] ?? 0);
88
89         /*
90          * Check for doubly-submitted posts, and reject duplicates
91          * Note that we have to ignore previews, otherwise nothing will post
92          * after it's been previewed
93          */
94         if (!$preview && !empty($_REQUEST['post_id_random'])) {
95                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
96                         Logger::info('item post: duplicate post');
97                         item_post_return(DI::baseUrl(), $api_source, $return_path);
98                 } else {
99                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
100                 }
101         }
102
103         // Is this a reply to something?
104         $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
105         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
106
107         $toplevel_item = null;
108         $parent_user = null;
109
110         $objecttype = null;
111         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
112         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
113
114         if ($toplevel_item_id || $thr_parent_uri) {
115                 if ($toplevel_item_id) {
116                         $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
117                 } elseif ($thr_parent_uri) {
118                         $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
119                 }
120
121                 // if this isn't the top-level parent of the conversation, find it
122                 if (DBA::isResult($toplevel_item)) {
123                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
124                         $thr_parent_uri = $toplevel_item['uri'];
125
126                         if ($toplevel_item['gravity'] != GRAVITY_PARENT) {
127                                 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item['parent']]);
128                         }
129                 }
130
131                 if (!DBA::isResult($toplevel_item)) {
132                         notice(DI::l10n()->t('Unable to locate original post.'));
133                         if ($return_path) {
134                                 DI::baseUrl()->redirect($return_path);
135                         }
136                         throw new HTTPException\NotFoundException(DI::l10n()->t('Unable to locate original post.'));
137                 }
138
139                 // When commenting on a public post then store the post for the current user
140                 // This enables interaction like starring and saving into folders
141                 if ($toplevel_item['uid'] == 0) {
142                         $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], local_user());
143                         Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
144                         if ($stored) {
145                                 $toplevel_item = Item::selectFirst([], ['id' => $stored]);
146                         }
147                 }
148
149                 $toplevel_item_id = $toplevel_item['id'];
150                 $parent_user = $toplevel_item['uid'];
151
152                 $objecttype = Activity\ObjectType::COMMENT;
153         }
154
155         if ($toplevel_item_id) {
156                 Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]);
157         }
158
159         $post_id     = intval($_REQUEST['post_id'] ?? 0);
160         $app         = strip_tags($_REQUEST['source'] ?? '');
161         $extid       = strip_tags($_REQUEST['extid'] ?? '');
162         $object      = $_REQUEST['object'] ?? '';
163
164         // Don't use "defaults" here. It would turn 0 to 1
165         if (!isset($_REQUEST['wall'])) {
166                 $wall = 1;
167         } else {
168                 $wall = $_REQUEST['wall'];
169         }
170
171         // Ensure that the user id in a thread always stay the same
172         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
173                 $profile_uid = $parent_user;
174         }
175
176         // Check for multiple posts with the same message id (when the post was created via API)
177         if (($message_id != '') && ($profile_uid != 0)) {
178                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
179                         Logger::info('Message already exists for user', ['uri' => $message_id, 'uid' => $profile_uid]);
180                         return 0;
181                 }
182         }
183
184         // Allow commenting if it is an answer to a public post
185         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
186
187         // Now check that valid personal details have been provided
188         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
189                 notice(DI::l10n()->t('Permission denied.'));
190                 if ($return_path) {
191                         DI::baseUrl()->redirect($return_path);
192                 }
193
194                 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
195         }
196
197         // Init post instance
198         $orig_post = null;
199
200         // is this an edited post?
201         if ($post_id > 0) {
202                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
203         }
204
205         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
206
207         if (!DBA::isResult($user) && !$toplevel_item_id) {
208                 return 0;
209         }
210
211         $categories = '';
212         $postopts = '';
213         $emailcc = '';
214         $body = $_REQUEST['body'] ?? '';
215         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
216
217         // If we have a speparate attachment, we need to add it to the body.
218         if (!empty($has_attachment)) {
219                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
220                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
221                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
222
223                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
224                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
225
226                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
227                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
228                 $attachment = [
229                         'type'   => $attachment_type,
230                         'title'  => $attachment_title,
231                         'text'   => $attachment_text,
232                         'url'    => $attachment_url,
233                 ];
234
235                 if (!empty($attachment_img_src)) {
236                         $attachment['images'] = [
237                                 0 => [
238                                         'src'    => $attachment_img_src,
239                                         'width'  => $attachment_img_width,
240                                         'height' => $attachment_img_height
241                                 ]
242                         ];
243                 }
244
245                 $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment);
246                 $body .= $att_bbcode;
247         }
248
249         // Convert links with empty descriptions to links without an explicit description
250         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
251
252         if (!empty($orig_post)) {
253                 $str_group_allow   = $orig_post['allow_gid'];
254                 $str_contact_allow = $orig_post['allow_cid'];
255                 $str_group_deny    = $orig_post['deny_gid'];
256                 $str_contact_deny  = $orig_post['deny_cid'];
257                 $location          = $orig_post['location'];
258                 $coord             = $orig_post['coord'];
259                 $verb              = $orig_post['verb'];
260                 $objecttype        = $orig_post['object-type'];
261                 $app               = $orig_post['app'];
262                 $categories        = $orig_post['file'] ?? '';
263                 $title             = trim($_REQUEST['title'] ?? '');
264                 $body              = trim($body);
265                 $private           = $orig_post['private'];
266                 $pubmail_enabled   = $orig_post['pubmail'];
267                 $network           = $orig_post['network'];
268                 $guid              = $orig_post['guid'];
269                 $extid             = $orig_post['extid'];
270         } else {
271                 $str_contact_allow = '';
272                 $str_group_allow   = '';
273                 $str_contact_deny  = '';
274                 $str_group_deny    = '';
275
276                 if (($_REQUEST['visibility'] ?? '') !== 'public') {
277                         $aclFormatter = DI::aclFormatter();
278                         $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? '';
279                         $str_group_allow   = isset($_REQUEST['group_allow'])   ? $aclFormatter->toString($_REQUEST['group_allow'])   : $user['allow_gid'] ?? '';
280                         $str_contact_deny  = isset($_REQUEST['contact_deny'])  ? $aclFormatter->toString($_REQUEST['contact_deny'])  : $user['deny_cid']  ?? '';
281                         $str_group_deny    = isset($_REQUEST['group_deny'])    ? $aclFormatter->toString($_REQUEST['group_deny'])    : $user['deny_gid']  ?? '';
282                 }
283
284                 $title             = trim($_REQUEST['title']    ?? '');
285                 $location          = trim($_REQUEST['location'] ?? '');
286                 $coord             = trim($_REQUEST['coord']    ?? '');
287                 $verb              = trim($_REQUEST['verb']     ?? '');
288                 $emailcc           = trim($_REQUEST['emailcc']  ?? '');
289                 $body              = trim($body);
290                 $network           = trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN);
291                 $guid              = System::createUUID();
292
293                 $postopts = $_REQUEST['postopts'] ?? '';
294
295                 if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) {
296                         $private = Item::PRIVATE;
297                 } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) {
298                         $private = Item::UNLISTED;
299                 } else {
300                         $private = Item::PUBLIC;
301                 }
302
303                 // If this is a comment, set the permissions from the parent.
304
305                 if ($toplevel_item) {
306                         // for non native networks use the network of the original post as network of the item
307                         if (($toplevel_item['network'] != Protocol::DIASPORA)
308                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
309                                 && ($network == "")) {
310                                 $network = $toplevel_item['network'];
311                         }
312
313                         $str_contact_allow = $toplevel_item['allow_cid'] ?? '';
314                         $str_group_allow   = $toplevel_item['allow_gid'] ?? '';
315                         $str_contact_deny  = $toplevel_item['deny_cid'] ?? '';
316                         $str_group_deny    = $toplevel_item['deny_gid'] ?? '';
317                         $private           = $toplevel_item['private'];
318
319                         $wall              = $toplevel_item['wall'];
320                 }
321
322                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
323
324                 // if using the API, we won't see pubmail_enable - figure out if it should be set
325                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
326                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
327                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
328                         }
329                 }
330
331                 if (!strlen($body)) {
332                         if ($preview) {
333                                 System::jsonExit(['preview' => '']);
334                         }
335
336                         notice(DI::l10n()->t('Empty post discarded.'));
337                         if ($return_path) {
338                                 DI::baseUrl()->redirect($return_path);
339                         }
340
341                         throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.'));
342                 }
343         }
344
345         if (!empty($categories)) {
346                 // get the "fileas" tags for this post
347                 $filedas = FileTag::fileToArray($categories);
348         }
349
350         // save old and new categories, so we can determine what needs to be deleted from pconfig
351         $categories_old = $categories;
352         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
353         $categories_new = $categories;
354
355         if (!empty($filedas) && is_array($filedas)) {
356                 // append the fileas stuff to the new categories list
357                 $categories .= FileTag::arrayToFile($filedas);
358         }
359
360         // get contact info for poster
361
362         $author = null;
363         $self   = false;
364         $contact_id = 0;
365
366         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
367                 $self = true;
368                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
369         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
370                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
371         }
372
373         if (DBA::isResult($author)) {
374                 $contact_id = $author['id'];
375         }
376
377         // get contact info for owner
378         if ($profile_uid == local_user() || $allow_comment) {
379                 $contact_record = $author ?: [];
380         } else {
381                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: [];
382         }
383
384         // Look for any tags and linkify them
385         $inform   = '';
386         $private_forum = false;
387         $private_id = null;
388         $only_to_forum = false;
389         $forum_contact = [];
390
391         $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) {
392                 $tags = BBCode::getTags($body);
393
394                 $tagged = [];
395
396                 foreach ($tags as $tag) {
397                         $tag_type = substr($tag, 0, 1);
398
399                         if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
400                                 continue;
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                         foreach ($tagged as $nextTag) {
407                                 if (stristr($nextTag, $tag . ' ')) {
408                                         continue 2;
409                                 }
410                         }
411
412                         $success = ItemHelper::replaceTag($body, $inform, local_user() ? local_user() : $profile_uid, $tag, $network);
413                         if ($success['replaced']) {
414                                 $tagged[] = $tag;
415                         }
416                         // When the forum is private or the forum is addressed with a "!" make the post private
417                         if (!empty($success['contact']['prv']) || ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
418                                 $private_forum = $success['contact']['prv'];
419                                 $only_to_forum = ($tag_type == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
420                                 $private_id = $success['contact']['id'];
421                                 $forum_contact = $success['contact'];
422                         } elseif (!empty($success['contact']['forum']) && ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
423                                 $private_forum = false;
424                                 $only_to_forum = true;
425                                 $private_id = $success['contact']['id'];
426                                 $forum_contact = $success['contact'];
427                         }
428                 }
429
430                 return $body;
431         });
432
433         $original_contact_id = $contact_id;
434
435         if (!$toplevel_item_id && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
436                 // we tagged a forum in a top level post. Now we change the post
437                 $private = $private_forum;
438
439                 $str_group_allow = '';
440                 $str_contact_deny = '';
441                 $str_group_deny = '';
442                 if ($private_forum) {
443                         $str_contact_allow = '<' . $private_id . '>';
444                 } else {
445                         $str_contact_allow = '';
446                 }
447                 $contact_id = $private_id;
448                 $contact_record = $forum_contact;
449                 $_REQUEST['origin'] = false;
450                 $wall = 0;
451         }
452
453         /*
454          * When a photo was uploaded into the message using the (profile wall) ajax
455          * uploader, The permissions are initially set to disallow anybody but the
456          * owner from seeing it. This is because the permissions may not yet have been
457          * set for the post. If it's private, the photo permissions should be set
458          * appropriately. But we didn't know the final permissions on the post until
459          * now. So now we'll look for links of uploaded messages that are in the
460          * post and set them to the same permissions as the post itself.
461          */
462
463         $match = null;
464
465         if (!$preview && Photo::setPermissionFromBody($body, $uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
466                 $objecttype = Activity\ObjectType::IMAGE;
467         }
468
469         /*
470          * Next link in any attachment references we find in the post.
471          */
472         $match = false;
473
474         /// @todo these lines should be moved to Model/Attach (Once it exists)
475         if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
476                 $attaches = $match[1];
477                 if (count($attaches)) {
478                         foreach ($attaches as $attach) {
479                                 // Ensure to only modify attachments that you own
480                                 $srch = '<' . intval($original_contact_id) . '>';
481
482                                 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
483                                                 'id' => $attach];
484                                 if (!Attach::exists($condition)) {
485                                         continue;
486                                 }
487
488                                 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
489                                                 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
490                                 $condition = ['id' => $attach];
491                                 Attach::update($fields, $condition);
492                         }
493                 }
494         }
495
496         // embedded bookmark or attachment in post? set bookmark flag
497
498         $data = BBCode::getAttachmentData($body);
499         if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
500                 && ($posttype != Item::PT_PERSONAL_NOTE)) {
501                 $posttype = Item::PT_PAGE;
502                 $objecttype =  Activity\ObjectType::BOOKMARK;
503         }
504
505         $body = DI::bbCodeVideo()->transform($body);
506
507         $body = BBCode::scaleExternalImages($body);
508
509         // Setting the object type if not defined before
510         if (!$objecttype) {
511                 $objecttype = Activity\ObjectType::NOTE; // Default value
512                 $objectdata = BBCode::getAttachedData($body);
513
514                 if ($objectdata["type"] == "link") {
515                         $objecttype = Activity\ObjectType::BOOKMARK;
516                 } elseif ($objectdata["type"] == "video") {
517                         $objecttype = Activity\ObjectType::VIDEO;
518                 } elseif ($objectdata["type"] == "photo") {
519                         $objecttype = Activity\ObjectType::IMAGE;
520                 }
521
522         }
523
524         $attachments = '';
525         $match = false;
526
527         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
528                 foreach ($match[2] as $mtch) {
529                         $fields = ['id', 'filename', 'filesize', 'filetype'];
530                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
531                         if ($attachment !== false) {
532                                 if (strlen($attachments)) {
533                                         $attachments .= ',';
534                                 }
535                                 $attachments .= '[attach]href="' . DI::baseUrl() . '/attach/' . $attachment['id'] .
536                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
537                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
538                         }
539                         $body = str_replace($match[1],'',$body);
540                 }
541         }
542
543         if (!strlen($verb)) {
544                 $verb = Activity::POST;
545         }
546
547         if ($network == "") {
548                 $network = Protocol::DFRN;
549         }
550
551         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
552
553         // even if the post arrived via API we are considering that it
554         // originated on this site by default for determining relayability.
555
556         // Don't use "defaults" here. It would turn 0 to 1
557         if (!isset($_REQUEST['origin'])) {
558                 $origin = 1;
559         } else {
560                 $origin = $_REQUEST['origin'];
561         }
562
563         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
564
565         // Fallback so that we alway have a parent uri
566         if (!$thr_parent_uri || !$toplevel_item_id) {
567                 $thr_parent_uri = $uri;
568         }
569
570         $datarray = [];
571         $datarray['uid']           = $profile_uid;
572         $datarray['wall']          = $wall;
573         $datarray['gravity']       = $gravity;
574         $datarray['network']       = $network;
575         $datarray['contact-id']    = $contact_id;
576         $datarray['owner-name']    = $contact_record['name'] ?? '';
577         $datarray['owner-link']    = $contact_record['url'] ?? '';
578         $datarray['owner-avatar']  = $contact_record['thumb'] ?? '';
579         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
580         $datarray['author-name']   = $author['name'];
581         $datarray['author-link']   = $author['url'];
582         $datarray['author-avatar'] = $author['thumb'];
583         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
584         $datarray['created']       = DateTimeFormat::utcNow();
585         $datarray['edited']        = DateTimeFormat::utcNow();
586         $datarray['commented']     = DateTimeFormat::utcNow();
587         $datarray['received']      = DateTimeFormat::utcNow();
588         $datarray['changed']       = DateTimeFormat::utcNow();
589         $datarray['extid']         = $extid;
590         $datarray['guid']          = $guid;
591         $datarray['uri']           = $uri;
592         $datarray['title']         = $title;
593         $datarray['body']          = $body;
594         $datarray['app']           = $app;
595         $datarray['location']      = $location;
596         $datarray['coord']         = $coord;
597         $datarray['file']          = $categories;
598         $datarray['inform']        = $inform;
599         $datarray['verb']          = $verb;
600         $datarray['post-type']     = $posttype;
601         $datarray['object-type']   = $objecttype;
602         $datarray['allow_cid']     = $str_contact_allow;
603         $datarray['allow_gid']     = $str_group_allow;
604         $datarray['deny_cid']      = $str_contact_deny;
605         $datarray['deny_gid']      = $str_group_deny;
606         $datarray['private']       = $private;
607         $datarray['pubmail']       = $pubmail_enabled;
608         $datarray['attach']        = $attachments;
609
610         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
611         $datarray['parent-uri']    = $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['parent-uri']]);
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         // Insert an item entry for UID=0 for global entries.
811         // We now do it in the background to save some time.
812         // This is important in interactive environments like the frontend or the API.
813         // We don't fork a new process since this is done anyway with the following command
814         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
815
816         // When we are doing some forum posting via ! we have to start the notifier manually.
817         // These kind of posts don't initiate the notifier call in the item class.
818         if ($only_to_forum) {
819                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
820         }
821
822         Logger::info('post_complete');
823
824         if ($api_source) {
825                 return $post_id;
826         }
827
828         item_post_return(DI::baseUrl(), $api_source, $return_path);
829         // NOTREACHED
830 }
831
832 function item_post_return($baseurl, $api_source, $return_path)
833 {
834         if ($api_source) {
835                 return;
836         }
837
838         if ($return_path) {
839                 DI::baseUrl()->redirect($return_path);
840         }
841
842         $json = ['success' => 1];
843         if (!empty($_REQUEST['jsreload'])) {
844                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
845         }
846
847         Logger::info('post_json', ['json' => $json]);
848
849         System::jsonExit($json);
850 }
851
852 function item_content(App $a)
853 {
854         if (!Session::isAuthenticated()) {
855                 return;
856         }
857
858         $o = '';
859
860         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
861                 if (DI::mode()->isAjax()) {
862                         Item::deleteForUser(['id' => $a->argv[2]], local_user());
863                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
864                         System::jsonExit([intval($a->argv[2]), local_user()]);
865                 } else {
866                         if (!empty($a->argv[3])) {
867                                 $o = drop_item($a->argv[2], $a->argv[3]);
868                         }
869                         else {
870                                 $o = drop_item($a->argv[2]);
871                         }
872                 }
873         }
874
875         return $o;
876 }
877
878 /**
879  * @param int    $id
880  * @param string $return
881  * @return string
882  * @throws HTTPException\InternalServerErrorException
883  */
884 function drop_item(int $id, string $return = '')
885 {
886         // locate item to be deleted
887         $fields = ['id', 'uid', 'guid', 'contact-id', 'deleted', 'gravity', 'parent'];
888         $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $id]);
889
890         if (!DBA::isResult($item)) {
891                 notice(DI::l10n()->t('Item not found.'));
892                 DI::baseUrl()->redirect('network');
893         }
894
895         if ($item['deleted']) {
896                 return '';
897         }
898
899         $contact_id = 0;
900
901         // check if logged in user is either the author or owner of this item
902         if (Session::getRemoteContactID($item['uid']) == $item['contact-id']) {
903                 $contact_id = $item['contact-id'];
904         }
905
906         if ((local_user() == $item['uid']) || $contact_id) {
907                 if (!empty($item['parent'])) {
908                         $parentitem = Item::selectFirstForUser(local_user(), ['guid'], ['id' => $item['parent']]);
909                 }
910
911                 // delete the item
912                 Item::deleteForUser(['id' => $item['id']], local_user());
913
914                 $return_url = hex2bin($return);
915
916                 // removes update_* from return_url to ignore Ajax refresh
917                 $return_url = str_replace("update_", "", $return_url);
918
919                 // Check if delete a comment
920                 if ($item['gravity'] == GRAVITY_COMMENT) {
921                         // Return to parent guid
922                         if (!empty($parentitem)) {
923                                 DI::baseUrl()->redirect('display/' . $parentitem['guid']);
924                                 //NOTREACHED
925                         } // In case something goes wrong
926                         else {
927                                 DI::baseUrl()->redirect('network');
928                                 //NOTREACHED
929                         }
930                 } else {
931                         // if unknown location or deleting top level post called from display
932                         if (empty($return_url) || strpos($return_url, 'display') !== false) {
933                                 DI::baseUrl()->redirect('network');
934                                 //NOTREACHED
935                         } else {
936                                 DI::baseUrl()->redirect($return_url);
937                                 //NOTREACHED
938                         }
939                 }
940         } else {
941                 notice(DI::l10n()->t('Permission denied.'));
942                 DI::baseUrl()->redirect('display/' . $item['guid']);
943                 //NOTREACHED
944         }
945
946         return '';
947 }