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