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