]> git.mxchange.org Git - friendica.git/blob - mod/item.php
Adapt naming convention
[friendica.git] / mod / item.php
1 <?php
2 /**
3  * @file mod/item.php
4  */
5
6 /*
7  * This is the POST destination for most all locally posted
8  * text stuff. This function handles status, wall-to-wall status,
9  * local comments, and remote coments that are posted on this site
10  * (as opposed to being delivered in a feed).
11  * Also processed here are posts and comments coming through the
12  * statusnet/twitter API.
13  *
14  * All of these become an "item" which is our basic unit of
15  * information.
16  */
17
18 use Friendica\App;
19 use Friendica\BaseObject;
20 use Friendica\Content\Pager;
21 use Friendica\Content\Text\BBCode;
22 use Friendica\Content\Text\HTML;
23 use Friendica\Core\Config;
24 use Friendica\Core\Hook;
25 use Friendica\Core\L10n;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Session;
29 use Friendica\Core\System;
30 use Friendica\Core\Worker;
31 use Friendica\Database\DBA;
32 use Friendica\Model\Attach;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\FileTag;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Term;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Protocol\Email;
41 use Friendica\Util\ACLFormatter;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Emailer;
44 use Friendica\Util\Security;
45 use Friendica\Util\Strings;
46 use Friendica\Worker\Delivery;
47
48 require_once __DIR__ . '/../include/items.php';
49
50 function item_post(App $a) {
51         if (!Session::isAuthenticated()) {
52                 return 0;
53         }
54
55         $uid = local_user();
56
57         if (!empty($_REQUEST['dropitems'])) {
58                 $arr_drop = explode(',', $_REQUEST['dropitems']);
59                 drop_items($arr_drop);
60                 $json = ['success' => 1];
61                 echo json_encode($json);
62                 exit();
63         }
64
65         Hook::callAll('post_local_start', $_REQUEST);
66
67         Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
68
69         $api_source = $_REQUEST['api_source'] ?? false;
70
71         $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
72
73         $return_path = $_REQUEST['return'] ?? '';
74         $preview = intval($_REQUEST['preview'] ?? 0);
75
76         /*
77          * Check for doubly-submitted posts, and reject duplicates
78          * Note that we have to ignore previews, otherwise nothing will post
79          * after it's been previewed
80          */
81         if (!$preview && !empty($_REQUEST['post_id_random'])) {
82                 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
83                         Logger::log("item post: duplicate post", Logger::DEBUG);
84                         item_post_return(System::baseUrl(), $api_source, $return_path);
85                 } else {
86                         $_SESSION['post-random'] = $_REQUEST['post_id_random'];
87                 }
88         }
89
90         // Is this a reply to something?
91         $toplevel_item_id = intval($_REQUEST['parent'] ?? 0);
92         $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? '');
93
94         $thread_parent_id = 0;
95         $thread_parent_contact = null;
96
97         $toplevel_item = null;
98         $parent_user = null;
99
100         $parent_contact = null;
101
102         $objecttype = null;
103         $profile_uid = ($_REQUEST['profile_uid'] ?? 0) ?: local_user();
104         $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE;
105
106         if ($toplevel_item_id || $thr_parent_uri) {
107                 if ($toplevel_item_id) {
108                         $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
109                 } elseif ($thr_parent_uri) {
110                         $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
111                 }
112
113                 // if this isn't the top-level parent of the conversation, find it
114                 if (DBA::isResult($toplevel_item)) {
115                         // The URI and the contact is taken from the direct parent which needn't to be the top parent
116                         $thread_parent_id = $toplevel_item['id'];
117                         $thr_parent_uri = $toplevel_item['uri'];
118                         $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
119
120                         if ($toplevel_item['id'] != $toplevel_item['parent']) {
121                                 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
122                         }
123                 }
124
125                 if (!DBA::isResult($toplevel_item)) {
126                         notice(L10n::t('Unable to locate original post.') . EOL);
127                         if (!empty($_REQUEST['return'])) {
128                                 $a->internalRedirect($return_path);
129                         }
130                         exit();
131                 }
132
133                 $toplevel_item_id = $toplevel_item['id'];
134                 $parent_user = $toplevel_item['uid'];
135
136                 $objecttype = ACTIVITY_OBJ_COMMENT;
137         }
138
139         if ($toplevel_item_id) {
140                 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
141         }
142
143         $post_id     = intval($_REQUEST['post_id'] ?? 0);
144         $app         = strip_tags($_REQUEST['source'] ?? '');
145         $extid       = strip_tags($_REQUEST['extid'] ?? '');
146         $object      = $_REQUEST['object'] ?? '';
147
148         // Don't use "defaults" here. It would turn 0 to 1
149         if (!isset($_REQUEST['wall'])) {
150                 $wall = 1;
151         } else {
152                 $wall = $_REQUEST['wall'];
153         }
154
155         // Ensure that the user id in a thread always stay the same
156         if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
157                 $profile_uid = $parent_user;
158         }
159
160         // Check for multiple posts with the same message id (when the post was created via API)
161         if (($message_id != '') && ($profile_uid != 0)) {
162                 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
163                         Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
164                         return 0;
165                 }
166         }
167
168         // Allow commenting if it is an answer to a public post
169         $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
170
171         // Now check that valid personal details have been provided
172         if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
173                 notice(L10n::t('Permission denied.') . EOL);
174
175                 if (!empty($_REQUEST['return'])) {
176                         $a->internalRedirect($return_path);
177                 }
178
179                 exit();
180         }
181
182         // Init post instance
183         $orig_post = null;
184
185         // is this an edited post?
186         if ($post_id > 0) {
187                 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
188         }
189
190         $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
191
192         if (!DBA::isResult($user) && !$toplevel_item_id) {
193                 return 0;
194         }
195
196         $categories = '';
197         $postopts = '';
198         $emailcc = '';
199         $body = $_REQUEST['body'] ?? '';
200         $has_attachment = $_REQUEST['has_attachment'] ?? 0;
201
202         // If we have a speparate attachment, we need to add it to the body.
203         if (!empty($has_attachment)) {
204                 $attachment_type  = $_REQUEST['attachment_type'] ??  '';
205                 $attachment_title = $_REQUEST['attachment_title'] ?? '';
206                 $attachment_text  = $_REQUEST['attachment_text'] ??  '';
207
208                 $attachment_url     = hex2bin($_REQUEST['attachment_url'] ??     '');
209                 $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? '');
210
211                 $attachment_img_width  = $_REQUEST['attachment_img_width'] ??  0;
212                 $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0;
213                 $attachment = [
214                         'type'   => $attachment_type,
215                         'title'  => $attachment_title,
216                         'text'   => $attachment_text,
217                         'url'    => $attachment_url,
218                 ];
219
220                 if (!empty($attachment_img_src)) {
221                         $attachment['images'] = [
222                                 0 => [
223                                         'src'    => $attachment_img_src,
224                                         'width'  => $attachment_img_width,
225                                         'height' => $attachment_img_height
226                                 ]
227                         ];
228                 }
229
230                 $att_bbcode = add_page_info_data($attachment);
231                 $body .= $att_bbcode;
232         }
233
234         // Convert links with empty descriptions to links without an explicit description
235         $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body);
236
237         if (!empty($orig_post)) {
238                 $str_group_allow   = $orig_post['allow_gid'];
239                 $str_contact_allow = $orig_post['allow_cid'];
240                 $str_group_deny    = $orig_post['deny_gid'];
241                 $str_contact_deny  = $orig_post['deny_cid'];
242                 $location          = $orig_post['location'];
243                 $coord             = $orig_post['coord'];
244                 $verb              = $orig_post['verb'];
245                 $objecttype        = $orig_post['object-type'];
246                 $app               = $orig_post['app'];
247                 $categories        = $orig_post['file'];
248                 $title             = Strings::escapeTags(trim($_REQUEST['title']));
249                 $body              = Strings::escapeHtml(trim($body));
250                 $private           = $orig_post['private'];
251                 $pubmail_enabled   = $orig_post['pubmail'];
252                 $network           = $orig_post['network'];
253                 $guid              = $orig_post['guid'];
254                 $extid             = $orig_post['extid'];
255
256         } else {
257
258                 /*
259                  * if coming from the API and no privacy settings are set,
260                  * use the user default permissions - as they won't have
261                  * been supplied via a form.
262                  */
263                 if ($api_source
264                         && !array_key_exists('contact_allow', $_REQUEST)
265                         && !array_key_exists('group_allow', $_REQUEST)
266                         && !array_key_exists('contact_deny', $_REQUEST)
267                         && !array_key_exists('group_deny', $_REQUEST)) {
268                         $str_group_allow   = $user['allow_gid'];
269                         $str_contact_allow = $user['allow_cid'];
270                         $str_group_deny    = $user['deny_gid'];
271                         $str_contact_deny  = $user['deny_cid'];
272                 } else {
273                         // use the posted permissions
274
275                         /** @var ACLFormatter $aclFormatter */
276                         $aclFormatter = BaseObject::getClass(ACLFormatter::class);
277
278                         $str_group_allow   = $aclFormatter->toString($_REQUEST['group_allow'] ?? '');
279                         $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? '');
280                         $str_group_deny    = $aclFormatter->toString($_REQUEST['group_deny'] ?? '');
281                         $str_contact_deny  = $aclFormatter->toString($_REQUEST['contact_deny'] ?? '');
282                 }
283
284                 $title             = Strings::escapeTags(trim($_REQUEST['title']    ?? ''));
285                 $location          = Strings::escapeTags(trim($_REQUEST['location'] ?? ''));
286                 $coord             = Strings::escapeTags(trim($_REQUEST['coord']    ?? ''));
287                 $verb              = Strings::escapeTags(trim($_REQUEST['verb']     ?? ''));
288                 $emailcc           = Strings::escapeTags(trim($_REQUEST['emailcc']  ?? ''));
289                 $body              = Strings::escapeHtml(trim($body));
290                 $network           = Strings::escapeTags(trim(($_REQUEST['network']  ?? '') ?: Protocol::DFRN));
291                 $guid              = System::createUUID();
292
293                 $postopts = $_REQUEST['postopts'] ?? '';
294
295                 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
296
297                 // If this is a comment, set the permissions from the parent.
298
299                 if ($toplevel_item) {
300                         // for non native networks use the network of the original post as network of the item
301                         if (($toplevel_item['network'] != Protocol::DIASPORA)
302                                 && ($toplevel_item['network'] != Protocol::OSTATUS)
303                                 && ($network == "")) {
304                                 $network = $toplevel_item['network'];
305                         }
306
307                         $str_contact_allow = $toplevel_item['allow_cid'];
308                         $str_group_allow   = $toplevel_item['allow_gid'];
309                         $str_contact_deny  = $toplevel_item['deny_cid'];
310                         $str_group_deny    = $toplevel_item['deny_gid'];
311                         $private           = $toplevel_item['private'];
312
313                         $wall              = $toplevel_item['wall'];
314                 }
315
316                 $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private;
317
318                 // if using the API, we won't see pubmail_enable - figure out if it should be set
319                 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
320                         if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
321                                 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
322                         }
323                 }
324
325                 if (!strlen($body)) {
326                         if ($preview) {
327                                 exit();
328                         }
329                         info(L10n::t('Empty post discarded.') . EOL);
330                         if (!empty($_REQUEST['return'])) {
331                                 $a->internalRedirect($return_path);
332                         }
333                         exit();
334                 }
335         }
336
337         if (!empty($categories)) {
338                 // get the "fileas" tags for this post
339                 $filedas = FileTag::fileToArray($categories);
340         }
341
342         // save old and new categories, so we can determine what needs to be deleted from pconfig
343         $categories_old = $categories;
344         $categories = FileTag::listToFile(trim($_REQUEST['category'] ?? ''), 'category');
345         $categories_new = $categories;
346
347         if (!empty($filedas) && is_array($filedas)) {
348                 // append the fileas stuff to the new categories list
349                 $categories .= FileTag::arrayToFile($filedas);
350         }
351
352         // get contact info for poster
353
354         $author = null;
355         $self   = false;
356         $contact_id = 0;
357
358         if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
359                 $self = true;
360                 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
361         } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
362                 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
363         }
364
365         if (DBA::isResult($author)) {
366                 $contact_id = $author['id'];
367         }
368
369         // get contact info for owner
370         if ($profile_uid == local_user() || $allow_comment) {
371                 $contact_record = $author;
372         } else {
373                 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
374         }
375
376         // Look for any tags and linkify them
377         $str_tags = '';
378         $inform   = '';
379
380         $tags = BBCode::getTags($body);
381
382         if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
383                 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
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 == Term::TAG_CHARACTER[Term::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, $str_tags, 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 == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
422                                 $private_forum = $success['contact']['prv'];
423                                 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::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, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
469                 $objecttype = ACTIVITY_OBJ_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_OBJ_BOOKMARK;
506         }
507
508         /** @var BBCode\Video $bbCodeVideo */
509         $bbCodeVideo = BaseObject::getClass(BBCode\Video::class);
510         $body =  $bbCodeVideo->transform($body);
511
512         // Fold multi-line [code] sequences
513         $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
514
515         $body = BBCode::scaleExternalImages($body, false);
516
517         // Setting the object type if not defined before
518         if (!$objecttype) {
519                 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
520                 $objectdata = BBCode::getAttachedData($body);
521
522                 if ($objectdata["type"] == "link") {
523                         $objecttype = ACTIVITY_OBJ_BOOKMARK;
524                 } elseif ($objectdata["type"] == "video") {
525                         $objecttype = ACTIVITY_OBJ_VIDEO;
526                 } elseif ($objectdata["type"] == "photo") {
527                         $objecttype = ACTIVITY_OBJ_IMAGE;
528                 }
529
530         }
531
532         $attachments = '';
533         $match = false;
534
535         if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
536                 foreach ($match[2] as $mtch) {
537                         $fields = ['id', 'filename', 'filesize', 'filetype'];
538                         $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
539                         if ($attachment !== false) {
540                                 if (strlen($attachments)) {
541                                         $attachments .= ',';
542                                 }
543                                 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
544                                                 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
545                                                 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
546                         }
547                         $body = str_replace($match[1],'',$body);
548                 }
549         }
550
551         if (!strlen($verb)) {
552                 $verb = ACTIVITY_POST;
553         }
554
555         if ($network == "") {
556                 $network = Protocol::DFRN;
557         }
558
559         $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
560
561         // even if the post arrived via API we are considering that it
562         // originated on this site by default for determining relayability.
563
564         // Don't use "defaults" here. It would turn 0 to 1
565         if (!isset($_REQUEST['origin'])) {
566                 $origin = 1;
567         } else {
568                 $origin = $_REQUEST['origin'];
569         }
570
571         $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
572
573         // Fallback so that we alway have a parent uri
574         if (!$thr_parent_uri || !$toplevel_item_id) {
575                 $thr_parent_uri = $uri;
576         }
577
578         $datarray = [];
579         $datarray['uid']           = $profile_uid;
580         $datarray['wall']          = $wall;
581         $datarray['gravity']       = $gravity;
582         $datarray['network']       = $network;
583         $datarray['contact-id']    = $contact_id;
584         $datarray['owner-name']    = $contact_record['name'];
585         $datarray['owner-link']    = $contact_record['url'];
586         $datarray['owner-avatar']  = $contact_record['thumb'];
587         $datarray['owner-id']      = Contact::getIdForURL($datarray['owner-link']);
588         $datarray['author-name']   = $author['name'];
589         $datarray['author-link']   = $author['url'];
590         $datarray['author-avatar'] = $author['thumb'];
591         $datarray['author-id']     = Contact::getIdForURL($datarray['author-link']);
592         $datarray['created']       = DateTimeFormat::utcNow();
593         $datarray['edited']        = DateTimeFormat::utcNow();
594         $datarray['commented']     = DateTimeFormat::utcNow();
595         $datarray['received']      = DateTimeFormat::utcNow();
596         $datarray['changed']       = DateTimeFormat::utcNow();
597         $datarray['extid']         = $extid;
598         $datarray['guid']          = $guid;
599         $datarray['uri']           = $uri;
600         $datarray['title']         = $title;
601         $datarray['body']          = $body;
602         $datarray['app']           = $app;
603         $datarray['location']      = $location;
604         $datarray['coord']         = $coord;
605         $datarray['tag']           = $str_tags;
606         $datarray['file']          = $categories;
607         $datarray['inform']        = $inform;
608         $datarray['verb']          = $verb;
609         $datarray['post-type']     = $posttype;
610         $datarray['object-type']   = $objecttype;
611         $datarray['allow_cid']     = $str_contact_allow;
612         $datarray['allow_gid']     = $str_group_allow;
613         $datarray['deny_cid']      = $str_contact_deny;
614         $datarray['deny_gid']      = $str_group_deny;
615         $datarray['private']       = $private;
616         $datarray['pubmail']       = $pubmail_enabled;
617         $datarray['attach']        = $attachments;
618
619         // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
620         $datarray['parent-uri']    = $thr_parent_uri;
621
622         $datarray['postopts']      = $postopts;
623         $datarray['origin']        = $origin;
624         $datarray['moderated']     = false;
625         $datarray['object']        = $object;
626
627         /*
628          * These fields are for the convenience of addons...
629          * 'self' if true indicates the owner is posting on their own wall
630          * If parent is 0 it is a top-level post.
631          */
632         $datarray['parent']        = $toplevel_item_id;
633         $datarray['self']          = $self;
634
635         // This triggers posts via API and the mirror functions
636         $datarray['api_source'] = $api_source;
637
638         // This field is for storing the raw conversation data
639         $datarray['protocol'] = Conversation::PARCEL_DFRN;
640
641         $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
642         if (DBA::isResult($conversation)) {
643                 if ($conversation['conversation-uri'] != '') {
644                         $datarray['conversation-uri'] = $conversation['conversation-uri'];
645                 }
646                 if ($conversation['conversation-href'] != '') {
647                         $datarray['conversation-href'] = $conversation['conversation-href'];
648                 }
649         }
650
651         if ($orig_post) {
652                 $datarray['edit'] = true;
653         } else {
654                 $datarray['edit'] = false;
655         }
656
657         // Check for hashtags in the body and repair or add hashtag links
658         if ($preview || $orig_post) {
659                 Item::setHashtags($datarray);
660         }
661
662         // preview mode - prepare the body for display and send it via json
663         if ($preview) {
664                 // We set the datarray ID to -1 because in preview mode the dataray
665                 // doesn't have an ID.
666                 $datarray["id"] = -1;
667                 $datarray["item_id"] = -1;
668                 $datarray["author-network"] = Protocol::DFRN;
669
670                 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
671                 Logger::log('preview: ' . $o);
672                 echo json_encode(['preview' => $o]);
673                 exit();
674         }
675
676         Hook::callAll('post_local',$datarray);
677
678         if (!empty($datarray['cancel'])) {
679                 Logger::log('mod_item: post cancelled by addon.');
680                 if ($return_path) {
681                         $a->internalRedirect($return_path);
682                 }
683
684                 $json = ['cancel' => 1];
685                 if (!empty($_REQUEST['jsreload'])) {
686                         $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
687                 }
688
689                 echo json_encode($json);
690                 exit();
691         }
692
693         if ($orig_post) {
694                 // Fill the cache field
695                 // This could be done in Item::update as well - but we have to check for the existance of some fields.
696                 Item::putInCache($datarray);
697
698                 $fields = [
699                         'title' => $datarray['title'],
700                         'body' => $datarray['body'],
701                         'tag' => $datarray['tag'],
702                         'attach' => $datarray['attach'],
703                         'file' => $datarray['file'],
704                         'rendered-html' => $datarray['rendered-html'],
705                         'rendered-hash' => $datarray['rendered-hash'],
706                         'edited' => DateTimeFormat::utcNow(),
707                         'changed' => DateTimeFormat::utcNow()];
708
709                 Item::update($fields, ['id' => $post_id]);
710
711                 // update filetags in pconfig
712                 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
713
714                 if (!empty($_REQUEST['return']) && strlen($return_path)) {
715                         Logger::log('return: ' . $return_path);
716                         $a->internalRedirect($return_path);
717                 }
718                 exit();
719         }
720
721         unset($datarray['edit']);
722         unset($datarray['self']);
723         unset($datarray['api_source']);
724
725         if ($origin) {
726                 $signed = Diaspora::createCommentSignature($uid, $datarray);
727                 if (!empty($signed)) {
728                         $datarray['diaspora_signed_text'] = json_encode($signed);
729                 }
730         }
731
732         $post_id = Item::insert($datarray);
733
734         if (!$post_id) {
735                 Logger::log("Item wasn't stored.");
736                 $a->internalRedirect($return_path);
737         }
738
739         $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
740
741         if (!DBA::isResult($datarray)) {
742                 Logger::log("Item with id ".$post_id." couldn't be fetched.");
743                 $a->internalRedirect($return_path);
744         }
745
746         // update filetags in pconfig
747         FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
748
749         // These notifications are sent if someone else is commenting other your wall
750         if ($toplevel_item_id) {
751                 if ($contact_record != $author) {
752                         notification([
753                                 'type'         => NOTIFY_COMMENT,
754                                 'notify_flags' => $user['notify-flags'],
755                                 'language'     => $user['language'],
756                                 'to_name'      => $user['username'],
757                                 'to_email'     => $user['email'],
758                                 'uid'          => $user['uid'],
759                                 'item'         => $datarray,
760                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
761                                 'source_name'  => $datarray['author-name'],
762                                 'source_link'  => $datarray['author-link'],
763                                 'source_photo' => $datarray['author-avatar'],
764                                 'verb'         => ACTIVITY_POST,
765                                 'otype'        => 'item',
766                                 'parent'       => $toplevel_item_id,
767                                 'parent_uri'   => $toplevel_item['uri']
768                         ]);
769                 }
770         } else {
771                 if (($contact_record != $author) && !count($forum_contact)) {
772                         notification([
773                                 'type'         => NOTIFY_WALL,
774                                 'notify_flags' => $user['notify-flags'],
775                                 'language'     => $user['language'],
776                                 'to_name'      => $user['username'],
777                                 'to_email'     => $user['email'],
778                                 'uid'          => $user['uid'],
779                                 'item'         => $datarray,
780                                 'link'         => System::baseUrl().'/display/'.urlencode($datarray['guid']),
781                                 'source_name'  => $datarray['author-name'],
782                                 'source_link'  => $datarray['author-link'],
783                                 'source_photo' => $datarray['author-avatar'],
784                                 'verb'         => ACTIVITY_POST,
785                                 'otype'        => 'item'
786                         ]);
787                 }
788         }
789
790         Hook::callAll('post_local_end', $datarray);
791
792         if (strlen($emailcc) && $profile_uid == local_user()) {
793                 $erecips = explode(',', $emailcc);
794                 if (count($erecips)) {
795                         foreach ($erecips as $recip) {
796                                 $addr = trim($recip);
797                                 if (!strlen($addr)) {
798                                         continue;
799                                 }
800                                 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
801                                         . '<br />';
802                                 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
803                                 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
804                                 if (!$datarray['title']=='') {
805                                         $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
806                                 } else {
807                                         $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
808                                 }
809                                 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
810                                 $html    = Item::prepareBody($datarray);
811                                 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
812                                 $params =  [
813                                         'fromName' => $a->user['username'],
814                                         'fromEmail' => $a->user['email'],
815                                         'toEmail' => $addr,
816                                         'replyTo' => $a->user['email'],
817                                         'messageSubject' => $subject,
818                                         'htmlVersion' => $message,
819                                         'textVersion' => HTML::toPlaintext($html.$disclaimer)
820                                 ];
821                                 Emailer::send($params);
822                         }
823                 }
824         }
825
826         // Insert an item entry for UID=0 for global entries.
827         // We now do it in the background to save some time.
828         // This is important in interactive environments like the frontend or the API.
829         // We don't fork a new process since this is done anyway with the following command
830         Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
831
832         // When we are doing some forum posting via ! we have to start the notifier manually.
833         // These kind of posts don't initiate the notifier call in the item class.
834         if ($only_to_forum) {
835                 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => false], "Notifier", Delivery::POST, $post_id);
836         }
837
838         Logger::log('post_complete');
839
840         if ($api_source) {
841                 return $post_id;
842         }
843
844         item_post_return(System::baseUrl(), $api_source, $return_path);
845         // NOTREACHED
846 }
847
848 function item_post_return($baseurl, $api_source, $return_path)
849 {
850         // figure out how to return, depending on from whence we came
851     $a = \get_app();
852
853         if ($api_source) {
854                 return;
855         }
856
857         if ($return_path) {
858                 $a->internalRedirect($return_path);
859         }
860
861         $json = ['success' => 1];
862         if (!empty($_REQUEST['jsreload'])) {
863                 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
864         }
865
866         Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
867
868         echo json_encode($json);
869         exit();
870 }
871
872 function item_content(App $a)
873 {
874         if (!Session::isAuthenticated()) {
875                 return;
876         }
877
878         $o = '';
879
880         if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
881                 if ($a->isAjax()) {
882                         $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
883                 } else {
884                         if (!empty($a->argv[3])) {
885                                 $o = drop_item($a->argv[2], $a->argv[3]);
886                         }
887                         else {
888                                 $o = drop_item($a->argv[2]);
889                         }
890                 }
891
892                 if ($a->isAjax()) {
893                         // ajax return: [<item id>, 0 (no perm) | <owner id>]
894                         echo json_encode([intval($a->argv[2]), intval($o)]);
895                         exit();
896                 }
897         }
898
899         return $o;
900 }
901
902 /**
903  * This function removes the tag $tag from the text $body and replaces it with
904  * the appropriate link.
905  *
906  * @param App     $a
907  * @param string  $body     the text to replace the tag in
908  * @param string  $inform   a comma-seperated string containing everybody to inform
909  * @param string  $str_tags string to add the tag to
910  * @param integer $profile_uid
911  * @param string  $tag      the tag to replace
912  * @param string  $network  The network of the post
913  *
914  * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
915  * @throws ImagickException
916  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
917  */
918 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
919 {
920         $replaced = false;
921         $r = null;
922
923         //is it a person tag?
924         if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
925                 $tag_type = substr($tag, 0, 1);
926                 //is it already replaced?
927                 if (strpos($tag, '[url=')) {
928                         //append tag to str_tags
929                         if (!stristr($str_tags, $tag)) {
930                                 if (strlen($str_tags)) {
931                                         $str_tags .= ',';
932                                 }
933                                 $str_tags .= $tag;
934                         }
935
936                         // Checking for the alias that is used for OStatus
937                         $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
938                         if (preg_match($pattern, $tag, $matches)) {
939                                 $data = Contact::getDetailsByURL($matches[1]);
940
941                                 if ($data["alias"] != "") {
942                                         $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
943
944                                         if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
945                                                 if (strlen($str_tags)) {
946                                                         $str_tags .= ',';
947                                                 }
948
949                                                 $str_tags .= $newtag;
950                                         }
951                                 }
952                         }
953
954                         return $replaced;
955                 }
956
957                 //get the person's name
958                 $name = substr($tag, 1);
959
960                 // Sometimes the tag detection doesn't seem to work right
961                 // This is some workaround
962                 $nameparts = explode(" ", $name);
963                 $name = $nameparts[0];
964
965                 // Try to detect the contact in various ways
966                 if (strpos($name, 'http://')) {
967                         // At first we have to ensure that the contact exists
968                         Contact::getIdForURL($name);
969
970                         // Now we should have something
971                         $contact = Contact::getDetailsByURL($name);
972                 } elseif (strpos($name, '@')) {
973                         // This function automatically probes when no entry was found
974                         $contact = Contact::getDetailsByAddr($name);
975                 } else {
976                         $contact = false;
977                         $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
978
979                         if (strrpos($name, '+')) {
980                                 // Is it in format @nick+number?
981                                 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
982                                 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
983                         }
984
985                         // select someone by nick or attag in the current network
986                         if (!DBA::isResult($contact) && ($network != "")) {
987                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
988                                                 $name, $name, $network, $profile_uid];
989                                 $contact = DBA::selectFirst('contact', $fields, $condition);
990                         }
991
992                         //select someone by name in the current network
993                         if (!DBA::isResult($contact) && ($network != "")) {
994                                 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
995                                 $contact = DBA::selectFirst('contact', $fields, $condition);
996                         }
997
998                         // select someone by nick or attag in any network
999                         if (!DBA::isResult($contact)) {
1000                                 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1001                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1002                         }
1003
1004                         // select someone by name in any network
1005                         if (!DBA::isResult($contact)) {
1006                                 $condition = ['name' => $name, 'uid' => $profile_uid];
1007                                 $contact = DBA::selectFirst('contact', $fields, $condition);
1008                         }
1009                 }
1010
1011                 // Check if $contact has been successfully loaded
1012                 if (DBA::isResult($contact)) {
1013                         if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1014                                 $inform .= ',';
1015                         }
1016
1017                         if (isset($contact["id"])) {
1018                                 $inform .= 'cid:' . $contact["id"];
1019                         } elseif (isset($contact["notify"])) {
1020                                 $inform  .= $contact["notify"];
1021                         }
1022
1023                         $profile = $contact["url"];
1024                         $alias   = $contact["alias"];
1025                         $newname = ($contact["name"] ?? '') ?: $contact["nick"];
1026                 }
1027
1028                 //if there is an url for this persons profile
1029                 if (isset($profile) && ($newname != "")) {
1030                         $replaced = true;
1031                         // create profile link
1032                         $profile = str_replace(',', '%2c', $profile);
1033                         $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1034                         $body = str_replace($tag_type . $name, $newtag, $body);
1035                         // append tag to str_tags
1036                         if (!stristr($str_tags, $newtag)) {
1037                                 if (strlen($str_tags)) {
1038                                         $str_tags .= ',';
1039                                 }
1040                                 $str_tags .= $newtag;
1041                         }
1042
1043                         /*
1044                          * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1045                          * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1046                          */
1047                         if (!empty($alias)) {
1048                                 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1049                                 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1050                                         if (strlen($str_tags)) {
1051                                                 $str_tags .= ',';
1052                                         }
1053                                         $str_tags .= $newtag;
1054                                 }
1055                         }
1056                 }
1057         }
1058
1059         return ['replaced' => $replaced, 'contact' => $contact];
1060 }
1061
1062 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1063 {
1064         if (Config::get('system', 'disable_implicit_mentions')) {
1065                 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1066                 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1067                         $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1068                         if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1069                                 $tags[] = $contact;
1070                         }
1071                 }
1072         } else {
1073                 $implicit_mentions = [
1074                         $thread_parent_contact['url'] => $thread_parent_contact['nick']
1075                 ];
1076
1077                 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1078
1079                 foreach ($parent_terms as $parent_term) {
1080                         $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1081                 }
1082
1083                 foreach ($implicit_mentions as $url => $label) {
1084                         if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1085                                 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';
1086                         }
1087                 }
1088         }
1089
1090         return $tags;
1091 }