5 * This is the POST destination for most all locally posted
6 * text stuff. This function handles status, wall-to-wall status,
7 * local comments, and remote coments that are posted on this site
8 * (as opposed to being delivered in a feed).
9 * Also processed here are posts and comments coming through the
10 * statusnet/twitter API.
11 * All of these become an "item" which is our basic unit of
13 * Posts that originate externally or do not fall into the above
14 * posting categories go through item_store() instead of this function.
18 require_once('include/crypto.php');
19 require_once('include/enotify.php');
20 require_once('include/email.php');
21 require_once('library/langdet/Text/LanguageDetect.php');
22 require_once('include/tags.php');
23 require_once('include/files.php');
24 require_once('include/threads.php');
26 function item_post(&$a) {
28 if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
31 require_once('include/security.php');
35 if(x($_REQUEST,'dropitems')) {
36 require_once('include/items.php');
37 $arr_drop = explode(',',$_REQUEST['dropitems']);
38 drop_items($arr_drop);
39 $json = array('success' => 1);
40 echo json_encode($json);
44 call_hooks('post_local_start', $_REQUEST);
45 // logger('postinput ' . file_get_contents('php://input'));
46 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
48 $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
50 $message_id = ((x($_REQUEST,'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
52 $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
53 $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
56 // Check for doubly-submitted posts, and reject duplicates
57 // Note that we have to ignore previews, otherwise nothing will post
58 // after it's been previewed
59 if(!$preview && x($_REQUEST['post_id_random'])) {
60 if(x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
61 logger("item post: duplicate post", LOGGER_DEBUG);
62 item_post_return($a->get_baseurl(), $api_source, $return_path);
65 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
69 * Is this a reply to something?
72 $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
73 $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
76 $parent_contact = null;
82 if($parent || $parent_uri) {
84 $objecttype = ACTIVITY_OBJ_COMMENT;
86 if(! x($_REQUEST,'type'))
87 $_REQUEST['type'] = 'net-comment';
90 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
93 } elseif($parent_uri && local_user()) {
94 // This is coming from an API source, and we are logged in
95 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
101 // if this isn't the real parent of the conversation, find it
102 if($r !== false && count($r)) {
103 $parid = $r[0]['parent'];
104 $parent_uri = $r[0]['uri'];
105 if($r[0]['id'] != $r[0]['parent']) {
106 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
112 if(($r === false) || (! count($r))) {
113 notice( t('Unable to locate original post.') . EOL);
114 if(x($_REQUEST,'return'))
115 goaway($a->get_baseurl() . "/" . $return_path );
118 $parent_item = $r[0];
119 $parent = $r[0]['id'];
121 // multi-level threading - preserve the info but re-parent to our single level threading
122 //if(($parid) && ($parid != $parent))
123 $thr_parent = $parent_uri;
125 if($parent_item['contact-id'] && $uid) {
126 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
127 intval($parent_item['contact-id']),
131 $parent_contact = $r[0];
133 // If the contact id doesn't fit with the contact, then set the contact to null
134 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($thr_parent));
135 if (count($thrparent) AND ($thrparent[0]["network"] === NETWORK_OSTATUS)
136 AND (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
137 $parent_contact = null;
139 require_once("include/Scrape.php");
140 $probed_contact = probe_url($thrparent[0]["author-link"]);
141 if ($probed_contact["network"] != NETWORK_FEED) {
142 $parent_contact = $probed_contact;
143 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
144 $parent_contact["thumb"] = $probed_contact["photo"];
145 $parent_contact["micro"] = $probed_contact["photo"];
147 logger('parent contact: '.print_r($parent_contact, true), LOGGER_DEBUG);
149 logger('no contact found: '.print_r($thrparent, true), LOGGER_DEBUG);
154 if($parent) logger('mod_item: item_post parent=' . $parent);
156 $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
157 $post_id = ((x($_REQUEST,'post_id')) ? intval($_REQUEST['post_id']) : 0);
158 $app = ((x($_REQUEST,'source')) ? strip_tags($_REQUEST['source']) : '');
159 $extid = ((x($_REQUEST,'extid')) ? strip_tags($_REQUEST['extid']) : '');
161 $allow_moderated = false;
163 // here is where we are going to check for permission to post a moderated comment.
165 // First check that the parent exists and it is a wall item.
167 if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
168 notice( t('Permission denied.') . EOL) ;
169 if(x($_REQUEST,'return'))
170 goaway($a->get_baseurl() . "/" . $return_path );
174 // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
175 // have been provided, and run any anti-spam plugins
183 if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
184 notice( t('Permission denied.') . EOL) ;
185 if(x($_REQUEST,'return'))
186 goaway($a->get_baseurl() . "/" . $return_path );
191 // is this an edited post?
196 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
197 intval($profile_uid),
207 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
214 $str_group_allow = $orig_post['allow_gid'];
215 $str_contact_allow = $orig_post['allow_cid'];
216 $str_group_deny = $orig_post['deny_gid'];
217 $str_contact_deny = $orig_post['deny_cid'];
218 $location = $orig_post['location'];
219 $coord = $orig_post['coord'];
220 $verb = $orig_post['verb'];
221 $objecttype = $orig_post['object-type'];
222 $emailcc = $orig_post['emailcc'];
223 $app = $orig_post['app'];
224 $categories = $orig_post['file'];
225 $title = notags(trim($_REQUEST['title']));
226 $body = escape_tags(trim($_REQUEST['body']));
227 $private = $orig_post['private'];
228 $pubmail_enable = $orig_post['pubmail'];
229 $network = $orig_post['network'];
230 $guid = $orig_post['guid'];
231 $extid = $orig_post['extid'];
235 // if coming from the API and no privacy settings are set,
236 // use the user default permissions - as they won't have
237 // been supplied via a form.
240 && (! array_key_exists('contact_allow',$_REQUEST))
241 && (! array_key_exists('group_allow',$_REQUEST))
242 && (! array_key_exists('contact_deny',$_REQUEST))
243 && (! array_key_exists('group_deny',$_REQUEST))) {
244 $str_group_allow = $user['allow_gid'];
245 $str_contact_allow = $user['allow_cid'];
246 $str_group_deny = $user['deny_gid'];
247 $str_contact_deny = $user['deny_cid'];
251 // use the posted permissions
253 $str_group_allow = perms2str($_REQUEST['group_allow']);
254 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
255 $str_group_deny = perms2str($_REQUEST['group_deny']);
256 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
259 $title = notags(trim($_REQUEST['title']));
260 $location = notags(trim($_REQUEST['location']));
261 $coord = notags(trim($_REQUEST['coord']));
262 $verb = notags(trim($_REQUEST['verb']));
263 $emailcc = notags(trim($_REQUEST['emailcc']));
264 $body = escape_tags(trim($_REQUEST['body']));
265 $network = notags(trim($_REQUEST['network']));
266 $guid = get_guid(32);
269 $naked_body = preg_replace('/\[(.+?)\]/','',$body);
271 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
272 $l = new Text_LanguageDetect;
273 //$lng = $l->detectConfidence($naked_body);
274 //$postopts = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
276 $lng = $l->detect($naked_body, 3);
278 if (sizeof($lng) > 0) {
281 foreach ($lng as $language => $score) {
287 $postopts .= $language.";".$score;
291 logger('mod_item: detect language' . print_r($lng,true) . $naked_body, LOGGER_DATA);
297 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
300 if($user['hidewall'])
303 // If this is a comment, set the permissions from the parent.
308 // for non native networks use the network of the original post as network of the item
309 if (($parent_item['network'] != NETWORK_DIASPORA)
310 AND ($parent_item['network'] != NETWORK_OSTATUS)
311 AND ($network == ""))
312 $network = $parent_item['network'];
314 if(($parent_item['private'])
315 || strlen($parent_item['allow_cid'])
316 || strlen($parent_item['allow_gid'])
317 || strlen($parent_item['deny_cid'])
318 || strlen($parent_item['deny_gid'])) {
319 $private = (($parent_item['private']) ? $parent_item['private'] : 1);
322 $str_contact_allow = $parent_item['allow_cid'];
323 $str_group_allow = $parent_item['allow_gid'];
324 $str_contact_deny = $parent_item['deny_cid'];
325 $str_group_deny = $parent_item['deny_gid'];
327 $pubmail_enable = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
329 // if using the API, we won't see pubmail_enable - figure out if it should be set
331 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
332 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
333 if(! $mail_disabled) {
334 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
337 if(count($r) && intval($r[0]['pubmail']))
338 $pubmail_enabled = true;
342 if(! strlen($body)) {
345 info( t('Empty post discarded.') . EOL );
346 if(x($_REQUEST,'return'))
347 goaway($a->get_baseurl() . "/" . $return_path );
352 if(strlen($categories)) {
353 // get the "fileas" tags for this post
354 $filedas = file_tag_file_to_list($categories, 'file');
356 // save old and new categories, so we can determine what needs to be deleted from pconfig
357 $categories_old = $categories;
358 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
359 $categories_new = $categories;
360 if(strlen($filedas)) {
361 // append the fileas stuff to the new categories list
362 $categories .= file_tag_list_to_file($filedas, 'file');
365 // Work around doubled linefeeds in Tinymce 3.5b2
366 // First figure out if it's a status post that would've been
367 // created using tinymce. Otherwise leave it alone.
369 /* $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0);
370 if((! $parent) && (! $api_source) && (! $plaintext)) {
371 $body = fix_mce_lf($body);
373 $plaintext = (local_user() ? !feature_enabled($profile_uid,'richtext') : 0);
374 if((! $parent) && (! $api_source) && (! $plaintext)) {
375 $body = fix_mce_lf($body);
379 // get contact info for poster
385 if((local_user()) && (local_user() == $profile_uid)) {
387 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
388 intval($_SESSION['uid'])
391 elseif(remote_user()) {
392 if(is_array($_SESSION['remote'])) {
393 foreach($_SESSION['remote'] as $v) {
394 if($v['uid'] == $profile_uid) {
395 $contact_id = $v['cid'];
401 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
409 $contact_id = $author['id'];
412 // get contact info for owner
414 if($profile_uid == local_user()) {
415 $contact_record = $author;
418 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
422 $contact_record = $r[0];
425 $post_type = notags(trim($_REQUEST['type']));
427 if($post_type === 'net-comment') {
428 if($parent_item !== null) {
429 if($parent_item['wall'] == 1)
430 $post_type = 'wall-comment';
432 $post_type = 'remote-comment';
438 * When a photo was uploaded into the message using the (profile wall) ajax
439 * uploader, The permissions are initially set to disallow anybody but the
440 * owner from seeing it. This is because the permissions may not yet have been
441 * set for the post. If it's private, the photo permissions should be set
442 * appropriately. But we didn't know the final permissions on the post until
443 * now. So now we'll look for links of uploaded messages that are in the
444 * post and set them to the same permissions as the post itself.
450 if((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
454 $objecttype = ACTIVITY_OBJ_IMAGE;
456 foreach($images as $image) {
457 if(! stristr($image,$a->get_baseurl() . '/photo/'))
459 $image_uri = substr($image,strrpos($image,'/') + 1);
460 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
461 if(! strlen($image_uri))
463 $srch = '<' . intval($contact_id) . '>';
465 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
466 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
476 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
477 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
478 dbesc($str_contact_allow),
479 dbesc($str_group_allow),
480 dbesc($str_contact_deny),
481 dbesc($str_group_deny),
483 intval($profile_uid),
484 dbesc( t('Wall Photos'))
493 * Next link in any attachment references we find in the post.
498 if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
499 $attaches = $match[1];
500 if(count($attaches)) {
501 foreach($attaches as $attach) {
502 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
503 intval($profile_uid),
507 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
508 WHERE `uid` = %d AND `id` = %d",
509 dbesc($str_contact_allow),
510 dbesc($str_group_allow),
511 dbesc($str_contact_deny),
512 dbesc($str_group_deny),
513 intval($profile_uid),
521 // embedded bookmark in post? set bookmark flag
524 if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
525 $objecttype = ACTIVITY_OBJ_BOOKMARK;
529 $body = bb_translate_video($body);
533 * Fold multi-line [code] sequences
536 $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body);
538 $body = scale_external_images($body,false);
541 // Setting the object type if not defined before
543 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
544 require_once("include/plaintext.php");
545 $objectdata = get_attached_data($body);
547 if ($post["type"] == "link")
548 $objecttype = ACTIVITY_OBJ_BOOKMARK;
549 elseif ($post["type"] == "video")
550 $objecttype = ACTIVITY_OBJ_VIDEO;
551 elseif ($post["type"] == "photo")
552 $objecttype = ACTIVITY_OBJ_IMAGE;
557 * Look for any tags and linkify them
564 $tags = get_tags($body);
567 * add a statusnet style reply tag if the original post was from there
568 * and we are replying, and there isn't one already
571 if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS)
572 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
573 $body = '@' . $parent_contact['nick'] . ' ' . $body;
574 $tags[] = '@' . $parent_contact['nick'];
579 $private_forum = false;
582 foreach($tags as $tag) {
584 // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
585 // Robert Johnson should be first in the $tags array
587 $fullnametagged = false;
588 for($x = 0; $x < count($tagged); $x ++) {
589 if(stristr($tagged[$x],$tag . ' ')) {
590 $fullnametagged = true;
597 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag, $network);
598 if($success['replaced'])
600 if(is_array($success['contact']) && intval($success['contact']['prv'])) {
601 $private_forum = true;
602 $private_id = $success['contact']['id'];
607 if(($private_forum) && (! $parent) && (! $private)) {
608 // we tagged a private forum in a top level post and the message was public.
611 $str_contact_allow = '<' . $private_id . '>';
617 if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
618 foreach($match[2] as $mtch) {
619 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
620 intval($profile_uid),
624 if(strlen($attachments))
626 $attachments .= '[attach]href="' . $a->get_baseurl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
628 $body = str_replace($match[1],'',$body);
634 if($post_type === 'wall' || $post_type === 'wall-comment')
638 $verb = ACTIVITY_POST ;
641 $network = NETWORK_DFRN;
643 $gravity = (($parent) ? 6 : 0 );
645 // even if the post arrived via API we are considering that it
646 // originated on this site by default for determining relayability.
648 $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
650 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
652 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid));
654 // Fallback so that we alway have a thr-parent
659 $datarray['uid'] = $profile_uid;
660 $datarray['type'] = $post_type;
661 $datarray['wall'] = $wall;
662 $datarray['gravity'] = $gravity;
663 $datarray['network'] = $network;
664 $datarray['contact-id'] = $contact_id;
665 $datarray['owner-name'] = $contact_record['name'];
666 $datarray['owner-link'] = $contact_record['url'];
667 $datarray['owner-avatar'] = $contact_record['thumb'];
668 $datarray['author-name'] = $author['name'];
669 $datarray['author-link'] = $author['url'];
670 $datarray['author-avatar'] = $author['thumb'];
671 $datarray['created'] = datetime_convert();
672 $datarray['edited'] = datetime_convert();
673 $datarray['commented'] = datetime_convert();
674 $datarray['received'] = datetime_convert();
675 $datarray['changed'] = datetime_convert();
676 $datarray['extid'] = $extid;
677 $datarray['guid'] = $guid;
678 $datarray['uri'] = $uri;
679 $datarray['title'] = $title;
680 $datarray['body'] = $body;
681 $datarray['app'] = $app;
682 $datarray['location'] = $location;
683 $datarray['coord'] = $coord;
684 $datarray['tag'] = $str_tags;
685 $datarray['file'] = $categories;
686 $datarray['inform'] = $inform;
687 $datarray['verb'] = $verb;
688 $datarray['object-type'] = $objecttype;
689 $datarray['allow_cid'] = $str_contact_allow;
690 $datarray['allow_gid'] = $str_group_allow;
691 $datarray['deny_cid'] = $str_contact_deny;
692 $datarray['deny_gid'] = $str_group_deny;
693 $datarray['private'] = $private;
694 $datarray['pubmail'] = $pubmail_enable;
695 $datarray['attach'] = $attachments;
696 $datarray['bookmark'] = intval($bookmark);
697 $datarray['thr-parent'] = $thr_parent;
698 $datarray['postopts'] = $postopts;
699 $datarray['origin'] = $origin;
700 $datarray['moderated'] = $allow_moderated;
703 * These fields are for the convenience of plugins...
704 * 'self' if true indicates the owner is posting on their own wall
705 * If parent is 0 it is a top-level post.
708 $datarray['parent'] = $parent;
709 $datarray['self'] = $self;
710 // $datarray['prvnets'] = $user['prvnets'];
713 $datarray['edit'] = true;
715 // preview mode - prepare the body for display and send it via json
718 require_once('include/conversation.php');
719 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
720 logger('preview: ' . $o);
721 echo json_encode(array('preview' => $o));
726 call_hooks('post_local',$datarray);
728 if(x($datarray,'cancel')) {
729 logger('mod_item: post cancelled by plugin.');
731 goaway($a->get_baseurl() . "/" . $return_path);
734 $json = array('cancel' => 1);
735 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
736 $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
738 echo json_encode($json);
744 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `edited` = '%s', `changed` = '%s' WHERE `id` = %d AND `uid` = %d",
745 dbesc($datarray['title']),
746 dbesc($datarray['body']),
747 dbesc($datarray['tag']),
748 dbesc($datarray['attach']),
749 dbesc($datarray['file']),
750 dbesc(datetime_convert()),
751 dbesc(datetime_convert()),
756 create_tags_from_item($post_id);
757 create_files_from_item($post_id);
758 update_thread($post_id);
760 // update filetags in pconfig
761 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
763 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
764 if((x($_REQUEST,'return')) && strlen($return_path)) {
765 logger('return: ' . $return_path);
766 goaway($a->get_baseurl() . "/" . $return_path );
774 $r = q("INSERT INTO `item` (`guid`, `extid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,`owner-name`,`owner-link`,`owner-avatar`,
775 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
776 `tag`, `inform`, `verb`, `object-type`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file` )
777 VALUES( '%s', '%s', %d, '%s', %d, %d, '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', %d, %d, %d, '%s' )",
778 dbesc($datarray['guid']),
779 dbesc($datarray['extid']),
780 intval($datarray['uid']),
781 dbesc($datarray['type']),
782 intval($datarray['wall']),
783 intval($datarray['gravity']),
784 dbesc($datarray['network']),
785 intval($datarray['contact-id']),
786 dbesc($datarray['owner-name']),
787 dbesc($datarray['owner-link']),
788 dbesc($datarray['owner-avatar']),
789 dbesc($datarray['author-name']),
790 dbesc($datarray['author-link']),
791 dbesc($datarray['author-avatar']),
792 dbesc($datarray['created']),
793 dbesc($datarray['edited']),
794 dbesc($datarray['commented']),
795 dbesc($datarray['received']),
796 dbesc($datarray['changed']),
797 dbesc($datarray['uri']),
798 dbesc($datarray['thr-parent']),
799 dbesc($datarray['title']),
800 dbesc($datarray['body']),
801 dbesc($datarray['app']),
802 dbesc($datarray['location']),
803 dbesc($datarray['coord']),
804 dbesc($datarray['tag']),
805 dbesc($datarray['inform']),
806 dbesc($datarray['verb']),
807 dbesc($datarray['object-type']),
808 dbesc($datarray['postopts']),
809 dbesc($datarray['allow_cid']),
810 dbesc($datarray['allow_gid']),
811 dbesc($datarray['deny_cid']),
812 dbesc($datarray['deny_gid']),
813 intval($datarray['private']),
814 intval($datarray['pubmail']),
815 dbesc($datarray['attach']),
816 intval($datarray['bookmark']),
817 intval($datarray['origin']),
818 intval($datarray['moderated']),
819 dbesc($datarray['file'])
822 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
823 dbesc($datarray['uri']));
825 $post_id = $r[0]['id'];
826 logger('mod_item: saved item ' . $post_id);
827 add_thread($post_id);
829 // update filetags in pconfig
830 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
832 // Store the fresh generated item into the cache
833 $cachefile = get_cachefile(urlencode($datarray["guid"])."-".hash("md5", $datarray['body']));
835 if (($cachefile != '') AND !file_exists($cachefile)) {
836 $s = prepare_text($datarray['body']);
837 $stamp1 = microtime(true);
838 file_put_contents($cachefile, $s);
839 $a->save_timestamp($stamp1, "file");
840 logger('mod_item: put item '.$r[0]['id'].' into cachefile '.$cachefile);
845 // This item is the last leaf and gets the comment box, clear any ancestors
846 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
847 dbesc(datetime_convert()),
850 update_thread($parent, true);
852 // Inherit ACLs from the parent item.
854 $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
856 dbesc($parent_item['allow_cid']),
857 dbesc($parent_item['allow_gid']),
858 dbesc($parent_item['deny_cid']),
859 dbesc($parent_item['deny_gid']),
860 intval($parent_item['private']),
864 if($contact_record != $author) {
866 'type' => NOTIFY_COMMENT,
867 'notify_flags' => $user['notify-flags'],
868 'language' => $user['language'],
869 'to_name' => $user['username'],
870 'to_email' => $user['email'],
871 'uid' => $user['uid'],
873 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
874 'source_name' => $datarray['author-name'],
875 'source_link' => $datarray['author-link'],
876 'source_photo' => $datarray['author-avatar'],
877 'verb' => ACTIVITY_POST,
880 'parent_uri' => $parent_item['uri']
886 // Store the comment signature information in case we need to relay to Diaspora
887 store_diaspora_comment_sig($datarray, $author, ($self ? $a->user['prvkey'] : false), $parent_item, $post_id);
892 if($contact_record != $author) {
894 'type' => NOTIFY_WALL,
895 'notify_flags' => $user['notify-flags'],
896 'language' => $user['language'],
897 'to_name' => $user['username'],
898 'to_email' => $user['email'],
899 'uid' => $user['uid'],
901 'link' => $a->get_baseurl().'/display/'.urlencode($datarray['guid']),
902 'source_name' => $datarray['author-name'],
903 'source_link' => $datarray['author-link'],
904 'source_photo' => $datarray['author-avatar'],
905 'verb' => ACTIVITY_POST,
911 // fallback so that parent always gets set to non-zero.
916 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
919 dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
920 dbesc($a->get_baseurl().'/display/'.urlencode($datarray['guid'])),
921 dbesc(datetime_convert()),
925 // photo comments turn the corresponding item visible to the profile wall
926 // This way we don't see every picture in your new photo album posted to your wall at once.
927 // They will show up as people comment on them.
929 if(! $parent_item['visible']) {
930 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
931 intval($parent_item['id'])
933 update_thread($parent_item['id']);
937 logger('mod_item: unable to retrieve post that was just stored.');
938 notice( t('System error. Post not saved.') . EOL);
939 goaway($a->get_baseurl() . "/" . $return_path );
943 // update the commented timestamp on the parent
945 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
946 dbesc(datetime_convert()),
947 dbesc(datetime_convert()),
950 update_thread($parent);
952 $datarray['id'] = $post_id;
953 $datarray['plink'] = $a->get_baseurl().'/display/'.urlencode($datarray['guid']);
955 call_hooks('post_local_end', $datarray);
957 if(strlen($emailcc) && $profile_uid == local_user()) {
958 $erecips = explode(',', $emailcc);
959 if(count($erecips)) {
960 foreach($erecips as $recip) {
961 $addr = trim($recip);
964 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username'])
966 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
967 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
968 if (!$datarray['title']=='') {
969 $subject = email_header_encode($datarray['title'],'UTF-8');
971 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
973 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
974 $html = prepare_body($datarray);
975 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
976 include_once('include/html2plain.php');
978 'fromName' => $a->user['username'],
979 'fromEmail' => $a->user['email'],
981 'replyTo' => $a->user['email'],
982 'messageSubject' => $subject,
983 'htmlVersion' => $message,
984 'textVersion' => html2plain($html.$disclaimer),
986 enotify::send($params);
991 create_tags_from_item($post_id);
992 create_files_from_item($post_id);
993 update_thread($post_id);
995 // This is a real juggling act on shared hosting services which kill your processes
996 // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
997 // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
998 // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
999 // likely to get killed off. If you end up looking at an /item URL and a blank page,
1000 // it's very likely the delivery got killed before all your friends could be notified.
1001 // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
1002 // or cut back on plugins which do remote deliveries.
1004 proc_run('php', "include/notifier.php", $notify_type, "$post_id");
1006 logger('post_complete');
1008 item_post_return($a->get_baseurl(), $api_source, $return_path);
1012 function item_post_return($baseurl, $api_source, $return_path) {
1013 // figure out how to return, depending on from whence we came
1019 goaway($baseurl . "/" . $return_path);
1022 $json = array('success' => 1);
1023 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
1024 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
1026 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
1028 echo json_encode($json);
1034 function item_content(&$a) {
1036 if((! local_user()) && (! remote_user()))
1039 require_once('include/security.php');
1042 if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
1043 require_once('include/items.php');
1044 $o = drop_item($a->argv[2], !is_ajax());
1046 // ajax return: [<item id>, 0 (no perm) | <owner id>]
1047 echo json_encode(array(intval($a->argv[2]), intval($o)));
1055 * This function removes the tag $tag from the text $body and replaces it with
1056 * the appropiate link.
1058 * @param unknown_type $body the text to replace the tag in
1059 * @param unknown_type $inform a comma-seperated string containing everybody to inform
1060 * @param unknown_type $str_tags string to add the tag to
1061 * @param unknown_type $profile_uid
1062 * @param unknown_type $tag the tag to replace
1064 * @return boolean true if replaced, false if not replaced
1066 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "") {
1072 if(strpos($tag,'#') === 0) {
1073 //if the tag is replaced...
1074 if(strpos($tag,'[url='))
1077 //base tag has the tags name only
1078 $basetag = str_replace('_',' ',substr($tag,1));
1079 //create text for link
1080 $newtag = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1081 //replace tag by the link
1082 $body = str_replace($tag, $newtag, $body);
1085 //is the link already in str_tags?
1086 if(! stristr($str_tags,$newtag)) {
1087 //append or set str_tags
1088 if(strlen($str_tags))
1090 $str_tags .= $newtag;
1094 //is it a person tag?
1095 if(strpos($tag,'@') === 0) {
1096 //is it already replaced?
1097 if(strpos($tag,'[url='))
1100 //get the person's name
1101 $name = substr($tag,1);
1102 //is it a link or a full dfrn address?
1103 if((strpos($name,'@')) || (strpos($name,'http://'))) {
1105 //get the profile links
1106 $links = @lrdd($name);
1108 //for all links, collect how is to inform and how's profile is to link
1109 foreach($links as $link) {
1110 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
1111 $profile = $link['@attributes']['href'];
1112 if($link['@attributes']['rel'] === 'salmon') {
1115 $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
1119 } elseif (($network != NETWORK_OSTATUS) AND ($network != NETWORK_TWITTER) AND
1120 ($network != NETWORK_STATUSNET) AND ($network != NETWORK_APPNET)) {
1121 //if it is a name rather than an address
1125 //is it some generated name?
1126 if(strrpos($newname,'+')) {
1128 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
1129 //remove the next word from tag's name
1130 if(strpos($name,' ')) {
1131 $name = substr($name,0,strpos($name,' '));
1134 if($tagcid) { //if there was an id
1135 //select contact with that id from the logged in user's contact list
1136 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1138 intval($profile_uid)
1142 $newname = str_replace('_',' ',$name);
1144 // At first try to fetch a contact according to the given network
1145 if ($network != "") {
1146 //select someone from this user's contacts by name
1147 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1150 intval($profile_uid)
1153 //select someone by attag or nick and the name passed in
1154 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1158 intval($profile_uid)
1165 //select someone from this user's contacts by name
1166 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1168 intval($profile_uid)
1173 //select someone by attag or nick and the name passed in
1174 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1177 intval($profile_uid)
1181 /* } elseif(strstr($name,'_') || strstr($name,' ')) { //no id
1183 $newname = str_replace('_',' ',$name);
1184 //select someone from this user's contacts by name
1185 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1187 intval($profile_uid)
1190 //select someone by attag or nick and the name passed in
1191 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1194 intval($profile_uid)
1197 //$r is set, if someone could be selected
1199 $profile = $r[0]['url'];
1200 //set newname to nick, find alias
1201 if(($r[0]['network'] === NETWORK_OSTATUS) OR ($r[0]['network'] === NETWORK_TWITTER)
1202 OR ($r[0]['network'] === NETWORK_STATUSNET) OR ($r[0]['network'] === NETWORK_APPNET)) {
1203 $newname = $r[0]['nick'];
1206 $alias = $r[0]['alias'];
1209 $newname = $r[0]['name'];
1210 //add person's id to $inform
1213 $inform .= 'cid:' . $r[0]['id'];
1216 //if there is an url for this persons profile
1217 if(isset($profile)) {
1219 //create profile link
1220 $profile = str_replace(',','%2c',$profile);
1221 $newtag = '@[url=' . $profile . ']' . $newname . '[/url]';
1222 $body = str_replace('@' . $name, $newtag, $body);
1223 //append tag to str_tags
1224 if(! stristr($str_tags,$newtag)) {
1225 if(strlen($str_tags))
1227 $str_tags .= $newtag;
1230 // Status.Net seems to require the numeric ID URL in a mention if the person isn't
1231 // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1233 if(strlen($alias)) {
1234 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1235 if(! stristr($str_tags,$newtag)) {
1236 if(strlen($str_tags))
1238 $str_tags .= $newtag;
1244 return array('replaced' => $replaced, 'contact' => $r[0]);
1248 function store_diaspora_comment_sig($datarray, $author, $uprvkey, $parent_item, $post_id) {
1249 // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
1251 $enabled = intval(get_config('system','diaspora_enabled'));
1253 logger('mod_item: diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
1258 logger('mod_item: storing diaspora comment signature');
1260 require_once('include/bb2diaspora.php');
1261 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
1263 // Only works for NETWORK_DFRN
1264 $contact_baseurl_start = strpos($author['url'],'://') + 3;
1265 $contact_baseurl_length = strpos($author['url'],'/profile') - $contact_baseurl_start;
1266 $contact_baseurl = substr($author['url'], $contact_baseurl_start, $contact_baseurl_length);
1267 $diaspora_handle = $author['nick'] . '@' . $contact_baseurl;
1269 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $diaspora_handle;
1271 if( $uprvkey !== false )
1272 $authorsig = base64_encode(rsa_sign($signed_text,$uprvkey,'sha256'));
1276 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1278 dbesc($signed_text),
1279 dbesc(base64_encode($authorsig)),
1280 dbesc($diaspora_handle)