4 * This is the POST destination for most all locally posted
5 * text stuff. This function handles status, wall-to-wall status,
6 * local comments, and remote coments that are posted on this site
7 * (as opposed to being delivered in a feed).
8 * Also processed here are posts and comments coming through the
9 * statusnet/twitter API.
11 * All of these become an "item" which is our basic unit of
14 * Posts that originate externally or do not fall into the above
15 * posting categories go through item_store() instead of this function.
19 use Friendica\Core\System;
21 require_once 'include/crypto.php';
22 require_once 'include/enotify.php';
23 require_once 'include/email.php';
24 require_once 'include/tags.php';
25 require_once 'include/files.php';
26 require_once 'include/threads.php';
27 require_once 'include/text.php';
28 require_once 'include/items.php';
29 require_once 'include/probe.php';
30 require_once 'include/diaspora.php';
31 require_once 'include/Contact.php';
33 function item_post(App $a) {
35 if ((! local_user()) && (! remote_user()) && (! x($_REQUEST, 'commenter'))) {
39 require_once 'include/security.php';
43 if (x($_REQUEST, 'dropitems')) {
44 $arr_drop = explode(',', $_REQUEST['dropitems']);
45 drop_items($arr_drop);
46 $json = array('success' => 1);
47 echo json_encode($json);
51 call_hooks('post_local_start', $_REQUEST);
52 // logger('postinput ' . file_get_contents('php://input'));
53 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
55 $api_source = ((x($_REQUEST, 'api_source') && $_REQUEST['api_source']) ? true : false);
57 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
59 $return_path = ((x($_REQUEST, 'return')) ? $_REQUEST['return'] : '');
60 $preview = ((x($_REQUEST, 'preview')) ? intval($_REQUEST['preview']) : 0);
63 * Check for doubly-submitted posts, and reject duplicates
64 * Note that we have to ignore previews, otherwise nothing will post
65 * after it's been previewed
67 if (!$preview && x($_REQUEST, 'post_id_random')) {
68 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
69 logger("item post: duplicate post", LOGGER_DEBUG);
70 item_post_return(System::baseUrl(), $api_source, $return_path);
72 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
76 // Is this a reply to something?
77 $parent = ((x($_REQUEST, 'parent')) ? intval($_REQUEST['parent']) : 0);
78 $parent_uri = ((x($_REQUEST, 'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
81 $parent_contact = null;
87 if ($parent || $parent_uri) {
89 $objecttype = ACTIVITY_OBJ_COMMENT;
91 if (! x($_REQUEST, 'type')) {
92 $_REQUEST['type'] = 'net-comment';
96 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
99 } elseif ($parent_uri && local_user()) {
100 // This is coming from an API source, and we are logged in
101 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
107 // if this isn't the real parent of the conversation, find it
108 if (dbm::is_result($r)) {
109 $parid = $r[0]['parent'];
110 $parent_uri = $r[0]['uri'];
111 if ($r[0]['id'] != $r[0]['parent']) {
112 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
118 if (! dbm::is_result($r)) {
119 notice( t('Unable to locate original post.') . EOL);
120 if (x($_REQUEST, 'return')) {
121 goaway($return_path);
125 $parent_item = $r[0];
126 $parent = $r[0]['id'];
128 // multi-level threading - preserve the info but re-parent to our single level threading
129 //if(($parid) && ($parid != $parent))
130 $thr_parent = $parent_uri;
132 if ($parent_item['contact-id'] && $uid) {
133 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
134 intval($parent_item['contact-id']),
137 if (dbm::is_result($r)) {
138 $parent_contact = $r[0];
141 // If the contact id doesn't fit with the contact, then set the contact to null
142 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent));
143 if (dbm::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
144 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
145 $parent_contact = get_contact_details_by_url($thrparent[0]["author-link"]);
147 if (!isset($parent_contact["nick"])) {
148 $probed_contact = probe_url($thrparent[0]["author-link"]);
149 if ($probed_contact["network"] != NETWORK_FEED) {
150 $parent_contact = $probed_contact;
151 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
152 $parent_contact["thumb"] = $probed_contact["photo"];
153 $parent_contact["micro"] = $probed_contact["photo"];
154 $parent_contact["addr"] = $probed_contact["addr"];
157 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
159 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
162 if ($parent_contact["nick"] == "") {
163 $parent_contact["nick"] = $parent_contact["name"];
169 logger('mod_item: item_post parent=' . $parent);
172 $profile_uid = ((x($_REQUEST, 'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
173 $post_id = ((x($_REQUEST, 'post_id')) ? intval($_REQUEST['post_id']) : 0);
174 $app = ((x($_REQUEST, 'source')) ? strip_tags($_REQUEST['source']) : '');
175 $extid = ((x($_REQUEST, 'extid')) ? strip_tags($_REQUEST['extid']) : '');
176 $object = ((x($_REQUEST, 'object')) ? $_REQUEST['object'] : '');
178 // Check for multiple posts with the same message id (when the post was created via API)
179 if (($message_id != '') && ($profile_uid != 0)) {
180 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
185 if (dbm::is_result($r)) {
186 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
191 $allow_moderated = false;
193 // here is where we are going to check for permission to post a moderated comment.
195 // First check that the parent exists and it is a wall item.
197 if ((x($_REQUEST, 'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
198 notice(t('Permission denied.') . EOL) ;
199 if (x($_REQUEST, 'return')) {
200 goaway($return_path);
206 * Now check that it is a page_type of PAGE_BLOG, and that valid personal details
207 * have been provided, and run any anti-spam plugins
209 if ((! can_write_wall($a, $profile_uid)) && (! $allow_moderated)) {
210 notice(t('Permission denied.') . EOL) ;
211 if (x($_REQUEST, 'return')) {
212 goaway($return_path);
218 // is this an edited post?
223 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
224 intval($profile_uid),
227 if (! dbm::is_result($i)) {
235 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
238 if (dbm::is_result($r)) {
243 $str_group_allow = $orig_post['allow_gid'];
244 $str_contact_allow = $orig_post['allow_cid'];
245 $str_group_deny = $orig_post['deny_gid'];
246 $str_contact_deny = $orig_post['deny_cid'];
247 $location = $orig_post['location'];
248 $coord = $orig_post['coord'];
249 $verb = $orig_post['verb'];
250 $objecttype = $orig_post['object-type'];
251 $emailcc = $orig_post['emailcc'];
252 $app = $orig_post['app'];
253 $categories = $orig_post['file'];
254 $title = notags(trim($_REQUEST['title']));
255 $body = escape_tags(trim($_REQUEST['body']));
256 $private = $orig_post['private'];
257 $pubmail_enable = $orig_post['pubmail'];
258 $network = $orig_post['network'];
259 $guid = $orig_post['guid'];
260 $extid = $orig_post['extid'];
265 * if coming from the API and no privacy settings are set,
266 * use the user default permissions - as they won't have
267 * been supplied via a form.
269 /// @TODO use x($_REQUEST, 'foo') here
271 && (! array_key_exists('contact_allow', $_REQUEST))
272 && (! array_key_exists('group_allow', $_REQUEST))
273 && (! array_key_exists('contact_deny', $_REQUEST))
274 && (! array_key_exists('group_deny', $_REQUEST))) {
275 $str_group_allow = $user['allow_gid'];
276 $str_contact_allow = $user['allow_cid'];
277 $str_group_deny = $user['deny_gid'];
278 $str_contact_deny = $user['deny_cid'];
281 // use the posted permissions
283 $str_group_allow = perms2str($_REQUEST['group_allow']);
284 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
285 $str_group_deny = perms2str($_REQUEST['group_deny']);
286 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
289 $title = notags(trim($_REQUEST['title']));
290 $location = notags(trim($_REQUEST['location']));
291 $coord = notags(trim($_REQUEST['coord']));
292 $verb = notags(trim($_REQUEST['verb']));
293 $emailcc = notags(trim($_REQUEST['emailcc']));
294 $body = escape_tags(trim($_REQUEST['body']));
295 $network = notags(trim($_REQUEST['network']));
296 $guid = get_guid(32);
298 item_add_language_opt($_REQUEST);
299 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
301 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
303 if ($user['hidewall']) {
307 // If this is a comment, set the permissions from the parent.
311 // for non native networks use the network of the original post as network of the item
312 if (($parent_item['network'] != NETWORK_DIASPORA)
313 && ($parent_item['network'] != NETWORK_OSTATUS)
314 && ($network == "")) {
315 $network = $parent_item['network'];
318 $str_contact_allow = $parent_item['allow_cid'];
319 $str_group_allow = $parent_item['allow_gid'];
320 $str_contact_deny = $parent_item['deny_cid'];
321 $str_group_deny = $parent_item['deny_gid'];
322 $private = $parent_item['private'];
325 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
327 // if using the API, we won't see pubmail_enable - figure out if it should be set
329 if ($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
330 $mail_disabled = ((function_exists('imap_open') && (! get_config('system', 'imap_disabled'))) ? 0 : 1);
331 if (! $mail_disabled) {
332 /// @TODO Check if only pubmail is loaded, * loads all columns
333 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
336 if (dbm::is_result($r) && intval($r[0]['pubmail'])) {
337 $pubmail_enabled = true;
342 if (! strlen($body)) {
346 info(t('Empty post discarded.') . EOL );
347 if (x($_REQUEST, 'return')) {
348 goaway($return_path);
354 if (strlen($categories)) {
355 // get the "fileas" tags for this post
356 $filedas = file_tag_file_to_list($categories, 'file');
358 // save old and new categories, so we can determine what needs to be deleted from pconfig
359 $categories_old = $categories;
360 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
361 $categories_new = $categories;
362 if (strlen($filedas)) {
363 // append the fileas stuff to the new categories list
364 $categories .= file_tag_list_to_file($filedas, 'file');
367 // get contact info for poster
373 if ((local_user()) && (local_user() == $profile_uid)) {
375 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
376 intval($_SESSION['uid']));
377 } elseif(remote_user()) {
378 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
379 foreach ($_SESSION['remote'] as $v) {
380 if ($v['uid'] == $profile_uid) {
381 $contact_id = $v['cid'];
387 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
393 if (dbm::is_result($r)) {
395 $contact_id = $author['id'];
398 // get contact info for owner
400 if ($profile_uid == local_user()) {
401 $contact_record = $author;
403 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
406 if (dbm::is_result($r)) {
407 $contact_record = $r[0];
411 $post_type = notags(trim($_REQUEST['type']));
413 if ($post_type === 'net-comment' && $parent_item !== null) {
414 if ($parent_item['wall'] == 1) {
415 $post_type = 'wall-comment';
417 $post_type = 'remote-comment';
422 * When a photo was uploaded into the message using the (profile wall) ajax
423 * uploader, The permissions are initially set to disallow anybody but the
424 * owner from seeing it. This is because the permissions may not yet have been
425 * set for the post. If it's private, the photo permissions should be set
426 * appropriately. But we didn't know the final permissions on the post until
427 * now. So now we'll look for links of uploaded messages that are in the
428 * post and set them to the same permissions as the post itself.
433 if ((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
435 if (count($images)) {
437 $objecttype = ACTIVITY_OBJ_IMAGE;
439 foreach ($images as $image) {
440 if (! stristr($image,System::baseUrl() . '/photo/')) {
443 $image_uri = substr($image,strrpos($image,'/') + 1);
444 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
445 if (! strlen($image_uri)) {
448 $srch = '<' . intval($contact_id) . '>';
450 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
451 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
457 if (! dbm::is_result($r)) {
461 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
462 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
463 dbesc($str_contact_allow),
464 dbesc($str_group_allow),
465 dbesc($str_contact_deny),
466 dbesc($str_group_deny),
468 intval($profile_uid),
469 dbesc( t('Wall Photos'))
477 * Next link in any attachment references we find in the post.
481 if ((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
482 $attaches = $match[1];
483 if (count($attaches)) {
484 foreach ($attaches as $attach) {
485 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
486 intval($profile_uid),
489 if (dbm::is_result($r)) {
490 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
491 WHERE `uid` = %d AND `id` = %d",
492 dbesc($str_contact_allow),
493 dbesc($str_group_allow),
494 dbesc($str_contact_deny),
495 dbesc($str_group_deny),
496 intval($profile_uid),
504 // embedded bookmark or attachment in post? set bookmark flag
507 $data = get_attachment_data($body);
508 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
509 $objecttype = ACTIVITY_OBJ_BOOKMARK;
513 $body = bb_translate_video($body);
516 // Fold multi-line [code] sequences
517 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
519 $body = scale_external_images($body, false);
521 // Setting the object type if not defined before
523 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
524 require_once 'include/plaintext.php';
525 $objectdata = get_attached_data($body);
527 if ($post["type"] == "link") {
528 $objecttype = ACTIVITY_OBJ_BOOKMARK;
529 } elseif ($post["type"] == "video") {
530 $objecttype = ACTIVITY_OBJ_VIDEO;
531 } elseif ($post["type"] == "photo") {
532 $objecttype = ACTIVITY_OBJ_IMAGE;
537 // Look for any tags and linkify them
541 $tags = get_tags($body);
544 * add a statusnet style reply tag if the original post was from there
545 * and we are replying, and there isn't one already
547 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
548 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
550 if (!in_array($contact, $tags)) {
551 $body = $contact . ' ' . $body;
555 $toplevel_contact = "";
556 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
557 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
558 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
559 if (dbm::is_result($toplevel_parent)) {
560 if (!empty($toplevel_parent[0]['addr'])) {
561 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
563 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
566 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
567 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
570 if (!in_array($toplevel_contact, $tags)) {
571 $tags[] = $toplevel_contact;
577 $private_forum = false;
580 foreach ($tags as $tag) {
582 $tag_type = substr($tag, 0, 1);
584 if ($tag_type == '#') {
589 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
590 * Robert Johnson should be first in the $tags array
592 $fullnametagged = false;
593 /// @TODO $tagged is initialized above if() block and is not filled, maybe old-lost code?
594 foreach ($tagged as $nextTag) {
595 if (stristr($nextTag, $tag . ' ')) {
596 $fullnametagged = true;
600 if ($fullnametagged) {
604 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
605 if ($success['replaced']) {
608 // When the forum is private or the forum is addressed with a "!" make the post private
609 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
610 $private_forum = true;
611 $private_id = $success['contact']['id'];
616 if ($private_forum && !$parent && !$private) {
617 // we tagged a private forum in a top level post and the message was public.
620 $str_contact_allow = '<' . $private_id . '>';
626 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
627 foreach ($match[2] as $mtch) {
628 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
629 intval($profile_uid),
632 if (dbm::is_result($r)) {
633 if (strlen($attachments)) {
636 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
638 $body = str_replace($match[1],'',$body);
644 if ($post_type === 'wall' || $post_type === 'wall-comment') {
648 if (! strlen($verb)) {
649 $verb = ACTIVITY_POST ;
652 if ($network == "") {
653 $network = NETWORK_DFRN;
656 $gravity = (($parent) ? 6 : 0 );
658 // even if the post arrived via API we are considering that it
659 // originated on this site by default for determining relayability.
661 $origin = ((x($_REQUEST, 'origin')) ? intval($_REQUEST['origin']) : 1);
663 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
665 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
667 // Fallback so that we alway have a thr-parent
673 $datarray['uid'] = $profile_uid;
674 $datarray['type'] = $post_type;
675 $datarray['wall'] = $wall;
676 $datarray['gravity'] = $gravity;
677 $datarray['network'] = $network;
678 $datarray['contact-id'] = $contact_id;
679 $datarray['owner-name'] = $contact_record['name'];
680 $datarray['owner-link'] = $contact_record['url'];
681 $datarray['owner-avatar'] = $contact_record['thumb'];
682 $datarray['owner-id'] = get_contact($datarray['owner-link'], 0);
683 $datarray['author-name'] = $author['name'];
684 $datarray['author-link'] = $author['url'];
685 $datarray['author-avatar'] = $author['thumb'];
686 $datarray['author-id'] = get_contact($datarray['author-link'], 0);
687 $datarray['created'] = datetime_convert();
688 $datarray['edited'] = datetime_convert();
689 $datarray['commented'] = datetime_convert();
690 $datarray['received'] = datetime_convert();
691 $datarray['changed'] = datetime_convert();
692 $datarray['extid'] = $extid;
693 $datarray['guid'] = $guid;
694 $datarray['uri'] = $uri;
695 $datarray['title'] = $title;
696 $datarray['body'] = $body;
697 $datarray['app'] = $app;
698 $datarray['location'] = $location;
699 $datarray['coord'] = $coord;
700 $datarray['tag'] = $str_tags;
701 $datarray['file'] = $categories;
702 $datarray['inform'] = $inform;
703 $datarray['verb'] = $verb;
704 $datarray['object-type'] = $objecttype;
705 $datarray['allow_cid'] = $str_contact_allow;
706 $datarray['allow_gid'] = $str_group_allow;
707 $datarray['deny_cid'] = $str_contact_deny;
708 $datarray['deny_gid'] = $str_group_deny;
709 $datarray['private'] = $private;
710 $datarray['pubmail'] = $pubmail_enable;
711 $datarray['attach'] = $attachments;
712 $datarray['bookmark'] = intval($bookmark);
713 $datarray['thr-parent'] = $thr_parent;
714 $datarray['postopts'] = $postopts;
715 $datarray['origin'] = $origin;
716 $datarray['moderated'] = $allow_moderated;
717 $datarray['gcontact-id'] = get_gcontact_id(array("url" => $datarray['author-link'], "network" => $datarray['network'],
718 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
719 $datarray['object'] = $object;
722 * These fields are for the convenience of plugins...
723 * 'self' if true indicates the owner is posting on their own wall
724 * If parent is 0 it is a top-level post.
726 $datarray['parent'] = $parent;
727 $datarray['self'] = $self;
728 // $datarray['prvnets'] = $user['prvnets'];
730 // This triggers posts via API and the mirror functions
731 $datarray['api_source'] = $api_source;
733 $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
734 $datarray['plink'] = System::baseUrl() . '/display/' . urlencode($datarray['guid']);
735 $datarray['last-child'] = 1;
736 $datarray['visible'] = 1;
738 $datarray['protocol'] = PROTOCOL_DFRN;
740 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
741 if (dbm::is_result($r)) {
742 if ($r['conversation-uri'] != '') {
743 $datarray['conversation-uri'] = $r['conversation-uri'];
745 if ($r['conversation-href'] != '') {
746 $datarray['conversation-href'] = $r['conversation-href'];
751 $datarray['edit'] = true;
754 // Search for hashtags
755 item_body_set_hashtags($datarray);
757 // preview mode - prepare the body for display and send it via json
759 require_once 'include/conversation.php';
760 // We set the datarray ID to -1 because in preview mode the dataray
761 // doesn't have an ID.
762 $datarray["id"] = -1;
763 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
764 logger('preview: ' . $o);
765 echo json_encode(array('preview' => $o));
769 call_hooks('post_local',$datarray);
771 if (x($datarray, 'cancel')) {
772 logger('mod_item: post cancelled by plugin.');
774 goaway($return_path);
777 $json = array('cancel' => 1);
778 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
779 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
782 echo json_encode($json);
786 // Fill the cache field
787 put_item_in_cache($datarray);
789 $datarray = store_conversation($datarray);
792 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `rendered-html` = '%s', `rendered-hash` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
793 dbesc($datarray['title']),
794 dbesc($datarray['body']),
795 dbesc($datarray['tag']),
796 dbesc($datarray['attach']),
797 dbesc($datarray['file']),
798 dbesc($datarray['rendered-html']),
799 dbesc($datarray['rendered-hash']),
800 dbesc(datetime_convert()),
801 dbesc(datetime_convert()),
806 create_tags_from_item($post_id);
807 create_files_from_item($post_id);
808 update_thread($post_id);
810 // update filetags in pconfig
811 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
813 proc_run(PRIORITY_HIGH, "include/notifier.php", 'edit_post', $post_id);
814 if ((x($_REQUEST, 'return')) && strlen($return_path)) {
815 logger('return: ' . $return_path);
816 goaway($return_path);
825 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
826 `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
827 `author-name`, `author-link`, `author-avatar`, `author-id`,
828 `created`, `edited`, `commented`, `received`, `changed`,
829 `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
830 `tag`, `inform`, `verb`, `object-type`, `postopts`,
831 `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
832 `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
833 `rendered-html`, `rendered-hash`, `gcontact-id`, `object`,
834 `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
835 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
836 '%s', '%s', '%s', %d,
837 '%s', '%s', '%s', %d,
838 '%s', '%s', '%s', '%s', '%s',
839 '%s', '%s', '%s', '%s', '%s', '%s', '%s',
840 '%s', '%s', '%s', '%s', '%s',
841 '%s', '%s', '%s', '%s', %d,
842 %d, '%s', %d, %d, %d, '%s',
843 '%s', '%s', %d, '%s',
844 %d, '%s', '%s', %d, %d)",
845 dbesc($datarray['guid']),
846 dbesc($datarray['extid']),
847 intval($datarray['uid']),
848 dbesc($datarray['type']),
849 intval($datarray['wall']),
850 intval($datarray['gravity']),
851 dbesc($datarray['network']),
852 intval($datarray['contact-id']),
853 dbesc($datarray['owner-name']),
854 dbesc($datarray['owner-link']),
855 dbesc($datarray['owner-avatar']),
856 intval($datarray['owner-id']),
857 dbesc($datarray['author-name']),
858 dbesc($datarray['author-link']),
859 dbesc($datarray['author-avatar']),
860 intval($datarray['author-id']),
861 dbesc($datarray['created']),
862 dbesc($datarray['edited']),
863 dbesc($datarray['commented']),
864 dbesc($datarray['received']),
865 dbesc($datarray['changed']),
866 dbesc($datarray['uri']),
867 dbesc($datarray['thr-parent']),
868 dbesc($datarray['title']),
869 dbesc($datarray['body']),
870 dbesc($datarray['app']),
871 dbesc($datarray['location']),
872 dbesc($datarray['coord']),
873 dbesc($datarray['tag']),
874 dbesc($datarray['inform']),
875 dbesc($datarray['verb']),
876 dbesc($datarray['object-type']),
877 dbesc($datarray['postopts']),
878 dbesc($datarray['allow_cid']),
879 dbesc($datarray['allow_gid']),
880 dbesc($datarray['deny_cid']),
881 dbesc($datarray['deny_gid']),
882 intval($datarray['private']),
883 intval($datarray['pubmail']),
884 dbesc($datarray['attach']),
885 intval($datarray['bookmark']),
886 intval($datarray['origin']),
887 intval($datarray['moderated']),
888 dbesc($datarray['file']),
889 dbesc($datarray['rendered-html']),
890 dbesc($datarray['rendered-hash']),
891 intval($datarray['gcontact-id']),
892 dbesc($datarray['object']),
893 intval($datarray['parent']),
894 dbesc($datarray['parent-uri']),
895 dbesc($datarray['plink']),
896 intval($datarray['last-child']),
897 intval($datarray['visible'])
900 if (dbm::is_result($r)) {
901 $post_id = dba::lastInsertId();
903 logger('mod_item: unable to create post.');
909 logger('mod_item: unable to retrieve post that was just stored.');
910 notice(t('System error. Post not saved.') . EOL);
911 goaway($return_path);
915 logger('mod_item: saved item ' . $post_id);
917 $datarray["id"] = $post_id;
919 item_set_last_item($datarray);
921 // update filetags in pconfig
922 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
926 // This item is the last leaf and gets the comment box, clear any ancestors
927 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
928 dbesc(datetime_convert()),
933 // update the commented timestamp on the parent
934 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
935 dbesc(datetime_convert()),
936 dbesc(datetime_convert()),
940 if ($contact_record != $author) {
942 'type' => NOTIFY_COMMENT,
943 'notify_flags' => $user['notify-flags'],
944 'language' => $user['language'],
945 'to_name' => $user['username'],
946 'to_email' => $user['email'],
947 'uid' => $user['uid'],
949 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
950 'source_name' => $datarray['author-name'],
951 'source_link' => $datarray['author-link'],
952 'source_photo' => $datarray['author-avatar'],
953 'verb' => ACTIVITY_POST,
956 'parent_uri' => $parent_item['uri']
962 // Store the comment signature information in case we need to relay to Diaspora
963 Diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
968 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
972 if ($contact_record != $author) {
974 'type' => NOTIFY_WALL,
975 'notify_flags' => $user['notify-flags'],
976 'language' => $user['language'],
977 'to_name' => $user['username'],
978 'to_email' => $user['email'],
979 'uid' => $user['uid'],
981 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
982 'source_name' => $datarray['author-name'],
983 'source_link' => $datarray['author-link'],
984 'source_photo' => $datarray['author-avatar'],
985 'verb' => ACTIVITY_POST,
991 call_hooks('post_local_end', $datarray);
993 if (strlen($emailcc) && $profile_uid == local_user()) {
994 $erecips = explode(',', $emailcc);
995 if (count($erecips)) {
996 foreach ($erecips as $recip) {
997 $addr = trim($recip);
998 if (! strlen($addr)) {
1001 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
1003 $disclaimer .= sprintf( t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
1004 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
1005 if (!$datarray['title']=='') {
1006 $subject = email_header_encode($datarray['title'], 'UTF-8');
1008 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'), $a->user['username']), 'UTF-8');
1010 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1011 $html = prepare_body($datarray);
1012 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1013 include_once 'include/html2plain.php';
1015 'fromName' => $a->user['username'],
1016 'fromEmail' => $a->user['email'],
1018 'replyTo' => $a->user['email'],
1019 'messageSubject' => $subject,
1020 'htmlVersion' => $message,
1021 'textVersion' => html2plain($html.$disclaimer),
1023 Emailer::send($params);
1028 if ($post_id == $parent) {
1029 add_thread($post_id);
1031 update_thread($parent, true);
1036 create_tags_from_item($post_id);
1037 create_files_from_item($post_id);
1039 // Insert an item entry for UID=0 for global entries.
1040 // We now do it in the background to save some time.
1041 // This is important in interactive environments like the frontend or the API.
1042 // We don't fork a new process since this is done anyway with the following command
1043 proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "include/create_shadowentry.php", $post_id);
1045 // Call the background process that is delivering the item to the receivers
1046 proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $post_id);
1048 logger('post_complete');
1050 item_post_return(System::baseUrl(), $api_source, $return_path);
1054 function item_post_return($baseurl, $api_source, $return_path) {
1055 // figure out how to return, depending on from whence we came
1062 goaway($return_path);
1065 $json = array('success' => 1);
1066 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
1067 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1070 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1072 echo json_encode($json);
1078 function item_content(App $a) {
1080 if ((! local_user()) && (! remote_user())) {
1084 require_once 'include/security.php';
1087 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1088 $o = drop_item($a->argv[2], !is_ajax());
1090 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1091 echo json_encode(array(intval($a->argv[2]), intval($o)));
1099 * This function removes the tag $tag from the text $body and replaces it with
1100 * the appropiate link.
1102 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
1103 * @param unknown_type $body the text to replace the tag in
1104 * @param string $inform a comma-seperated string containing everybody to inform
1105 * @param string $str_tags string to add the tag to
1106 * @param integer $profile_uid
1107 * @param string $tag the tag to replace
1108 * @param string $network The network of the post
1110 * @return boolean true if replaced, false if not replaced
1112 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1113 require_once 'include/socgraph.php';
1119 //is it a person tag?
1120 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1121 $tag_type = substr($tag, 0, 1);
1122 //is it already replaced?
1123 if (strpos($tag, '[url=')) {
1124 //append tag to str_tags
1125 if (!stristr($str_tags, $tag)) {
1126 if (strlen($str_tags)) {
1132 // Checking for the alias that is used for OStatus
1133 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1134 if (preg_match($pattern, $tag, $matches)) {
1136 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1137 normalise_link($matches[1]));
1138 if (!dbm::is_result($r)) {
1139 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1140 normalise_link($matches[1]));
1142 if (dbm::is_result($r)) {
1145 $data = probe_url($matches[1]);
1148 if ($data["alias"] != "") {
1149 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1150 if (!stristr($str_tags, $newtag)) {
1151 if (strlen($str_tags)) {
1154 $str_tags .= $newtag;
1162 //get the person's name
1163 $name = substr($tag, 1);
1165 // Sometimes the tag detection doesn't seem to work right
1166 // This is some workaround
1167 $nameparts = explode(" ", $name);
1168 $name = $nameparts[0];
1170 // Try to detect the contact in various ways
1171 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1172 // Is it in format @user@domain.tld or @http://domain.tld/...?
1174 // First check the contact table for the address
1175 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1176 WHERE `addr` = '%s' AND `uid` = %d AND
1177 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1180 intval($profile_uid),
1181 dbesc(NETWORK_OSTATUS)
1184 // Then check in the contact table for the url
1185 if (!dbm::is_result($r)) {
1186 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1187 WHERE `nurl` = '%s' AND `uid` = %d AND
1188 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1190 dbesc(normalise_link($name)),
1191 intval($profile_uid),
1192 dbesc(NETWORK_OSTATUS)
1196 // Then check in the global contacts for the address
1197 if (!dbm::is_result($r)) {
1198 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1199 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1202 dbesc(NETWORK_OSTATUS)
1206 // Then check in the global contacts for the url
1207 if (!dbm::is_result($r)) {
1208 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1209 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1211 dbesc(normalise_link($name)),
1212 dbesc(NETWORK_OSTATUS)
1216 if (!dbm::is_result($r)) {
1217 $probed = probe_url($name);
1218 if ($result['network'] != NETWORK_PHANTOM) {
1219 update_gcontact($probed);
1220 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1221 dbesc(normalise_link($probed["url"])));
1226 if (strrpos($name, '+')) {
1227 // Is it in format @nick+number?
1228 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1230 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1232 intval($profile_uid)
1236 // select someone by attag or nick and the name passed in the current network
1237 if(!dbm::is_result($r) && ($network != ""))
1238 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1242 intval($profile_uid)
1245 //select someone from this user's contacts by name in the current network
1246 if (!dbm::is_result($r) && ($network != "")) {
1247 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1250 intval($profile_uid)
1254 // select someone by attag or nick and the name passed in
1255 if(!dbm::is_result($r)) {
1256 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1259 intval($profile_uid)
1263 // select someone from this user's contacts by name
1264 if(!dbm::is_result($r)) {
1265 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1267 intval($profile_uid)
1272 if (dbm::is_result($r)) {
1273 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1277 if (isset($r[0]["id"])) {
1278 $inform .= 'cid:' . $r[0]["id"];
1279 } elseif (isset($r[0]["notify"])) {
1280 $inform .= $r[0]["notify"];
1283 $profile = $r[0]["url"];
1284 $alias = $r[0]["alias"];
1285 $newname = $r[0]["nick"];
1286 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1287 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1288 $newname = $r[0]["name"];
1292 //if there is an url for this persons profile
1293 if (isset($profile) && ($newname != "")) {
1295 // create profile link
1296 $profile = str_replace(',', '%2c', $profile);
1297 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1298 $body = str_replace($tag_type . $name, $newtag, $body);
1299 // append tag to str_tags
1300 if (! stristr($str_tags, $newtag)) {
1301 if (strlen($str_tags)) {
1304 $str_tags .= $newtag;
1308 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1309 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1311 if (strlen($alias)) {
1312 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1313 if (! stristr($str_tags, $newtag)) {
1314 if (strlen($str_tags)) {
1317 $str_tags .= $newtag;
1323 return array('replaced' => $replaced, 'contact' => $r[0]);