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