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