<?php

/**
 * Implementation of hook_menu()
 */
function emonocot_feedback_menu(){
  $items['feedback'] = array(
    'title' => 'eMonocot Feedback',
    'page callback' => 'emonocot_feedback_get_feedback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

function emonocot_feedback_get_feedback(){
  $ok_ips = array(
    '129.67.24.39',
    '129.67.24.160'
  );
  if(!in_array(ip_address(), $ok_ips)){
    emonocot_feedback_bad_request(ip_address() . ' is not a trusted IP address.');
  }else{
    $params = emonocot_feedback_process_get($_GET);
    $comment = emonocot_feedback_comment_create($params);
    emonocot_feedback_comment_save($comment);
    return 'O...K....';
  }
}

function emonocot_feedback_process_get($get){
  $return = array();
  if(isset($get['uri'])){
    $return['uri'] = $get['uri'];
    $return['nid'] = emonocot_feedback_nid_from_uri($return['uri']);
    $node = node_load($return['nid']);
    if($node->comment != '2'){
      emonocot_feedback_bad_request('Node does not allow comments');
    }
  }else{
    emonocot_feedback_bad_request('Could not identify target node');
  }
  if(isset($get['mail'])){
    $return['mail'] = $get['mail'];
    $return['uid'] = emonocot_feedback_uid_from_mail($return['mail']);
  }else{
    $return['mail'] = FALSE;
    $return['uid'] = FALSE;
  }
  if($return['uid'] != FALSE){
    if(isset($get['username'])){
      $return['name'] = $get['username'];
    }
  }
  if(isset($get['inreplyto'])){
    $needle = '-comment';
    $start = strpos(urldecode($get['inreplyto']), $needle);
    if($start){
      $return['pid'] = substr($get['inreplyto'], $start + strlen($needle));
    }
  }
  if(isset($get['comment'])){
    $return['comment_body'] = $get['comment'];
  }
  if(isset($get['title'])){
    $return['comment_subject'] = $get['title'];
  }
  return $return;
}

function emonocot_feedback_bad_request($msg){
  drupal_add_http_header('Status', '400', FALSE);
  drupal_send_headers();
  print $msg;
  exit();
}

function emonocot_feedback_created(){
  drupal_add_http_header('Status', '201', FALSE);
}

function emonocot_feedback_comment_create($params){
  if(isset($params['pid'])){
    $parent = comment_load($params['pid']);
    $params['thread'] = str_replace('/', '', $parent->thread) . '.1/';
  }else{
    $params['thread'] = '01/';
  }
  $comment = new stdClass();
  $comment->nid = 0;
  $comment->cid = 0;
  $comment->pid = 0;
  $comment->uid = 0;
  $comment->mail = '';
  $comment->name = 'Anonymous';
  //$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
  $comment->is_anonymous = 0;
  $comment->status = COMMENT_PUBLISHED;
  $comment->language = LANGUAGE_NONE;
  $comment->subject = 'Comment subject';
  $comment->comment_body[$comment->language][0]['value'] = 'Comment body text';
  $comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
  foreach($params as $key => $value){
    $comment->$key = $value;
  }
  return $comment;
}

function emonocot_feedback_comment_save($comment){
  comment_submit($comment);
  comment_save($comment);
  emonocot_feedback_created();
}

function emonocot_feedback_nid_from_uri($uri){
  global $base_url;
  $base_url_length = strlen($base_url);
  $path = FALSE;
  //Let's get a Drupal path
  if(substr($uri, 0, $base_url_length) == $base_url){
    if(substr($uri, $base_url_length + 1, 3) == '?q='){
      $path = substr($uri, $base_url_length + 4);
    }else{
      $path = substr($uri, $base_url_length + 1);
    }
    //Convert path to nid
    $node = menu_get_object('node', 1, $path);
    return $node->nid;
  }
}

function emonocot_feedback_uid_from_mail($mail){
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')->propertyCondition('mail', $mail);
  $result = $query->execute();
  // not found?                                                      
  if(!isset($result['user']))
    return 0;
     // found, keys are uids                                            
  $uids = array_keys($result['user']);
  $uid = user_load($uids[0]);
  return $uid->uid;
}