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\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Core\Addon;
22 use Friendica\Core\Config;
23 use Friendica\Core\L10n;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\System;
26 use Friendica\Core\Worker;
27 use Friendica\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Conversation;
30 use Friendica\Model\Item;
31 use Friendica\Protocol\Diaspora;
32 use Friendica\Protocol\Email;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\Emailer;
35 use Friendica\Util\Security;
37 require_once 'include/enotify.php';
38 require_once 'include/text.php';
39 require_once 'include/items.php';
41 function item_post(App $a) {
42 if (!local_user() && !remote_user()) {
46 require_once 'include/security.php';
50 if (!empty($_REQUEST['dropitems'])) {
51 $arr_drop = explode(',', $_REQUEST['dropitems']);
52 drop_items($arr_drop);
53 $json = ['success' => 1];
54 echo json_encode($json);
58 Addon::callHooks('post_local_start', $_REQUEST);
60 logger('postvars ' . print_r($_REQUEST, true), LOGGER_DATA);
62 $api_source = defaults($_REQUEST, 'api_source', false);
64 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
66 $return_path = defaults($_REQUEST, 'return', '');
67 $preview = intval(defaults($_REQUEST, 'preview', 0));
70 * Check for doubly-submitted posts, and reject duplicates
71 * Note that we have to ignore previews, otherwise nothing will post
72 * after it's been previewed
74 if (!$preview && !empty($_REQUEST['post_id_random'])) {
75 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
76 logger("item post: duplicate post", LOGGER_DEBUG);
77 item_post_return(System::baseUrl(), $api_source, $return_path);
79 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
83 // Is this a reply to something?
84 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
85 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
87 $thr_parent_contact = null;
93 $parent_contact = null;
96 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
97 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
99 if ($thr_parent || $thr_parent_uri) {
101 $parent_item = Item::selectFirst([], ['id' => $thr_parent]);
102 } elseif ($thr_parent_uri) {
103 $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
106 // if this isn't the real parent of the conversation, find it
107 if (DBA::isResult($parent_item)) {
108 // The URI and the contact is taken from the direct parent which needn't to be the top parent
109 $thr_parent_uri = $parent_item['uri'];
110 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
112 if ($parent_item['id'] != $parent_item['parent']) {
113 $parent_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
117 if (!DBA::isResult($parent_item)) {
118 notice(L10n::t('Unable to locate original post.') . EOL);
119 if (!empty($_REQUEST['return'])) {
120 goaway($return_path);
125 $parent = $parent_item['id'];
126 $parent_user = $parent_item['uid'];
128 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
130 $objecttype = ACTIVITY_OBJ_COMMENT;
134 logger('mod_item: item_post parent=' . $parent);
137 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
138 $app = strip_tags(defaults($_REQUEST, 'source', ''));
139 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
140 $object = defaults($_REQUEST, 'object', '');
142 // Don't use "defaults" here. It would turn 0 to 1
143 if (!isset($_REQUEST['wall'])) {
146 $wall = $_REQUEST['wall'];
149 // Ensure that the user id in a thread always stay the same
150 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
151 $profile_uid = $parent_user;
154 // Check for multiple posts with the same message id (when the post was created via API)
155 if (($message_id != '') && ($profile_uid != 0)) {
156 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
157 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
162 // Allow commenting if it is an answer to a public post
163 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
165 // Now check that valid personal details have been provided
166 if (!Security::can_write_wall($profile_uid) && !$allow_comment) {
167 notice(L10n::t('Permission denied.') . EOL) ;
169 if (!empty($_REQUEST['return'])) {
170 goaway($return_path);
176 // Init post instance
179 // is this an edited post?
181 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
184 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
186 if (!DBA::isResult($user) && !$parent) {
194 if (!empty($orig_post)) {
195 $str_group_allow = $orig_post['allow_gid'];
196 $str_contact_allow = $orig_post['allow_cid'];
197 $str_group_deny = $orig_post['deny_gid'];
198 $str_contact_deny = $orig_post['deny_cid'];
199 $location = $orig_post['location'];
200 $coord = $orig_post['coord'];
201 $verb = $orig_post['verb'];
202 $objecttype = $orig_post['object-type'];
203 $app = $orig_post['app'];
204 $categories = $orig_post['file'];
205 $title = notags(trim($_REQUEST['title']));
206 $body = escape_tags(trim($_REQUEST['body']));
207 $private = $orig_post['private'];
208 $pubmail_enabled = $orig_post['pubmail'];
209 $network = $orig_post['network'];
210 $guid = $orig_post['guid'];
211 $extid = $orig_post['extid'];
216 * if coming from the API and no privacy settings are set,
217 * use the user default permissions - as they won't have
218 * been supplied via a form.
221 && !array_key_exists('contact_allow', $_REQUEST)
222 && !array_key_exists('group_allow', $_REQUEST)
223 && !array_key_exists('contact_deny', $_REQUEST)
224 && !array_key_exists('group_deny', $_REQUEST)) {
225 $str_group_allow = $user['allow_gid'];
226 $str_contact_allow = $user['allow_cid'];
227 $str_group_deny = $user['deny_gid'];
228 $str_contact_deny = $user['deny_cid'];
230 // use the posted permissions
231 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
232 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
233 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
234 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
237 $title = notags(trim(defaults($_REQUEST, 'title' , '')));
238 $location = notags(trim(defaults($_REQUEST, 'location', '')));
239 $coord = notags(trim(defaults($_REQUEST, 'coord' , '')));
240 $verb = notags(trim(defaults($_REQUEST, 'verb' , '')));
241 $emailcc = notags(trim(defaults($_REQUEST, 'emailcc' , '')));
242 $body = escape_tags(trim(defaults($_REQUEST, 'body' , '')));
243 $network = notags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
244 $guid = System::createUUID();
246 $postopts = defaults($_REQUEST, 'postopts', '');
248 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
250 if ($user['hidewall']) {
254 // If this is a comment, set the permissions from the parent.
257 // for non native networks use the network of the original post as network of the item
258 if (($parent_item['network'] != Protocol::DIASPORA)
259 && ($parent_item['network'] != Protocol::OSTATUS)
260 && ($network == "")) {
261 $network = $parent_item['network'];
264 $str_contact_allow = $parent_item['allow_cid'];
265 $str_group_allow = $parent_item['allow_gid'];
266 $str_contact_deny = $parent_item['deny_cid'];
267 $str_group_deny = $parent_item['deny_gid'];
268 $private = $parent_item['private'];
270 $wall = $parent_item['wall'];
273 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
275 // if using the API, we won't see pubmail_enable - figure out if it should be set
276 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
277 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
278 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
282 if (!strlen($body)) {
286 info(L10n::t('Empty post discarded.') . EOL);
287 if (!empty($_REQUEST['return'])) {
288 goaway($return_path);
294 if (!empty($categories)) {
295 // get the "fileas" tags for this post
296 $filedas = file_tag_file_to_list($categories, 'file');
298 // save old and new categories, so we can determine what needs to be deleted from pconfig
299 $categories_old = $categories;
300 $categories = file_tag_list_to_file(trim(defaults($_REQUEST, 'category', '')), 'category');
301 $categories_new = $categories;
302 if (!empty($filedas)) {
303 // append the fileas stuff to the new categories list
304 $categories .= file_tag_list_to_file($filedas, 'file');
307 // get contact info for poster
313 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
315 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
316 } elseif (remote_user()) {
317 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
318 foreach ($_SESSION['remote'] as $v) {
319 if ($v['uid'] == $profile_uid) {
320 $contact_id = $v['cid'];
326 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
330 if (DBA::isResult($author)) {
331 $contact_id = $author['id'];
334 // get contact info for owner
335 if ($profile_uid == local_user() || $allow_comment) {
336 $contact_record = $author;
338 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
341 // Look for any tags and linkify them
345 $tags = get_tags($body);
347 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
348 if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
349 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
350 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
357 $private_forum = false;
358 $only_to_forum = false;
362 foreach ($tags as $tag) {
363 $tag_type = substr($tag, 0, 1);
365 if ($tag_type == '#') {
370 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
371 * Robert Johnson should be first in the $tags array
373 $fullnametagged = false;
374 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
375 foreach ($tagged as $nextTag) {
376 if (stristr($nextTag, $tag . ' ')) {
377 $fullnametagged = true;
381 if ($fullnametagged) {
385 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
386 if ($success['replaced']) {
389 // When the forum is private or the forum is addressed with a "!" make the post private
390 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
391 $private_forum = $success['contact']['prv'];
392 $only_to_forum = ($tag_type == '!');
393 $private_id = $success['contact']['id'];
394 $forum_contact = $success['contact'];
395 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
396 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
397 $private_forum = false;
398 $only_to_forum = true;
399 $private_id = $success['contact']['id'];
400 $forum_contact = $success['contact'];
405 $original_contact_id = $contact_id;
407 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
408 // we tagged a forum in a top level post. Now we change the post
409 $private = $private_forum;
411 $str_group_allow = '';
412 $str_contact_deny = '';
413 $str_group_deny = '';
414 if ($private_forum) {
415 $str_contact_allow = '<' . $private_id . '>';
417 $str_contact_allow = '';
419 $contact_id = $private_id;
420 $contact_record = $forum_contact;
421 $_REQUEST['origin'] = false;
426 * When a photo was uploaded into the message using the (profile wall) ajax
427 * uploader, The permissions are initially set to disallow anybody but the
428 * owner from seeing it. This is because the permissions may not yet have been
429 * set for the post. If it's private, the photo permissions should be set
430 * appropriately. But we didn't know the final permissions on the post until
431 * now. So now we'll look for links of uploaded messages that are in the
432 * post and set them to the same permissions as the post itself.
437 /// @todo these lines should be moved to Model/Photo
438 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
440 if (count($images)) {
442 $objecttype = ACTIVITY_OBJ_IMAGE;
444 foreach ($images as $image) {
445 if (!stristr($image, System::baseUrl() . '/photo/')) {
448 $image_uri = substr($image,strrpos($image,'/') + 1);
449 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
450 if (!strlen($image_uri)) {
454 // Ensure to only modify photos that you own
455 $srch = '<' . intval($original_contact_id) . '>';
457 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
458 'resource-id' => $image_uri, 'uid' => $profile_uid];
459 if (!DBA::exists('photo', $condition)) {
463 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
464 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
465 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => L10n::t('Wall Photos')];
466 DBA::update('photo', $fields, $condition);
473 * Next link in any attachment references we find in the post.
477 /// @todo these lines should be moved to Model/Attach (Once it exists)
478 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
479 $attaches = $match[1];
480 if (count($attaches)) {
481 foreach ($attaches as $attach) {
482 // Ensure to only modify attachments that you own
483 $srch = '<' . intval($original_contact_id) . '>';
485 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
487 if (!DBA::exists('attach', $condition)) {
491 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
492 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
493 $condition = ['id' => $attach];
494 DBA::update('attach', $fields, $condition);
499 // embedded bookmark or attachment in post? set bookmark flag
501 $data = BBCode::getAttachmentData($body);
502 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
503 && ($posttype != Item::PT_PERSONAL_NOTE)) {
504 $posttype = Item::PT_PAGE;
505 $objecttype = ACTIVITY_OBJ_BOOKMARK;
508 $body = bb_translate_video($body);
511 // Fold multi-line [code] sequences
512 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
514 $body = BBCode::scaleExternalImages($body, false);
516 // Setting the object type if not defined before
518 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
519 $objectdata = BBCode::getAttachedData($body);
521 if ($objectdata["type"] == "link") {
522 $objecttype = ACTIVITY_OBJ_BOOKMARK;
523 } elseif ($objectdata["type"] == "video") {
524 $objecttype = ACTIVITY_OBJ_VIDEO;
525 } elseif ($objectdata["type"] == "photo") {
526 $objecttype = ACTIVITY_OBJ_IMAGE;
534 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
535 foreach ($match[2] as $mtch) {
536 $fields = ['id', 'filename', 'filesize', 'filetype'];
537 $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
538 if (DBA::isResult($attachment)) {
539 if (strlen($attachments)) {
542 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
543 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
544 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
546 $body = str_replace($match[1],'',$body);
550 if (!strlen($verb)) {
551 $verb = ACTIVITY_POST;
554 if ($network == "") {
555 $network = Protocol::DFRN;
558 $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
560 // even if the post arrived via API we are considering that it
561 // originated on this site by default for determining relayability.
563 // Don't use "defaults" here. It would turn 0 to 1
564 if (!isset($_REQUEST['origin'])) {
567 $origin = $_REQUEST['origin'];
570 $notify_type = ($parent ? 'comment-new' : 'wall-new');
572 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
574 // Fallback so that we alway have a parent uri
575 if (!$thr_parent_uri || !$parent) {
576 $thr_parent_uri = $uri;
580 $datarray['uid'] = $profile_uid;
581 $datarray['wall'] = $wall;
582 $datarray['gravity'] = $gravity;
583 $datarray['network'] = $network;
584 $datarray['contact-id'] = $contact_id;
585 $datarray['owner-name'] = $contact_record['name'];
586 $datarray['owner-link'] = $contact_record['url'];
587 $datarray['owner-avatar'] = $contact_record['thumb'];
588 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
589 $datarray['author-name'] = $author['name'];
590 $datarray['author-link'] = $author['url'];
591 $datarray['author-avatar'] = $author['thumb'];
592 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
593 $datarray['created'] = DateTimeFormat::utcNow();
594 $datarray['edited'] = DateTimeFormat::utcNow();
595 $datarray['commented'] = DateTimeFormat::utcNow();
596 $datarray['received'] = DateTimeFormat::utcNow();
597 $datarray['changed'] = DateTimeFormat::utcNow();
598 $datarray['extid'] = $extid;
599 $datarray['guid'] = $guid;
600 $datarray['uri'] = $uri;
601 $datarray['title'] = $title;
602 $datarray['body'] = $body;
603 $datarray['app'] = $app;
604 $datarray['location'] = $location;
605 $datarray['coord'] = $coord;
606 $datarray['tag'] = $str_tags;
607 $datarray['file'] = $categories;
608 $datarray['inform'] = $inform;
609 $datarray['verb'] = $verb;
610 $datarray['post-type'] = $posttype;
611 $datarray['object-type'] = $objecttype;
612 $datarray['allow_cid'] = $str_contact_allow;
613 $datarray['allow_gid'] = $str_group_allow;
614 $datarray['deny_cid'] = $str_contact_deny;
615 $datarray['deny_gid'] = $str_group_deny;
616 $datarray['private'] = $private;
617 $datarray['pubmail'] = $pubmail_enabled;
618 $datarray['attach'] = $attachments;
620 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
621 $datarray['parent-uri'] = $thr_parent_uri;
623 $datarray['postopts'] = $postopts;
624 $datarray['origin'] = $origin;
625 $datarray['moderated'] = false;
626 $datarray['object'] = $object;
629 * These fields are for the convenience of addons...
630 * 'self' if true indicates the owner is posting on their own wall
631 * If parent is 0 it is a top-level post.
633 $datarray['parent'] = $parent;
634 $datarray['self'] = $self;
636 // This triggers posts via API and the mirror functions
637 $datarray['api_source'] = $api_source;
639 // This field is for storing the raw conversation data
640 $datarray['protocol'] = Conversation::PARCEL_DFRN;
642 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
643 if (DBA::isResult($conversation)) {
644 if ($conversation['conversation-uri'] != '') {
645 $datarray['conversation-uri'] = $conversation['conversation-uri'];
647 if ($conversation['conversation-href'] != '') {
648 $datarray['conversation-href'] = $conversation['conversation-href'];
653 $datarray['edit'] = true;
655 $datarray['edit'] = false;
658 // Check for hashtags in the body and repair or add hashtag links
659 if ($preview || $orig_post) {
660 Item::setHashtags($datarray);
663 // preview mode - prepare the body for display and send it via json
665 require_once 'include/conversation.php';
666 // We set the datarray ID to -1 because in preview mode the dataray
667 // doesn't have an ID.
668 $datarray["id"] = -1;
669 $datarray["item_id"] = -1;
670 $datarray["author-network"] = Protocol::DFRN;
672 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
673 logger('preview: ' . $o);
674 echo json_encode(['preview' => $o]);
678 Addon::callHooks('post_local',$datarray);
680 if (!empty($datarray['cancel'])) {
681 logger('mod_item: post cancelled by addon.');
683 goaway($return_path);
686 $json = ['cancel' => 1];
687 if (!empty($_REQUEST['jsreload']) && strlen($_REQUEST['jsreload'])) {
688 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
691 echo json_encode($json);
697 // Fill the cache field
698 // This could be done in Item::update as well - but we have to check for the existance of some fields.
699 put_item_in_cache($datarray);
702 'title' => $datarray['title'],
703 'body' => $datarray['body'],
704 'tag' => $datarray['tag'],
705 'attach' => $datarray['attach'],
706 'file' => $datarray['file'],
707 'rendered-html' => $datarray['rendered-html'],
708 'rendered-hash' => $datarray['rendered-hash'],
709 'edited' => DateTimeFormat::utcNow(),
710 'changed' => DateTimeFormat::utcNow()];
712 Item::update($fields, ['id' => $post_id]);
714 // update filetags in pconfig
715 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
717 if (!empty($_REQUEST['return']) && strlen($return_path)) {
718 logger('return: ' . $return_path);
719 goaway($return_path);
726 unset($datarray['edit']);
727 unset($datarray['self']);
728 unset($datarray['api_source']);
730 $post_id = Item::insert($datarray);
733 logger("Item wasn't stored.");
734 goaway($return_path);
737 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
739 if (!DBA::isResult($datarray)) {
740 logger("Item with id ".$post_id." couldn't be fetched.");
741 goaway($return_path);
744 // update filetags in pconfig
745 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
747 // These notifications are sent if someone else is commenting other your wall
749 if ($contact_record != $author) {
751 'type' => NOTIFY_COMMENT,
752 'notify_flags' => $user['notify-flags'],
753 'language' => $user['language'],
754 'to_name' => $user['username'],
755 'to_email' => $user['email'],
756 'uid' => $user['uid'],
758 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
759 'source_name' => $datarray['author-name'],
760 'source_link' => $datarray['author-link'],
761 'source_photo' => $datarray['author-avatar'],
762 'verb' => ACTIVITY_POST,
765 'parent_uri' => $parent_item['uri']
769 // Store the comment signature information in case we need to relay to Diaspora
770 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
772 if (($contact_record != $author) && !count($forum_contact)) {
774 'type' => NOTIFY_WALL,
775 'notify_flags' => $user['notify-flags'],
776 'language' => $user['language'],
777 'to_name' => $user['username'],
778 'to_email' => $user['email'],
779 'uid' => $user['uid'],
781 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
782 'source_name' => $datarray['author-name'],
783 'source_link' => $datarray['author-link'],
784 'source_photo' => $datarray['author-avatar'],
785 'verb' => ACTIVITY_POST,
791 Addon::callHooks('post_local_end', $datarray);
793 if (strlen($emailcc) && $profile_uid == local_user()) {
794 $erecips = explode(',', $emailcc);
795 if (count($erecips)) {
796 foreach ($erecips as $recip) {
797 $addr = trim($recip);
798 if (!strlen($addr)) {
801 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
803 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
804 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
805 if (!$datarray['title']=='') {
806 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
808 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
810 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
811 $html = prepare_body($datarray);
812 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
814 'fromName' => $a->user['username'],
815 'fromEmail' => $a->user['email'],
817 'replyTo' => $a->user['email'],
818 'messageSubject' => $subject,
819 'htmlVersion' => $message,
820 'textVersion' => HTML::toPlaintext($html.$disclaimer)
822 Emailer::send($params);
827 // Insert an item entry for UID=0 for global entries.
828 // We now do it in the background to save some time.
829 // This is important in interactive environments like the frontend or the API.
830 // We don't fork a new process since this is done anyway with the following command
831 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
833 // Call the background process that is delivering the item to the receivers
834 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
836 logger('post_complete');
842 item_post_return(System::baseUrl(), $api_source, $return_path);
846 function item_post_return($baseurl, $api_source, $return_path)
848 // figure out how to return, depending on from whence we came
855 goaway($return_path);
858 $json = ['success' => 1];
859 if (!empty($_REQUEST['jsreload']) && strlen($_REQUEST['jsreload'])) {
860 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
863 logger('post_json: ' . print_r($json, true), LOGGER_DEBUG);
865 echo json_encode($json);
869 function item_content(App $a)
871 if (!local_user() && !remote_user()) {
875 require_once 'include/security.php';
879 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
881 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
883 $o = drop_item($a->argv[2]);
887 // ajax return: [<item id>, 0 (no perm) | <owner id>]
888 echo json_encode([intval($a->argv[2]), intval($o)]);
897 * This function removes the tag $tag from the text $body and replaces it with
898 * the appropiate link.
900 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
901 * @param unknown_type $body the text to replace the tag in
902 * @param string $inform a comma-seperated string containing everybody to inform
903 * @param string $str_tags string to add the tag to
904 * @param integer $profile_uid
905 * @param string $tag the tag to replace
906 * @param string $network The network of the post
908 * @return boolean true if replaced, false if not replaced
910 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
916 //is it a person tag?
917 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
918 $tag_type = substr($tag, 0, 1);
919 //is it already replaced?
920 if (strpos($tag, '[url=')) {
921 //append tag to str_tags
922 if (!stristr($str_tags, $tag)) {
923 if (strlen($str_tags)) {
929 // Checking for the alias that is used for OStatus
930 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
931 if (preg_match($pattern, $tag, $matches)) {
932 $data = Contact::getDetailsByURL($matches[1]);
934 if ($data["alias"] != "") {
935 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
937 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
938 if (strlen($str_tags)) {
942 $str_tags .= $newtag;
951 //get the person's name
952 $name = substr($tag, 1);
954 // Sometimes the tag detection doesn't seem to work right
955 // This is some workaround
956 $nameparts = explode(" ", $name);
957 $name = $nameparts[0];
959 // Try to detect the contact in various ways
960 if (strpos($name, 'http://')) {
961 // At first we have to ensure that the contact exists
962 Contact::getIdForURL($name);
964 // Now we should have something
965 $contact = Contact::getDetailsByURL($name);
966 } elseif (strpos($name, '@')) {
967 // This function automatically probes when no entry was found
968 $contact = Contact::getDetailsByAddr($name);
971 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
973 if (strrpos($name, '+')) {
974 // Is it in format @nick+number?
975 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
976 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
979 // select someone by nick or attag in the current network
980 if (!DBA::isResult($contact) && ($network != "")) {
981 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
982 $name, $name, $network, $profile_uid];
983 $contact = DBA::selectFirst('contact', $fields, $condition);
986 //select someone by name in the current network
987 if (!DBA::isResult($contact) && ($network != "")) {
988 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
989 $contact = DBA::selectFirst('contact', $fields, $condition);
992 // select someone by nick or attag in any network
993 if (!DBA::isResult($contact)) {
994 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
995 $contact = DBA::selectFirst('contact', $fields, $condition);
998 // select someone by name in any network
999 if (!DBA::isResult($contact)) {
1000 $condition = ['name' => $name, 'uid' => $profile_uid];
1001 $contact = DBA::selectFirst('contact', $fields, $condition);
1005 // Check if $contact has been successfully loaded
1006 if (DBA::isResult($contact)) {
1007 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1011 if (isset($contact["id"])) {
1012 $inform .= 'cid:' . $contact["id"];
1013 } elseif (isset($contact["notify"])) {
1014 $inform .= $contact["notify"];
1017 $profile = $contact["url"];
1018 $alias = $contact["alias"];
1019 $newname = $contact["nick"];
1021 if (($newname == "") || !in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::TWITTER, Protocol::STATUSNET])) {
1022 $newname = $contact["name"];
1026 //if there is an url for this persons profile
1027 if (isset($profile) && ($newname != "")) {
1029 // create profile link
1030 $profile = str_replace(',', '%2c', $profile);
1031 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1032 $body = str_replace($tag_type . $name, $newtag, $body);
1033 // append tag to str_tags
1034 if (!stristr($str_tags, $newtag)) {
1035 if (strlen($str_tags)) {
1038 $str_tags .= $newtag;
1042 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1043 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1045 if (strlen($alias)) {
1046 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1047 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1048 if (strlen($str_tags)) {
1051 $str_tags .= $newtag;
1057 return ['replaced' => $replaced, 'contact' => $contact];