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