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\Addon;
23 use Friendica\Core\Config;
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\Protocol\Diaspora;
36 use Friendica\Protocol\Email;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Emailer;
39 use Friendica\Util\Security;
40 use Friendica\Util\Strings;
42 function item_post(App $a) {
43 if (!local_user() && !remote_user()) {
49 if (!empty($_REQUEST['dropitems'])) {
50 $arr_drop = explode(',', $_REQUEST['dropitems']);
51 drop_items($arr_drop);
52 $json = ['success' => 1];
53 echo json_encode($json);
57 Addon::callHooks('post_local_start', $_REQUEST);
59 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
61 $api_source = defaults($_REQUEST, 'api_source', false);
63 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
65 $return_path = defaults($_REQUEST, 'return', '');
66 $preview = intval(defaults($_REQUEST, 'preview', 0));
69 * Check for doubly-submitted posts, and reject duplicates
70 * Note that we have to ignore previews, otherwise nothing will post
71 * after it's been previewed
73 if (!$preview && !empty($_REQUEST['post_id_random'])) {
74 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
75 Logger::log("item post: duplicate post", Logger::DEBUG);
76 item_post_return(System::baseUrl(), $api_source, $return_path);
78 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
82 // Is this a reply to something?
83 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
84 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
86 $thr_parent_contact = null;
92 $parent_contact = null;
95 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
96 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
98 if ($thr_parent || $thr_parent_uri) {
100 $parent_item = Item::selectFirst([], ['id' => $thr_parent]);
101 } elseif ($thr_parent_uri) {
102 $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
105 // if this isn't the real parent of the conversation, find it
106 if (DBA::isResult($parent_item)) {
107 // The URI and the contact is taken from the direct parent which needn't to be the top parent
108 $thr_parent_uri = $parent_item['uri'];
109 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
111 if ($parent_item['id'] != $parent_item['parent']) {
112 $parent_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
116 if (!DBA::isResult($parent_item)) {
117 notice(L10n::t('Unable to locate original post.') . EOL);
118 if (!empty($_REQUEST['return'])) {
119 $a->internalRedirect($return_path);
124 $parent = $parent_item['id'];
125 $parent_user = $parent_item['uid'];
127 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
129 $objecttype = ACTIVITY_OBJ_COMMENT;
133 Logger::log('mod_item: item_post parent=' . $parent);
136 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
137 $app = strip_tags(defaults($_REQUEST, 'source', ''));
138 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
139 $object = defaults($_REQUEST, 'object', '');
141 // Don't use "defaults" here. It would turn 0 to 1
142 if (!isset($_REQUEST['wall'])) {
145 $wall = $_REQUEST['wall'];
148 // Ensure that the user id in a thread always stay the same
149 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
150 $profile_uid = $parent_user;
153 // Check for multiple posts with the same message id (when the post was created via API)
154 if (($message_id != '') && ($profile_uid != 0)) {
155 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
156 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
161 // Allow commenting if it is an answer to a public post
162 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
164 // Now check that valid personal details have been provided
165 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
166 notice(L10n::t('Permission denied.') . EOL);
168 if (!empty($_REQUEST['return'])) {
169 $a->internalRedirect($return_path);
175 // Init post instance
178 // is this an edited post?
180 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
183 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
185 if (!DBA::isResult($user) && !$parent) {
193 if (!empty($orig_post)) {
194 $str_group_allow = $orig_post['allow_gid'];
195 $str_contact_allow = $orig_post['allow_cid'];
196 $str_group_deny = $orig_post['deny_gid'];
197 $str_contact_deny = $orig_post['deny_cid'];
198 $location = $orig_post['location'];
199 $coord = $orig_post['coord'];
200 $verb = $orig_post['verb'];
201 $objecttype = $orig_post['object-type'];
202 $app = $orig_post['app'];
203 $categories = $orig_post['file'];
204 $title = Strings::escapeTags(trim($_REQUEST['title']));
205 $body = Strings::escapeHtml(trim($_REQUEST['body']));
206 $private = $orig_post['private'];
207 $pubmail_enabled = $orig_post['pubmail'];
208 $network = $orig_post['network'];
209 $guid = $orig_post['guid'];
210 $extid = $orig_post['extid'];
215 * if coming from the API and no privacy settings are set,
216 * use the user default permissions - as they won't have
217 * been supplied via a form.
220 && !array_key_exists('contact_allow', $_REQUEST)
221 && !array_key_exists('group_allow', $_REQUEST)
222 && !array_key_exists('contact_deny', $_REQUEST)
223 && !array_key_exists('group_deny', $_REQUEST)) {
224 $str_group_allow = $user['allow_gid'];
225 $str_contact_allow = $user['allow_cid'];
226 $str_group_deny = $user['deny_gid'];
227 $str_contact_deny = $user['deny_cid'];
229 // use the posted permissions
230 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
231 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
232 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
233 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
236 $title = Strings::escapeTags(trim(defaults($_REQUEST, 'title' , '')));
237 $location = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
238 $coord = Strings::escapeTags(trim(defaults($_REQUEST, 'coord' , '')));
239 $verb = Strings::escapeTags(trim(defaults($_REQUEST, 'verb' , '')));
240 $emailcc = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
241 $body = Strings::escapeHtml(trim(defaults($_REQUEST, 'body' , '')));
242 $network = Strings::escapeTags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
243 $guid = System::createUUID();
245 $postopts = defaults($_REQUEST, 'postopts', '');
247 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
249 if ($user['hidewall']) {
253 // If this is a comment, set the permissions from the parent.
256 // for non native networks use the network of the original post as network of the item
257 if (($parent_item['network'] != Protocol::DIASPORA)
258 && ($parent_item['network'] != Protocol::OSTATUS)
259 && ($network == "")) {
260 $network = $parent_item['network'];
263 $str_contact_allow = $parent_item['allow_cid'];
264 $str_group_allow = $parent_item['allow_gid'];
265 $str_contact_deny = $parent_item['deny_cid'];
266 $str_group_deny = $parent_item['deny_gid'];
267 $private = $parent_item['private'];
269 $wall = $parent_item['wall'];
272 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
274 // if using the API, we won't see pubmail_enable - figure out if it should be set
275 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
276 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
277 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
281 if (!strlen($body)) {
285 info(L10n::t('Empty post discarded.') . EOL);
286 if (!empty($_REQUEST['return'])) {
287 $a->internalRedirect($return_path);
293 if (!empty($categories))
295 // get the "fileas" tags for this post
296 $filedas = FileTag::fileToList($categories, 'file');
299 // save old and new categories, so we can determine what needs to be deleted from pconfig
300 $categories_old = $categories;
301 $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
302 $categories_new = $categories;
304 if (!empty($filedas))
306 // append the fileas stuff to the new categories list
307 $categories .= FileTag::listToFile($filedas, 'file');
310 // get contact info for poster
316 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
318 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
319 } elseif (remote_user()) {
320 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
321 foreach ($_SESSION['remote'] as $v) {
322 if ($v['uid'] == $profile_uid) {
323 $contact_id = $v['cid'];
329 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
333 if (DBA::isResult($author)) {
334 $contact_id = $author['id'];
337 // get contact info for owner
338 if ($profile_uid == local_user() || $allow_comment) {
339 $contact_record = $author;
341 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
344 // Look for any tags and linkify them
348 $tags = BBCode::getTags($body);
350 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
351 if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
352 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
353 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
360 $private_forum = false;
361 $only_to_forum = false;
365 foreach ($tags as $tag) {
366 $tag_type = substr($tag, 0, 1);
368 if ($tag_type == '#') {
373 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
374 * Robert Johnson should be first in the $tags array
376 $fullnametagged = false;
377 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
378 foreach ($tagged as $nextTag) {
379 if (stristr($nextTag, $tag . ' ')) {
380 $fullnametagged = true;
384 if ($fullnametagged) {
388 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
389 if ($success['replaced']) {
392 // When the forum is private or the forum is addressed with a "!" make the post private
393 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
394 $private_forum = $success['contact']['prv'];
395 $only_to_forum = ($tag_type == '!');
396 $private_id = $success['contact']['id'];
397 $forum_contact = $success['contact'];
398 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
399 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
400 $private_forum = false;
401 $only_to_forum = true;
402 $private_id = $success['contact']['id'];
403 $forum_contact = $success['contact'];
408 $original_contact_id = $contact_id;
410 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
411 // we tagged a forum in a top level post. Now we change the post
412 $private = $private_forum;
414 $str_group_allow = '';
415 $str_contact_deny = '';
416 $str_group_deny = '';
417 if ($private_forum) {
418 $str_contact_allow = '<' . $private_id . '>';
420 $str_contact_allow = '';
422 $contact_id = $private_id;
423 $contact_record = $forum_contact;
424 $_REQUEST['origin'] = false;
429 * When a photo was uploaded into the message using the (profile wall) ajax
430 * uploader, The permissions are initially set to disallow anybody but the
431 * owner from seeing it. This is because the permissions may not yet have been
432 * set for the post. If it's private, the photo permissions should be set
433 * appropriately. But we didn't know the final permissions on the post until
434 * now. So now we'll look for links of uploaded messages that are in the
435 * post and set them to the same permissions as the post itself.
440 /// @todo these lines should be moved to Model/Photo
441 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
443 if (count($images)) {
445 $objecttype = ACTIVITY_OBJ_IMAGE;
447 foreach ($images as $image) {
448 if (!stristr($image, System::baseUrl() . '/photo/')) {
451 $image_uri = substr($image,strrpos($image,'/') + 1);
452 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
453 if (!strlen($image_uri)) {
457 // Ensure to only modify photos that you own
458 $srch = '<' . intval($original_contact_id) . '>';
461 'allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
462 'resource-id' => $image_uri, 'uid' => $profile_uid
464 if (!Photo::exists($condition)) {
468 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
469 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
470 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
471 Photo::update($fields, $condition);
478 * Next link in any attachment references we find in the post.
482 /// @todo these lines should be moved to Model/Attach (Once it exists)
483 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
484 $attaches = $match[1];
485 if (count($attaches)) {
486 foreach ($attaches as $attach) {
487 // Ensure to only modify attachments that you own
488 $srch = '<' . intval($original_contact_id) . '>';
490 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
492 if (!DBA::exists('attach', $condition)) {
496 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
497 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
498 $condition = ['id' => $attach];
499 DBA::update('attach', $fields, $condition);
504 // embedded bookmark or attachment in post? set bookmark flag
506 $data = BBCode::getAttachmentData($body);
507 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
508 && ($posttype != Item::PT_PERSONAL_NOTE)) {
509 $posttype = Item::PT_PAGE;
510 $objecttype = ACTIVITY_OBJ_BOOKMARK;
513 $body = bb_translate_video($body);
516 // Fold multi-line [code] sequences
517 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
519 $body = BBCode::scaleExternalImages($body, false);
521 // Setting the object type if not defined before
523 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
524 $objectdata = BBCode::getAttachedData($body);
526 if ($objectdata["type"] == "link") {
527 $objecttype = ACTIVITY_OBJ_BOOKMARK;
528 } elseif ($objectdata["type"] == "video") {
529 $objecttype = ACTIVITY_OBJ_VIDEO;
530 } elseif ($objectdata["type"] == "photo") {
531 $objecttype = ACTIVITY_OBJ_IMAGE;
539 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
540 foreach ($match[2] as $mtch) {
541 $fields = ['id', 'filename', 'filesize', 'filetype'];
542 $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
543 if (DBA::isResult($attachment)) {
544 if (strlen($attachments)) {
547 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
548 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
549 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
551 $body = str_replace($match[1],'',$body);
555 if (!strlen($verb)) {
556 $verb = ACTIVITY_POST;
559 if ($network == "") {
560 $network = Protocol::DFRN;
563 $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
565 // even if the post arrived via API we are considering that it
566 // originated on this site by default for determining relayability.
568 // Don't use "defaults" here. It would turn 0 to 1
569 if (!isset($_REQUEST['origin'])) {
572 $origin = $_REQUEST['origin'];
575 $notify_type = ($parent ? 'comment-new' : 'wall-new');
577 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
579 // Fallback so that we alway have a parent uri
580 if (!$thr_parent_uri || !$parent) {
581 $thr_parent_uri = $uri;
585 $datarray['uid'] = $profile_uid;
586 $datarray['wall'] = $wall;
587 $datarray['gravity'] = $gravity;
588 $datarray['network'] = $network;
589 $datarray['contact-id'] = $contact_id;
590 $datarray['owner-name'] = $contact_record['name'];
591 $datarray['owner-link'] = $contact_record['url'];
592 $datarray['owner-avatar'] = $contact_record['thumb'];
593 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
594 $datarray['author-name'] = $author['name'];
595 $datarray['author-link'] = $author['url'];
596 $datarray['author-avatar'] = $author['thumb'];
597 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
598 $datarray['created'] = DateTimeFormat::utcNow();
599 $datarray['edited'] = DateTimeFormat::utcNow();
600 $datarray['commented'] = DateTimeFormat::utcNow();
601 $datarray['received'] = DateTimeFormat::utcNow();
602 $datarray['changed'] = DateTimeFormat::utcNow();
603 $datarray['extid'] = $extid;
604 $datarray['guid'] = $guid;
605 $datarray['uri'] = $uri;
606 $datarray['title'] = $title;
607 $datarray['body'] = $body;
608 $datarray['app'] = $app;
609 $datarray['location'] = $location;
610 $datarray['coord'] = $coord;
611 $datarray['tag'] = $str_tags;
612 $datarray['file'] = $categories;
613 $datarray['inform'] = $inform;
614 $datarray['verb'] = $verb;
615 $datarray['post-type'] = $posttype;
616 $datarray['object-type'] = $objecttype;
617 $datarray['allow_cid'] = $str_contact_allow;
618 $datarray['allow_gid'] = $str_group_allow;
619 $datarray['deny_cid'] = $str_contact_deny;
620 $datarray['deny_gid'] = $str_group_deny;
621 $datarray['private'] = $private;
622 $datarray['pubmail'] = $pubmail_enabled;
623 $datarray['attach'] = $attachments;
625 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
626 $datarray['parent-uri'] = $thr_parent_uri;
628 $datarray['postopts'] = $postopts;
629 $datarray['origin'] = $origin;
630 $datarray['moderated'] = false;
631 $datarray['object'] = $object;
634 * These fields are for the convenience of addons...
635 * 'self' if true indicates the owner is posting on their own wall
636 * If parent is 0 it is a top-level post.
638 $datarray['parent'] = $parent;
639 $datarray['self'] = $self;
641 // This triggers posts via API and the mirror functions
642 $datarray['api_source'] = $api_source;
644 // This field is for storing the raw conversation data
645 $datarray['protocol'] = Conversation::PARCEL_DFRN;
647 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
648 if (DBA::isResult($conversation)) {
649 if ($conversation['conversation-uri'] != '') {
650 $datarray['conversation-uri'] = $conversation['conversation-uri'];
652 if ($conversation['conversation-href'] != '') {
653 $datarray['conversation-href'] = $conversation['conversation-href'];
658 $datarray['edit'] = true;
660 $datarray['edit'] = false;
663 // Check for hashtags in the body and repair or add hashtag links
664 if ($preview || $orig_post) {
665 Item::setHashtags($datarray);
668 // preview mode - prepare the body for display and send it via json
670 // We set the datarray ID to -1 because in preview mode the dataray
671 // doesn't have an ID.
672 $datarray["id"] = -1;
673 $datarray["item_id"] = -1;
674 $datarray["author-network"] = Protocol::DFRN;
676 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
677 Logger::log('preview: ' . $o);
678 echo json_encode(['preview' => $o]);
682 Addon::callHooks('post_local',$datarray);
684 if (!empty($datarray['cancel'])) {
685 Logger::log('mod_item: post cancelled by addon.');
687 $a->internalRedirect($return_path);
690 $json = ['cancel' => 1];
691 if (!empty($_REQUEST['jsreload'])) {
692 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
695 echo json_encode($json);
700 // Fill the cache field
701 // This could be done in Item::update as well - but we have to check for the existance of some fields.
702 Item::putInCache($datarray);
705 'title' => $datarray['title'],
706 'body' => $datarray['body'],
707 'tag' => $datarray['tag'],
708 'attach' => $datarray['attach'],
709 'file' => $datarray['file'],
710 'rendered-html' => $datarray['rendered-html'],
711 'rendered-hash' => $datarray['rendered-hash'],
712 'edited' => DateTimeFormat::utcNow(),
713 'changed' => DateTimeFormat::utcNow()];
715 Item::update($fields, ['id' => $post_id]);
717 // update filetags in pconfig
718 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
720 if (!empty($_REQUEST['return']) && strlen($return_path)) {
721 Logger::log('return: ' . $return_path);
722 $a->internalRedirect($return_path);
729 unset($datarray['edit']);
730 unset($datarray['self']);
731 unset($datarray['api_source']);
734 $signed = Diaspora::createCommentSignature($uid, $datarray);
735 if (!empty($signed)) {
736 $datarray['diaspora_signed_text'] = json_encode($signed);
740 $post_id = Item::insert($datarray);
743 Logger::log("Item wasn't stored.");
744 $a->internalRedirect($return_path);
747 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
749 if (!DBA::isResult($datarray)) {
750 Logger::log("Item with id ".$post_id." couldn't be fetched.");
751 $a->internalRedirect($return_path);
754 // update filetags in pconfig
755 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
757 // These notifications are sent if someone else is commenting other your wall
759 if ($contact_record != $author) {
761 'type' => NOTIFY_COMMENT,
762 'notify_flags' => $user['notify-flags'],
763 'language' => $user['language'],
764 'to_name' => $user['username'],
765 'to_email' => $user['email'],
766 'uid' => $user['uid'],
768 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
769 'source_name' => $datarray['author-name'],
770 'source_link' => $datarray['author-link'],
771 'source_photo' => $datarray['author-avatar'],
772 'verb' => ACTIVITY_POST,
775 'parent_uri' => $parent_item['uri']
779 if (($contact_record != $author) && !count($forum_contact)) {
781 'type' => NOTIFY_WALL,
782 'notify_flags' => $user['notify-flags'],
783 'language' => $user['language'],
784 'to_name' => $user['username'],
785 'to_email' => $user['email'],
786 'uid' => $user['uid'],
788 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
789 'source_name' => $datarray['author-name'],
790 'source_link' => $datarray['author-link'],
791 'source_photo' => $datarray['author-avatar'],
792 'verb' => ACTIVITY_POST,
798 Addon::callHooks('post_local_end', $datarray);
800 if (strlen($emailcc) && $profile_uid == local_user()) {
801 $erecips = explode(',', $emailcc);
802 if (count($erecips)) {
803 foreach ($erecips as $recip) {
804 $addr = trim($recip);
805 if (!strlen($addr)) {
808 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
810 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
811 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
812 if (!$datarray['title']=='') {
813 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
815 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
817 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
818 $html = Item::prepareBody($datarray);
819 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
821 'fromName' => $a->user['username'],
822 'fromEmail' => $a->user['email'],
824 'replyTo' => $a->user['email'],
825 'messageSubject' => $subject,
826 'htmlVersion' => $message,
827 'textVersion' => HTML::toPlaintext($html.$disclaimer)
829 Emailer::send($params);
834 // Insert an item entry for UID=0 for global entries.
835 // We now do it in the background to save some time.
836 // This is important in interactive environments like the frontend or the API.
837 // We don't fork a new process since this is done anyway with the following command
838 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
840 // When we are doing some forum posting via ! we have to start the notifier manually.
841 // These kind of posts don't initiate the notifier call in the item class.
842 if ($only_to_forum) {
843 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
846 Logger::log('post_complete');
852 item_post_return(System::baseUrl(), $api_source, $return_path);
856 function item_post_return($baseurl, $api_source, $return_path)
858 // figure out how to return, depending on from whence we came
866 $a->internalRedirect($return_path);
869 $json = ['success' => 1];
870 if (!empty($_REQUEST['jsreload'])) {
871 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
874 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
876 echo json_encode($json);
880 function item_content(App $a)
882 if (!local_user() && !remote_user()) {
888 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
890 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
892 if (!empty($a->argv[3])) {
893 $o = drop_item($a->argv[2], $a->argv[3]);
896 $o = drop_item($a->argv[2]);
901 // ajax return: [<item id>, 0 (no perm) | <owner id>]
902 echo json_encode([intval($a->argv[2]), intval($o)]);
911 * This function removes the tag $tag from the text $body and replaces it with
912 * the appropiate link.
914 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
915 * @param string $body the text to replace the tag in
916 * @param string $inform a comma-seperated string containing everybody to inform
917 * @param string $str_tags string to add the tag to
918 * @param integer $profile_uid
919 * @param string $tag the tag to replace
920 * @param string $network The network of the post
922 * @return boolean true if replaced, false if not replaced
924 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
930 //is it a person tag?
931 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
932 $tag_type = substr($tag, 0, 1);
933 //is it already replaced?
934 if (strpos($tag, '[url=')) {
935 //append tag to str_tags
936 if (!stristr($str_tags, $tag)) {
937 if (strlen($str_tags)) {
943 // Checking for the alias that is used for OStatus
944 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
945 if (preg_match($pattern, $tag, $matches)) {
946 $data = Contact::getDetailsByURL($matches[1]);
948 if ($data["alias"] != "") {
949 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
951 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
952 if (strlen($str_tags)) {
956 $str_tags .= $newtag;
965 //get the person's name
966 $name = substr($tag, 1);
968 // Sometimes the tag detection doesn't seem to work right
969 // This is some workaround
970 $nameparts = explode(" ", $name);
971 $name = $nameparts[0];
973 // Try to detect the contact in various ways
974 if (strpos($name, 'http://')) {
975 // At first we have to ensure that the contact exists
976 Contact::getIdForURL($name);
978 // Now we should have something
979 $contact = Contact::getDetailsByURL($name);
980 } elseif (strpos($name, '@')) {
981 // This function automatically probes when no entry was found
982 $contact = Contact::getDetailsByAddr($name);
985 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
987 if (strrpos($name, '+')) {
988 // Is it in format @nick+number?
989 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
990 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
993 // select someone by nick or attag in the current network
994 if (!DBA::isResult($contact) && ($network != "")) {
995 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
996 $name, $name, $network, $profile_uid];
997 $contact = DBA::selectFirst('contact', $fields, $condition);
1000 //select someone by name in the current network
1001 if (!DBA::isResult($contact) && ($network != "")) {
1002 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1003 $contact = DBA::selectFirst('contact', $fields, $condition);
1006 // select someone by nick or attag in any network
1007 if (!DBA::isResult($contact)) {
1008 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1009 $contact = DBA::selectFirst('contact', $fields, $condition);
1012 // select someone by name in any network
1013 if (!DBA::isResult($contact)) {
1014 $condition = ['name' => $name, 'uid' => $profile_uid];
1015 $contact = DBA::selectFirst('contact', $fields, $condition);
1019 // Check if $contact has been successfully loaded
1020 if (DBA::isResult($contact)) {
1021 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1025 if (isset($contact["id"])) {
1026 $inform .= 'cid:' . $contact["id"];
1027 } elseif (isset($contact["notify"])) {
1028 $inform .= $contact["notify"];
1031 $profile = $contact["url"];
1032 $alias = $contact["alias"];
1033 $newname = defaults($contact, "name", $contact["nick"]);
1036 //if there is an url for this persons profile
1037 if (isset($profile) && ($newname != "")) {
1039 // create profile link
1040 $profile = str_replace(',', '%2c', $profile);
1041 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1042 $body = str_replace($tag_type . $name, $newtag, $body);
1043 // append tag to str_tags
1044 if (!stristr($str_tags, $newtag)) {
1045 if (strlen($str_tags)) {
1048 $str_tags .= $newtag;
1052 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1053 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1055 if (strlen($alias)) {
1056 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1057 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1058 if (strlen($str_tags)) {
1061 $str_tags .= $newtag;
1067 return ['replaced' => $replaced, 'contact' => $contact];