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\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Conversation;
31 use Friendica\Model\Item;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Protocol\Email;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Emailer;
36 use Friendica\Util\Security;
38 require_once 'include/enotify.php';
39 require_once 'include/text.php';
40 require_once 'include/items.php';
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('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("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('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("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 = notags(trim($_REQUEST['title']));
205 $body = escape_tags(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 = notags(trim(defaults($_REQUEST, 'title' , '')));
237 $location = notags(trim(defaults($_REQUEST, 'location', '')));
238 $coord = notags(trim(defaults($_REQUEST, 'coord' , '')));
239 $verb = notags(trim(defaults($_REQUEST, 'verb' , '')));
240 $emailcc = notags(trim(defaults($_REQUEST, 'emailcc' , '')));
241 $body = escape_tags(trim(defaults($_REQUEST, 'body' , '')));
242 $network = notags(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)) {
294 // get the "fileas" tags for this post
295 $filedas = file_tag_file_to_list($categories, 'file');
297 // save old and new categories, so we can determine what needs to be deleted from pconfig
298 $categories_old = $categories;
299 $categories = file_tag_list_to_file(trim(defaults($_REQUEST, 'category', '')), 'category');
300 $categories_new = $categories;
301 if (!empty($filedas)) {
302 // append the fileas stuff to the new categories list
303 $categories .= file_tag_list_to_file($filedas, 'file');
306 // get contact info for poster
312 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
314 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
315 } elseif (remote_user()) {
316 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
317 foreach ($_SESSION['remote'] as $v) {
318 if ($v['uid'] == $profile_uid) {
319 $contact_id = $v['cid'];
325 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
329 if (DBA::isResult($author)) {
330 $contact_id = $author['id'];
333 // get contact info for owner
334 if ($profile_uid == local_user() || $allow_comment) {
335 $contact_record = $author;
337 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
340 // Look for any tags and linkify them
344 $tags = get_tags($body);
346 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
347 if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
348 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
349 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
356 $private_forum = false;
357 $only_to_forum = false;
361 foreach ($tags as $tag) {
362 $tag_type = substr($tag, 0, 1);
364 if ($tag_type == '#') {
369 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
370 * Robert Johnson should be first in the $tags array
372 $fullnametagged = false;
373 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
374 foreach ($tagged as $nextTag) {
375 if (stristr($nextTag, $tag . ' ')) {
376 $fullnametagged = true;
380 if ($fullnametagged) {
384 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
385 if ($success['replaced']) {
388 // When the forum is private or the forum is addressed with a "!" make the post private
389 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
390 $private_forum = $success['contact']['prv'];
391 $only_to_forum = ($tag_type == '!');
392 $private_id = $success['contact']['id'];
393 $forum_contact = $success['contact'];
394 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
395 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
396 $private_forum = false;
397 $only_to_forum = true;
398 $private_id = $success['contact']['id'];
399 $forum_contact = $success['contact'];
404 $original_contact_id = $contact_id;
406 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
407 // we tagged a forum in a top level post. Now we change the post
408 $private = $private_forum;
410 $str_group_allow = '';
411 $str_contact_deny = '';
412 $str_group_deny = '';
413 if ($private_forum) {
414 $str_contact_allow = '<' . $private_id . '>';
416 $str_contact_allow = '';
418 $contact_id = $private_id;
419 $contact_record = $forum_contact;
420 $_REQUEST['origin'] = false;
425 * When a photo was uploaded into the message using the (profile wall) ajax
426 * uploader, The permissions are initially set to disallow anybody but the
427 * owner from seeing it. This is because the permissions may not yet have been
428 * set for the post. If it's private, the photo permissions should be set
429 * appropriately. But we didn't know the final permissions on the post until
430 * now. So now we'll look for links of uploaded messages that are in the
431 * post and set them to the same permissions as the post itself.
436 /// @todo these lines should be moved to Model/Photo
437 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
439 if (count($images)) {
441 $objecttype = ACTIVITY_OBJ_IMAGE;
443 foreach ($images as $image) {
444 if (!stristr($image, System::baseUrl() . '/photo/')) {
447 $image_uri = substr($image,strrpos($image,'/') + 1);
448 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
449 if (!strlen($image_uri)) {
453 // Ensure to only modify photos that you own
454 $srch = '<' . intval($original_contact_id) . '>';
456 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
457 'resource-id' => $image_uri, 'uid' => $profile_uid];
458 if (!DBA::exists('photo', $condition)) {
462 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
463 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
464 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => L10n::t('Wall Photos')];
465 DBA::update('photo', $fields, $condition);
472 * Next link in any attachment references we find in the post.
476 /// @todo these lines should be moved to Model/Attach (Once it exists)
477 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
478 $attaches = $match[1];
479 if (count($attaches)) {
480 foreach ($attaches as $attach) {
481 // Ensure to only modify attachments that you own
482 $srch = '<' . intval($original_contact_id) . '>';
484 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
486 if (!DBA::exists('attach', $condition)) {
490 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
491 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
492 $condition = ['id' => $attach];
493 DBA::update('attach', $fields, $condition);
498 // embedded bookmark or attachment in post? set bookmark flag
500 $data = BBCode::getAttachmentData($body);
501 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
502 && ($posttype != Item::PT_PERSONAL_NOTE)) {
503 $posttype = Item::PT_PAGE;
504 $objecttype = ACTIVITY_OBJ_BOOKMARK;
507 $body = bb_translate_video($body);
510 // Fold multi-line [code] sequences
511 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
513 $body = BBCode::scaleExternalImages($body, false);
515 // Setting the object type if not defined before
517 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
518 $objectdata = BBCode::getAttachedData($body);
520 if ($objectdata["type"] == "link") {
521 $objecttype = ACTIVITY_OBJ_BOOKMARK;
522 } elseif ($objectdata["type"] == "video") {
523 $objecttype = ACTIVITY_OBJ_VIDEO;
524 } elseif ($objectdata["type"] == "photo") {
525 $objecttype = ACTIVITY_OBJ_IMAGE;
533 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
534 foreach ($match[2] as $mtch) {
535 $fields = ['id', 'filename', 'filesize', 'filetype'];
536 $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
537 if (DBA::isResult($attachment)) {
538 if (strlen($attachments)) {
541 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
542 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
543 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
545 $body = str_replace($match[1],'',$body);
549 if (!strlen($verb)) {
550 $verb = ACTIVITY_POST;
553 if ($network == "") {
554 $network = Protocol::DFRN;
557 $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
559 // even if the post arrived via API we are considering that it
560 // originated on this site by default for determining relayability.
562 // Don't use "defaults" here. It would turn 0 to 1
563 if (!isset($_REQUEST['origin'])) {
566 $origin = $_REQUEST['origin'];
569 $notify_type = ($parent ? 'comment-new' : 'wall-new');
571 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
573 // Fallback so that we alway have a parent uri
574 if (!$thr_parent_uri || !$parent) {
575 $thr_parent_uri = $uri;
579 $datarray['uid'] = $profile_uid;
580 $datarray['wall'] = $wall;
581 $datarray['gravity'] = $gravity;
582 $datarray['network'] = $network;
583 $datarray['contact-id'] = $contact_id;
584 $datarray['owner-name'] = $contact_record['name'];
585 $datarray['owner-link'] = $contact_record['url'];
586 $datarray['owner-avatar'] = $contact_record['thumb'];
587 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
588 $datarray['author-name'] = $author['name'];
589 $datarray['author-link'] = $author['url'];
590 $datarray['author-avatar'] = $author['thumb'];
591 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
592 $datarray['created'] = DateTimeFormat::utcNow();
593 $datarray['edited'] = DateTimeFormat::utcNow();
594 $datarray['commented'] = DateTimeFormat::utcNow();
595 $datarray['received'] = DateTimeFormat::utcNow();
596 $datarray['changed'] = DateTimeFormat::utcNow();
597 $datarray['extid'] = $extid;
598 $datarray['guid'] = $guid;
599 $datarray['uri'] = $uri;
600 $datarray['title'] = $title;
601 $datarray['body'] = $body;
602 $datarray['app'] = $app;
603 $datarray['location'] = $location;
604 $datarray['coord'] = $coord;
605 $datarray['tag'] = $str_tags;
606 $datarray['file'] = $categories;
607 $datarray['inform'] = $inform;
608 $datarray['verb'] = $verb;
609 $datarray['post-type'] = $posttype;
610 $datarray['object-type'] = $objecttype;
611 $datarray['allow_cid'] = $str_contact_allow;
612 $datarray['allow_gid'] = $str_group_allow;
613 $datarray['deny_cid'] = $str_contact_deny;
614 $datarray['deny_gid'] = $str_group_deny;
615 $datarray['private'] = $private;
616 $datarray['pubmail'] = $pubmail_enabled;
617 $datarray['attach'] = $attachments;
619 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
620 $datarray['parent-uri'] = $thr_parent_uri;
622 $datarray['postopts'] = $postopts;
623 $datarray['origin'] = $origin;
624 $datarray['moderated'] = false;
625 $datarray['object'] = $object;
628 * These fields are for the convenience of addons...
629 * 'self' if true indicates the owner is posting on their own wall
630 * If parent is 0 it is a top-level post.
632 $datarray['parent'] = $parent;
633 $datarray['self'] = $self;
635 // This triggers posts via API and the mirror functions
636 $datarray['api_source'] = $api_source;
638 // This field is for storing the raw conversation data
639 $datarray['protocol'] = Conversation::PARCEL_DFRN;
641 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
642 if (DBA::isResult($conversation)) {
643 if ($conversation['conversation-uri'] != '') {
644 $datarray['conversation-uri'] = $conversation['conversation-uri'];
646 if ($conversation['conversation-href'] != '') {
647 $datarray['conversation-href'] = $conversation['conversation-href'];
652 $datarray['edit'] = true;
654 $datarray['edit'] = false;
657 // Check for hashtags in the body and repair or add hashtag links
658 if ($preview || $orig_post) {
659 Item::setHashtags($datarray);
662 // preview mode - prepare the body for display and send it via json
664 require_once 'include/conversation.php';
665 // We set the datarray ID to -1 because in preview mode the dataray
666 // doesn't have an ID.
667 $datarray["id"] = -1;
668 $datarray["item_id"] = -1;
669 $datarray["author-network"] = Protocol::DFRN;
671 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
672 logger('preview: ' . $o);
673 echo json_encode(['preview' => $o]);
677 Addon::callHooks('post_local',$datarray);
679 if (!empty($datarray['cancel'])) {
680 logger('mod_item: post cancelled by addon.');
682 $a->internalRedirect($return_path);
685 $json = ['cancel' => 1];
686 if (!empty($_REQUEST['jsreload']) && strlen($_REQUEST['jsreload'])) {
687 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
690 echo json_encode($json);
696 // Fill the cache field
697 // This could be done in Item::update as well - but we have to check for the existance of some fields.
698 put_item_in_cache($datarray);
701 'title' => $datarray['title'],
702 'body' => $datarray['body'],
703 'tag' => $datarray['tag'],
704 'attach' => $datarray['attach'],
705 'file' => $datarray['file'],
706 'rendered-html' => $datarray['rendered-html'],
707 'rendered-hash' => $datarray['rendered-hash'],
708 'edited' => DateTimeFormat::utcNow(),
709 'changed' => DateTimeFormat::utcNow()];
711 Item::update($fields, ['id' => $post_id]);
713 // update filetags in pconfig
714 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
716 if (!empty($_REQUEST['return']) && strlen($return_path)) {
717 logger('return: ' . $return_path);
718 $a->internalRedirect($return_path);
725 unset($datarray['edit']);
726 unset($datarray['self']);
727 unset($datarray['api_source']);
729 $post_id = Item::insert($datarray);
732 logger("Item wasn't stored.");
733 $a->internalRedirect($return_path);
736 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
738 if (!DBA::isResult($datarray)) {
739 logger("Item with id ".$post_id." couldn't be fetched.");
740 $a->internalRedirect($return_path);
743 // update filetags in pconfig
744 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
746 // These notifications are sent if someone else is commenting other your wall
748 if ($contact_record != $author) {
750 'type' => NOTIFY_COMMENT,
751 'notify_flags' => $user['notify-flags'],
752 'language' => $user['language'],
753 'to_name' => $user['username'],
754 'to_email' => $user['email'],
755 'uid' => $user['uid'],
757 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
758 'source_name' => $datarray['author-name'],
759 'source_link' => $datarray['author-link'],
760 'source_photo' => $datarray['author-avatar'],
761 'verb' => ACTIVITY_POST,
764 'parent_uri' => $parent_item['uri']
768 // Store the comment signature information in case we need to relay to Diaspora
769 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
771 if (($contact_record != $author) && !count($forum_contact)) {
773 'type' => NOTIFY_WALL,
774 'notify_flags' => $user['notify-flags'],
775 'language' => $user['language'],
776 'to_name' => $user['username'],
777 'to_email' => $user['email'],
778 'uid' => $user['uid'],
780 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
781 'source_name' => $datarray['author-name'],
782 'source_link' => $datarray['author-link'],
783 'source_photo' => $datarray['author-avatar'],
784 'verb' => ACTIVITY_POST,
790 Addon::callHooks('post_local_end', $datarray);
792 if (strlen($emailcc) && $profile_uid == local_user()) {
793 $erecips = explode(',', $emailcc);
794 if (count($erecips)) {
795 foreach ($erecips as $recip) {
796 $addr = trim($recip);
797 if (!strlen($addr)) {
800 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
802 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
803 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
804 if (!$datarray['title']=='') {
805 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
807 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
809 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
810 $html = prepare_body($datarray);
811 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
813 'fromName' => $a->user['username'],
814 'fromEmail' => $a->user['email'],
816 'replyTo' => $a->user['email'],
817 'messageSubject' => $subject,
818 'htmlVersion' => $message,
819 'textVersion' => HTML::toPlaintext($html.$disclaimer)
821 Emailer::send($params);
826 // Insert an item entry for UID=0 for global entries.
827 // We now do it in the background to save some time.
828 // This is important in interactive environments like the frontend or the API.
829 // We don't fork a new process since this is done anyway with the following command
830 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
832 logger('post_complete');
838 item_post_return(System::baseUrl(), $api_source, $return_path);
842 function item_post_return($baseurl, $api_source, $return_path)
844 // figure out how to return, depending on from whence we came
852 $a->internalRedirect($return_path);
855 $json = ['success' => 1];
856 if (!empty($_REQUEST['jsreload']) && strlen($_REQUEST['jsreload'])) {
857 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
860 logger('post_json: ' . print_r($json, true), LOGGER_DEBUG);
862 echo json_encode($json);
866 function item_content(App $a)
868 if (!local_user() && !remote_user()) {
874 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
876 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
878 $o = drop_item($a->argv[2]);
882 // ajax return: [<item id>, 0 (no perm) | <owner id>]
883 echo json_encode([intval($a->argv[2]), intval($o)]);
892 * This function removes the tag $tag from the text $body and replaces it with
893 * the appropiate link.
895 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
896 * @param unknown_type $body the text to replace the tag in
897 * @param string $inform a comma-seperated string containing everybody to inform
898 * @param string $str_tags string to add the tag to
899 * @param integer $profile_uid
900 * @param string $tag the tag to replace
901 * @param string $network The network of the post
903 * @return boolean true if replaced, false if not replaced
905 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
911 //is it a person tag?
912 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
913 $tag_type = substr($tag, 0, 1);
914 //is it already replaced?
915 if (strpos($tag, '[url=')) {
916 //append tag to str_tags
917 if (!stristr($str_tags, $tag)) {
918 if (strlen($str_tags)) {
924 // Checking for the alias that is used for OStatus
925 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
926 if (preg_match($pattern, $tag, $matches)) {
927 $data = Contact::getDetailsByURL($matches[1]);
929 if ($data["alias"] != "") {
930 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
932 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
933 if (strlen($str_tags)) {
937 $str_tags .= $newtag;
946 //get the person's name
947 $name = substr($tag, 1);
949 // Sometimes the tag detection doesn't seem to work right
950 // This is some workaround
951 $nameparts = explode(" ", $name);
952 $name = $nameparts[0];
954 // Try to detect the contact in various ways
955 if (strpos($name, 'http://')) {
956 // At first we have to ensure that the contact exists
957 Contact::getIdForURL($name);
959 // Now we should have something
960 $contact = Contact::getDetailsByURL($name);
961 } elseif (strpos($name, '@')) {
962 // This function automatically probes when no entry was found
963 $contact = Contact::getDetailsByAddr($name);
966 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
968 if (strrpos($name, '+')) {
969 // Is it in format @nick+number?
970 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
971 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
974 // select someone by nick or attag in the current network
975 if (!DBA::isResult($contact) && ($network != "")) {
976 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
977 $name, $name, $network, $profile_uid];
978 $contact = DBA::selectFirst('contact', $fields, $condition);
981 //select someone by name in the current network
982 if (!DBA::isResult($contact) && ($network != "")) {
983 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
984 $contact = DBA::selectFirst('contact', $fields, $condition);
987 // select someone by nick or attag in any network
988 if (!DBA::isResult($contact)) {
989 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
990 $contact = DBA::selectFirst('contact', $fields, $condition);
993 // select someone by name in any network
994 if (!DBA::isResult($contact)) {
995 $condition = ['name' => $name, 'uid' => $profile_uid];
996 $contact = DBA::selectFirst('contact', $fields, $condition);
1000 // Check if $contact has been successfully loaded
1001 if (DBA::isResult($contact)) {
1002 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1006 if (isset($contact["id"])) {
1007 $inform .= 'cid:' . $contact["id"];
1008 } elseif (isset($contact["notify"])) {
1009 $inform .= $contact["notify"];
1012 $profile = $contact["url"];
1013 $alias = $contact["alias"];
1014 $newname = defaults($contact, "name", $contact["nick"]);
1017 //if there is an url for this persons profile
1018 if (isset($profile) && ($newname != "")) {
1020 // create profile link
1021 $profile = str_replace(',', '%2c', $profile);
1022 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1023 $body = str_replace($tag_type . $name, $newtag, $body);
1024 // append tag to str_tags
1025 if (!stristr($str_tags, $newtag)) {
1026 if (strlen($str_tags)) {
1029 $str_tags .= $newtag;
1033 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1034 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1036 if (strlen($alias)) {
1037 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1038 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1039 if (strlen($str_tags)) {
1042 $str_tags .= $newtag;
1048 return ['replaced' => $replaced, 'contact' => $contact];