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\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\FileTag;
33 use Friendica\Model\Item;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Attach;
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;
44 require_once 'include/items.php';
46 function item_post(App $a) {
47 if (!local_user() && !remote_user()) {
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);
61 Hook::callAll('post_local_start', $_REQUEST);
63 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
65 $api_source = defaults($_REQUEST, 'api_source', false);
67 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
69 $return_path = defaults($_REQUEST, 'return', '');
70 $preview = intval(defaults($_REQUEST, 'preview', 0));
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
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);
82 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
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', ''));
90 $thread_parent_id = 0;
91 $thread_parent_contact = null;
93 $toplevel_item = null;
96 $parent_contact = null;
99 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
100 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
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]);
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"]);
116 if ($toplevel_item['id'] != $toplevel_item['parent']) {
117 $toplevel_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $toplevel_item['parent']]);
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);
129 $toplevel_item_id = $toplevel_item['id'];
130 $parent_user = $toplevel_item['uid'];
132 $objecttype = ACTIVITY_OBJ_COMMENT;
135 if ($toplevel_item_id) {
136 Logger::info('mod_item: item_post parent=' . $toplevel_item_id);
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', '');
144 // Don't use "defaults" here. It would turn 0 to 1
145 if (!isset($_REQUEST['wall'])) {
148 $wall = $_REQUEST['wall'];
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;
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);
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]);
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);
171 if (!empty($_REQUEST['return'])) {
172 $a->internalRedirect($return_path);
178 // Init post instance
181 // is this an edited post?
183 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
186 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
188 if (!DBA::isResult($user) && !$toplevel_item_id) {
195 $body = defaults($_REQUEST, 'body', '');
196 $has_attachment = defaults($_REQUEST, 'has_attachment', 0);
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', '');
204 $attachment_url = hex2bin(defaults($_REQUEST, 'attachment_url', ''));
205 $attachment_img_src = hex2bin(defaults($_REQUEST, 'attachment_img_src', ''));
207 $attachment_img_width = defaults($_REQUEST, 'attachment_img_width', 0);
208 $attachment_img_height = defaults($_REQUEST, 'attachment_img_height', 0);
210 'type' => $attachment_type,
211 'title' => $attachment_title,
212 'text' => $attachment_text,
213 'url' => $attachment_url,
216 if (!empty($attachment_img_src)) {
217 $attachment['images'] = [
219 'src' => $attachment_img_src,
220 'width' => $attachment_img_width,
221 'height' => $attachment_img_height
226 $att_bbcode = add_page_info_data($attachment);
227 $body .= $att_bbcode;
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'];
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.
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'];
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', ''));
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();
282 $postopts = defaults($_REQUEST, 'postopts', '');
284 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
286 if ($user['hidewall']) {
290 // If this is a comment, set the permissions from the parent.
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'];
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'];
306 $wall = $toplevel_item['wall'];
309 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
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(), '']);
318 if (!strlen($body)) {
322 info(L10n::t('Empty post discarded.') . EOL);
323 if (!empty($_REQUEST['return'])) {
324 $a->internalRedirect($return_path);
330 if (!empty($categories))
332 // get the "fileas" tags for this post
333 $filedas = FileTag::fileToList($categories, 'file');
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))
343 // append the fileas stuff to the new categories list
344 $categories .= FileTag::listToFile($filedas, 'file');
347 // get contact info for poster
353 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
355 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
356 } elseif (remote_user()) {
357 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
358 foreach ($_SESSION['remote'] as $v) {
359 if ($v['uid'] == $profile_uid) {
360 $contact_id = $v['cid'];
366 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
370 if (DBA::isResult($author)) {
371 $contact_id = $author['id'];
374 // get contact info for owner
375 if ($profile_uid == local_user() || $allow_comment) {
376 $contact_record = $author;
378 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
381 // Look for any tags and linkify them
385 $tags = BBCode::getTags($body);
387 if ($thread_parent_id && !\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions')) {
388 $tags = item_add_implicit_mentions($tags, $thread_parent_contact, $thread_parent_id);
393 $private_forum = false;
394 $only_to_forum = false;
398 foreach ($tags as $tag) {
399 $tag_type = substr($tag, 0, 1);
401 if ($tag_type == Term::TAG_CHARACTER[Term::HASHTAG]) {
406 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
407 * Robert Johnson should be first in the $tags array
409 $fullnametagged = false;
410 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
411 foreach ($tagged as $nextTag) {
412 if (stristr($nextTag, $tag . ' ')) {
413 $fullnametagged = true;
417 if ($fullnametagged) {
421 $success = handle_tag($body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
422 if ($success['replaced']) {
425 // When the forum is private or the forum is addressed with a "!" make the post private
426 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]))) {
427 $private_forum = $success['contact']['prv'];
428 $only_to_forum = ($tag_type == Term::TAG_CHARACTER[Term::EXCLUSIVE_MENTION]);
429 $private_id = $success['contact']['id'];
430 $forum_contact = $success['contact'];
431 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
432 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
433 $private_forum = false;
434 $only_to_forum = true;
435 $private_id = $success['contact']['id'];
436 $forum_contact = $success['contact'];
441 $original_contact_id = $contact_id;
443 if (!$toplevel_item_id && count($forum_contact) && ($private_forum || $only_to_forum)) {
444 // we tagged a forum in a top level post. Now we change the post
445 $private = $private_forum;
447 $str_group_allow = '';
448 $str_contact_deny = '';
449 $str_group_deny = '';
450 if ($private_forum) {
451 $str_contact_allow = '<' . $private_id . '>';
453 $str_contact_allow = '';
455 $contact_id = $private_id;
456 $contact_record = $forum_contact;
457 $_REQUEST['origin'] = false;
462 * When a photo was uploaded into the message using the (profile wall) ajax
463 * uploader, The permissions are initially set to disallow anybody but the
464 * owner from seeing it. This is because the permissions may not yet have been
465 * set for the post. If it's private, the photo permissions should be set
466 * appropriately. But we didn't know the final permissions on the post until
467 * now. So now we'll look for links of uploaded messages that are in the
468 * post and set them to the same permissions as the post itself.
473 /// @todo these lines should be moved to Model/Photo
474 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
476 if (count($images)) {
478 $objecttype = ACTIVITY_OBJ_IMAGE;
480 foreach ($images as $image) {
481 if (!stristr($image, System::baseUrl() . '/photo/')) {
484 $image_uri = substr($image,strrpos($image,'/') + 1);
485 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
486 if (!strlen($image_uri)) {
490 // Ensure to only modify photos that you own
491 $srch = '<' . intval($original_contact_id) . '>';
494 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
495 'resource-id' => $image_uri, 'uid' => $profile_uid
497 if (!Photo::exists($condition)) {
501 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
502 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
503 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
504 Photo::update($fields, $condition);
511 * Next link in any attachment references we find in the post.
515 /// @todo these lines should be moved to Model/Attach (Once it exists)
516 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
517 $attaches = $match[1];
518 if (count($attaches)) {
519 foreach ($attaches as $attach) {
520 // Ensure to only modify attachments that you own
521 $srch = '<' . intval($original_contact_id) . '>';
523 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
525 if (!Attach::exists($condition)) {
529 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
530 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
531 $condition = ['id' => $attach];
532 Attach::update($fields, $condition);
537 // embedded bookmark or attachment in post? set bookmark flag
539 $data = BBCode::getAttachmentData($body);
540 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
541 && ($posttype != Item::PT_PERSONAL_NOTE)) {
542 $posttype = Item::PT_PAGE;
543 $objecttype = ACTIVITY_OBJ_BOOKMARK;
546 $body = bb_translate_video($body);
549 // Fold multi-line [code] sequences
550 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
552 $body = BBCode::scaleExternalImages($body, false);
554 // Setting the object type if not defined before
556 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
557 $objectdata = BBCode::getAttachedData($body);
559 if ($objectdata["type"] == "link") {
560 $objecttype = ACTIVITY_OBJ_BOOKMARK;
561 } elseif ($objectdata["type"] == "video") {
562 $objecttype = ACTIVITY_OBJ_VIDEO;
563 } elseif ($objectdata["type"] == "photo") {
564 $objecttype = ACTIVITY_OBJ_IMAGE;
572 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
573 foreach ($match[2] as $mtch) {
574 $fields = ['id', 'filename', 'filesize', 'filetype'];
575 $attachment = Attach::selectFirst($fields, ['id' => $mtch]);
576 if ($attachment !== false) {
577 if (strlen($attachments)) {
580 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
581 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
582 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
584 $body = str_replace($match[1],'',$body);
588 if (!strlen($verb)) {
589 $verb = ACTIVITY_POST;
592 if ($network == "") {
593 $network = Protocol::DFRN;
596 $gravity = ($toplevel_item_id ? GRAVITY_COMMENT : GRAVITY_PARENT);
598 // even if the post arrived via API we are considering that it
599 // originated on this site by default for determining relayability.
601 // Don't use "defaults" here. It would turn 0 to 1
602 if (!isset($_REQUEST['origin'])) {
605 $origin = $_REQUEST['origin'];
608 $notify_type = ($toplevel_item_id ? 'comment-new' : 'wall-new');
610 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
612 // Fallback so that we alway have a parent uri
613 if (!$thr_parent_uri || !$toplevel_item_id) {
614 $thr_parent_uri = $uri;
618 $datarray['uid'] = $profile_uid;
619 $datarray['wall'] = $wall;
620 $datarray['gravity'] = $gravity;
621 $datarray['network'] = $network;
622 $datarray['contact-id'] = $contact_id;
623 $datarray['owner-name'] = $contact_record['name'];
624 $datarray['owner-link'] = $contact_record['url'];
625 $datarray['owner-avatar'] = $contact_record['thumb'];
626 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
627 $datarray['author-name'] = $author['name'];
628 $datarray['author-link'] = $author['url'];
629 $datarray['author-avatar'] = $author['thumb'];
630 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
631 $datarray['created'] = DateTimeFormat::utcNow();
632 $datarray['edited'] = DateTimeFormat::utcNow();
633 $datarray['commented'] = DateTimeFormat::utcNow();
634 $datarray['received'] = DateTimeFormat::utcNow();
635 $datarray['changed'] = DateTimeFormat::utcNow();
636 $datarray['extid'] = $extid;
637 $datarray['guid'] = $guid;
638 $datarray['uri'] = $uri;
639 $datarray['title'] = $title;
640 $datarray['body'] = $body;
641 $datarray['app'] = $app;
642 $datarray['location'] = $location;
643 $datarray['coord'] = $coord;
644 $datarray['tag'] = $str_tags;
645 $datarray['file'] = $categories;
646 $datarray['inform'] = $inform;
647 $datarray['verb'] = $verb;
648 $datarray['post-type'] = $posttype;
649 $datarray['object-type'] = $objecttype;
650 $datarray['allow_cid'] = $str_contact_allow;
651 $datarray['allow_gid'] = $str_group_allow;
652 $datarray['deny_cid'] = $str_contact_deny;
653 $datarray['deny_gid'] = $str_group_deny;
654 $datarray['private'] = $private;
655 $datarray['pubmail'] = $pubmail_enabled;
656 $datarray['attach'] = $attachments;
658 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
659 $datarray['parent-uri'] = $thr_parent_uri;
661 $datarray['postopts'] = $postopts;
662 $datarray['origin'] = $origin;
663 $datarray['moderated'] = false;
664 $datarray['object'] = $object;
667 * These fields are for the convenience of addons...
668 * 'self' if true indicates the owner is posting on their own wall
669 * If parent is 0 it is a top-level post.
671 $datarray['parent'] = $toplevel_item_id;
672 $datarray['self'] = $self;
674 // This triggers posts via API and the mirror functions
675 $datarray['api_source'] = $api_source;
677 // This field is for storing the raw conversation data
678 $datarray['protocol'] = Conversation::PARCEL_DFRN;
680 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
681 if (DBA::isResult($conversation)) {
682 if ($conversation['conversation-uri'] != '') {
683 $datarray['conversation-uri'] = $conversation['conversation-uri'];
685 if ($conversation['conversation-href'] != '') {
686 $datarray['conversation-href'] = $conversation['conversation-href'];
691 $datarray['edit'] = true;
693 $datarray['edit'] = false;
696 // Check for hashtags in the body and repair or add hashtag links
697 if ($preview || $orig_post) {
698 Item::setHashtags($datarray);
701 // preview mode - prepare the body for display and send it via json
703 // We set the datarray ID to -1 because in preview mode the dataray
704 // doesn't have an ID.
705 $datarray["id"] = -1;
706 $datarray["item_id"] = -1;
707 $datarray["author-network"] = Protocol::DFRN;
709 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
710 Logger::log('preview: ' . $o);
711 echo json_encode(['preview' => $o]);
715 Hook::callAll('post_local',$datarray);
717 if (!empty($datarray['cancel'])) {
718 Logger::log('mod_item: post cancelled by addon.');
720 $a->internalRedirect($return_path);
723 $json = ['cancel' => 1];
724 if (!empty($_REQUEST['jsreload'])) {
725 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
728 echo json_encode($json);
733 // Fill the cache field
734 // This could be done in Item::update as well - but we have to check for the existance of some fields.
735 Item::putInCache($datarray);
738 'title' => $datarray['title'],
739 'body' => $datarray['body'],
740 'tag' => $datarray['tag'],
741 'attach' => $datarray['attach'],
742 'file' => $datarray['file'],
743 'rendered-html' => $datarray['rendered-html'],
744 'rendered-hash' => $datarray['rendered-hash'],
745 'edited' => DateTimeFormat::utcNow(),
746 'changed' => DateTimeFormat::utcNow()];
748 Item::update($fields, ['id' => $post_id]);
750 // update filetags in pconfig
751 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
753 if (!empty($_REQUEST['return']) && strlen($return_path)) {
754 Logger::log('return: ' . $return_path);
755 $a->internalRedirect($return_path);
760 unset($datarray['edit']);
761 unset($datarray['self']);
762 unset($datarray['api_source']);
765 $signed = Diaspora::createCommentSignature($uid, $datarray);
766 if (!empty($signed)) {
767 $datarray['diaspora_signed_text'] = json_encode($signed);
771 $post_id = Item::insert($datarray);
774 Logger::log("Item wasn't stored.");
775 $a->internalRedirect($return_path);
778 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
780 if (!DBA::isResult($datarray)) {
781 Logger::log("Item with id ".$post_id." couldn't be fetched.");
782 $a->internalRedirect($return_path);
785 // update filetags in pconfig
786 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
788 // These notifications are sent if someone else is commenting other your wall
789 if ($toplevel_item_id) {
790 if ($contact_record != $author) {
792 'type' => NOTIFY_COMMENT,
793 'notify_flags' => $user['notify-flags'],
794 'language' => $user['language'],
795 'to_name' => $user['username'],
796 'to_email' => $user['email'],
797 'uid' => $user['uid'],
799 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
800 'source_name' => $datarray['author-name'],
801 'source_link' => $datarray['author-link'],
802 'source_photo' => $datarray['author-avatar'],
803 'verb' => ACTIVITY_POST,
805 'parent' => $toplevel_item_id,
806 'parent_uri' => $toplevel_item['uri']
810 if (($contact_record != $author) && !count($forum_contact)) {
812 'type' => NOTIFY_WALL,
813 'notify_flags' => $user['notify-flags'],
814 'language' => $user['language'],
815 'to_name' => $user['username'],
816 'to_email' => $user['email'],
817 'uid' => $user['uid'],
819 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
820 'source_name' => $datarray['author-name'],
821 'source_link' => $datarray['author-link'],
822 'source_photo' => $datarray['author-avatar'],
823 'verb' => ACTIVITY_POST,
829 Hook::callAll('post_local_end', $datarray);
831 if (strlen($emailcc) && $profile_uid == local_user()) {
832 $erecips = explode(',', $emailcc);
833 if (count($erecips)) {
834 foreach ($erecips as $recip) {
835 $addr = trim($recip);
836 if (!strlen($addr)) {
839 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
841 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
842 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
843 if (!$datarray['title']=='') {
844 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
846 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
848 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
849 $html = Item::prepareBody($datarray);
850 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
852 'fromName' => $a->user['username'],
853 'fromEmail' => $a->user['email'],
855 'replyTo' => $a->user['email'],
856 'messageSubject' => $subject,
857 'htmlVersion' => $message,
858 'textVersion' => HTML::toPlaintext($html.$disclaimer)
860 Emailer::send($params);
865 // Insert an item entry for UID=0 for global entries.
866 // We now do it in the background to save some time.
867 // This is important in interactive environments like the frontend or the API.
868 // We don't fork a new process since this is done anyway with the following command
869 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
871 // When we are doing some forum posting via ! we have to start the notifier manually.
872 // These kind of posts don't initiate the notifier call in the item class.
873 if ($only_to_forum) {
874 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
877 Logger::log('post_complete');
883 item_post_return(System::baseUrl(), $api_source, $return_path);
887 function item_post_return($baseurl, $api_source, $return_path)
889 // figure out how to return, depending on from whence we came
897 $a->internalRedirect($return_path);
900 $json = ['success' => 1];
901 if (!empty($_REQUEST['jsreload'])) {
902 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
905 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
907 echo json_encode($json);
911 function item_content(App $a)
913 if (!local_user() && !remote_user()) {
919 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
921 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
923 if (!empty($a->argv[3])) {
924 $o = drop_item($a->argv[2], $a->argv[3]);
927 $o = drop_item($a->argv[2]);
932 // ajax return: [<item id>, 0 (no perm) | <owner id>]
933 echo json_encode([intval($a->argv[2]), intval($o)]);
942 * This function removes the tag $tag from the text $body and replaces it with
943 * the appropriate link.
946 * @param string $body the text to replace the tag in
947 * @param string $inform a comma-seperated string containing everybody to inform
948 * @param string $str_tags string to add the tag to
949 * @param integer $profile_uid
950 * @param string $tag the tag to replace
951 * @param string $network The network of the post
953 * @return array|bool ['replaced' => $replaced, 'contact' => $contact];
954 * @throws ImagickException
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 function handle_tag(&$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
962 //is it a person tag?
963 if (Term::isType($tag, Term::MENTION, Term::IMPLICIT_MENTION, Term::EXCLUSIVE_MENTION)) {
964 $tag_type = substr($tag, 0, 1);
965 //is it already replaced?
966 if (strpos($tag, '[url=')) {
967 //append tag to str_tags
968 if (!stristr($str_tags, $tag)) {
969 if (strlen($str_tags)) {
975 // Checking for the alias that is used for OStatus
976 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
977 if (preg_match($pattern, $tag, $matches)) {
978 $data = Contact::getDetailsByURL($matches[1]);
980 if ($data["alias"] != "") {
981 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
983 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
984 if (strlen($str_tags)) {
988 $str_tags .= $newtag;
996 //get the person's name
997 $name = substr($tag, 1);
999 // Sometimes the tag detection doesn't seem to work right
1000 // This is some workaround
1001 $nameparts = explode(" ", $name);
1002 $name = $nameparts[0];
1004 // Try to detect the contact in various ways
1005 if (strpos($name, 'http://')) {
1006 // At first we have to ensure that the contact exists
1007 Contact::getIdForURL($name);
1009 // Now we should have something
1010 $contact = Contact::getDetailsByURL($name);
1011 } elseif (strpos($name, '@')) {
1012 // This function automatically probes when no entry was found
1013 $contact = Contact::getDetailsByAddr($name);
1016 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
1018 if (strrpos($name, '+')) {
1019 // Is it in format @nick+number?
1020 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1021 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
1024 // select someone by nick or attag in the current network
1025 if (!DBA::isResult($contact) && ($network != "")) {
1026 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
1027 $name, $name, $network, $profile_uid];
1028 $contact = DBA::selectFirst('contact', $fields, $condition);
1031 //select someone by name in the current network
1032 if (!DBA::isResult($contact) && ($network != "")) {
1033 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1034 $contact = DBA::selectFirst('contact', $fields, $condition);
1037 // select someone by nick or attag in any network
1038 if (!DBA::isResult($contact)) {
1039 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1040 $contact = DBA::selectFirst('contact', $fields, $condition);
1043 // select someone by name in any network
1044 if (!DBA::isResult($contact)) {
1045 $condition = ['name' => $name, 'uid' => $profile_uid];
1046 $contact = DBA::selectFirst('contact', $fields, $condition);
1050 // Check if $contact has been successfully loaded
1051 if (DBA::isResult($contact)) {
1052 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1056 if (isset($contact["id"])) {
1057 $inform .= 'cid:' . $contact["id"];
1058 } elseif (isset($contact["notify"])) {
1059 $inform .= $contact["notify"];
1062 $profile = $contact["url"];
1063 $alias = $contact["alias"];
1064 $newname = defaults($contact, "name", $contact["nick"]);
1067 //if there is an url for this persons profile
1068 if (isset($profile) && ($newname != "")) {
1070 // create profile link
1071 $profile = str_replace(',', '%2c', $profile);
1072 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1073 $body = str_replace($tag_type . $name, $newtag, $body);
1074 // append tag to str_tags
1075 if (!stristr($str_tags, $newtag)) {
1076 if (strlen($str_tags)) {
1079 $str_tags .= $newtag;
1083 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1084 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1086 if (!empty($alias)) {
1087 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1088 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1089 if (strlen($str_tags)) {
1092 $str_tags .= $newtag;
1098 return ['replaced' => $replaced, 'contact' => $contact];
1101 function item_add_implicit_mentions(array $tags, array $thread_parent_contact, $thread_parent_id)
1103 if (Config::get('system', 'disable_implicit_mentions')) {
1104 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
1105 if (in_array($thread_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
1106 $contact = Term::TAG_CHARACTER[Term::MENTION] . '[url=' . $thread_parent_contact['url'] . ']' . $thread_parent_contact['nick'] . '[/url]';
1107 if (!stripos(implode($tags), '[url=' . $thread_parent_contact['url'] . ']')) {
1112 $implicit_mentions = [
1113 $thread_parent_contact['url'] => $thread_parent_contact['nick']
1116 $parent_terms = Term::tagArrayFromItemId($thread_parent_id, [Term::MENTION, Term::IMPLICIT_MENTION]);
1118 foreach ($parent_terms as $parent_term) {
1119 $implicit_mentions[$parent_term['url']] = $parent_term['term'];
1122 foreach ($implicit_mentions as $url => $label) {
1123 if ($url != \Friendica\Model\Profile::getMyURL() && !stripos(implode($tags), '[url=' . $url . ']')) {
1124 $tags[] = Term::TAG_CHARACTER[Term::IMPLICIT_MENTION] . '[url=' . $url . ']' . $label . '[/url]';