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\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 use Friendica\Worker\Delivery;
45 require_once 'include/items.php';
47 function item_post(App $a) {
48 if (!local_user() && !remote_user()) {
54 if (!empty($_REQUEST['dropitems'])) {
55 $arr_drop = explode(',', $_REQUEST['dropitems']);
56 drop_items($arr_drop);
57 $json = ['success' => 1];
58 echo json_encode($json);
62 Hook::callAll('post_local_start', $_REQUEST);
64 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
66 $api_source = defaults($_REQUEST, 'api_source', false);
68 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
70 $return_path = defaults($_REQUEST, 'return', '');
71 $preview = intval(defaults($_REQUEST, 'preview', 0));
74 * Check for doubly-submitted posts, and reject duplicates
75 * Note that we have to ignore previews, otherwise nothing will post
76 * after it's been previewed
78 if (!$preview && !empty($_REQUEST['post_id_random'])) {
79 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
80 Logger::log("item post: duplicate post", Logger::DEBUG);
81 item_post_return(System::baseUrl(), $api_source, $return_path);
83 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
87 // Is this a reply to something?
88 $toplevel_item_id = intval(defaults($_REQUEST, 'parent', 0));
89 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
91 $thread_parent_id = 0;
92 $thread_parent_contact = null;
94 $toplevel_item = null;
97 $parent_contact = null;
100 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
101 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
103 if ($toplevel_item_id || $thr_parent_uri) {
104 if ($toplevel_item_id) {
105 $toplevel_item = Item::selectFirst([], ['id' => $toplevel_item_id]);
106 } elseif ($thr_parent_uri) {
107 $toplevel_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
110 // if this isn't the top-level parent of the conversation, find it
111 if (DBA::isResult($toplevel_item)) {
112 // The URI and the contact is taken from the direct parent which needn't to be the top parent
113 $thread_parent_id = $toplevel_item['id'];
114 $thr_parent_uri = $toplevel_item['uri'];
115 $thread_parent_contact = Contact::getDetailsByURL($toplevel_item["author-link"]);
117 if ($toplevel_item['id'] != $toplevel_item['parent']) {
118 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
122 if (!DBA::isResult($toplevel_item)) {
123 notice(L10n::t('Unable to locate original post.') . EOL);
124 if (!empty($_REQUEST['return'])) {
125 $a->internalRedirect($return_path);
130 $toplevel_item_id = $toplevel_item['id'];
131 $parent_user = $toplevel_item['uid'];
133 $objecttype = ACTIVITY_OBJ_COMMENT;
136 if ($toplevel_item_id) {
137 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
140 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
141 $app = strip_tags(defaults($_REQUEST, 'source', ''));
142 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
143 $object = defaults($_REQUEST, 'object', '');
145 // Don't use "defaults" here. It would turn 0 to 1
146 if (!isset($_REQUEST['wall'])) {
149 $wall = $_REQUEST['wall'];
152 // Ensure that the user id in a thread always stay the same
153 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
154 $profile_uid = $parent_user;
157 // Check for multiple posts with the same message id (when the post was created via API)
158 if (($message_id != '') && ($profile_uid != 0)) {
159 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
160 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
165 // Allow commenting if it is an answer to a public post
166 $allow_comment = local_user() && ($profile_uid == 0) && $toplevel_item_id && in_array($toplevel_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
168 // Now check that valid personal details have been provided
169 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
170 notice(L10n::t('Permission denied.') . EOL);
172 if (!empty($_REQUEST['return'])) {
173 $a->internalRedirect($return_path);
179 // Init post instance
182 // is this an edited post?
184 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
187 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
189 if (!DBA::isResult($user) && !$toplevel_item_id) {
196 $body = defaults($_REQUEST, 'body', '');
197 $has_attachment = defaults($_REQUEST, 'has_attachment', 0);
199 // If we have a speparate attachment, we need to add it to the body.
200 if (!empty($has_attachment)) {
201 $attachment_type = defaults($_REQUEST, 'attachment_type', '');
202 $attachment_title = defaults($_REQUEST, 'attachment_title', '');
203 $attachment_text = defaults($_REQUEST, 'attachment_text', '');
205 $attachment_url = hex2bin(defaults($_REQUEST, 'attachment_url', ''));
206 $attachment_img_src = hex2bin(defaults($_REQUEST, 'attachment_img_src', ''));
208 $attachment_img_width = defaults($_REQUEST, 'attachment_img_width', 0);
209 $attachment_img_height = defaults($_REQUEST, 'attachment_img_height', 0);
211 'type' => $attachment_type,
212 'title' => $attachment_title,
213 'text' => $attachment_text,
214 'url' => $attachment_url,
217 if (!empty($attachment_img_src)) {
218 $attachment['images'] = [
220 'src' => $attachment_img_src,
221 'width' => $attachment_img_width,
222 'height' => $attachment_img_height
227 $att_bbcode = add_page_info_data($attachment);
228 $body .= $att_bbcode;
231 if (!empty($orig_post)) {
232 $str_group_allow = $orig_post['allow_gid'];
233 $str_contact_allow = $orig_post['allow_cid'];
234 $str_group_deny = $orig_post['deny_gid'];
235 $str_contact_deny = $orig_post['deny_cid'];
236 $location = $orig_post['location'];
237 $coord = $orig_post['coord'];
238 $verb = $orig_post['verb'];
239 $objecttype = $orig_post['object-type'];
240 $app = $orig_post['app'];
241 $categories = $orig_post['file'];
242 $title = Strings::escapeTags(trim($_REQUEST['title']));
243 $body = Strings::escapeHtml(trim($body));
244 $private = $orig_post['private'];
245 $pubmail_enabled = $orig_post['pubmail'];
246 $network = $orig_post['network'];
247 $guid = $orig_post['guid'];
248 $extid = $orig_post['extid'];
253 * if coming from the API and no privacy settings are set,
254 * use the user default permissions - as they won't have
255 * been supplied via a form.
258 && !array_key_exists('contact_allow', $_REQUEST)
259 && !array_key_exists('group_allow', $_REQUEST)
260 && !array_key_exists('contact_deny', $_REQUEST)
261 && !array_key_exists('group_deny', $_REQUEST)) {
262 $str_group_allow = $user['allow_gid'];
263 $str_contact_allow = $user['allow_cid'];
264 $str_group_deny = $user['deny_gid'];
265 $str_contact_deny = $user['deny_cid'];
267 // use the posted permissions
268 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
269 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
270 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
271 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
274 $title = Strings::escapeTags(trim(defaults($_REQUEST, 'title' , '')));
275 $location = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
276 $coord = Strings::escapeTags(trim(defaults($_REQUEST, 'coord' , '')));
277 $verb = Strings::escapeTags(trim(defaults($_REQUEST, 'verb' , '')));
278 $emailcc = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
279 $body = Strings::escapeHtml(trim($body));
280 $network = Strings::escapeTags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
281 $guid = System::createUUID();
283 $postopts = defaults($_REQUEST, 'postopts', '');
285 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
287 if ($user['hidewall']) {
291 // If this is a comment, set the permissions from the parent.
293 if ($toplevel_item) {
294 // for non native networks use the network of the original post as network of the item
295 if (($toplevel_item['network'] != Protocol::DIASPORA)
296 && ($toplevel_item['network'] != Protocol::OSTATUS)
297 && ($network == "")) {
298 $network = $toplevel_item['network'];
301 $str_contact_allow = $toplevel_item['allow_cid'];
302 $str_group_allow = $toplevel_item['allow_gid'];
303 $str_contact_deny = $toplevel_item['deny_cid'];
304 $str_group_deny = $toplevel_item['deny_gid'];
305 $private = $toplevel_item['private'];
307 $wall = $toplevel_item['wall'];
310 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
312 // if using the API, we won't see pubmail_enable - figure out if it should be set
313 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
314 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
315 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
319 if (!strlen($body)) {
323 info(L10n::t('Empty post discarded.') . EOL);
324 if (!empty($_REQUEST['return'])) {
325 $a->internalRedirect($return_path);
331 if (!empty($categories)) {
332 // get the "fileas" tags for this post
333 $filedas = FileTag::fileToArray($categories);
336 // save old and new categories, so we can determine what needs to be deleted from pconfig
337 $categories_old = $categories;
338 $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
339 $categories_new = $categories;
341 if (!empty($filedas) && is_array($filedas)) {
342 // append the fileas stuff to the new categories list
343 $categories .= FileTag::arrayToFile($filedas);
346 // get contact info for poster
352 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
354 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
355 } elseif (remote_user()) {
356 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
357 foreach ($_SESSION['remote'] as $v) {
358 if ($v['uid'] == $profile_uid) {
359 $contact_id = $v['cid'];
365 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
369 if (DBA::isResult($author)) {
370 $contact_id = $author['id'];
373 // get contact info for owner
374 if ($profile_uid == local_user() || $allow_comment) {
375 $contact_record = $author;
377 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
380 // Look for any tags and linkify them
384 $tags = BBCode::getTags($body);
386 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
387 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
392 $private_forum = false;
393 $only_to_forum = false;
397 foreach ($tags as $tag) {
398 $tag_type = substr($tag, 0, 1);
400 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
405 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
406 * Robert Johnson should be first in the $tags array
408 $fullnametagged = false;
409 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
410 foreach ($tagged as $nextTag) {
411 if (stristr($nextTag, $tag . ' ')) {
412 $fullnametagged = true;
416 if ($fullnametagged) {
420 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
421 if ($success['replaced']) {
424 // When the forum is private or the forum is addressed with a "!" make the post private
425 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
426 $private_forum = $success['contact']['prv'];
427 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
428 $private_id = $success['contact']['id'];
429 $forum_contact = $success['contact'];
430 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
431 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
432 $private_forum = false;
433 $only_to_forum = true;
434 $private_id = $success['contact']['id'];
435 $forum_contact = $success['contact'];
440 $original_contact_id = $contact_id;
442 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
443 // we tagged a forum in a top level post. Now we change the post
444 $private = $private_forum;
446 $str_group_allow = '';
447 $str_contact_deny = '';
448 $str_group_deny = '';
449 if ($private_forum) {
450 $str_contact_allow = '<' . $private_id . '>';
452 $str_contact_allow = '';
454 $contact_id = $private_id;
455 $contact_record = $forum_contact;
456 $_REQUEST['origin'] = false;
461 * When a photo was uploaded into the message using the (profile wall) ajax
462 * uploader, The permissions are initially set to disallow anybody but the
463 * owner from seeing it. This is because the permissions may not yet have been
464 * set for the post. If it's private, the photo permissions should be set
465 * appropriately. But we didn't know the final permissions on the post until
466 * now. So now we'll look for links of uploaded messages that are in the
467 * post and set them to the same permissions as the post itself.
472 /// @todo these lines should be moved to Model/Photo
473 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
475 if (count($images)) {
477 $objecttype = ACTIVITY_OBJ_IMAGE;
479 foreach ($images as $image) {
480 if (!stristr($image, System::baseUrl() . '/photo/')) {
483 $image_uri = substr($image,strrpos($image,'/') + 1);
484 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
485 if (!strlen($image_uri)) {
489 // Ensure to only modify photos that you own
490 $srch = '<' . intval($original_contact_id) . '>';
493 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
494 'resource-id' => $image_uri, 'uid' => $profile_uid
496 if (!Photo::exists($condition)) {
500 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
501 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
502 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
503 Photo::update($fields, $condition);
510 * Next link in any attachment references we find in the post.
514 /// @todo these lines should be moved to Model/Attach (Once it exists)
515 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
516 $attaches = $match[1];
517 if (count($attaches)) {
518 foreach ($attaches as $attach) {
519 // Ensure to only modify attachments that you own
520 $srch = '<' . intval($original_contact_id) . '>';
522 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
524 if (!Attach::exists($condition)) {
528 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
529 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
530 $condition = ['id' => $attach];
531 Attach::update($fields, $condition);
536 // embedded bookmark or attachment in post? set bookmark flag
538 $data = BBCode::getAttachmentData($body);
539 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
540 && ($posttype != Item::PT_PERSONAL_NOTE)) {
541 $posttype = Item::PT_PAGE;
542 $objecttype = ACTIVITY_OBJ_BOOKMARK;
545 $body = bb_translate_video($body);
548 // Fold multi-line [code] sequences
549 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
551 $body = BBCode::scaleExternalImages($body, false);
553 // Setting the object type if not defined before
555 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
556 $objectdata = BBCode::getAttachedData($body);
558 if ($objectdata["type"] == "link") {
559 $objecttype = ACTIVITY_OBJ_BOOKMARK;
560 } elseif ($objectdata["type"] == "video") {
561 $objecttype = ACTIVITY_OBJ_VIDEO;
562 } elseif ($objectdata["type"] == "photo") {
563 $objecttype = ACTIVITY_OBJ_IMAGE;
571 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
572 foreach ($match[2] as $mtch) {
573 $fields = ['id', 'filename', 'filesize', 'filetype'];
574 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
575 if ($attachment !== false) {
576 if (strlen($attachments)) {
579 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
580 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
581 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
583 $body = str_replace($match[1],'',$body);
587 if (!strlen($verb)) {
588 $verb = ACTIVITY_POST;
591 if ($network == "") {
592 $network = Protocol::DFRN;
595 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
597 // even if the post arrived via API we are considering that it
598 // originated on this site by default for determining relayability.
600 // Don't use "defaults" here. It would turn 0 to 1
601 if (!isset($_REQUEST['origin'])) {
604 $origin = $_REQUEST['origin'];
607 $notify_type = ($toplevel_item_id ? Delivery::COMMENT : Delivery::POST);
609 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
611 // Fallback so that we alway have a parent uri
612 if (!$thr_parent_uri || !$toplevel_item_id) {
613 $thr_parent_uri = $uri;
617 $datarray['uid'] = $profile_uid;
618 $datarray['wall'] = $wall;
619 $datarray['gravity'] = $gravity;
620 $datarray['network'] = $network;
621 $datarray['contact-id'] = $contact_id;
622 $datarray['owner-name'] = $contact_record['name'];
623 $datarray['owner-link'] = $contact_record['url'];
624 $datarray['owner-avatar'] = $contact_record['thumb'];
625 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
626 $datarray['author-name'] = $author['name'];
627 $datarray['author-link'] = $author['url'];
628 $datarray['author-avatar'] = $author['thumb'];
629 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
630 $datarray['created'] = DateTimeFormat::utcNow();
631 $datarray['edited'] = DateTimeFormat::utcNow();
632 $datarray['commented'] = DateTimeFormat::utcNow();
633 $datarray['received'] = DateTimeFormat::utcNow();
634 $datarray['changed'] = DateTimeFormat::utcNow();
635 $datarray['extid'] = $extid;
636 $datarray['guid'] = $guid;
637 $datarray['uri'] = $uri;
638 $datarray['title'] = $title;
639 $datarray['body'] = $body;
640 $datarray['app'] = $app;
641 $datarray['location'] = $location;
642 $datarray['coord'] = $coord;
643 $datarray['tag'] = $str_tags;
644 $datarray['file'] = $categories;
645 $datarray['inform'] = $inform;
646 $datarray['verb'] = $verb;
647 $datarray['post-type'] = $posttype;
648 $datarray['object-type'] = $objecttype;
649 $datarray['allow_cid'] = $str_contact_allow;
650 $datarray['allow_gid'] = $str_group_allow;
651 $datarray['deny_cid'] = $str_contact_deny;
652 $datarray['deny_gid'] = $str_group_deny;
653 $datarray['private'] = $private;
654 $datarray['pubmail'] = $pubmail_enabled;
655 $datarray['attach'] = $attachments;
657 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
658 $datarray['parent-uri'] = $thr_parent_uri;
660 $datarray['postopts'] = $postopts;
661 $datarray['origin'] = $origin;
662 $datarray['moderated'] = false;
663 $datarray['object'] = $object;
666 * These fields are for the convenience of addons...
667 * 'self' if true indicates the owner is posting on their own wall
668 * If parent is 0 it is a top-level post.
670 $datarray['parent'] = $toplevel_item_id;
671 $datarray['self'] = $self;
673 // This triggers posts via API and the mirror functions
674 $datarray['api_source'] = $api_source;
676 // This field is for storing the raw conversation data
677 $datarray['protocol'] = Conversation::PARCEL_DFRN;
679 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
680 if (DBA::isResult($conversation)) {
681 if ($conversation['conversation-uri'] != '') {
682 $datarray['conversation-uri'] = $conversation['conversation-uri'];
684 if ($conversation['conversation-href'] != '') {
685 $datarray['conversation-href'] = $conversation['conversation-href'];
690 $datarray['edit'] = true;
692 $datarray['edit'] = false;
695 // Check for hashtags in the body and repair or add hashtag links
696 if ($preview || $orig_post) {
697 Item::setHashtags($datarray);
700 // preview mode - prepare the body for display and send it via json
702 // We set the datarray ID to -1 because in preview mode the dataray
703 // doesn't have an ID.
704 $datarray["id"] = -1;
705 $datarray["item_id"] = -1;
706 $datarray["author-network"] = Protocol::DFRN;
708 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
709 Logger::log('preview: ' . $o);
710 echo json_encode(['preview' => $o]);
714 Hook::callAll('post_local',$datarray);
716 if (!empty($datarray['cancel'])) {
717 Logger::log('mod_item: post cancelled by addon.');
719 $a->internalRedirect($return_path);
722 $json = ['cancel' => 1];
723 if (!empty($_REQUEST['jsreload'])) {
724 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
727 echo json_encode($json);
732 // Fill the cache field
733 // This could be done in Item::update as well - but we have to check for the existance of some fields.
734 Item::putInCache($datarray);
737 'title' => $datarray['title'],
738 'body' => $datarray['body'],
739 'tag' => $datarray['tag'],
740 'attach' => $datarray['attach'],
741 'file' => $datarray['file'],
742 'rendered-html' => $datarray['rendered-html'],
743 'rendered-hash' => $datarray['rendered-hash'],
744 'edited' => DateTimeFormat::utcNow(),
745 'changed' => DateTimeFormat::utcNow()];
747 Item::update($fields, ['id' => $post_id]);
749 // update filetags in pconfig
750 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
752 if (!empty($_REQUEST['return']) && strlen($return_path)) {
753 Logger::log('return: ' . $return_path);
754 $a->internalRedirect($return_path);
759 unset($datarray['edit']);
760 unset($datarray['self']);
761 unset($datarray['api_source']);
764 $signed = Diaspora::createCommentSignature($uid, $datarray);
765 if (!empty($signed)) {
766 $datarray['diaspora_signed_text'] = json_encode($signed);
770 $post_id = Item::insert($datarray);
773 Logger::log("Item wasn't stored.");
774 $a->internalRedirect($return_path);
777 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
779 if (!DBA::isResult($datarray)) {
780 Logger::log("Item with id ".$post_id." couldn't be fetched.");
781 $a->internalRedirect($return_path);
784 // update filetags in pconfig
785 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
787 // These notifications are sent if someone else is commenting other your wall
788 if ($toplevel_item_id) {
789 if ($contact_record != $author) {
791 'type' => NOTIFY_COMMENT,
792 'notify_flags' => $user['notify-flags'],
793 'language' => $user['language'],
794 'to_name' => $user['username'],
795 'to_email' => $user['email'],
796 'uid' => $user['uid'],
798 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
799 'source_name' => $datarray['author-name'],
800 'source_link' => $datarray['author-link'],
801 'source_photo' => $datarray['author-avatar'],
802 'verb' => ACTIVITY_POST,
804 'parent' => $toplevel_item_id,
805 'parent_uri' => $toplevel_item['uri']
809 if (($contact_record != $author) && !count($forum_contact)) {
811 'type' => NOTIFY_WALL,
812 'notify_flags' => $user['notify-flags'],
813 'language' => $user['language'],
814 'to_name' => $user['username'],
815 'to_email' => $user['email'],
816 'uid' => $user['uid'],
818 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
819 'source_name' => $datarray['author-name'],
820 'source_link' => $datarray['author-link'],
821 'source_photo' => $datarray['author-avatar'],
822 'verb' => ACTIVITY_POST,
828 Hook::callAll('post_local_end', $datarray);
830 if (strlen($emailcc) && $profile_uid == local_user()) {
831 $erecips = explode(',', $emailcc);
832 if (count($erecips)) {
833 foreach ($erecips as $recip) {
834 $addr = trim($recip);
835 if (!strlen($addr)) {
838 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
840 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
841 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
842 if (!$datarray['title']=='') {
843 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
845 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
847 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
848 $html = Item::prepareBody($datarray);
849 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
851 'fromName' => $a->user['username'],
852 'fromEmail' => $a->user['email'],
854 'replyTo' => $a->user['email'],
855 'messageSubject' => $subject,
856 'htmlVersion' => $message,
857 'textVersion' => HTML::toPlaintext($html.$disclaimer)
859 Emailer::send($params);
864 // Insert an item entry for UID=0 for global entries.
865 // We now do it in the background to save some time.
866 // This is important in interactive environments like the frontend or the API.
867 // We don't fork a new process since this is done anyway with the following command
868 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
870 // When we are doing some forum posting via ! we have to start the notifier manually.
871 // These kind of posts don't initiate the notifier call in the item class.
872 if ($only_to_forum) {
873 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
876 Logger::log('post_complete');
882 item_post_return(System::baseUrl(), $api_source, $return_path);
886 function item_post_return($baseurl, $api_source, $return_path)
888 // figure out how to return, depending on from whence we came
896 $a->internalRedirect($return_path);
899 $json = ['success' => 1];
900 if (!empty($_REQUEST['jsreload'])) {
901 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
904 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
906 echo json_encode($json);
910 function item_content(App $a)
912 if (!local_user() && !remote_user()) {
918 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
920 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
922 if (!empty($a->argv[3])) {
923 $o = drop_item($a->argv[2], $a->argv[3]);
926 $o = drop_item($a->argv[2]);
931 // ajax return: [<item id>, 0 (no perm) | <owner id>]
932 echo json_encode([intval($a->argv[2]), intval($o)]);
941 * This function removes the tag $tag from the text $body and replaces it with
942 * the appropriate link.
945 * @param string $body the text to replace the tag in
946 * @param string $inform a comma-seperated string containing everybody to inform
947 * @param string $str_tags string to add the tag to
948 * @param integer $profile_uid
949 * @param string $tag the tag to replace
950 * @param string $network The network of the post
952 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
953 * @throws ImagickException
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
956 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
961 //is it a person tag?
962 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
963 $tag_type = substr($tag, 0, 1);
964 //is it already replaced?
965 if (strpos($tag, '[url=')) {
966 //append tag to str_tags
967 if (!stristr($str_tags, $tag)) {
968 if (strlen($str_tags)) {
974 // Checking for the alias that is used for OStatus
975 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
976 if (preg_match($pattern, $tag, $matches)) {
977 $data = Contact::getDetailsByURL($matches[1]);
979 if ($data["alias"] != "") {
980 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
982 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
983 if (strlen($str_tags)) {
987 $str_tags .= $newtag;
995 //get the person's name
996 $name = substr($tag, 1);
998 // Sometimes the tag detection doesn't seem to work right
999 // This is some workaround
1000 $nameparts = explode(" ", $name);
1001 $name = $nameparts[0];
1003 // Try to detect the contact in various ways
1004 if (strpos($name, 'http://')) {
1005 // At first we have to ensure that the contact exists
1006 Contact::getIdForURL($name);
1008 // Now we should have something
1009 $contact = Contact::getDetailsByURL($name);
1010 } elseif (strpos($name, '@')) {
1011 // This function automatically probes when no entry was found
1012 $contact = Contact::getDetailsByAddr($name);
1015 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
1017 if (strrpos($name, '+')) {
1018 // Is it in format @nick+number?
1019 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1020 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
1023 // select someone by nick or attag in the current network
1024 if (!DBA::isResult($contact) && ($network != "")) {
1025 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
1026 $name, $name, $network, $profile_uid];
1027 $contact = DBA::selectFirst('contact', $fields, $condition);
1030 //select someone by name in the current network
1031 if (!DBA::isResult($contact) && ($network != "")) {
1032 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1033 $contact = DBA::selectFirst('contact', $fields, $condition);
1036 // select someone by nick or attag in any network
1037 if (!DBA::isResult($contact)) {
1038 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1039 $contact = DBA::selectFirst('contact', $fields, $condition);
1042 // select someone by name in any network
1043 if (!DBA::isResult($contact)) {
1044 $condition = ['name' => $name, 'uid' => $profile_uid];
1045 $contact = DBA::selectFirst('contact', $fields, $condition);
1049 // Check if $contact has been successfully loaded
1050 if (DBA::isResult($contact)) {
1051 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1055 if (isset($contact["id"])) {
1056 $inform .= 'cid:' . $contact["id"];
1057 } elseif (isset($contact["notify"])) {
1058 $inform .= $contact["notify"];
1061 $profile = $contact["url"];
1062 $alias = $contact["alias"];
1063 $newname = defaults($contact, "name", $contact["nick"]);
1066 //if there is an url for this persons profile
1067 if (isset($profile) && ($newname != "")) {
1069 // create profile link
1070 $profile = str_replace(',', '%2c', $profile);
1071 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1072 $body = str_replace($tag_type . $name, $newtag, $body);
1073 // append tag to str_tags
1074 if (!stristr($str_tags, $newtag)) {
1075 if (strlen($str_tags)) {
1078 $str_tags .= $newtag;
1082 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1083 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1085 if (!empty($alias)) {
1086 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1087 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1088 if (strlen($str_tags)) {
1091 $str_tags .= $newtag;
1097 return ['replaced' => $replaced, 'contact' => $contact];
1100 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1102 if (Config::get('system', 'disable_implicit_mentions')) {
1103 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1104 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1105 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1106 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1111 $implicit_mentions = [
1112 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1115 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1117 foreach ($parent_terms as $parent_term) {
1118 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1121 foreach ($implicit_mentions as $url => $label) {
1122 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1123 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';