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\Protocol\Diaspora;
35 use Friendica\Protocol\Email;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Emailer;
38 use Friendica\Util\Security;
39 use Friendica\Util\Strings;
41 require_once 'include/enotify.php';
42 require_once 'include/text.php';
43 require_once 'include/items.php';
45 function item_post(App $a) {
46 if (!local_user() && !remote_user()) {
52 if (!empty($_REQUEST['dropitems'])) {
53 $arr_drop = explode(',', $_REQUEST['dropitems']);
54 drop_items($arr_drop);
55 $json = ['success' => 1];
56 echo json_encode($json);
60 Addon::callHooks('post_local_start', $_REQUEST);
62 Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
64 $api_source = defaults($_REQUEST, 'api_source', false);
66 $message_id = ((!empty($_REQUEST['message_id']) && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
68 $return_path = defaults($_REQUEST, 'return', '');
69 $preview = intval(defaults($_REQUEST, 'preview', 0));
72 * Check for doubly-submitted posts, and reject duplicates
73 * Note that we have to ignore previews, otherwise nothing will post
74 * after it's been previewed
76 if (!$preview && !empty($_REQUEST['post_id_random'])) {
77 if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
78 Logger::log("item post: duplicate post", Logger::DEBUG);
79 item_post_return(System::baseUrl(), $api_source, $return_path);
81 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
85 // Is this a reply to something?
86 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
87 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
89 $thr_parent_contact = null;
95 $parent_contact = null;
98 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
99 $posttype = defaults($_REQUEST, 'post_type', Item::PT_ARTICLE);
101 if ($thr_parent || $thr_parent_uri) {
103 $parent_item = Item::selectFirst([], ['id' => $thr_parent]);
104 } elseif ($thr_parent_uri) {
105 $parent_item = Item::selectFirst([], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
108 // if this isn't the real parent of the conversation, find it
109 if (DBA::isResult($parent_item)) {
110 // The URI and the contact is taken from the direct parent which needn't to be the top parent
111 $thr_parent_uri = $parent_item['uri'];
112 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
114 if ($parent_item['id'] != $parent_item['parent']) {
115 $parent_item = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item['parent']]);
119 if (!DBA::isResult($parent_item)) {
120 notice(L10n::t('Unable to locate original post.') . EOL);
121 if (!empty($_REQUEST['return'])) {
122 $a->internalRedirect($return_path);
127 $parent = $parent_item['id'];
128 $parent_user = $parent_item['uid'];
130 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
132 $objecttype = ACTIVITY_OBJ_COMMENT;
136 Logger::log('mod_item: item_post parent=' . $parent);
139 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
140 $app = strip_tags(defaults($_REQUEST, 'source', ''));
141 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
142 $object = defaults($_REQUEST, 'object', '');
144 // Don't use "defaults" here. It would turn 0 to 1
145 if (!isset($_REQUEST['wall'])) {
148 $wall = $_REQUEST['wall'];
151 // Ensure that the user id in a thread always stay the same
152 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
153 $profile_uid = $parent_user;
156 // Check for multiple posts with the same message id (when the post was created via API)
157 if (($message_id != '') && ($profile_uid != 0)) {
158 if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
159 Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
164 // Allow commenting if it is an answer to a public post
165 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
167 // Now check that valid personal details have been provided
168 if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) {
169 notice(L10n::t('Permission denied.') . EOL);
171 if (!empty($_REQUEST['return'])) {
172 $a->internalRedirect($return_path);
178 // Init post instance
181 // is this an edited post?
183 $orig_post = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
186 $user = DBA::selectFirst('user', [], ['uid' => $profile_uid]);
188 if (!DBA::isResult($user) && !$parent) {
196 if (!empty($orig_post)) {
197 $str_group_allow = $orig_post['allow_gid'];
198 $str_contact_allow = $orig_post['allow_cid'];
199 $str_group_deny = $orig_post['deny_gid'];
200 $str_contact_deny = $orig_post['deny_cid'];
201 $location = $orig_post['location'];
202 $coord = $orig_post['coord'];
203 $verb = $orig_post['verb'];
204 $objecttype = $orig_post['object-type'];
205 $app = $orig_post['app'];
206 $categories = $orig_post['file'];
207 $title = Strings::escapeTags(trim($_REQUEST['title']));
208 $body = Strings::escapeHtml(trim($_REQUEST['body']));
209 $private = $orig_post['private'];
210 $pubmail_enabled = $orig_post['pubmail'];
211 $network = $orig_post['network'];
212 $guid = $orig_post['guid'];
213 $extid = $orig_post['extid'];
218 * if coming from the API and no privacy settings are set,
219 * use the user default permissions - as they won't have
220 * been supplied via a form.
223 && !array_key_exists('contact_allow', $_REQUEST)
224 && !array_key_exists('group_allow', $_REQUEST)
225 && !array_key_exists('contact_deny', $_REQUEST)
226 && !array_key_exists('group_deny', $_REQUEST)) {
227 $str_group_allow = $user['allow_gid'];
228 $str_contact_allow = $user['allow_cid'];
229 $str_group_deny = $user['deny_gid'];
230 $str_contact_deny = $user['deny_cid'];
232 // use the posted permissions
233 $str_group_allow = perms2str(defaults($_REQUEST, 'group_allow', ''));
234 $str_contact_allow = perms2str(defaults($_REQUEST, 'contact_allow', ''));
235 $str_group_deny = perms2str(defaults($_REQUEST, 'group_deny', ''));
236 $str_contact_deny = perms2str(defaults($_REQUEST, 'contact_deny', ''));
239 $title = Strings::escapeTags(trim(defaults($_REQUEST, 'title' , '')));
240 $location = Strings::escapeTags(trim(defaults($_REQUEST, 'location', '')));
241 $coord = Strings::escapeTags(trim(defaults($_REQUEST, 'coord' , '')));
242 $verb = Strings::escapeTags(trim(defaults($_REQUEST, 'verb' , '')));
243 $emailcc = Strings::escapeTags(trim(defaults($_REQUEST, 'emailcc' , '')));
244 $body = Strings::escapeHtml(trim(defaults($_REQUEST, 'body' , '')));
245 $network = Strings::escapeTags(trim(defaults($_REQUEST, 'network' , Protocol::DFRN)));
246 $guid = System::createUUID();
248 $postopts = defaults($_REQUEST, 'postopts', '');
250 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
252 if ($user['hidewall']) {
256 // If this is a comment, set the permissions from the parent.
259 // for non native networks use the network of the original post as network of the item
260 if (($parent_item['network'] != Protocol::DIASPORA)
261 && ($parent_item['network'] != Protocol::OSTATUS)
262 && ($network == "")) {
263 $network = $parent_item['network'];
266 $str_contact_allow = $parent_item['allow_cid'];
267 $str_group_allow = $parent_item['allow_gid'];
268 $str_contact_deny = $parent_item['deny_cid'];
269 $str_group_deny = $parent_item['deny_gid'];
270 $private = $parent_item['private'];
272 $wall = $parent_item['wall'];
275 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
277 // if using the API, we won't see pubmail_enable - figure out if it should be set
278 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
279 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
280 $pubmail_enabled = DBA::exists('mailacct', ["`uid` = ? AND `server` != ? AND `pubmail`", local_user(), '']);
284 if (!strlen($body)) {
288 info(L10n::t('Empty post discarded.') . EOL);
289 if (!empty($_REQUEST['return'])) {
290 $a->internalRedirect($return_path);
296 if (!empty($categories))
298 // get the "fileas" tags for this post
299 $filedas = FileTag::fileToList($categories, 'file');
302 // save old and new categories, so we can determine what needs to be deleted from pconfig
303 $categories_old = $categories;
304 $categories = FileTag::listToFile(trim(defaults($_REQUEST, 'category', '')), 'category');
305 $categories_new = $categories;
307 if (!empty($filedas))
309 // append the fileas stuff to the new categories list
310 $categories .= FileTag::listToFile($filedas, 'file');
313 // get contact info for poster
319 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
321 $author = DBA::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
322 } elseif (remote_user()) {
323 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
324 foreach ($_SESSION['remote'] as $v) {
325 if ($v['uid'] == $profile_uid) {
326 $contact_id = $v['cid'];
332 $author = DBA::selectFirst('contact', [], ['id' => $contact_id]);
336 if (DBA::isResult($author)) {
337 $contact_id = $author['id'];
340 // get contact info for owner
341 if ($profile_uid == local_user() || $allow_comment) {
342 $contact_record = $author;
344 $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
347 // Look for any tags and linkify them
351 $tags = BBCode::getTags($body);
353 // Add a tag if the parent contact is from ActivityPub or OStatus (This will notify them)
354 if ($parent && in_array($thr_parent_contact['network'], [Protocol::OSTATUS, Protocol::ACTIVITYPUB])) {
355 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
356 if (!stripos(implode($tags), '[url=' . $thr_parent_contact['url'] . ']')) {
363 $private_forum = false;
364 $only_to_forum = false;
368 foreach ($tags as $tag) {
369 $tag_type = substr($tag, 0, 1);
371 if ($tag_type == '#') {
376 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
377 * Robert Johnson should be first in the $tags array
379 $fullnametagged = false;
380 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
381 foreach ($tagged as $nextTag) {
382 if (stristr($nextTag, $tag . ' ')) {
383 $fullnametagged = true;
387 if ($fullnametagged) {
391 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
392 if ($success['replaced']) {
395 // When the forum is private or the forum is addressed with a "!" make the post private
396 if (is_array($success['contact']) && (!empty($success['contact']['prv']) || ($tag_type == '!'))) {
397 $private_forum = $success['contact']['prv'];
398 $only_to_forum = ($tag_type == '!');
399 $private_id = $success['contact']['id'];
400 $forum_contact = $success['contact'];
401 } elseif (is_array($success['contact']) && !empty($success['contact']['forum']) &&
402 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
403 $private_forum = false;
404 $only_to_forum = true;
405 $private_id = $success['contact']['id'];
406 $forum_contact = $success['contact'];
411 $original_contact_id = $contact_id;
413 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
414 // we tagged a forum in a top level post. Now we change the post
415 $private = $private_forum;
417 $str_group_allow = '';
418 $str_contact_deny = '';
419 $str_group_deny = '';
420 if ($private_forum) {
421 $str_contact_allow = '<' . $private_id . '>';
423 $str_contact_allow = '';
425 $contact_id = $private_id;
426 $contact_record = $forum_contact;
427 $_REQUEST['origin'] = false;
432 * When a photo was uploaded into the message using the (profile wall) ajax
433 * uploader, The permissions are initially set to disallow anybody but the
434 * owner from seeing it. This is because the permissions may not yet have been
435 * set for the post. If it's private, the photo permissions should be set
436 * appropriately. But we didn't know the final permissions on the post until
437 * now. So now we'll look for links of uploaded messages that are in the
438 * post and set them to the same permissions as the post itself.
443 /// @todo these lines should be moved to Model/Photo
444 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
446 if (count($images)) {
448 $objecttype = ACTIVITY_OBJ_IMAGE;
450 foreach ($images as $image) {
451 if (!stristr($image, System::baseUrl() . '/photo/')) {
454 $image_uri = substr($image,strrpos($image,'/') + 1);
455 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
456 if (!strlen($image_uri)) {
460 // Ensure to only modify photos that you own
461 $srch = '<' . intval($original_contact_id) . '>';
463 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
464 'resource-id' => $image_uri, 'uid' => $profile_uid];
465 if (!DBA::exists('photo', $condition)) {
469 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
470 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
471 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid];
472 DBA::update('photo', $fields, $condition);
479 * Next link in any attachment references we find in the post.
483 /// @todo these lines should be moved to Model/Attach (Once it exists)
484 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
485 $attaches = $match[1];
486 if (count($attaches)) {
487 foreach ($attaches as $attach) {
488 // Ensure to only modify attachments that you own
489 $srch = '<' . intval($original_contact_id) . '>';
491 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
493 if (!DBA::exists('attach', $condition)) {
497 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
498 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
499 $condition = ['id' => $attach];
500 DBA::update('attach', $fields, $condition);
505 // embedded bookmark or attachment in post? set bookmark flag
507 $data = BBCode::getAttachmentData($body);
508 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"]))
509 && ($posttype != Item::PT_PERSONAL_NOTE)) {
510 $posttype = Item::PT_PAGE;
511 $objecttype = ACTIVITY_OBJ_BOOKMARK;
514 $body = bb_translate_video($body);
517 // Fold multi-line [code] sequences
518 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
520 $body = BBCode::scaleExternalImages($body, false);
522 // Setting the object type if not defined before
524 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
525 $objectdata = BBCode::getAttachedData($body);
527 if ($objectdata["type"] == "link") {
528 $objecttype = ACTIVITY_OBJ_BOOKMARK;
529 } elseif ($objectdata["type"] == "video") {
530 $objecttype = ACTIVITY_OBJ_VIDEO;
531 } elseif ($objectdata["type"] == "photo") {
532 $objecttype = ACTIVITY_OBJ_IMAGE;
540 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
541 foreach ($match[2] as $mtch) {
542 $fields = ['id', 'filename', 'filesize', 'filetype'];
543 $attachment = DBA::selectFirst('attach', $fields, ['id' => $mtch]);
544 if (DBA::isResult($attachment)) {
545 if (strlen($attachments)) {
548 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
549 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
550 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
552 $body = str_replace($match[1],'',$body);
556 if (!strlen($verb)) {
557 $verb = ACTIVITY_POST;
560 if ($network == "") {
561 $network = Protocol::DFRN;
564 $gravity = ($parent ? GRAVITY_COMMENT : GRAVITY_PARENT);
566 // even if the post arrived via API we are considering that it
567 // originated on this site by default for determining relayability.
569 // Don't use "defaults" here. It would turn 0 to 1
570 if (!isset($_REQUEST['origin'])) {
573 $origin = $_REQUEST['origin'];
576 $notify_type = ($parent ? 'comment-new' : 'wall-new');
578 $uri = ($message_id ? $message_id : Item::newURI($api_source ? $profile_uid : $uid, $guid));
580 // Fallback so that we alway have a parent uri
581 if (!$thr_parent_uri || !$parent) {
582 $thr_parent_uri = $uri;
586 $datarray['uid'] = $profile_uid;
587 $datarray['wall'] = $wall;
588 $datarray['gravity'] = $gravity;
589 $datarray['network'] = $network;
590 $datarray['contact-id'] = $contact_id;
591 $datarray['owner-name'] = $contact_record['name'];
592 $datarray['owner-link'] = $contact_record['url'];
593 $datarray['owner-avatar'] = $contact_record['thumb'];
594 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']);
595 $datarray['author-name'] = $author['name'];
596 $datarray['author-link'] = $author['url'];
597 $datarray['author-avatar'] = $author['thumb'];
598 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']);
599 $datarray['created'] = DateTimeFormat::utcNow();
600 $datarray['edited'] = DateTimeFormat::utcNow();
601 $datarray['commented'] = DateTimeFormat::utcNow();
602 $datarray['received'] = DateTimeFormat::utcNow();
603 $datarray['changed'] = DateTimeFormat::utcNow();
604 $datarray['extid'] = $extid;
605 $datarray['guid'] = $guid;
606 $datarray['uri'] = $uri;
607 $datarray['title'] = $title;
608 $datarray['body'] = $body;
609 $datarray['app'] = $app;
610 $datarray['location'] = $location;
611 $datarray['coord'] = $coord;
612 $datarray['tag'] = $str_tags;
613 $datarray['file'] = $categories;
614 $datarray['inform'] = $inform;
615 $datarray['verb'] = $verb;
616 $datarray['post-type'] = $posttype;
617 $datarray['object-type'] = $objecttype;
618 $datarray['allow_cid'] = $str_contact_allow;
619 $datarray['allow_gid'] = $str_group_allow;
620 $datarray['deny_cid'] = $str_contact_deny;
621 $datarray['deny_gid'] = $str_group_deny;
622 $datarray['private'] = $private;
623 $datarray['pubmail'] = $pubmail_enabled;
624 $datarray['attach'] = $attachments;
626 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
627 $datarray['parent-uri'] = $thr_parent_uri;
629 $datarray['postopts'] = $postopts;
630 $datarray['origin'] = $origin;
631 $datarray['moderated'] = false;
632 $datarray['object'] = $object;
635 * These fields are for the convenience of addons...
636 * 'self' if true indicates the owner is posting on their own wall
637 * If parent is 0 it is a top-level post.
639 $datarray['parent'] = $parent;
640 $datarray['self'] = $self;
642 // This triggers posts via API and the mirror functions
643 $datarray['api_source'] = $api_source;
645 // This field is for storing the raw conversation data
646 $datarray['protocol'] = Conversation::PARCEL_DFRN;
648 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $datarray['parent-uri']]);
649 if (DBA::isResult($conversation)) {
650 if ($conversation['conversation-uri'] != '') {
651 $datarray['conversation-uri'] = $conversation['conversation-uri'];
653 if ($conversation['conversation-href'] != '') {
654 $datarray['conversation-href'] = $conversation['conversation-href'];
659 $datarray['edit'] = true;
661 $datarray['edit'] = false;
664 // Check for hashtags in the body and repair or add hashtag links
665 if ($preview || $orig_post) {
666 Item::setHashtags($datarray);
669 // preview mode - prepare the body for display and send it via json
671 require_once 'include/conversation.php';
672 // We set the datarray ID to -1 because in preview mode the dataray
673 // doesn't have an ID.
674 $datarray["id"] = -1;
675 $datarray["item_id"] = -1;
676 $datarray["author-network"] = Protocol::DFRN;
678 $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
679 Logger::log('preview: ' . $o);
680 echo json_encode(['preview' => $o]);
684 Addon::callHooks('post_local',$datarray);
686 if (!empty($datarray['cancel'])) {
687 Logger::log('mod_item: post cancelled by addon.');
689 $a->internalRedirect($return_path);
692 $json = ['cancel' => 1];
693 if (!empty($_REQUEST['jsreload'])) {
694 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
697 echo json_encode($json);
702 // Fill the cache field
703 // This could be done in Item::update as well - but we have to check for the existance of some fields.
704 Item::putInCache($datarray);
707 'title' => $datarray['title'],
708 'body' => $datarray['body'],
709 'tag' => $datarray['tag'],
710 'attach' => $datarray['attach'],
711 'file' => $datarray['file'],
712 'rendered-html' => $datarray['rendered-html'],
713 'rendered-hash' => $datarray['rendered-hash'],
714 'edited' => DateTimeFormat::utcNow(),
715 'changed' => DateTimeFormat::utcNow()];
717 Item::update($fields, ['id' => $post_id]);
719 // update filetags in pconfig
720 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
722 if (!empty($_REQUEST['return']) && strlen($return_path)) {
723 Logger::log('return: ' . $return_path);
724 $a->internalRedirect($return_path);
731 unset($datarray['edit']);
732 unset($datarray['self']);
733 unset($datarray['api_source']);
736 $signed = Diaspora::createCommentSignature($uid, $datarray);
737 if (!empty($signed)) {
738 $datarray['diaspora_signed_text'] = json_encode($signed);
742 $post_id = Item::insert($datarray);
745 Logger::log("Item wasn't stored.");
746 $a->internalRedirect($return_path);
749 $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
751 if (!DBA::isResult($datarray)) {
752 Logger::log("Item with id ".$post_id." couldn't be fetched.");
753 $a->internalRedirect($return_path);
756 // update filetags in pconfig
757 FileTag::updatePconfig($uid, $categories_old, $categories_new, 'category');
759 // These notifications are sent if someone else is commenting other your wall
761 if ($contact_record != $author) {
763 'type' => NOTIFY_COMMENT,
764 'notify_flags' => $user['notify-flags'],
765 'language' => $user['language'],
766 'to_name' => $user['username'],
767 'to_email' => $user['email'],
768 'uid' => $user['uid'],
770 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
771 'source_name' => $datarray['author-name'],
772 'source_link' => $datarray['author-link'],
773 'source_photo' => $datarray['author-avatar'],
774 'verb' => ACTIVITY_POST,
777 'parent_uri' => $parent_item['uri']
781 if (($contact_record != $author) && !count($forum_contact)) {
783 'type' => NOTIFY_WALL,
784 'notify_flags' => $user['notify-flags'],
785 'language' => $user['language'],
786 'to_name' => $user['username'],
787 'to_email' => $user['email'],
788 'uid' => $user['uid'],
790 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
791 'source_name' => $datarray['author-name'],
792 'source_link' => $datarray['author-link'],
793 'source_photo' => $datarray['author-avatar'],
794 'verb' => ACTIVITY_POST,
800 Addon::callHooks('post_local_end', $datarray);
802 if (strlen($emailcc) && $profile_uid == local_user()) {
803 $erecips = explode(',', $emailcc);
804 if (count($erecips)) {
805 foreach ($erecips as $recip) {
806 $addr = trim($recip);
807 if (!strlen($addr)) {
810 $disclaimer = '<hr />' . L10n::t('This message was sent to you by %s, a member of the Friendica social network.', $a->user['username'])
812 $disclaimer .= L10n::t('You may visit them online at %s', System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
813 $disclaimer .= L10n::t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
814 if (!$datarray['title']=='') {
815 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
817 $subject = Email::encodeHeader('[Friendica]' . ' ' . L10n::t('%s posted an update.', $a->user['username']), 'UTF-8');
819 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
820 $html = Item::prepareBody($datarray);
821 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
823 'fromName' => $a->user['username'],
824 'fromEmail' => $a->user['email'],
826 'replyTo' => $a->user['email'],
827 'messageSubject' => $subject,
828 'htmlVersion' => $message,
829 'textVersion' => HTML::toPlaintext($html.$disclaimer)
831 Emailer::send($params);
836 // Insert an item entry for UID=0 for global entries.
837 // We now do it in the background to save some time.
838 // This is important in interactive environments like the frontend or the API.
839 // We don't fork a new process since this is done anyway with the following command
840 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
842 // When we are doing some forum posting via ! we have to start the notifier manually.
843 // These kind of posts don't initiate the notifier call in the item class.
844 if ($only_to_forum) {
845 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
848 Logger::log('post_complete');
854 item_post_return(System::baseUrl(), $api_source, $return_path);
858 function item_post_return($baseurl, $api_source, $return_path)
860 // figure out how to return, depending on from whence we came
868 $a->internalRedirect($return_path);
871 $json = ['success' => 1];
872 if (!empty($_REQUEST['jsreload'])) {
873 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
876 Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
878 echo json_encode($json);
882 function item_content(App $a)
884 if (!local_user() && !remote_user()) {
890 if (($a->argc >= 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
892 $o = Item::deleteForUser(['id' => $a->argv[2]], local_user());
894 if (!empty($a->argv[3])) {
895 $o = drop_item($a->argv[2], $a->argv[3]);
898 $o = drop_item($a->argv[2]);
903 // ajax return: [<item id>, 0 (no perm) | <owner id>]
904 echo json_encode([intval($a->argv[2]), intval($o)]);
913 * This function removes the tag $tag from the text $body and replaces it with
914 * the appropiate link.
916 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
917 * @param unknown_type $body the text to replace the tag in
918 * @param string $inform a comma-seperated string containing everybody to inform
919 * @param string $str_tags string to add the tag to
920 * @param integer $profile_uid
921 * @param string $tag the tag to replace
922 * @param string $network The network of the post
924 * @return boolean true if replaced, false if not replaced
926 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
932 //is it a person tag?
933 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
934 $tag_type = substr($tag, 0, 1);
935 //is it already replaced?
936 if (strpos($tag, '[url=')) {
937 //append tag to str_tags
938 if (!stristr($str_tags, $tag)) {
939 if (strlen($str_tags)) {
945 // Checking for the alias that is used for OStatus
946 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
947 if (preg_match($pattern, $tag, $matches)) {
948 $data = Contact::getDetailsByURL($matches[1]);
950 if ($data["alias"] != "") {
951 $newtag = '@[url=' . $data["alias"] . ']' . $data["nick"] . '[/url]';
953 if (!stripos($str_tags, '[url=' . $data["alias"] . ']')) {
954 if (strlen($str_tags)) {
958 $str_tags .= $newtag;
967 //get the person's name
968 $name = substr($tag, 1);
970 // Sometimes the tag detection doesn't seem to work right
971 // This is some workaround
972 $nameparts = explode(" ", $name);
973 $name = $nameparts[0];
975 // Try to detect the contact in various ways
976 if (strpos($name, 'http://')) {
977 // At first we have to ensure that the contact exists
978 Contact::getIdForURL($name);
980 // Now we should have something
981 $contact = Contact::getDetailsByURL($name);
982 } elseif (strpos($name, '@')) {
983 // This function automatically probes when no entry was found
984 $contact = Contact::getDetailsByAddr($name);
987 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
989 if (strrpos($name, '+')) {
990 // Is it in format @nick+number?
991 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
992 $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
995 // select someone by nick or attag in the current network
996 if (!DBA::isResult($contact) && ($network != "")) {
997 $condition = ["(`nick` = ? OR `attag` = ?) AND `network` = ? AND `uid` = ?",
998 $name, $name, $network, $profile_uid];
999 $contact = DBA::selectFirst('contact', $fields, $condition);
1002 //select someone by name in the current network
1003 if (!DBA::isResult($contact) && ($network != "")) {
1004 $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
1005 $contact = DBA::selectFirst('contact', $fields, $condition);
1008 // select someone by nick or attag in any network
1009 if (!DBA::isResult($contact)) {
1010 $condition = ["(`nick` = ? OR `attag` = ?) AND `uid` = ?", $name, $name, $profile_uid];
1011 $contact = DBA::selectFirst('contact', $fields, $condition);
1014 // select someone by name in any network
1015 if (!DBA::isResult($contact)) {
1016 $condition = ['name' => $name, 'uid' => $profile_uid];
1017 $contact = DBA::selectFirst('contact', $fields, $condition);
1021 // Check if $contact has been successfully loaded
1022 if (DBA::isResult($contact)) {
1023 if (strlen($inform) && (isset($contact["notify"]) || isset($contact["id"]))) {
1027 if (isset($contact["id"])) {
1028 $inform .= 'cid:' . $contact["id"];
1029 } elseif (isset($contact["notify"])) {
1030 $inform .= $contact["notify"];
1033 $profile = $contact["url"];
1034 $alias = $contact["alias"];
1035 $newname = defaults($contact, "name", $contact["nick"]);
1038 //if there is an url for this persons profile
1039 if (isset($profile) && ($newname != "")) {
1041 // create profile link
1042 $profile = str_replace(',', '%2c', $profile);
1043 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1044 $body = str_replace($tag_type . $name, $newtag, $body);
1045 // append tag to str_tags
1046 if (!stristr($str_tags, $newtag)) {
1047 if (strlen($str_tags)) {
1050 $str_tags .= $newtag;
1054 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1055 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1057 if (strlen($alias)) {
1058 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1059 if (!stripos($str_tags, '[url=' . $alias . ']')) {
1060 if (strlen($str_tags)) {
1063 $str_tags .= $newtag;
1069 return ['replaced' => $replaced, 'contact' => $contact];