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 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
562 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
563 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
566 if (!in_array($toplevel_contact, $tags)) {
567 $tags[] = $toplevel_contact;
573 $private_forum = false;
576 foreach ($tags as $tag) {
578 if (strpos($tag, '#') === 0) {
583 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
584 * Robert Johnson should be first in the $tags array
586 $fullnametagged = false;
587 /// @TODO $tagged is initialized above if() block and is not filled, maybe old-lost code?
588 foreach ($tagged as $nextTag) {
589 if (stristr($nextTag, $tag . ' ')) {
590 $fullnametagged = true;
594 if ($fullnametagged) {
598 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
599 if ($success['replaced']) {
602 if (is_array($success['contact']) && intval($success['contact']['prv'])) {
603 $private_forum = true;
604 $private_id = $success['contact']['id'];
609 if (($private_forum) && (! $parent) && (! $private)) {
610 // we tagged a private forum in a top level post and the message was public.
613 $str_contact_allow = '<' . $private_id . '>';
619 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
620 foreach ($match[2] as $mtch) {
621 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
622 intval($profile_uid),
625 if (dbm::is_result($r)) {
626 if (strlen($attachments)) {
629 $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]';
631 $body = str_replace($match[1],'',$body);
637 if ($post_type === 'wall' || $post_type === 'wall-comment') {
641 if (! strlen($verb)) {
642 $verb = ACTIVITY_POST ;
645 if ($network == "") {
646 $network = NETWORK_DFRN;
649 $gravity = (($parent) ? 6 : 0 );
651 // even if the post arrived via API we are considering that it
652 // originated on this site by default for determining relayability.
654 $origin = ((x($_REQUEST, 'origin')) ? intval($_REQUEST['origin']) : 1);
656 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
658 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid, $guid));
660 // Fallback so that we alway have a thr-parent
666 $datarray['uid'] = $profile_uid;
667 $datarray['type'] = $post_type;
668 $datarray['wall'] = $wall;
669 $datarray['gravity'] = $gravity;
670 $datarray['network'] = $network;
671 $datarray['contact-id'] = $contact_id;
672 $datarray['owner-name'] = $contact_record['name'];
673 $datarray['owner-link'] = $contact_record['url'];
674 $datarray['owner-avatar'] = $contact_record['thumb'];
675 $datarray['owner-id'] = get_contact($datarray['owner-link'], 0);
676 $datarray['author-name'] = $author['name'];
677 $datarray['author-link'] = $author['url'];
678 $datarray['author-avatar'] = $author['thumb'];
679 $datarray['author-id'] = get_contact($datarray['author-link'], 0);
680 $datarray['created'] = datetime_convert();
681 $datarray['edited'] = datetime_convert();
682 $datarray['commented'] = datetime_convert();
683 $datarray['received'] = datetime_convert();
684 $datarray['changed'] = datetime_convert();
685 $datarray['extid'] = $extid;
686 $datarray['guid'] = $guid;
687 $datarray['uri'] = $uri;
688 $datarray['title'] = $title;
689 $datarray['body'] = $body;
690 $datarray['app'] = $app;
691 $datarray['location'] = $location;
692 $datarray['coord'] = $coord;
693 $datarray['tag'] = $str_tags;
694 $datarray['file'] = $categories;
695 $datarray['inform'] = $inform;
696 $datarray['verb'] = $verb;
697 $datarray['object-type'] = $objecttype;
698 $datarray['allow_cid'] = $str_contact_allow;
699 $datarray['allow_gid'] = $str_group_allow;
700 $datarray['deny_cid'] = $str_contact_deny;
701 $datarray['deny_gid'] = $str_group_deny;
702 $datarray['private'] = $private;
703 $datarray['pubmail'] = $pubmail_enable;
704 $datarray['attach'] = $attachments;
705 $datarray['bookmark'] = intval($bookmark);
706 $datarray['thr-parent'] = $thr_parent;
707 $datarray['postopts'] = $postopts;
708 $datarray['origin'] = $origin;
709 $datarray['moderated'] = $allow_moderated;
710 $datarray['gcontact-id'] = get_gcontact_id(array("url" => $datarray['author-link'], "network" => $datarray['network'],
711 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']));
712 $datarray['object'] = $object;
715 * These fields are for the convenience of plugins...
716 * 'self' if true indicates the owner is posting on their own wall
717 * If parent is 0 it is a top-level post.
719 $datarray['parent'] = $parent;
720 $datarray['self'] = $self;
721 // $datarray['prvnets'] = $user['prvnets'];
723 $datarray['parent-uri'] = ($parent == 0) ? $uri : $parent_item['uri'];
724 $datarray['plink'] = System::baseUrl() . '/display/' . urlencode($datarray['guid']);
725 $datarray['last-child'] = 1;
726 $datarray['visible'] = 1;
728 $datarray['protocol'] = PROTOCOL_DFRN;
730 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
731 if (dbm::is_result($r)) {
732 if ($r['conversation-uri'] != '') {
733 $datarray['conversation-uri'] = $r['conversation-uri'];
735 if ($r['conversation-href'] != '') {
736 $datarray['conversation-href'] = $r['conversation-href'];
741 $datarray['edit'] = true;
744 // Search for hashtags
745 item_body_set_hashtags($datarray);
747 // preview mode - prepare the body for display and send it via json
749 require_once 'include/conversation.php';
750 // We set the datarray ID to -1 because in preview mode the dataray
751 // doesn't have an ID.
752 $datarray["id"] = -1;
753 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
754 logger('preview: ' . $o);
755 echo json_encode(array('preview' => $o));
759 call_hooks('post_local',$datarray);
761 if (x($datarray, 'cancel')) {
762 logger('mod_item: post cancelled by plugin.');
764 goaway($return_path);
767 $json = array('cancel' => 1);
768 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
769 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
772 echo json_encode($json);
776 // Fill the cache field
777 put_item_in_cache($datarray);
779 $datarray = store_conversation($datarray);
782 $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",
783 dbesc($datarray['title']),
784 dbesc($datarray['body']),
785 dbesc($datarray['tag']),
786 dbesc($datarray['attach']),
787 dbesc($datarray['file']),
788 dbesc($datarray['rendered-html']),
789 dbesc($datarray['rendered-hash']),
790 dbesc(datetime_convert()),
791 dbesc(datetime_convert()),
796 create_tags_from_item($post_id);
797 create_files_from_item($post_id);
798 update_thread($post_id);
800 // update filetags in pconfig
801 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
803 proc_run(PRIORITY_HIGH, "include/notifier.php", 'edit_post', $post_id);
804 if ((x($_REQUEST, 'return')) && strlen($return_path)) {
805 logger('return: ' . $return_path);
806 goaway($return_path);
815 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,
816 `owner-name`,`owner-link`,`owner-avatar`, `owner-id`,
817 `author-name`, `author-link`, `author-avatar`, `author-id`,
818 `created`, `edited`, `commented`, `received`, `changed`,
819 `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
820 `tag`, `inform`, `verb`, `object-type`, `postopts`,
821 `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`,
822 `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file`,
823 `rendered-html`, `rendered-hash`, `gcontact-id`, `object`,
824 `parent`, `parent-uri`, `plink`, `last-child`, `visible`)
825 VALUES('%s', '%s', %d, '%s', %d, %d, '%s', %d,
826 '%s', '%s', '%s', %d,
827 '%s', '%s', '%s', %d,
828 '%s', '%s', '%s', '%s', '%s',
829 '%s', '%s', '%s', '%s', '%s', '%s', '%s',
830 '%s', '%s', '%s', '%s', '%s',
831 '%s', '%s', '%s', '%s', %d,
832 %d, '%s', %d, %d, %d, '%s',
833 '%s', '%s', %d, '%s',
834 %d, '%s', '%s', %d, %d)",
835 dbesc($datarray['guid']),
836 dbesc($datarray['extid']),
837 intval($datarray['uid']),
838 dbesc($datarray['type']),
839 intval($datarray['wall']),
840 intval($datarray['gravity']),
841 dbesc($datarray['network']),
842 intval($datarray['contact-id']),
843 dbesc($datarray['owner-name']),
844 dbesc($datarray['owner-link']),
845 dbesc($datarray['owner-avatar']),
846 intval($datarray['owner-id']),
847 dbesc($datarray['author-name']),
848 dbesc($datarray['author-link']),
849 dbesc($datarray['author-avatar']),
850 intval($datarray['author-id']),
851 dbesc($datarray['created']),
852 dbesc($datarray['edited']),
853 dbesc($datarray['commented']),
854 dbesc($datarray['received']),
855 dbesc($datarray['changed']),
856 dbesc($datarray['uri']),
857 dbesc($datarray['thr-parent']),
858 dbesc($datarray['title']),
859 dbesc($datarray['body']),
860 dbesc($datarray['app']),
861 dbesc($datarray['location']),
862 dbesc($datarray['coord']),
863 dbesc($datarray['tag']),
864 dbesc($datarray['inform']),
865 dbesc($datarray['verb']),
866 dbesc($datarray['object-type']),
867 dbesc($datarray['postopts']),
868 dbesc($datarray['allow_cid']),
869 dbesc($datarray['allow_gid']),
870 dbesc($datarray['deny_cid']),
871 dbesc($datarray['deny_gid']),
872 intval($datarray['private']),
873 intval($datarray['pubmail']),
874 dbesc($datarray['attach']),
875 intval($datarray['bookmark']),
876 intval($datarray['origin']),
877 intval($datarray['moderated']),
878 dbesc($datarray['file']),
879 dbesc($datarray['rendered-html']),
880 dbesc($datarray['rendered-hash']),
881 intval($datarray['gcontact-id']),
882 dbesc($datarray['object']),
883 intval($datarray['parent']),
884 dbesc($datarray['parent-uri']),
885 dbesc($datarray['plink']),
886 intval($datarray['last-child']),
887 intval($datarray['visible'])
890 if (dbm::is_result($r)) {
891 $post_id = dba::lastInsertId();
893 logger('mod_item: unable to create post.');
899 logger('mod_item: unable to retrieve post that was just stored.');
900 notice(t('System error. Post not saved.') . EOL);
901 goaway($return_path);
905 logger('mod_item: saved item ' . $post_id);
907 $datarray["id"] = $post_id;
909 item_set_last_item($datarray);
911 // update filetags in pconfig
912 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
916 // This item is the last leaf and gets the comment box, clear any ancestors
917 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d AND `last-child` AND `id` != %d",
918 dbesc(datetime_convert()),
923 // update the commented timestamp on the parent
924 q("UPDATE `item` SET `visible` = 1, `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
925 dbesc(datetime_convert()),
926 dbesc(datetime_convert()),
930 if ($contact_record != $author) {
932 'type' => NOTIFY_COMMENT,
933 'notify_flags' => $user['notify-flags'],
934 'language' => $user['language'],
935 'to_name' => $user['username'],
936 'to_email' => $user['email'],
937 'uid' => $user['uid'],
939 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
940 'source_name' => $datarray['author-name'],
941 'source_link' => $datarray['author-link'],
942 'source_photo' => $datarray['author-avatar'],
943 'verb' => ACTIVITY_POST,
946 'parent_uri' => $parent_item['uri']
952 // Store the comment signature information in case we need to relay to Diaspora
953 Diaspora::store_comment_signature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
958 $r = q("UPDATE `item` SET `parent` = %d WHERE `id` = %d",
962 if ($contact_record != $author) {
964 'type' => NOTIFY_WALL,
965 'notify_flags' => $user['notify-flags'],
966 'language' => $user['language'],
967 'to_name' => $user['username'],
968 'to_email' => $user['email'],
969 'uid' => $user['uid'],
971 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
972 'source_name' => $datarray['author-name'],
973 'source_link' => $datarray['author-link'],
974 'source_photo' => $datarray['author-avatar'],
975 'verb' => ACTIVITY_POST,
981 call_hooks('post_local_end', $datarray);
983 if (strlen($emailcc) && $profile_uid == local_user()) {
984 $erecips = explode(',', $emailcc);
985 if (count($erecips)) {
986 foreach ($erecips as $recip) {
987 $addr = trim($recip);
988 if (! strlen($addr)) {
991 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
993 $disclaimer .= sprintf( t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
994 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
995 if (!$datarray['title']=='') {
996 $subject = email_header_encode($datarray['title'], 'UTF-8');
998 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'), $a->user['username']), 'UTF-8');
1000 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
1001 $html = prepare_body($datarray);
1002 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
1003 include_once 'include/html2plain.php';
1005 'fromName' => $a->user['username'],
1006 'fromEmail' => $a->user['email'],
1008 'replyTo' => $a->user['email'],
1009 'messageSubject' => $subject,
1010 'htmlVersion' => $message,
1011 'textVersion' => html2plain($html.$disclaimer),
1013 Emailer::send($params);
1018 if ($post_id == $parent) {
1019 add_thread($post_id);
1021 update_thread($parent, true);
1026 create_tags_from_item($post_id);
1027 create_files_from_item($post_id);
1029 // Insert an item entry for UID=0 for global entries.
1030 // We now do it in the background to save some time.
1031 // This is important in interactive environments like the frontend or the API.
1032 // We don't fork a new process since this is done anyway with the following command
1033 proc_run(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "include/create_shadowentry.php", $post_id);
1035 // Call the background process that is delivering the item to the receivers
1036 proc_run(PRIORITY_HIGH, "include/notifier.php", $notify_type, $post_id);
1038 logger('post_complete');
1040 item_post_return(System::baseUrl(), $api_source, $return_path);
1044 function item_post_return($baseurl, $api_source, $return_path) {
1045 // figure out how to return, depending on from whence we came
1052 goaway($return_path);
1055 $json = array('success' => 1);
1056 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
1057 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1060 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1062 echo json_encode($json);
1068 function item_content(App $a) {
1070 if ((! local_user()) && (! remote_user())) {
1074 require_once 'include/security.php';
1077 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1078 $o = drop_item($a->argv[2], !is_ajax());
1080 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1081 echo json_encode(array(intval($a->argv[2]), intval($o)));
1089 * This function removes the tag $tag from the text $body and replaces it with
1090 * the appropiate link.
1092 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
1093 * @param unknown_type $body the text to replace the tag in
1094 * @param string $inform a comma-seperated string containing everybody to inform
1095 * @param string $str_tags string to add the tag to
1096 * @param integer $profile_uid
1097 * @param string $tag the tag to replace
1098 * @param string $network The network of the post
1100 * @return boolean true if replaced, false if not replaced
1102 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1103 require_once 'include/socgraph.php';
1108 //is it a person tag?
1109 if (strpos($tag, '@') === 0) {
1110 //is it already replaced?
1111 if (strpos($tag, '[url=')) {
1112 //append tag to str_tags
1113 if (!stristr($str_tags, $tag)) {
1114 if (strlen($str_tags)) {
1120 // Checking for the alias that is used for OStatus
1121 $pattern = "/@\[url\=(.*?)\](.*?)\[\/url\]/ism";
1122 if (preg_match($pattern, $tag, $matches)) {
1124 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1125 normalise_link($matches[1]));
1126 if (!dbm::is_result($r)) {
1127 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1128 normalise_link($matches[1]));
1130 if (dbm::is_result($r)) {
1133 $data = probe_url($matches[1]);
1136 if ($data["alias"] != "") {
1137 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1138 if (!stristr($str_tags, $newtag)) {
1139 if (strlen($str_tags)) {
1142 $str_tags .= $newtag;
1150 //get the person's name
1151 $name = substr($tag, 1);
1153 // Sometimes the tag detection doesn't seem to work right
1154 // This is some workaround
1155 $nameparts = explode(" ", $name);
1156 $name = $nameparts[0];
1158 // Try to detect the contact in various ways
1159 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1160 // Is it in format @user@domain.tld or @http://domain.tld/...?
1162 // First check the contact table for the address
1163 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1164 WHERE `addr` = '%s' AND `uid` = %d AND
1165 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1168 intval($profile_uid),
1169 dbesc(NETWORK_OSTATUS)
1172 // Then check in the contact table for the url
1173 if (!dbm::is_result($r)) {
1174 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `contact`
1175 WHERE `nurl` = '%s' AND `uid` = %d AND
1176 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1178 dbesc(normalise_link($name)),
1179 intval($profile_uid),
1180 dbesc(NETWORK_OSTATUS)
1184 // Then check in the global contacts for the address
1185 if (!dbm::is_result($r)) {
1186 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1187 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1190 dbesc(NETWORK_OSTATUS)
1194 // Then check in the global contacts for the url
1195 if (!dbm::is_result($r)) {
1196 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1197 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1199 dbesc(normalise_link($name)),
1200 dbesc(NETWORK_OSTATUS)
1204 if (!dbm::is_result($r)) {
1205 $probed = probe_url($name);
1206 if ($result['network'] != NETWORK_PHANTOM) {
1207 update_gcontact($probed);
1208 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1209 dbesc(normalise_link($probed["url"])));
1214 if (strrpos($name, '+')) {
1215 // Is it in format @nick+number?
1216 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1218 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1220 intval($profile_uid)
1224 // select someone by attag or nick and the name passed in the current network
1225 if(!dbm::is_result($r) && ($network != ""))
1226 $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",
1230 intval($profile_uid)
1233 //select someone from this user's contacts by name in the current network
1234 if (!dbm::is_result($r) && ($network != "")) {
1235 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1238 intval($profile_uid)
1242 // select someone by attag or nick and the name passed in
1243 if(!dbm::is_result($r)) {
1244 $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",
1247 intval($profile_uid)
1251 // select someone from this user's contacts by name
1252 if(!dbm::is_result($r)) {
1253 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1255 intval($profile_uid)
1260 if (dbm::is_result($r)) {
1261 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1265 if (isset($r[0]["id"])) {
1266 $inform .= 'cid:' . $r[0]["id"];
1267 } elseif (isset($r[0]["notify"])) {
1268 $inform .= $r[0]["notify"];
1271 $profile = $r[0]["url"];
1272 $alias = $r[0]["alias"];
1273 $newname = $r[0]["nick"];
1274 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1275 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1276 $newname = $r[0]["name"];
1280 //if there is an url for this persons profile
1281 if (isset($profile) && ($newname != "")) {
1284 // create profile link
1285 $profile = str_replace(',', '%2c', $profile);
1286 $newtag = '@[url=' . $profile . ']' . $newname . '[/url]';
1287 $body = str_replace('@' . $name, $newtag, $body);
1288 // append tag to str_tags
1289 if (! stristr($str_tags, $newtag)) {
1290 if (strlen($str_tags)) {
1293 $str_tags .= $newtag;
1297 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1298 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1300 if (strlen($alias)) {
1301 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1302 if (! stristr($str_tags, $newtag)) {
1303 if (strlen($str_tags)) {
1306 $str_tags .= $newtag;
1312 return array('replaced' => $replaced, 'contact' => $r[0]);