<?php
/**
 * Comment module
 * 
 * Provides basics methods called from public templates
 * These methods can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 * 
 * @package linea21\modules\comment
 * @author $Author$ - Simon Georget <simon@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once(override('../comment/'.SQL.'.inc.php'));
include_once('../class/class.comment.php');
include_once(override('../vote/display.php'));

if(!function_exists('getPostCommentAnchor')) {

  function getPostCommentAnchor() {

    $str = 	'<a id="anchor-post-comment" href="'.str_replace('&', '&amp;', $_SERVER["REQUEST_URI"]).'#add-comment" title="'._t('comment', 'add').'">'._t('comment', 'add').'</a>';
    return $str;
  }
}

if(!function_exists('getCommentsAnchor')) {

  function getCommentsAnchor($a) {
    $nb = getNbComments($a);
    $str = 	'<a id="anchor-comment" href="'.str_replace('&', '&amp;', $_SERVER["REQUEST_URI"]).'#comments" title="'._t('comment', 'go_to').'">'.sprintf(_t('comment', 'number'), '<span id="cc">'.$nb.'</span>').'</a>';
    return $str;
  }
}

if(!function_exists('getNbComments')) {

  function getNbComments($a) {
    $data = $GLOBALS['sql_object']->DBSelect(SQL_getCommentsNumber($a));
    return $data[0]['nb'];
  }

}

if(!function_exists('displayComments')) {

  function displayComments($a, $moderation = false, $get_permalink = false) {
    echo getComments($a, $moderation, $get_permalink);
  }
}

if(!function_exists('getComments')) {

  function getComments($a, $moderation = false, $get_permalink = false) {

    $comm = new comment;
    $comments = $comm->get($a, $GLOBALS['sql_object']);

    if (!is_array($comments)) {
        if(isset($a['module']) && $a['module'] == 'contribute') return '<p>' . _t('comment', 'nocontrib_yet') . '</p>';
        else return '<p class="no-comment-yet">' . _t('comment', 'nocomment_yet') . '</p>';
    }
    
    if($a['module'] == 'contribute') $comments = array_reverse($comments);
    
    return getMarkup($comments, $moderation, $get_permalink);

  }

}

if(!function_exists('postCommentAction')) {

  function postCommentAction($a) {

    // comment submit
    if(isset($_POST['cbody'])) {
      $arr = array();

      isset($_SESSION['userlogin']) ? $arr['user_id'] = base64_decode($_SESSION['userid']) : $arr['user_id'] = '';
      $arr['module'] = $a['module'];
      $arr['module_id'] = $a['module_id'];
      isset($_POST['cname']) ? $arr['name'] = $_POST['cname'] : $arr['name'] = '';
      isset($_POST['cemail']) ? $arr['email'] = $_POST['cemail'] : $arr['email'] = '';
      isset($_POST['curl']) ? $arr['url'] = $_POST['curl'] : $arr['url'] = '';
      isset($_POST['cbody']) ? $arr['body'] = $_POST['cbody'] : $arr['body'] = '';
      isset($_POST['cnotification']) ? $arr['notification'] = 'Y' : $arr['notification'] = 'N';

      $comm = new comment;

      // prevent spam if user not authenticated
      if(!isset($_SESSION['authenticated']) && $_SESSION['securityaction']!=md5($_POST['securitycode'])) {
      	$passed =_t('security','message');
      }

      if(!isset($passed))  $passed = $comm->checkDataIntegrity($arr);

      // errors on input
      if(is_string($passed)) {
        $msg = '<p class="error">'. $passed .'</p>';
        // everything is OK
      } else {
        $r = $comm->add($arr, $GLOBALS['sql_object']);
        if(!is_numeric($r)) system_error('adding comment on ' . $arr['module'] . '/' . $arr['module_id']);
        // we send an email to default user for moderation if needed
        emailModerators($arr, $r, $comm);
        // we notify users if needed
        notifyUsers($arr, $r, $comm);
        $msg = '<b>' . _t('comment', 'successful') . '</b>';
        (COMMENT_MODERATION == 1) ? $msg .= '<br />'._t('comment', 'moderation_msg') : '';
        $msg = '<p class="confirmed">'. $msg .'</p>';
        echo '<script type="text/javascript">
                  $(function() {
                  	setTimeout(\'jQuery.smoothScroll({scrollTarget: "#com-'.$r.'"});\', '.SCROLL_DELAY.');
                  });
              </script>';
        footerAddJS('../lib/js/jquery.smooth-scroll.min.js');
      }

      echo $msg;
      return true;
    }

    return false;
  }
}

if(!function_exists('displayCommentForm')) {

  function displayCommentForm($a) {

    // prepare vars fo form
    isset($a['module']) ? $rub = $a['module'] : $rub = $_REQUEST['rub'];
    isset($a['module_id']) ? $id = $a['module_id'] : $id = $_REQUEST['id'];

    // prepare name var
    $fullname ='';
    if(isset($_SESSION['userfirstname'])) $fullname = $_SESSION['userfirstname'];
    if(isset($_SESSION['userlastname'])) $fullname .= ' '. $_SESSION['userlastname'];
    if(!empty($fullname)) $fullname = ' ('.$fullname.')';

    $f_name = '';
    $f_email = '';
    $f_url = '';
    $f_body = '';
    $f_notification ='';

    // comment submit
    if(isset($_POST['cbody'])) {
      $arr = array();

      isset($_SESSION['userlogin']) ? $arr['user_id'] = base64_decode($_SESSION['userid']) : $arr['user_id'] = '';
      $arr['module'] = $a['module'];
      $arr['module_id'] = $a['module_id'];
      isset($_POST['cname']) ? $arr['name'] = $_POST['cname'] : $arr['name'] = '';
      isset($_POST['cemail']) ? $arr['email'] = $_POST['cemail'] : $arr['email'] = '';
      isset($_POST['curl']) ? $arr['url'] = $_POST['curl'] : $arr['url'] = '';
      isset($_POST['cbody']) ? $arr['body'] = $_POST['cbody'] : $arr['body'] = '';
      isset($_POST['cnotification']) ? $arr['notification'] = 'Y' : $arr['notification'] = 'N';


      $comm = new comment;
      $passed = $comm->checkDataIntegrity($arr);

      // errors on input
      if(is_string($passed)) {
        if(isset($_POST['cname'])) $f_name = $_POST['cname'];
        if(isset($_POST['cemail'])) $f_email = $_POST['cemail'];
        if(isset($_POST['curl'])) $f_url = $_POST['curl'];
        if(isset($_POST['cbody'])) $f_body = $_POST['cbody'];
        if(isset($_POST['cnotification'])) $f_notification = ' checked="checked"';
      }

    }
    // we prepare message
    $link = HrefMaker(array('rub'=> $GLOBALS['links'][U_L]['user-prefs']['linkvalue']));
    $link_create = HrefMaker(array('rub'=> $GLOBALS['links'][U_L]['user-registration']['linkvalue']));
    if($rub == 'contribute') {
        $title = _t('comment', 'add_contrib');
        $msg_only_registered = sprintf(_t('comment', 'only_registered_contrib'), $link, 'login-link');
        if(defined('FREE_REGISTRATION') && FREE_REGISTRATION == 1) $msg_only_registered .= ' ' . sprintf(_t('comment', 'create_account'), $link_create, '');
        $msg_moderation = _t('comment', 'moderation_msg_contrib');
    }
    else {
        $title = _t('comment', 'add');
        $msg_only_registered = sprintf(_t('comment', 'only_registered'), $link, 'login-link');
        if(defined('FREE_REGISTRATION') && FREE_REGISTRATION == 1) $msg_only_registered .= ' ' . sprintf(_t('comment', 'create_account'), $link_create, '');
        $msg_moderation = _t('comment', 'moderation_msg');
    }



    if(COMMENT_ONLY_REGISTERED == 1 && !isset($_SESSION['userlogin'])) {
      
      $content = '<p class="info" id="add-comment">'.$msg_only_registered.'</p>';
    } else {
      $content = '<div id="add-comment" class="no-print">
          			<h3>'.$title.'</h3>
          			<form id="add-comment-form" method="post" action="'. CURRENT_APP_URL .'index.php">
              		<div>';
      if(!isset($_SESSION['authenticated'])) {
        $content .= '<p><label for="cname" class="labelised">'._t('comment', 'name').' : </label>
                  	  <input type="text" name="cname" id="cname" class="shorttextfield" value="' . $f_name . '" /></p>
                      <p><label for="cemail" class="labelised">'._t('comment', 'email').' : </label>
                      <input type="text" name="cemail" id="cemail" class="shorttextfield" value="' . $f_email . '" /></p>
                      <p><label for="curl" class="labelised">'._t('comment', 'website').' ('._t('divers', 'optional').') : </label>
                      <input type="text" name="curl" id="curl" class="shorttextfield" value="' . $f_url . '" /></p>
        							<p class="antispam">
        							<span class="labelmargin labelised">' . _t('security','info2') . ' : </span>
        							<img src="'.SITE_ROOT_URL.'lib/securitycode.php" alt="' . _t('security','info2') .'" id="securityimg"  />
        							</p>
        							<p><label for="securitycode" class="labelised">' . _t('antispam','info') . ' * : </label>
        							<input type="text" class="textfield" id="securitycode" maxlength="5" name="securitycode" /></p> ';
      } else {
        $content .= '<p class="label-leftmargin">'.sprintf(_t('comment', 'logged-in_post'), '<strong>'.$_SESSION['userlogin'].'</strong> '.$fullname).'</p>';
      }
      $content .= '<p><label for="cbody" class="labelised">'._t('comment', 'body').' : </label>
                      <textarea name="cbody" id="cbody" cols="30"  class="shorttextfield" rows="5" required>' . $f_body . '</textarea></p>';
      // no ability to subscribe on 'contribute' module
      if(COMMENT_NOTIFICATION == 1 && $a['module']!='contribute') {
        $content .= '<p class="label-leftmargin"><input type="checkbox" name="cnotification" id="cnotification" value="1"'.$f_notification.' /><label for="cnotification" class="labelised autowidth">' . _t('comment', 'email_notification') . '</label></p>';
      }
      $content .= '<input type="hidden" name="module" id="module" value="'.$a['module'].'" />
                      <input type="hidden" name="rub" id="rub" value="'.$rub.'" />
                      <input type="hidden" name="id" id="id" value="'.$id.'" />';
      if(COMMENT_MODERATION == 1) {
        if(!isset($_SESSION['userlogin']) || (isset($_SESSION['userlogin']) && COMMENT_MODERATE_REGISTERED == 1))
        $content .= '<p class="info">'.$msg_moderation.'</p>';
      }
      $content .= '<input type="submit" class="submitbut" value="'._t('btn','valid').'" />
                  </div>
              </form>
          </div>';
    }
    // for ajax implementation
    footerAddInlineJS('<script>var mainURL = "'.SITE_ROOT_URL .'";</script>', $pos = 'default', false);
    footerAddJS('../lib/js/comment_submit.js');

    echo $content;

  }

}

if(!function_exists('getMarkup')) {

  function getMarkup($comments, $moderation = false, $get_permalink = false) {

    $str = '';
    $registered ='';
    $class= 'odd';

    if (!is_array($comments)) return '';
    foreach($comments as $c) {
      $cdate       = $c['comment_date_crea_display'];
      $cdateshort  = substr($c['comment_date_crea_display'], 0, 10);
      $cbody       = formatText($c['comment_body']);
      (trim($class) == 'odd') ? $class = '' : $class = ' odd';
      
      // if vote is enabled on contribution and it is a contribution
      if(voteEnabled('contribute') && $c['comment_module'] == 'contribute') $likes_number = getNbVotes(array('module' => 'contribute', 'module_id' => $c['comment_id']));

      // get fullname
      if(!empty($c['profile_firstname']) || !empty($c['profile_lastname'])) {
      	$fullname = '('.$c['profile_firstname']. ' '.$c['profile_lastname'].')';
      } else {
      	$fullname = '';
      }
      
      if(CURRENT_APP == 'admin') {
      	$is_editable = ' contenteditable="true"';      	
      } else {
      	$is_editable = '';
      }

      if(!empty($c['profile_avatar'])) {
        $avatar = SITE_ROOT_URL . $c['profile_avatar'];
      } else {
        $avatar = PUBLIC_THEME_URL. 'images/no_avatar.png';
      }
      if($c['comment_status']=='D') {
        $extraclass = ' to-moderate';
        if(CURRENT_APP != 'admin') {
          $tomoderate = '<p class="moderation">'._t('comment', 'to_moderate').'</p>';
        } else {
          $tomoderate = '';
        }
      } else {
        $extraclass = '';
        $tomoderate = '';
      }
      if($c['comment_user_id']!=0) {
        if(CURRENT_APP == 'admin') {
          $link = 'index.php?rub=user&amp;todo=det&amp;id='.$c['comment_user_id'];
          $data = $GLOBALS['sql_object']->DBSelect(SQL_getUserInfo($c['comment_user_id']));
          $cemail = ' - <a href="mailto:'.$data[0]['profile_email'].'">'.$data[0]['profile_email'].'</a>';
          $registered = ' ['._t('comment', 'registered_user').'] ';
        } else {
          $link = HrefMaker(array('rub' => $GLOBALS['links'][U_L]['user-profile']['linkvalue'], 'id' => $c['user_id'], 'name' => $c['user_login']));
          $cemail = '';
        }
        $cname = '<a href="'. $link.'" title="' . $GLOBALS['links'][U_L]['user-profile']['desc'].'">'.$c['user_login'].'</a>' . ' ' .$fullname;
        if($c['user_validity'] == 'N') $cname = $c['user_login'] . ' (' . _t('user', 'deleted-account') . ')';
        $cname_raw = $c['user_login'];
      } else {
        if(CURRENT_APP == 'admin') {
          $cemail = ' - <a href="mailto:'.$c['comment_email'].'">'.$c['comment_email'].'</a>';
          $registered = '';
        } else {
          $cemail = '';
        }
        if(!empty($c['comment_url']))
        $cname = '<a href="'.$c['comment_url'].'">'.$c['comment_name'].'</a>';
        else {
          $cname = $c['comment_name'];
        }
        $cname_raw = $c['comment_name'];
      }

      $item = itemMapping($c['comment_module']);

      if($get_permalink == true) {
        $permalink = '<a href="'.str_replace('&', '&amp;', $_SERVER["REQUEST_URI"]).'#com-'.$c['comment_id'].'">#'.$c['comment_id'].'</a>';
      } else {
        $permalink = '#'.$c['comment_id'];
      }
      if($c['comment_status']== 'E') {
        $marker = _t('comment', 'disapproved');
        $cmarker = ' disapprove';
      }
      if($c['comment_status']== 'P') {
        $marker = _t('comment', 'approved');
        $cmarker = ' approve';
      }
      if($c['comment_status']== 'D') {
        $marker = _t('comment', 'awaiting');
        $cmarker = ' awaiting';
      }
      $str .= '<div class="comment'.$class.$extraclass.'" id="com-'.$c['comment_id'].'">

				<div class="avatar">
					<img src="'.$avatar.'" alt="'.$cname_raw.'" />
				</div>
				<div class="name">' . $cname . $registered . $cemail.'</div>
				<div class="date" title="'. $cdate .'">'. $permalink .' - '. $cdateshort .'</div>
				<div class="body"'. $is_editable .' id="com-body-'.$c['comment_id'].'" data-comment-id="'.$c['comment_id'].'">'. formatText($cbody, '2HTML') .'</div>';
      if(isset($likes_number) && CURRENT_APP != 'admin') {
          if($item['link'] == 'contribute') $t = mb_ucfirst(_t('like', 'i_like_proposal'));
          else $t = mb_ucfirst(_t('like', 'i_like_project'));
          $str .= '<div class="votes flex-container">'.PHP_EOL;
          $str .= '<div class="votes-number txtcenter"><span class="cnt-votes" id="cnt-votes-'.$c['comment_id'].'">' . $likes_number . '</span> ' . _t('like', 'likes')  .'</div>'.PHP_EOL;
          $str .= '<div class="i-like-it item-fluid"><a href="'.SITE_ROOT_URL.'vote/_vote.php" data-id="'.$c['comment_id'].'">'. $t .'</a>';
          $str .= '<p class="vote-msg" id="vote-msg-'.$c['comment_id'].'">&nbsp;</p>'.PHP_EOL;
          $str .= '</div>'.PHP_EOL;
          $str .= '</div>'.PHP_EOL;         
      }
      $str .= $tomoderate;
      if($moderation === true || ( $moderation == 'smart' && $c['comment_status'] == 'D') ) {
        $str .= '<div class="comment-actions">
        	<div class="iconetab">
					<a href="'. SITE_ROOT_URL .'comment/_ajax_admin.php?todo=approve&amp;id='.$c['comment_id'].'" class="ico_approve" title="'.ucfirst(_t('comment', 'approve')).'"><i class="icon-ok"></i><span>'.ucfirst(_t('comment', 'approve')).'</span></a>
					<a href="'. SITE_ROOT_URL .'comment/_ajax_admin.php?todo=disapprove&amp;id='.$c['comment_id'].'" class="ico_disapprove" title="'.ucfirst(_t('comment', 'disapprove')).'"><i class="icon-cancel"></i><span>'.ucfirst(_t('comment', 'disapprove')).'</span></a>
					<a href="'. SITE_ROOT_URL .'comment/_ajax_admin.php?todo=del&amp;id='.$c['comment_id'].'" class="ico_sup" title="'.ucfirst(_t('comment', 'delete')).'"><i class="icon-trash"></i><span>'.ucfirst(_t('comment', 'delete')).'</span></a>

					</div><br style="clear:both" />
					<div class="action-marker'.$cmarker.'">'.$marker.'</div>
				</div>
				';
      }
      if(CURRENT_APP == 'admin') {
        if($item['link'] == 'library') {
          $key = 'expandedFolder';
        } else {
          $key = 'id';
        }
        if($item['link'] != 'contribute') {
          $str .= '<p class="item">'. _t('comment', 'posted_in') .' <a href="../admin/index.php?rub='.$item['link'].'&amp;todo=det&amp;'.$key.'='.$c['comment_module_id'].'" title="'.$c['item_title'].'">'.$c['item_title'].'</a> ('. $item['name']. ')</p>';
        } else {
          // no link to item for 'contribute' module
          $str .= '<p class="item">'. _t('comment', 'posted_in') .' '. $item['name']. '</p>';
          // display votes number if is set
          if(isset($likes_number)) $str .= '<p class="votes-number item"><span class="cnt-votes">' . $likes_number . '</span> ' . _t('like', 'likes')  .'</p>'.PHP_EOL;
        }
      }
      $str .= '</div>';
    }
    
    // we add ajax code if needed
    // if vote is enabled on contribution and it is a contribution
    if(CURRENT_APP != 'admin' && voteEnabled('contribute') && $c['comment_module'] == 'contribute') echo getAjaxVotesFunction(array('module' => 'contribute'));
    
    if(CURRENT_APP == 'admin') {
        // we add code to allow inline edition
        $js = "	if (typeof CKEDITOR !== 'undefined') {
    				CKEDITOR.disableAutoInline = true;
    				$(\"div.body[contenteditable='true']\").each(function( index ) {
        		
    				var element_id = $(this).attr('id');
    				var comment_id = $(this).attr('data-comment-id');
    				// console.log(element_id);
    
    				CKEDITOR.inline( element_id, {
    					 customConfig: 'l21_light_confignoimgur.js', // because imgur make multi-instance bug
    				      on: {
    				        blur: function( event ) {
    				          var data = event.editor.getData();
    				          // alert('Sending: ' + data.length + ' to ' + comment_id );
    						  if(data.length < 15)  alertify.error('". addslashes(_t('comment', 'error_edit')) ."');
    						  else {
    							$.ajax({type:'POST', url: '../comment/_ajax_edit.php', data: { body: data, id: comment_id }, dataType: 'json', success: function(data) {
    								if(data.status==1) {
    									alertify.success(data.msg);
    								} else {
    									alertify.error(data.msg);
    								}
    							}});
    						   }
    				        }
    				      }
    					});
    				});
    			}";
        
        footerAddInlineJS($js);
    }
    
    
    return $str;
  }

}

/**
 * notifyUsers()
 * @param array
 * @param integer
 * @param object
 * @param bool
 * $arr : array of needed data
 * $id : inserted comment id
 * $o : comment object
 * $overpass : to overpass tests
 */
if(!function_exists('notifyUsers')) {
  function notifyUsers($arr, $id, $o, $overpass = false) {

  	include_once(override('../mail/mail_actions.php'));
  	include_once(override('../mail/send.php'));
  	
  	include_once('../class/class.emailq.php');
  	$emailqo = new emailq;
  	
    $pass = false;

    // we prepare values
    $arr['cid'] = $id;
    $a = getValues($arr);
    $data = $o->getCommentItem($arr, $GLOBALS['sql_object']);

    $a['item_title'] = $data[0]['item_title'];
    $a['action'] = 'notify_comment';

    if(COMMENT_NOTIFICATION == 1) {

      // we send it only if new comment is automatically approved
      if(COMMENT_MODERATION == 0 || (COMMENT_MODERATE_REGISTERED == 0 && !empty($arr['user_id']))) {
        $pass = true;
      }

      if($pass === true || $overpass === true) {
        $users_email = $o->getSubscribers($arr, $GLOBALS['sql_object']);

        foreach($users_email as $email) {
        	// we don't send mail to author
        	if($email != $a['author_email']) {
        		 
        		$a['recipient'] = $email;
        		 
        		$emailContainer = prepare_email($a);
        		 
        		// if no email queue, we send mail directly
        		if(!defined('MAIL_BULK') || MAIL_BULK == 'nodelay') {
        			 
        			$r = send_email($emailContainer);
        			 
        			// we prepare the email queue and store it in database
        			// emails are sent later using cron
        		} else {
        			 
        			$queue = array();
        			$queue = $emailContainer;
        			$queue['module'] 		= 'comment';
        			 
        			$r = $emailqo->addToQueue($queue, $GLOBALS['sql_object']);
        			 
        		}
        		 
        	}
        }
      }
    }
    // if $overpass we stop there
    if($overpass === true) return true;

    // in any case we send an email to admin users when message is posted
    // if moderation is disabled
    if(COMMENT_MODERATION == 0 || (COMMENT_MODERATE_REGISTERED == 0 && !empty($arr['user_id']))) {
//       $a['recipient'] = SITE_MAIL;
//       $a['adminuser'] = true;
//       $emailContainer = prepare_email($a);
//       $r = send_email($emailContainer);
      
      $a['adminuser'] = true;
      
      $data = $GLOBALS['sql_object']->DBSelect(SQL_getSuperAdmins());
      
      // if no administrator we send mail to SITE_MAIL
      if(!isset($data[0])) $data[0]['profile_email'] = SITE_MAIL;
      
      foreach($data as $el) {
      	// we don't send mail to author
      	if($el['profile_email'] != $a['author_email']) {
      		 
      		$a['recipient'] = $el['profile_email'];
      		
      		$emailContainer = prepare_email($a);
      		
      		$r = send_email($emailContainer);
      		 
      	}
      }
      
    }

  }
}

/**
 * emailModerators()
 * @param array
 * @param integer
 * @param object
 * $arr : array of needed data
 * $id : inserted comment id
 * $o : comment object
 * @todo send mail to all super admin. Not only to SITE_MAIL
 */
if(!function_exists('emailModerators')) {
  function emailModerators($arr, $id, $o) {
  	
  	include_once(override('../mail/mail_actions.php'));
  	include_once(override('../mail/send.php'));

    if(COMMENT_MODERATION == 1) {
      // if logged-in user and no moderation on registered user, we exit
      if(!empty($arr['user_id']) && COMMENT_MODERATE_REGISTERED == 0) return true;

      $arr['cid'] = $id;
      $a = getValues($arr, true);

      if($arr['module'] != 'contribute') {
        $data = $o->getCommentItem($arr, $GLOBALS['sql_object']);
      } else {
        $data[0]['item_title'] = _t('comment', 'contribute_item');
      }

      $a['item_title'] = $data[0]['item_title'];
      $a['action'] = 'moderate_comment';
      
      $data = $GLOBALS['sql_object']->DBSelect(SQL_getSuperAdmins());
      
      // print_r($a);
      
      // if no administrator we send mail to SITE_MAIL
      if(!isset($data[0]['profile_email'])) $data[0]['profile_email'] = SITE_MAIL;

	      foreach($data as $el) {
	      	// we don't send mail to author
	      	if($el['profile_email'] != $a['author_email']) {
	      		
	      		$a['recipient'] = $el['profile_email'];
	      		$a['reply_to'] = $a['author_email'];
	      		
	      		$emailContainer = prepare_email($a);
	      		
	      		$r = send_email($emailContainer);
	      		
	      	}
      }

    }

  }
}

if(!function_exists('getValues')) {
  function getValues($a, $get_email = false) {

    $output = array();

    if(!empty($a['user_id'])) {
      $data = $GLOBALS['sql_object']->DBSelect(SQL_getUserInfo($a['user_id']));
      $output['name'] = $data[0]['user_login'];
      $output['author_email'] = $data[0]['profile_email'];
      if($get_email) $output['name'] .= ' ('.$output['author_email'].')';
    } else {
      $output['name'] = $a['name'];
      $output['author_email'] = $a['email'];
    }
    $output['body'] = $a['body'];
    $output['moderate_link'] = SITE_ROOT_URL . 'admin/index.php?rub=comment&todo=list&module=all&statut=D';

    $item = itemMapping($a['module']);
    $output['item_type'] = $item['name'];
    $output['admin_link'] = SITE_ROOT_URL  . 'admin/index.php?rub='.$item['link'].'&todo=det&id='. $a['module_id'];

    if($a['module']=='files') {
      $wg = explode('/', $a['module_id']);
      if($wg[1] == 'shared') {
        $output['item_link'] = SITE_ROOT_URL  . 'public/index.php?rub='.$GLOBALS['links'][U_L]['workgroup']['linkvalue'];
      } else {
        $output['item_link'] = SITE_ROOT_URL  . 'public/index.php?rub='.$GLOBALS['links'][U_L]['workgroup']['linkvalue'].'&id='.$wg[1];
      }
      $output['item_link_comments'] = $output['item_link'];
      $output['item_link_the_comment'] = $output['item_link'];
    } else {
      $output['item_link'] = SITE_ROOT_URL  . 'public/index.php?rub='.$GLOBALS['links'][U_L][$item['link']]['linkvalue'].'&id='.$a['module_id'];
      $output['item_link_comments'] = $output['item_link'].'#comments';
      if(isset($a['cid'])) $output['item_link_the_comment'] = $output['item_link'].'#com-'.$a['cid'];
    }
    $output['unsubscribe_link'] = SITE_ROOT_URL  . 'public/index.php?rub='.$GLOBALS['links'][U_L]['comment-unsubscribe']['linkvalue'].'&name='.$a['module'].'&id='.$a['module_id'];
    $output['item_link_comments'] = $output['item_link'].'#comments';

    return $output;
  }
}

if(!function_exists('getAjaxFunction')) {
  function getAjaxFunction($data = '') {
    $str = '<script type="text/javascript">
                  $(function() {
                  	$(".comment-actions a").click(function() {
                  		var url = $(this).attr("href");

    					$.ajax({
                      	  type: "GET",
                          url: url,
                          data: "call=ajax",
                          dataType: "json",
                          success: function(data){
                          	if(data.status == 1) {
                          		if(data.page != "comment") {
                          			$(data.el).addClass(data.action).fadeOut("slow");
                          			// we update the comment counter
																$("#cc").text( parseInt($("#cc").text()) - 1);
                          		} else {
                          			if(data.action == "del") {
                          				$(data.el).addClass(data.action).fadeOut("slow");
                          			} else {
                          				$(data.el).removeClass("to-moderate");
                          				var col = $(data.el).css("background-color");

                          				$(data.el + " div.action-marker").removeClass("awaiting approve disapprove").addClass(data.action).empty().text(data.msg);
                          				// $(data.el).css("background-color","#F2F2F2").animate({backgroundColor: col}, 1500 ); // @todo fix - cause problem with new jquery version
                          				if(data.action == "disapprove") var col = "#E295B3";
                          				if(data.action == "approve") var col = "#D0EDBB";
                          				$(data.el).css("border-left","5px solid " + col);
                          			}
                          		}
                          	}
                          }
                        });
						return false;
					});

                  });
          </script>';

    footerAddJS('../lib/js/jquery.color.js');

    return $str;
  }
}

if(!function_exists('itemMapping')) {

  function itemMapping($module) {

    $a = array();
    $a['name'] = _t('comment_map', $module);

    switch ($module) {
      case 'news':
        $a['link'] = 'news';
        break;
      case 'project':
        $a['link'] = 'project';
        break;
      case 'workgroups':
        $a['link'] = 'workshop';
        break;
      case 'indicator':
        $a['link'] = 'dashboard';
        break;
      case 'publication':
        $a['link'] = 'publication';
        break;
      case 'report':
        $a['link'] = 'report';
        break;
      case 'files':
        $a['link'] = 'library';
        break;
      case 'contribute':
        $a['link'] = 'contribute';
        break;
      default:
        die($module . ' is not a valid option.');
      break;
    }
    return $a;
  }

}


?>