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');
24 function item_post(&$a) {
26 if((! local_user()) && (! remote_user()) && (! x($_REQUEST,'commenter')))
29 require_once('include/security.php');
33 if(x($_REQUEST,'dropitems')) {
34 require_once('include/items.php');
35 $arr_drop = explode(',',$_REQUEST['dropitems']);
36 drop_items($arr_drop);
37 $json = array('success' => 1);
38 echo json_encode($json);
42 call_hooks('post_local_start', $_REQUEST);
43 // logger('postinput ' . file_get_contents('php://input'));
44 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
46 $api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);
48 $message_id = ((x($_REQUEST,'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
50 $return_path = ((x($_REQUEST,'return')) ? $_REQUEST['return'] : '');
51 $preview = ((x($_REQUEST,'preview')) ? intval($_REQUEST['preview']) : 0);
54 // Check for doubly-submitted posts, and reject duplicates
55 // Note that we have to ignore previews, otherwise nothing will post
56 // after it's been previewed
57 if(!$preview && x($_REQUEST['post_id_random'])) {
58 if(x($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
59 logger("item post: duplicate post", LOGGER_DEBUG);
60 item_post_return($a->get_baseurl(), $api_source, $return_path);
63 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
67 * Is this a reply to something?
70 $parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
71 $parent_uri = ((x($_REQUEST,'parent_uri')) ? trim($_REQUEST['parent_uri']) : '');
74 $parent_contact = null;
79 if($parent || $parent_uri) {
81 if(! x($_REQUEST,'type'))
82 $_REQUEST['type'] = 'net-comment';
85 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
89 elseif($parent_uri && local_user()) {
90 // This is coming from an API source, and we are logged in
91 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
96 // if this isn't the real parent of the conversation, find it
97 if($r !== false && count($r)) {
98 $parid = $r[0]['parent'];
99 $parent_uri = $r[0]['uri'];
100 if($r[0]['id'] != $r[0]['parent']) {
101 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
107 if(($r === false) || (! count($r))) {
108 notice( t('Unable to locate original post.') . EOL);
109 if(x($_REQUEST,'return'))
110 goaway($a->get_baseurl() . "/" . $return_path );
113 $parent_item = $r[0];
114 $parent = $r[0]['id'];
116 // multi-level threading - preserve the info but re-parent to our single level threading
117 //if(($parid) && ($parid != $parent))
118 $thr_parent = $parent_uri;
120 if($parent_item['contact-id'] && $uid) {
121 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
122 intval($parent_item['contact-id']),
126 $parent_contact = $r[0];
130 if($parent) logger('mod_item: item_post parent=' . $parent);
132 $profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid']) : 0);
133 $post_id = ((x($_REQUEST,'post_id')) ? intval($_REQUEST['post_id']) : 0);
134 $app = ((x($_REQUEST,'source')) ? strip_tags($_REQUEST['source']) : '');
136 $allow_moderated = false;
138 // here is where we are going to check for permission to post a moderated comment.
140 // First check that the parent exists and it is a wall item.
142 if((x($_REQUEST,'commenter')) && ((! $parent) || (! $parent_item['wall']))) {
143 notice( t('Permission denied.') . EOL) ;
144 if(x($_REQUEST,'return'))
145 goaway($a->get_baseurl() . "/" . $return_path );
149 // Now check that it is a page_type of PAGE_BLOG, and that valid personal details
150 // have been provided, and run any anti-spam plugins
158 if((! can_write_wall($a,$profile_uid)) && (! $allow_moderated)) {
159 notice( t('Permission denied.') . EOL) ;
160 if(x($_REQUEST,'return'))
161 goaway($a->get_baseurl() . "/" . $return_path );
166 // is this an edited post?
171 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
172 intval($profile_uid),
182 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
189 $str_group_allow = $orig_post['allow_gid'];
190 $str_contact_allow = $orig_post['allow_cid'];
191 $str_group_deny = $orig_post['deny_gid'];
192 $str_contact_deny = $orig_post['deny_cid'];
193 $location = $orig_post['location'];
194 $coord = $orig_post['coord'];
195 $verb = $orig_post['verb'];
196 $emailcc = $orig_post['emailcc'];
197 $app = $orig_post['app'];
198 $categories = $orig_post['file'];
199 $title = notags(trim($_REQUEST['title']));
200 $body = escape_tags(trim($_REQUEST['body']));
201 $private = $orig_post['private'];
202 $pubmail_enable = $orig_post['pubmail'];
203 $network = $orig_post['network'];
208 // if coming from the API and no privacy settings are set,
209 // use the user default permissions - as they won't have
210 // been supplied via a form.
213 && (! array_key_exists('contact_allow',$_REQUEST))
214 && (! array_key_exists('group_allow',$_REQUEST))
215 && (! array_key_exists('contact_deny',$_REQUEST))
216 && (! array_key_exists('group_deny',$_REQUEST))) {
217 $str_group_allow = $user['allow_gid'];
218 $str_contact_allow = $user['allow_cid'];
219 $str_group_deny = $user['deny_gid'];
220 $str_contact_deny = $user['deny_cid'];
224 // use the posted permissions
226 $str_group_allow = perms2str($_REQUEST['group_allow']);
227 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
228 $str_group_deny = perms2str($_REQUEST['group_deny']);
229 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
232 $title = notags(trim($_REQUEST['title']));
233 $location = notags(trim($_REQUEST['location']));
234 $coord = notags(trim($_REQUEST['coord']));
235 $verb = notags(trim($_REQUEST['verb']));
236 $emailcc = notags(trim($_REQUEST['emailcc']));
237 $body = escape_tags(trim($_REQUEST['body']));
238 $network = notags(trim($_REQUEST['network']));
241 $naked_body = preg_replace('/\[(.+?)\]/','',$body);
243 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
244 $l = new Text_LanguageDetect;
245 //$lng = $l->detectConfidence($naked_body);
246 //$postopts = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
248 $lng = $l->detect($naked_body, 3);
250 if (sizeof($lng) > 0) {
253 foreach ($lng as $language => $score) {
259 $postopts .= $language.";".$score;
263 logger('mod_item: detect language' . print_r($lng,true) . $naked_body, LOGGER_DATA);
269 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
272 if($user['hidewall'])
275 // If this is a comment, set the permissions from the parent.
280 // for non native networks use the network of the original post as network of the item
281 if (($parent_item['network'] != NETWORK_DIASPORA)
282 AND ($parent_item['network'] != NETWORK_OSTATUS)
283 AND ($network == ""))
284 $network = $parent_item['network'];
286 if(($parent_item['private'])
287 || strlen($parent_item['allow_cid'])
288 || strlen($parent_item['allow_gid'])
289 || strlen($parent_item['deny_cid'])
290 || strlen($parent_item['deny_gid'])) {
291 $private = (($parent_item['private']) ? $parent_item['private'] : 1);
294 $str_contact_allow = $parent_item['allow_cid'];
295 $str_group_allow = $parent_item['allow_gid'];
296 $str_contact_deny = $parent_item['deny_cid'];
297 $str_group_deny = $parent_item['deny_gid'];
299 $pubmail_enable = ((x($_REQUEST,'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && (! $private)) ? 1 : 0);
301 // if using the API, we won't see pubmail_enable - figure out if it should be set
303 if($api_source && $profile_uid && $profile_uid == local_user() && (! $private)) {
304 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
305 if(! $mail_disabled) {
306 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
309 if(count($r) && intval($r[0]['pubmail']))
310 $pubmail_enabled = true;
314 if(! strlen($body)) {
317 info( t('Empty post discarded.') . EOL );
318 if(x($_REQUEST,'return'))
319 goaway($a->get_baseurl() . "/" . $return_path );
324 if(strlen($categories)) {
325 // get the "fileas" tags for this post
326 $filedas = file_tag_file_to_list($categories, 'file');
328 // save old and new categories, so we can determine what needs to be deleted from pconfig
329 $categories_old = $categories;
330 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
331 $categories_new = $categories;
332 if(strlen($filedas)) {
333 // append the fileas stuff to the new categories list
334 $categories .= file_tag_list_to_file($filedas, 'file');
337 // Work around doubled linefeeds in Tinymce 3.5b2
338 // First figure out if it's a status post that would've been
339 // created using tinymce. Otherwise leave it alone.
341 /* $plaintext = (local_user() ? intval(get_pconfig(local_user(),'system','plaintext')) || !feature_enabled($profile_uid,'richtext') : 0);
342 if((! $parent) && (! $api_source) && (! $plaintext)) {
343 $body = fix_mce_lf($body);
345 $plaintext = (local_user() ? !feature_enabled($profile_uid,'richtext') : 0);
346 if((! $parent) && (! $api_source) && (! $plaintext)) {
347 $body = fix_mce_lf($body);
351 // get contact info for poster
357 if((local_user()) && (local_user() == $profile_uid)) {
359 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
360 intval($_SESSION['uid'])
363 elseif(remote_user()) {
364 if(is_array($_SESSION['remote'])) {
365 foreach($_SESSION['remote'] as $v) {
366 if($v['uid'] == $profile_uid) {
367 $contact_id = $v['cid'];
373 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
381 $contact_id = $author['id'];
384 // get contact info for owner
386 if($profile_uid == local_user()) {
387 $contact_record = $author;
390 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` = 1 LIMIT 1",
394 $contact_record = $r[0];
397 $post_type = notags(trim($_REQUEST['type']));
399 if($post_type === 'net-comment') {
400 if($parent_item !== null) {
401 if($parent_item['wall'] == 1)
402 $post_type = 'wall-comment';
404 $post_type = 'remote-comment';
410 * When a photo was uploaded into the message using the (profile wall) ajax
411 * uploader, The permissions are initially set to disallow anybody but the
412 * owner from seeing it. This is because the permissions may not yet have been
413 * set for the post. If it's private, the photo permissions should be set
414 * appropriately. But we didn't know the final permissions on the post until
415 * now. So now we'll look for links of uploaded messages that are in the
416 * post and set them to the same permissions as the post itself.
422 if((! $preview) && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
425 foreach($images as $image) {
426 if(! stristr($image,$a->get_baseurl() . '/photo/'))
428 $image_uri = substr($image,strrpos($image,'/') + 1);
429 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
430 if(! strlen($image_uri))
432 $srch = '<' . intval($contact_id) . '>';
434 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
435 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
445 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
446 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
447 dbesc($str_contact_allow),
448 dbesc($str_group_allow),
449 dbesc($str_contact_deny),
450 dbesc($str_group_deny),
452 intval($profile_uid),
453 dbesc( t('Wall Photos'))
462 * Next link in any attachment references we find in the post.
467 if((! $preview) && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
468 $attaches = $match[1];
469 if(count($attaches)) {
470 foreach($attaches as $attach) {
471 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
472 intval($profile_uid),
476 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
477 WHERE `uid` = %d AND `id` = %d",
478 dbesc($str_contact_allow),
479 dbesc($str_group_allow),
480 dbesc($str_contact_deny),
481 dbesc($str_group_deny),
482 intval($profile_uid),
490 // embedded bookmark in post? set bookmark flag
493 if(preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$body,$match,PREG_SET_ORDER)) {
497 $body = bb_translate_video($body);
501 * Fold multi-line [code] sequences
504 $body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body);
506 $body = scale_external_images($body,false);
511 * Look for any tags and linkify them
518 $tags = get_tags($body);
521 * add a statusnet style reply tag if the original post was from there
522 * and we are replying, and there isn't one already
525 if(($parent_contact) && ($parent_contact['network'] === NETWORK_OSTATUS)
526 && ($parent_contact['nick']) && (! in_array('@' . $parent_contact['nick'],$tags))) {
527 $body = '@' . $parent_contact['nick'] . ' ' . $body;
528 $tags[] = '@' . $parent_contact['nick'];
533 $private_forum = false;
536 foreach($tags as $tag) {
538 // If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
539 // Robert Johnson should be first in the $tags array
541 $fullnametagged = false;
542 for($x = 0; $x < count($tagged); $x ++) {
543 if(stristr($tagged[$x],$tag . ' ')) {
544 $fullnametagged = true;
551 $success = handle_tag($a, $body, $inform, $str_tags, (local_user()) ? local_user() : $profile_uid , $tag);
552 if($success['replaced'])
554 if(is_array($success['contact']) && intval($success['contact']['prv'])) {
555 $private_forum = true;
556 $private_id = $success['contact']['id'];
561 if(($private_forum) && (! $parent) && (! $private)) {
562 // we tagged a private forum in a top level post and the message was public.
565 $str_contact_allow = '<' . $private_id . '>';
571 if(preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
572 foreach($match[2] as $mtch) {
573 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
574 intval($profile_uid),
578 if(strlen($attachments))
580 $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]';
582 $body = str_replace($match[1],'',$body);
588 if($post_type === 'wall' || $post_type === 'wall-comment')
592 $verb = ACTIVITY_POST ;
595 $network = NETWORK_DFRN;
597 $gravity = (($parent) ? 6 : 0 );
599 // even if the post arrived via API we are considering that it
600 // originated on this site by default for determining relayability.
602 $origin = ((x($_REQUEST,'origin')) ? intval($_REQUEST['origin']) : 1);
604 $notify_type = (($parent) ? 'comment-new' : 'wall-new' );
606 $uri = (($message_id) ? $message_id : item_new_uri($a->get_hostname(),$profile_uid));
608 // Fallback so that we alway have a thr-parent
613 $datarray['uid'] = $profile_uid;
614 $datarray['type'] = $post_type;
615 $datarray['wall'] = $wall;
616 $datarray['gravity'] = $gravity;
617 $datarray['network'] = $network;
618 $datarray['contact-id'] = $contact_id;
619 $datarray['owner-name'] = $contact_record['name'];
620 $datarray['owner-link'] = $contact_record['url'];
621 $datarray['owner-avatar'] = $contact_record['thumb'];
622 $datarray['author-name'] = $author['name'];
623 $datarray['author-link'] = $author['url'];
624 $datarray['author-avatar'] = $author['thumb'];
625 $datarray['created'] = datetime_convert();
626 $datarray['edited'] = datetime_convert();
627 $datarray['commented'] = datetime_convert();
628 $datarray['received'] = datetime_convert();
629 $datarray['changed'] = datetime_convert();
630 $datarray['uri'] = $uri;
631 $datarray['title'] = $title;
632 $datarray['body'] = $body;
633 $datarray['app'] = $app;
634 $datarray['location'] = $location;
635 $datarray['coord'] = $coord;
636 $datarray['tag'] = $str_tags;
637 $datarray['file'] = $categories;
638 $datarray['inform'] = $inform;
639 $datarray['verb'] = $verb;
640 $datarray['allow_cid'] = $str_contact_allow;
641 $datarray['allow_gid'] = $str_group_allow;
642 $datarray['deny_cid'] = $str_contact_deny;
643 $datarray['deny_gid'] = $str_group_deny;
644 $datarray['private'] = $private;
645 $datarray['pubmail'] = $pubmail_enable;
646 $datarray['attach'] = $attachments;
647 $datarray['bookmark'] = intval($bookmark);
648 $datarray['thr-parent'] = $thr_parent;
649 $datarray['postopts'] = $postopts;
650 $datarray['origin'] = $origin;
651 $datarray['moderated'] = $allow_moderated;
654 * These fields are for the convenience of plugins...
655 * 'self' if true indicates the owner is posting on their own wall
656 * If parent is 0 it is a top-level post.
659 $datarray['parent'] = $parent;
660 $datarray['self'] = $self;
661 // $datarray['prvnets'] = $user['prvnets'];
664 $datarray['edit'] = true;
666 $datarray['guid'] = get_guid();
668 // preview mode - prepare the body for display and send it via json
671 require_once('include/conversation.php');
672 $o = conversation($a,array(array_merge($contact_record,$datarray)),'search', false, true);
673 logger('preview: ' . $o);
674 echo json_encode(array('preview' => $o));
679 call_hooks('post_local',$datarray);
681 if(x($datarray,'cancel')) {
682 logger('mod_item: post cancelled by plugin.');
684 goaway($a->get_baseurl() . "/" . $return_path);
687 $json = array('cancel' => 1);
688 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
689 $json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];
691 echo json_encode($json);
697 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `attach` = '%s', `file` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
698 dbesc($datarray['title']),
699 dbesc($datarray['body']),
700 dbesc($datarray['tag']),
701 dbesc($datarray['attach']),
702 dbesc($datarray['file']),
703 dbesc(datetime_convert()),
707 create_tags_from_itemuri($post_id, $profile_uid);
709 // update filetags in pconfig
710 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
712 proc_run('php', "include/notifier.php", 'edit_post', "$post_id");
713 if((x($_REQUEST,'return')) && strlen($return_path)) {
714 logger('return: ' . $return_path);
715 goaway($a->get_baseurl() . "/" . $return_path );
723 $r = q("INSERT INTO `item` (`guid`, `uid`,`type`,`wall`,`gravity`, `network`, `contact-id`,`owner-name`,`owner-link`,`owner-avatar`,
724 `author-name`, `author-link`, `author-avatar`, `created`, `edited`, `commented`, `received`, `changed`, `uri`, `thr-parent`, `title`, `body`, `app`, `location`, `coord`,
725 `tag`, `inform`, `verb`, `postopts`, `allow_cid`, `allow_gid`, `deny_cid`, `deny_gid`, `private`, `pubmail`, `attach`, `bookmark`,`origin`, `moderated`, `file` )
726 VALUES( '%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', %d, %d, '%s', %d, %d, %d, '%s' )",
727 dbesc($datarray['guid']),
728 intval($datarray['uid']),
729 dbesc($datarray['type']),
730 intval($datarray['wall']),
731 intval($datarray['gravity']),
732 dbesc($datarray['network']),
733 intval($datarray['contact-id']),
734 dbesc($datarray['owner-name']),
735 dbesc($datarray['owner-link']),
736 dbesc($datarray['owner-avatar']),
737 dbesc($datarray['author-name']),
738 dbesc($datarray['author-link']),
739 dbesc($datarray['author-avatar']),
740 dbesc($datarray['created']),
741 dbesc($datarray['edited']),
742 dbesc($datarray['commented']),
743 dbesc($datarray['received']),
744 dbesc($datarray['changed']),
745 dbesc($datarray['uri']),
746 dbesc($datarray['thr-parent']),
747 dbesc($datarray['title']),
748 dbesc($datarray['body']),
749 dbesc($datarray['app']),
750 dbesc($datarray['location']),
751 dbesc($datarray['coord']),
752 dbesc($datarray['tag']),
753 dbesc($datarray['inform']),
754 dbesc($datarray['verb']),
755 dbesc($datarray['postopts']),
756 dbesc($datarray['allow_cid']),
757 dbesc($datarray['allow_gid']),
758 dbesc($datarray['deny_cid']),
759 dbesc($datarray['deny_gid']),
760 intval($datarray['private']),
761 intval($datarray['pubmail']),
762 dbesc($datarray['attach']),
763 intval($datarray['bookmark']),
764 intval($datarray['origin']),
765 intval($datarray['moderated']),
766 dbesc($datarray['file'])
769 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' LIMIT 1",
770 dbesc($datarray['uri']));
772 $post_id = $r[0]['id'];
773 logger('mod_item: saved item ' . $post_id);
774 create_tags_from_item($post_id);
776 // update filetags in pconfig
777 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
779 // Store the fresh generated item into the cache
780 $cachefile = get_cachefile($datarray["guid"]."-".hash("md5", $datarray['body']));
782 if (($cachefile != '') AND !file_exists($cachefile)) {
783 $s = prepare_text($datarray['body']);
784 $stamp1 = microtime(true);
785 file_put_contents($cachefile, $s);
786 $a->save_timestamp($stamp1, "file");
787 logger('mod_item: put item '.$r[0]['id'].' into cachefile '.$cachefile);
792 // This item is the last leaf and gets the comment box, clear any ancestors
793 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent` = %d ",
794 dbesc(datetime_convert()),
798 // Inherit ACL's from the parent item.
800 $r = q("UPDATE `item` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d
802 dbesc($parent_item['allow_cid']),
803 dbesc($parent_item['allow_gid']),
804 dbesc($parent_item['deny_cid']),
805 dbesc($parent_item['deny_gid']),
806 intval($parent_item['private']),
810 if($contact_record != $author) {
812 'type' => NOTIFY_COMMENT,
813 'notify_flags' => $user['notify-flags'],
814 'language' => $user['language'],
815 'to_name' => $user['username'],
816 'to_email' => $user['email'],
817 'uid' => $user['uid'],
819 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
820 'source_name' => $datarray['author-name'],
821 'source_link' => $datarray['author-link'],
822 'source_photo' => $datarray['author-avatar'],
823 'verb' => ACTIVITY_POST,
826 'parent_uri' => $parent_item['uri']
832 // Store the comment signature information in case we need to relay to Diaspora
833 store_diaspora_comment_sig($datarray, $author, ($self ? $a->user['prvkey'] : false), $parent_item, $post_id);
839 if($contact_record != $author) {
841 'type' => NOTIFY_WALL,
842 'notify_flags' => $user['notify-flags'],
843 'language' => $user['language'],
844 'to_name' => $user['username'],
845 'to_email' => $user['email'],
846 'uid' => $user['uid'],
848 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id,
849 'source_name' => $datarray['author-name'],
850 'source_link' => $datarray['author-link'],
851 'source_photo' => $datarray['author-avatar'],
852 'verb' => ACTIVITY_POST,
858 // fallback so that parent always gets set to non-zero.
863 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s', `plink` = '%s', `changed` = '%s', `last-child` = 1, `visible` = 1
866 dbesc(($parent == $post_id) ? $uri : $parent_item['uri']),
867 dbesc($a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id),
868 dbesc(datetime_convert()),
872 // photo comments turn the corresponding item visible to the profile wall
873 // This way we don't see every picture in your new photo album posted to your wall at once.
874 // They will show up as people comment on them.
876 if(! $parent_item['visible']) {
877 $r = q("UPDATE `item` SET `visible` = 1 WHERE `id` = %d",
878 intval($parent_item['id'])
883 logger('mod_item: unable to retrieve post that was just stored.');
884 notice( t('System error. Post not saved.') . EOL);
885 goaway($a->get_baseurl() . "/" . $return_path );
889 // update the commented timestamp on the parent
891 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
892 dbesc(datetime_convert()),
893 dbesc(datetime_convert()),
897 $datarray['id'] = $post_id;
898 $datarray['plink'] = $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $post_id;
900 call_hooks('post_local_end', $datarray);
902 if(strlen($emailcc) && $profile_uid == local_user()) {
903 $erecips = explode(',', $emailcc);
904 if(count($erecips)) {
905 foreach($erecips as $recip) {
906 $addr = trim($recip);
909 $disclaimer = '<hr />' . sprintf( t('This message was sent to you by %s, a member of the Friendica social network.'),$a->user['username'])
911 $disclaimer .= sprintf( t('You may visit them online at %s'), $a->get_baseurl() . '/profile/' . $a->user['nickname']) . EOL;
912 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
913 if (!$datarray['title']=='') {
914 $subject = email_header_encode($datarray['title'],'UTF-8');
916 $subject = email_header_encode('[Friendica]' . ' ' . sprintf( t('%s posted an update.'),$a->user['username']),'UTF-8');
918 $link = '<a href="' . $a->get_baseurl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
919 $html = prepare_body($datarray);
920 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
921 include_once('include/html2plain.php');
923 'fromName' => $a->user['username'],
924 'fromEmail' => $a->user['email'],
926 'replyTo' => $a->user['email'],
927 'messageSubject' => $subject,
928 'htmlVersion' => $message,
929 'textVersion' => html2plain($html.$disclaimer),
931 enotify::send($params);
936 // This is a real juggling act on shared hosting services which kill your processes
937 // e.g. dreamhost. We used to start delivery to our native delivery agents in the background
938 // and then run our plugin delivery from the foreground. We're now doing plugin delivery first,
939 // because as soon as you start loading up a bunch of remote delivey processes, *this* page is
940 // likely to get killed off. If you end up looking at an /item URL and a blank page,
941 // it's very likely the delivery got killed before all your friends could be notified.
942 // Currently the only realistic fixes are to use a reliable server - which precludes shared hosting,
943 // or cut back on plugins which do remote deliveries.
945 proc_run('php', "include/notifier.php", $notify_type, "$post_id");
947 logger('post_complete');
949 item_post_return($a->get_baseurl(), $api_source, $return_path);
953 function item_post_return($baseurl, $api_source, $return_path) {
954 // figure out how to return, depending on from whence we came
960 goaway($baseurl . "/" . $return_path);
963 $json = array('success' => 1);
964 if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
965 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
967 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
969 echo json_encode($json);
975 function item_content(&$a) {
977 if((! local_user()) && (! remote_user()))
980 require_once('include/security.php');
983 if(($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
984 require_once('include/items.php');
985 $o = drop_item($a->argv[2], !is_ajax());
987 // ajax return: [<item id>, 0 (no perm) | <owner id>]
988 echo json_encode(array(intval($a->argv[2]), intval($o)));
996 * This function removes the tag $tag from the text $body and replaces it with
997 * the appropiate link.
999 * @param unknown_type $body the text to replace the tag in
1000 * @param unknown_type $inform a comma-seperated string containing everybody to inform
1001 * @param unknown_type $str_tags string to add the tag to
1002 * @param unknown_type $profile_uid
1003 * @param unknown_type $tag the tag to replace
1005 * @return boolean true if replaced, false if not replaced
1007 function handle_tag($a, &$body, &$inform, &$str_tags, $profile_uid, $tag) {
1013 if(strpos($tag,'#') === 0) {
1014 //if the tag is replaced...
1015 if(strpos($tag,'[url='))
1018 //base tag has the tags name only
1019 $basetag = str_replace('_',' ',substr($tag,1));
1020 //create text for link
1021 $newtag = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1022 //replace tag by the link
1023 $body = str_replace($tag, $newtag, $body);
1026 //is the link already in str_tags?
1027 if(! stristr($str_tags,$newtag)) {
1028 //append or set str_tags
1029 if(strlen($str_tags))
1031 $str_tags .= $newtag;
1035 //is it a person tag?
1036 if(strpos($tag,'@') === 0) {
1037 //is it already replaced?
1038 if(strpos($tag,'[url='))
1041 //get the person's name
1042 $name = substr($tag,1);
1043 //is it a link or a full dfrn address?
1044 if((strpos($name,'@')) || (strpos($name,'http://'))) {
1046 //get the profile links
1047 $links = @lrdd($name);
1049 //for all links, collect how is to inform and how's profile is to link
1050 foreach($links as $link) {
1051 if($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page')
1052 $profile = $link['@attributes']['href'];
1053 if($link['@attributes']['rel'] === 'salmon') {
1056 $inform .= 'url:' . str_replace(',','%2c',$link['@attributes']['href']);
1060 } else { //if it is a name rather than an address
1064 //is it some generated name?
1065 if(strrpos($newname,'+')) {
1067 $tagcid = intval(substr($newname,strrpos($newname,'+') + 1));
1068 //remove the next word from tag's name
1069 if(strpos($name,' ')) {
1070 $name = substr($name,0,strpos($name,' '));
1073 if($tagcid) { //if there was an id
1074 //select contact with that id from the logged in user's contact list
1075 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1077 intval($profile_uid)
1081 $newname = str_replace('_',' ',$name);
1083 //select someone from this user's contacts by name
1084 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1086 intval($profile_uid)
1090 //select someone by attag or nick and the name passed in
1091 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1094 intval($profile_uid)
1098 /* } elseif(strstr($name,'_') || strstr($name,' ')) { //no id
1100 $newname = str_replace('_',' ',$name);
1101 //select someone from this user's contacts by name
1102 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1104 intval($profile_uid)
1107 //select someone by attag or nick and the name passed in
1108 $r = q("SELECT * FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1111 intval($profile_uid)
1114 //$r is set, if someone could be selected
1116 $profile = $r[0]['url'];
1117 //set newname to nick, find alias
1118 if(($r[0]['network'] === NETWORK_OSTATUS) OR ($r[0]['network'] === NETWORK_TWITTER)) {
1119 $newname = $r[0]['nick'];
1122 $alias = $r[0]['alias'];
1125 $newname = $r[0]['name'];
1126 //add person's id to $inform
1129 $inform .= 'cid:' . $r[0]['id'];
1132 //if there is an url for this persons profile
1133 if(isset($profile)) {
1135 //create profile link
1136 $profile = str_replace(',','%2c',$profile);
1137 $newtag = '@[url=' . $profile . ']' . $newname . '[/url]';
1138 $body = str_replace('@' . $name, $newtag, $body);
1139 //append tag to str_tags
1140 if(! stristr($str_tags,$newtag)) {
1141 if(strlen($str_tags))
1143 $str_tags .= $newtag;
1146 // Status.Net seems to require the numeric ID URL in a mention if the person isn't
1147 // subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1149 if(strlen($alias)) {
1150 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1151 if(! stristr($str_tags,$newtag)) {
1152 if(strlen($str_tags))
1154 $str_tags .= $newtag;
1160 return array('replaced' => $replaced, 'contact' => $r[0]);
1164 function store_diaspora_comment_sig($datarray, $author, $uprvkey, $parent_item, $post_id) {
1165 // We won't be able to sign Diaspora comments for authenticated visitors - we don't have their private key
1167 $enabled = intval(get_config('system','diaspora_enabled'));
1169 logger('mod_item: diaspora support disabled, not storing comment signature', LOGGER_DEBUG);
1174 logger('mod_item: storing diaspora comment signature');
1176 require_once('include/bb2diaspora.php');
1177 $signed_body = html_entity_decode(bb2diaspora($datarray['body']));
1179 // Only works for NETWORK_DFRN
1180 $contact_baseurl_start = strpos($author['url'],'://') + 3;
1181 $contact_baseurl_length = strpos($author['url'],'/profile') - $contact_baseurl_start;
1182 $contact_baseurl = substr($author['url'], $contact_baseurl_start, $contact_baseurl_length);
1183 $diaspora_handle = $author['nick'] . '@' . $contact_baseurl;
1185 $signed_text = $datarray['guid'] . ';' . $parent_item['guid'] . ';' . $signed_body . ';' . $diaspora_handle;
1187 if( $uprvkey !== false )
1188 $authorsig = base64_encode(rsa_sign($signed_text,$uprvkey,'sha256'));
1192 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1194 dbesc($signed_text),
1195 dbesc(base64_encode($authorsig)),
1196 dbesc($diaspora_handle)