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.
14 * All of these become an "item" which is our basic unit of
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\Session;
29 use Friendica\Core\Worker;
30 use Friendica\Database\DBA;
31 use Friendica\Model\Attach;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Conversation;
34 use Friendica\Model\FileTag;
35 use Friendica\Model\Item;
36 use Friendica\Model\Photo;
37 use Friendica\Model\Term;
38 use Friendica\Protocol\Diaspora;
39 use Friendica\Protocol\Email;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Emailer;
42 use Friendica\Util\Security;
43 use Friendica\Util\Strings;
44 use Friendica\Worker\Delivery;
46 require_once __DIR__ . '/../include/items.php';
48 function item_post(App $a) {
49 if (!Session::isAuthenticated()) {
55 if (!empty($_REQUEST['dropitems'])) {
56 $arr_drop = explode(',', $_REQUEST['dropitems']);
57 drop_items($arr_drop);
58 $json = ['success' => 1];
59 echo json_encode($json);
63 Hook::callAll('post_local_start', $_REQUEST);
65 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
67 $api_source = defaults($_REQUEST, 'api_source', false);
69 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
71 $return_path = defaults($_REQUEST, 'return', '');
72 $preview = intval(defaults($_REQUEST, 'preview', 0));
75 * Check for doubly-submitted posts, and reject duplicates
76 * Note that we have to ignore previews, otherwise nothing will post
77 * after it's been previewed
79 if (!$preview && !empty($_REQUEST['post_id_random'])) {
80 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
81 Logger::log("item post: duplicate post", Logger::DEBUG);
82 item_post_return(System::baseUrl(), $api_source, $return_path);
84 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
88 // Is this a reply to something?
89 $toplevel_item_id = intval(defaults($_REQUEST, 'parent', 0));
90 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
92 $thread_parent_id = 0;
93 $thread_parent_contact = null;
95 $toplevel_item = null;
98 $parent_contact = null;
101 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
102 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
104 if ($toplevel_item_id || $thr_parent_uri) {
105 if ($toplevel_item_id) {
106 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
107 } elseif ($thr_parent_uri) {
108 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
111 // if this isn't the top-level parent of the conversation, find it
112 if (DBA::isResult($toplevel_item)) {
113 // The URI and the contact is taken from the direct parent which needn't to be the top parent
114 $thread_parent_id = $toplevel_item['id'];
115 $thr_parent_uri = $toplevel_item['uri'];
116 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
118 if ($toplevel_item['id'] != $toplevel_item['parent']) {
119 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
123 if (!DBA::isResult($toplevel_item)) {
124 notice(L10n::t('Unable to locate original post.') . EOL);
125 if (!empty($_REQUEST['return'])) {
126 $a->internalRedirect($return_path);
131 $toplevel_item_id = $toplevel_item['id'];
132 $parent_user = $toplevel_item['uid'];
134 $objecttype = ACTIVITY_OBJ_COMMENT;
137 if ($toplevel_item_id) {
138 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
141 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
142 $app = strip_tags(defaults($_REQUEST, 'source', ''));
143 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
144 $object = defaults($_REQUEST, 'object', '');
146 // Don't use "defaults" here. It would turn 0 to 1
147 if (!isset($_REQUEST['wall'])) {
150 $wall = $_REQUEST['wall'];
153 // Ensure that the user id in a thread always stay the same
154 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
155 $profile_uid = $parent_user;
158 // Check for multiple posts with the same message id (when the post was created via API)
159 if (($message_id != '') && ($profile_uid != 0)) {
160 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
161 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
166 // Allow commenting if it is an answer to a public post
167 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], Protocol::FEDERATED);
169 // Now check that valid personal details have been provided
170 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
171 notice(L10n::t('Permission denied.') . EOL);
173 if (!empty($_REQUEST['return'])) {
174 $a->internalRedirect($return_path);
180 // Init post instance
183 // is this an edited post?
185 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
188 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
190 if (!DBA::isResult($user) && !$toplevel_item_id) {
197 $body = defaults($_REQUEST, 'body', '');
198 $has_attachment = defaults($_REQUEST, 'has_attachment', 0);
200 // If we have a speparate attachment, we need to add it to the body.
201 if (!empty($has_attachment)) {
202 $attachment_type = defaults($_REQUEST, 'attachment_type', '');
203 $attachment_title = defaults($_REQUEST, 'attachment_title', '');
204 $attachment_text = defaults($_REQUEST, 'attachment_text', '');
206 $attachment_url = hex2bin(defaults($_REQUEST, 'attachment_url', ''));
207 $attachment_img_src = hex2bin(defaults($_REQUEST, 'attachment_img_src', ''));
209 $attachment_img_width = defaults($_REQUEST, 'attachment_img_width', 0);
210 $attachment_img_height = defaults($_REQUEST, 'attachment_img_height', 0);
212 'type' => $attachment_type,
213 'title' => $attachment_title,
214 'text' => $attachment_text,
215 'url' => $attachment_url,
218 if (!empty($attachment_img_src)) {
219 $attachment['images'] = [
221 'src' => $attachment_img_src,
222 'width' => $attachment_img_width,
223 'height' => $attachment_img_height
228 $att_bbcode = add_page_info_data($attachment);
229 $body .= $att_bbcode;
232 if (!empty($orig_post)) {
233 $str_group_allow = $orig_post['allow_gid'];
234 $str_contact_allow = $orig_post['allow_cid'];
235 $str_group_deny = $orig_post['deny_gid'];
236 $str_contact_deny = $orig_post['deny_cid'];
237 $location = $orig_post['location'];
238 $coord = $orig_post['coord'];
239 $verb = $orig_post['verb'];
240 $objecttype = $orig_post['object-type'];
241 $app = $orig_post['app'];
242 $categories = $orig_post['file'];
243 $title = Strings::escapeTags(trim($_REQUEST['title']));
244 $body = Strings::escapeHtml(trim($body));
245 $private = $orig_post['private'];
246 $pubmail_enabled = $orig_post['pubmail'];
247 $network = $orig_post['network'];
248 $guid = $orig_post['guid'];
249 $extid = $orig_post['extid'];
254 * if coming from the API and no privacy settings are set,
255 * use the user default permissions - as they won't have
256 * been supplied via a form.
259 && !array_key_exists('contact_allow', $_REQUEST)
260 && !array_key_exists('group_allow', $_REQUEST)
261 && !array_key_exists('contact_deny', $_REQUEST)
262 && !array_key_exists('group_deny', $_REQUEST)) {
263 $str_group_allow = $user['allow_gid'];
264 $str_contact_allow = $user['allow_cid'];
265 $str_group_deny = $user['deny_gid'];
266 $str_contact_deny = $user['deny_cid'];
268 // use the posted permissions
269 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
270 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
271 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
272 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
275 $title = Strings::escapeTags(trim(defaults($_REQUEST, 'title' , '')));
276 $location = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
277 $coord = Strings::escapeTags(trim(defaults($_REQUEST, 'coord' , '')));
278 $verb = Strings::escapeTags(trim(defaults($_REQUEST, 'verb' , '')));
279 $emailcc = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
280 $body = Strings::escapeHtml(trim($body));
281 $network = Strings::escapeTags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
282 $guid = System::createUUID();
284 $postopts = defaults($_REQUEST, 'postopts', '');
286 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
288 // If this is a comment, set the permissions from the parent.
290 if ($toplevel_item) {
291 // for non native networks use the network of the original post as network of the item
292 if (($toplevel_item['network'] != Protocol::DIASPORA)
293 && ($toplevel_item['network'] != Protocol::OSTATUS)
294 && ($network == "")) {
295 $network = $toplevel_item['network'];
298 $str_contact_allow = $toplevel_item['allow_cid'];
299 $str_group_allow = $toplevel_item['allow_gid'];
300 $str_contact_deny = $toplevel_item['deny_cid'];
301 $str_group_deny = $toplevel_item['deny_gid'];
302 $private = $toplevel_item['private'];
304 $wall = $toplevel_item['wall'];
307 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
309 // if using the API, we won't see pubmail_enable - figure out if it should be set
310 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
311 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
312 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
316 if (!strlen($body)) {
320 info(L10n::t('Empty post discarded.') . EOL);
321 if (!empty($_REQUEST['return'])) {
322 $a->internalRedirect($return_path);
328 if (!empty($categories)) {
329 // get the "fileas" tags for this post
330 $filedas = FileTag::fileToArray($categories);
333 // save old and new categories, so we can determine what needs to be deleted from pconfig
334 $categories_old = $categories;
335 $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
336 $categories_new = $categories;
338 if (!empty($filedas) && is_array($filedas)) {
339 // append the fileas stuff to the new categories list
340 $categories .= FileTag::arrayToFile($filedas);
343 // get contact info for poster
349 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
351 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
352 } elseif (!empty(Session::getRemoteContactID($profile_uid))) {
353 $author = DBA::selectFirst('contact', [], ['id' => Session::getRemoteContactID($profile_uid)]);
356 if (DBA::isResult($author)) {
357 $contact_id = $author['id'];
360 // get contact info for owner
361 if ($profile_uid == local_user() || $allow_comment) {
362 $contact_record = $author;
364 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
367 // Look for any tags and linkify them
371 $tags = BBCode::getTags($body);
373 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
374 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
379 $private_forum = false;
380 $only_to_forum = false;
384 foreach ($tags as $tag) {
385 $tag_type = substr($tag, 0, 1);
387 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
392 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
393 * Robert Johnson should be first in the $tags array
395 $fullnametagged = false;
396 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
397 foreach ($tagged as $nextTag) {
398 if (stristr($nextTag, $tag . ' ')) {
399 $fullnametagged = true;
403 if ($fullnametagged) {
407 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
408 if ($success['replaced']) {
411 // When the forum is private or the forum is addressed with a "!" make the post private
412 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
413 $private_forum = $success['contact']['prv'];
414 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
415 $private_id = $success['contact']['id'];
416 $forum_contact = $success['contact'];
417 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
418 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
419 $private_forum = false;
420 $only_to_forum = true;
421 $private_id = $success['contact']['id'];
422 $forum_contact = $success['contact'];
427 $original_contact_id = $contact_id;
429 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
430 // we tagged a forum in a top level post. Now we change the post
431 $private = $private_forum;
433 $str_group_allow = '';
434 $str_contact_deny = '';
435 $str_group_deny = '';
436 if ($private_forum) {
437 $str_contact_allow = '<' . $private_id . '>';
439 $str_contact_allow = '';
441 $contact_id = $private_id;
442 $contact_record = $forum_contact;
443 $_REQUEST['origin'] = false;
448 * When a photo was uploaded into the message using the (profile wall) ajax
449 * uploader, The permissions are initially set to disallow anybody but the
450 * owner from seeing it. This is because the permissions may not yet have been
451 * set for the post. If it's private, the photo permissions should be set
452 * appropriately. But we didn't know the final permissions on the post until
453 * now. So now we'll look for links of uploaded messages that are in the
454 * post and set them to the same permissions as the post itself.
459 if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) {
460 $objecttype = ACTIVITY_OBJ_IMAGE;
464 * Next link in any attachment references we find in the post.
468 /// @todo these lines should be moved to Model/Attach (Once it exists)
469 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
470 $attaches = $match[1];
471 if (count($attaches)) {
472 foreach ($attaches as $attach) {
473 // Ensure to only modify attachments that you own
474 $srch = '<' . intval($original_contact_id) . '>';
476 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
478 if (!Attach::exists($condition)) {
482 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
483 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
484 $condition = ['id' => $attach];
485 Attach::update($fields, $condition);
490 // embedded bookmark or attachment in post? set bookmark flag
492 $data = BBCode::getAttachmentData($body);
493 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
494 && ($posttype != Item::PT_PERSONAL_NOTE)) {
495 $posttype = Item::PT_PAGE;
496 $objecttype = ACTIVITY_OBJ_BOOKMARK;
499 $body = bb_translate_video($body);
502 // Fold multi-line [code] sequences
503 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
505 $body = BBCode::scaleExternalImages($body, false);
507 // Setting the object type if not defined before
509 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
510 $objectdata = BBCode::getAttachedData($body);
512 if ($objectdata["type"] == "link") {
513 $objecttype = ACTIVITY_OBJ_BOOKMARK;
514 } elseif ($objectdata["type"] == "video") {
515 $objecttype = ACTIVITY_OBJ_VIDEO;
516 } elseif ($objectdata["type"] == "photo") {
517 $objecttype = ACTIVITY_OBJ_IMAGE;
525 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
526 foreach ($match[2] as $mtch) {
527 $fields = ['id', 'filename', 'filesize', 'filetype'];
528 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
529 if ($attachment !== false) {
530 if (strlen($attachments)) {
533 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
534 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
535 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
537 $body = str_replace($match[1],'',$body);
541 if (!strlen($verb)) {
542 $verb = ACTIVITY_POST;
545 if ($network == "") {
546 $network = Protocol::DFRN;
549 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
551 // even if the post arrived via API we are considering that it
552 // originated on this site by default for determining relayability.
554 // Don't use "defaults" here. It would turn 0 to 1
555 if (!isset($_REQUEST['origin'])) {
558 $origin = $_REQUEST['origin'];
561 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
563 // Fallback so that we alway have a parent uri
564 if (!$thr_parent_uri || !$toplevel_item_id) {
565 $thr_parent_uri = $uri;
569 $datarray['uid'] = $profile_uid;
570 $datarray['wall'] = $wall;
571 $datarray['gravity'] = $gravity;
572 $datarray['network'] = $network;
573 $datarray['contact-id'] = $contact_id;
574 $datarray['owner-name'] = $contact_record['name'];
575 $datarray['owner-link'] = $contact_record['url'];
576 $datarray['owner-avatar'] = $contact_record['thumb'];
577 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
578 $datarray['author-name'] = $author['name'];
579 $datarray['author-link'] = $author['url'];
580 $datarray['author-avatar'] = $author['thumb'];
581 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
582 $datarray['created'] = DateTimeFormat::utcNow();
583 $datarray['edited'] = DateTimeFormat::utcNow();
584 $datarray['commented'] = DateTimeFormat::utcNow();
585 $datarray['received'] = DateTimeFormat::utcNow();
586 $datarray['changed'] = DateTimeFormat::utcNow();
587 $datarray['extid'] = $extid;
588 $datarray['guid'] = $guid;
589 $datarray['uri'] = $uri;
590 $datarray['title'] = $title;
591 $datarray['body'] = $body;
592 $datarray['app'] = $app;
593 $datarray['location'] = $location;
594 $datarray['coord'] = $coord;
595 $datarray['tag'] = $str_tags;
596 $datarray['file'] = $categories;
597 $datarray['inform'] = $inform;
598 $datarray['verb'] = $verb;
599 $datarray['post-type'] = $posttype;
600 $datarray['object-type'] = $objecttype;
601 $datarray['allow_cid'] = $str_contact_allow;
602 $datarray['allow_gid'] = $str_group_allow;
603 $datarray['deny_cid'] = $str_contact_deny;
604 $datarray['deny_gid'] = $str_group_deny;
605 $datarray['private'] = $private;
606 $datarray['pubmail'] = $pubmail_enabled;
607 $datarray['attach'] = $attachments;
609 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
610 $datarray['parent-uri'] = $thr_parent_uri;
612 $datarray['postopts'] = $postopts;
613 $datarray['origin'] = $origin;
614 $datarray['moderated'] = false;
615 $datarray['object'] = $object;
618 * These fields are for the convenience of addons...
619 * 'self' if true indicates the owner is posting on their own wall
620 * If parent is 0 it is a top-level post.
622 $datarray['parent'] = $toplevel_item_id;
623 $datarray['self'] = $self;
625 // This triggers posts via API and the mirror functions
626 $datarray['api_source'] = $api_source;
628 // This field is for storing the raw conversation data
629 $datarray['protocol'] = Conversation::PARCEL_DFRN;
631 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
632 if (DBA::isResult($conversation)) {
633 if ($conversation['conversation-uri'] != '') {
634 $datarray['conversation-uri'] = $conversation['conversation-uri'];
636 if ($conversation['conversation-href'] != '') {
637 $datarray['conversation-href'] = $conversation['conversation-href'];
642 $datarray['edit'] = true;
644 $datarray['edit'] = false;
647 // Check for hashtags in the body and repair or add hashtag links
648 if ($preview || $orig_post) {
649 Item::setHashtags($datarray);
652 // preview mode - prepare the body for display and send it via json
654 // We set the datarray ID to -1 because in preview mode the dataray
655 // doesn't have an ID.
656 $datarray["id"] = -1;
657 $datarray["item_id"] = -1;
658 $datarray["author-network"] = Protocol::DFRN;
660 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
661 Logger::log('preview: ' . $o);
662 echo json_encode(['preview' => $o]);
666 Hook::callAll('post_local',$datarray);
668 if (!empty($datarray['cancel'])) {
669 Logger::log('mod_item: post cancelled by addon.');
671 $a->internalRedirect($return_path);
674 $json = ['cancel' => 1];
675 if (!empty($_REQUEST['jsreload'])) {
676 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
679 echo json_encode($json);
684 // Fill the cache field
685 // This could be done in Item::update as well - but we have to check for the existance of some fields.
686 Item::putInCache($datarray);
689 'title' => $datarray['title'],
690 'body' => $datarray['body'],
691 'tag' => $datarray['tag'],
692 'attach' => $datarray['attach'],
693 'file' => $datarray['file'],
694 'rendered-html' => $datarray['rendered-html'],
695 'rendered-hash' => $datarray['rendered-hash'],
696 'edited' => DateTimeFormat::utcNow(),
697 'changed' => DateTimeFormat::utcNow()];
699 Item::update($fields, ['id' => $post_id]);
701 // update filetags in pconfig
702 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
704 if (!empty($_REQUEST['return']) && strlen($return_path)) {
705 Logger::log('return: ' . $return_path);
706 $a->internalRedirect($return_path);
711 unset($datarray['edit']);
712 unset($datarray['self']);
713 unset($datarray['api_source']);
716 $signed = Diaspora::createCommentSignature($uid, $datarray);
717 if (!empty($signed)) {
718 $datarray['diaspora_signed_text'] = json_encode($signed);
722 $post_id = Item::insert($datarray);
725 Logger::log("Item wasn't stored.");
726 $a->internalRedirect($return_path);
729 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
731 if (!DBA::isResult($datarray)) {
732 Logger::log("Item with id ".$post_id." couldn't be fetched.");
733 $a->internalRedirect($return_path);
736 // update filetags in pconfig
737 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
739 // These notifications are sent if someone else is commenting other your wall
740 if ($toplevel_item_id) {
741 if ($contact_record != $author) {
743 'type' => NOTIFY_COMMENT,
744 'notify_flags' => $user['notify-flags'],
745 'language' => $user['language'],
746 'to_name' => $user['username'],
747 'to_email' => $user['email'],
748 'uid' => $user['uid'],
750 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
751 'source_name' => $datarray['author-name'],
752 'source_link' => $datarray['author-link'],
753 'source_photo' => $datarray['author-avatar'],
754 'verb' => ACTIVITY_POST,
756 'parent' => $toplevel_item_id,
757 'parent_uri' => $toplevel_item['uri']
761 if (($contact_record != $author) && !count($forum_contact)) {
763 'type' => NOTIFY_WALL,
764 'notify_flags' => $user['notify-flags'],
765 'language' => $user['language'],
766 'to_name' => $user['username'],
767 'to_email' => $user['email'],
768 'uid' => $user['uid'],
770 'link' => System::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,
780 Hook::callAll('post_local_end', $datarray);
782 if (strlen($emailcc) && $profile_uid == local_user()) {
783 $erecips = explode(',', $emailcc);
784 if (count($erecips)) {
785 foreach ($erecips as $recip) {
786 $addr = trim($recip);
787 if (!strlen($addr)) {
790 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
792 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
793 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
794 if (!$datarray['title']=='') {
795 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
797 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
799 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
800 $html = Item::prepareBody($datarray);
801 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
803 'fromName' => $a->user['username'],
804 'fromEmail' => $a->user['email'],
806 'replyTo' => $a->user['email'],
807 'messageSubject' => $subject,
808 'htmlVersion' => $message,
809 'textVersion' => HTML::toPlaintext($html.$disclaimer)
811 Emailer::send($params);
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);
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);
828 Logger::log('post_complete');
834 item_post_return(System::baseUrl(), $api_source, $return_path);
838 function item_post_return($baseurl, $api_source, $return_path)
840 // figure out how to return, depending on from whence we came
848 $a->internalRedirect($return_path);
851 $json = ['success' => 1];
852 if (!empty($_REQUEST['jsreload'])) {
853 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
856 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
858 echo json_encode($json);
862 function item_content(App $a)
864 if (!Session::isAuthenticated()) {
870 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
872 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
874 if (!empty($a->argv[3])) {
875 $o = drop_item($a->argv[2], $a->argv[3]);
878 $o = drop_item($a->argv[2]);
883 // ajax return: [<item id>, 0 (no perm) | <owner id>]
884 echo json_encode([intval($a->argv[2]), intval($o)]);
893 * This function removes the tag $tag from the text $body and replaces it with
894 * the appropriate link.
897 * @param string $body the text to replace the tag in
898 * @param string $inform a comma-seperated string containing everybody to inform
899 * @param string $str_tags string to add the tag to
900 * @param integer $profile_uid
901 * @param string $tag the tag to replace
902 * @param string $network The network of the post
904 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
905 * @throws ImagickException
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
913 //is it a person tag?
914 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
915 $tag_type = substr($tag, 0, 1);
916 //is it already replaced?
917 if (strpos($tag, '[url=')) {
918 //append tag to str_tags
919 if (!stristr($str_tags, $tag)) {
920 if (strlen($str_tags)) {
926 // Checking for the alias that is used for OStatus
927 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
928 if (preg_match($pattern, $tag, $matches)) {
929 $data = Contact::getDetailsByURL($matches[1]);
931 if ($data["alias"] != "") {
932 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
934 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
935 if (strlen($str_tags)) {
939 $str_tags .= $newtag;
947 //get the person's name
948 $name = substr($tag, 1);
950 // Sometimes the tag detection doesn't seem to work right
951 // This is some workaround
952 $nameparts = explode(" ", $name);
953 $name = $nameparts[0];
955 // Try to detect the contact in various ways
956 if (strpos($name, 'http://')) {
957 // At first we have to ensure that the contact exists
958 Contact::getIdForURL($name);
960 // Now we should have something
961 $contact = Contact::getDetailsByURL($name);
962 } elseif (strpos($name, '@')) {
963 // This function automatically probes when no entry was found
964 $contact = Contact::getDetailsByAddr($name);
967 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
969 if (strrpos($name, '+')) {
970 // Is it in format @nick+number?
971 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
972 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
975 // select someone by nick or attag in the current network
976 if (!DBA::isResult($contact) && ($network != "")) {
977 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
978 $name, $name, $network, $profile_uid];
979 $contact = DBA::selectFirst('contact', $fields, $condition);
982 //select someone by name in the current network
983 if (!DBA::isResult($contact) && ($network != "")) {
984 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
985 $contact = DBA::selectFirst('contact', $fields, $condition);
988 // select someone by nick or attag in any network
989 if (!DBA::isResult($contact)) {
990 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
991 $contact = DBA::selectFirst('contact', $fields, $condition);
994 // select someone by name in any network
995 if (!DBA::isResult($contact)) {
996 $condition = ['name' => $name, 'uid' => $profile_uid];
997 $contact = DBA::selectFirst('contact', $fields, $condition);
1001 // Check if $contact has been successfully loaded
1002 if (DBA::isResult($contact)) {
1003 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1007 if (isset($contact["id"])) {
1008 $inform .= 'cid:' . $contact["id"];
1009 } elseif (isset($contact["notify"])) {
1010 $inform .= $contact["notify"];
1013 $profile = $contact["url"];
1014 $alias = $contact["alias"];
1015 $newname = defaults($contact, "name", $contact["nick"]);
1018 //if there is an url for this persons profile
1019 if (isset($profile) && ($newname != "")) {
1021 // create profile link
1022 $profile = str_replace(',', '%2c', $profile);
1023 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1024 $body = str_replace($tag_type . $name, $newtag, $body);
1025 // append tag to str_tags
1026 if (!stristr($str_tags, $newtag)) {
1027 if (strlen($str_tags)) {
1030 $str_tags .= $newtag;
1034 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1035 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1037 if (!empty($alias)) {
1038 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1039 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1040 if (strlen($str_tags)) {
1043 $str_tags .= $newtag;
1049 return ['replaced' => $replaced, 'contact' => $contact];
1052 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1054 if (Config::get('system', 'disable_implicit_mentions')) {
1055 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1056 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1057 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1058 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1063 $implicit_mentions = [
1064 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1067 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1069 foreach ($parent_terms as $parent_term) {
1070 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1073 foreach ($implicit_mentions as $url => $label) {
1074 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1075 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';