<?php
/**
 * DokuWiki AJAX call handler
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author Pavel Vitis <pavel.vitis@seznam.cz>
 */

//fix for Opera XMLHttpRequests
if(!count($_POST) && $HTTP_RAW_POST_DATA){
  parse_str($HTTP_RAW_POST_DATA, $_POST);
}

if(!defined('DOKU_INC'))
  define('DOKU_INC',realpath(dirname(__FILE__).'/../../../').'/');
require_once(DOKU_INC.'inc/init.php');
require_once(DOKU_INC.'inc/common.php');
require_once(DOKU_INC.'inc/auth.php');
require_once(DOKU_INC.'inc/html.php');

define(SHOW_GRAVATAR, false);
define(BASE_URL, preg_replace('!(.+)(/.+){3}!', '\\1/', DOKU_BASE));

session_write_close();

header('Content-Type: text/html; charset=UTF-8');

//call the requested function
$call = 'ajax_'.$_REQUEST['call'];
if ($call == '') {
  $call = 'ajax_'.$_REQUEST['call'];
}
if(function_exists($call)){
  $call();
}else{
  print "The called function '".htmlspecialchars($call)."' does not exist!";
}

function _getChatHtml($pageFN, $ltime = 0, $mtime = 0) {
    if (!@file_exists($pageFN)) {
	return;
	print "1,";
    }

//    echo '<a style="text-decoration:none;" href="" title="'.$ltime.' / '.$mtime.'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>';

    $file = trim(io_readFile($pageFN));

    if ($file == ' ') {
	$file = '';
    }

    $html = "";

//    $html .= "1,";
    
    $lines = explode("\n----\n", $file."\n");

    $patterns = array(
	'!(\[\[((http|https|ftp)://[^\]\|]+)\]\])!',
	'!(\[\[((http|https|ftp)://[^\]\|]+)\|([^\]]+)\]\])!',
	'!(\[\[([^\]\|]+)\|([^\]]+)\]\])!',
	'!(\[\[([^\]\|]+)\]\])!',
	'!(\s)((http|https|ftp)://[^\s\n\r]+)!',
	'!\*{2}([^\*]+)\*{2}!',
	'!(\s)/{2}([^/]+)/{2}(\s)!',
	'!(\s)_{2}([^_]+)_{2}(\s)!'
    );
    $replaces = array(
        '<a href="\\2" class="urlextern" target="_blank">\\2</a>',
        '<a href="\\2" class="urlextern" target="_blank">\\4</a>',
        '<a href="\\2" class="urlintern">\\3</a>',
        '<a href="\\2" class="urlintern">\\2</a>',
        '\\1<a href="\\2" class="urlextern" target="_blank">\\2</a>',
	'<strong>\\1</strong>',
	'\\1<em>\\2</em>\\3',
	'\\1<u>\\2</u>\\3'
    );

    $smileys = getSmileys();
    foreach ($smileys as $key=>$value) {
	$key_escaped = preg_replace(
	    array("/\\\\/","/\*/",'/\&/','/\(/','/\)/','/\[/','/\]/','/\|/','/\=/','!/!','/\?/'),
	    array('\\\\\\','\\*','\\&','\\(','\\)','\\[','\\]','\\|','\\=','\\/','\\?'),
	    $key);
//	echo $key_escaped.'<br />';
//	echo $value;
	$patterns[] = '@'.$key_escaped.'@';
	$files = preg_split('/\|/', $value);
	if (count($files) > 1) {
	    $file = $files[mt_rand(0,count($files)-1)];
	}
	else {
	    $file = $files[0];
	}
	$replaces[] = '<img src="'.BASE_URL.'lib/images/smileys/'.$file.'" '.
	    'class="smiley" alt="'.str_replace('"',"'",$key).'" title="'.str_replace('"',"'",$key).'" />';
    }
//    print implode('|', array_keys($smileys));

    if (true == SHOW_GRAVATAR) {
		@require_once(DOKU_INC.'lib/plugins/gravatar/syntax.php');
		if (true == SHOW_GRAVATAR && class_exists('syntax_plugin_gravatar')) {
			$gravatar = true;
		}
    }

	$color = count($lines) % 2 == 0 ? 0 : 1;

    for ($i = 0; $i < count($lines); $i++) {
	if (trim($lines[$i]) == '') {
	    continue;
	}
	preg_match('/\(([^\)]+)\)[\s]+([^:]+):[\s]+(.+)/', $lines[$i], $parts);

	if ($parts[1]*1 != 0 && $parts[1]*1 <= $ltime) {
//	    print $ltime.'<br />';
//	    print $parts[1].'<br />';
	    break;
	}
	
	$uinfo = explode('|', $parts[2]);

	$html .= '<div class="chat-line ';
    	$html .= ' chat-line-'.(0 == ($color++) % 2 ? 'even' : 'odd');

//		if ($i == 0 && $ltime < $mtime) {
//			$html .= ' chat-line-last" id="chat-last-message"';
//		}
//		else {
			$html .= '"';
//		}
		$html .= '>';

		if ($gravatar) {
			if (!empty($uinfo[1])) {
			$html .= syntax_plugin_gravatar::_renderAvatar(
		    	$uinfo[1],
		    	'left',
		    	40,
		    	'',
		    	DOKU_INC,
		    	BASE_URL);
	    	}
		}

		$lang = $_REQUEST['HTTP_ACCEPT_LANGUAGE'];
		if (date('Yz',time()) == date('Yz',$parts[1])) {
			$datetime = date('H:i:s',$parts[1]);
		}
		else {
			if ($lang) {
			}
			$datetime = date('Y/m/d, H:i:s',$parts[1]);
		}

		$html .= '<strong>'.(!empty($uinfo[2]) ? $uinfo[2] : $uinfo[0]).'</strong> ('.$datetime.'): <br /><blockquote>';
		$html .= preg_replace($patterns, $replaces, ' '.$parts[3].' ');
		if ($i+1 < count($lines)) {
	    	$html .= '<br />';//'<hr noshade="noshade" size="1" />';
		}
		else {
		    $html .= '<br />';
		}

		$html .= '</blockquote></div>';
    }

    return $html;
}

/**
 * Get number of new comments
 *
 * @author Pavel Vitis <pavel.vitis@seznam.cz>
 */
function ajax_check() {
    global $conf;
    global $lang;

    $pageId = cleanID($_POST['pageId']);
    if(empty($pageId)) {
	return;
    }
    
    $ltime = (int)$_POST['time'];
    $pageFN = wikiFN($pageId);
    $mtime = @filemtime($pageFN);

    if ($ltime == 0 || $mtime > $ltime) {
	echo "1";
    }
}

/**
 * Get new comments
 *
 * @author Pavel Vitis <pavel.vitis@seznam.cz>
 */
function ajax_checkAndGet() {
    global $conf;
    global $lang;

    $pageId = cleanID($_POST['pageId']);
    if(empty($pageId)) {
    	return;
    }

    if ($conf['useacl'] && auth_quickAclCheck($pageId) < AUTH_READ) {
        print "<!--AJAXCHAT_MTIME:0-->\n";
	print "<p><em>Not sufficient user rights. Please re-login to see the messages.<br />".
	"If that does not work for you from some reason, clear your browser cookies and then login again:</em></p>".
	"<p><strong>IE:</strong> Tools->Internet options...->Delete cookies...<br />".
	"<strong>Mozilla/Firefox:</strong> Tools->Options...->Privacy->Cookies->Clear cookies now...</p>";
	return;
    }

    $pageFN = wikiFN($pageId);
    $mtime = @filemtime($pageFN);

    $ltime = (int)$_POST['time'];
//  echo $time ." - " . $pageId;
//  echo "<BR>$mtime";

    if ($ltime == 0 || $mtime > $ltime) {
        print "<!--AJAXCHAT_MTIME:$mtime-->\n";
    	print _getChatHtml($pageFN, $ltime, $mtime);
	print ' ';
    }
}

function ajax_send(){
    global $conf;
    global $auth;
    global $lang;

    // check pageid validity
    $pageId = cleanID($_POST['pageId']);
    if(empty($pageId)) {
	return;
    }

    $ltime = (int)$_POST['time'];
    if ($ltime > 0) {
	while (time() - $ltime < 1) {
	    sleep(5);
	}
    }
    
    // modified now
    $mtime = time();
    // set modified header
    $html = "<!--AJAXCHAT_MTIME:$mtime-->\n";

    // check user rights
    if ($conf['useacl'] && auth_quickAclCheck($pageId) < AUTH_EDIT) {
	// and append warning if not possible to send messages
	$html .= "<p><em>Insufficient user rights. Please re-login to be able to send the messages.</em></p>";
    }
    else {
//        $ltime = (int)$_POST['time'];
        $user = cleanUser($_POST['user']);
	
        $message = cleanMessage($_POST['msg']);

	while (checklock($pageId)) {
	    sleep(50);
        }
	lock($pageId);

        $pageFN = wikiFN($pageId);
        $file = trim(@io_readFile($pageFN));

	if ($file == ' ') {
	    $file = '';
        }

	$udata = $auth->getUserData($user);

        $line = "(".time().") ".$user;
	if (!empty($udata['mail'])) {
	    $line .= "|".$udata['mail'];
        }
	if (!empty($udata['name'])) {
	    $line .= "|".$udata['name'];
        }
	$line .= ": ".htmlspecialchars($message);

        $file = $line."\n----\n".$file."\n";

	saveWikiText($pageId, $file, "Message added", true);

        unlock($pageId);
    }

    print $html . _getChatHtml($pageFN, $ltime, $mtime);
}

function ajax_clear(){
    global $conf;
    global $lang;

    $ltime = $_POST['time'];
    $ltime = (int)$ltime;

    $pageId = $_POST['pageId'];
    $user = cleanUser($_POST['user']);
    $message = $_POST['msg'];

    $pageFN = wikiFN($pageId);
    if (!@file_exists($pageFN)) {
	return;
    }

    while (checklock($pageId)) {
	usleep(50);
    }
    lock($pageId);

    saveWikiText($pageId, ' ', "Messages cleared", true);

//    @touch($pageFN);

    unlock($pageId);

    print ' ';
}

function cleanUser($user) {
    global $conf;

    $user = preg_replace('/[^ .,a-zA-Z0-9_\-]/i', '', $user);
    $user = substr($user, 0, 40);
    return $user;
}

function cleanMessage($msg) {
    global $conf;

    $maxmsgsize = (int) $conf['chat']['max-message-size'];
    if ($maxmsgsize <= 0) {
	$maxmsgsize = 1024;
    }
    if ($maxmsgsize > 4*1024) {
	$maxmsgsize = 4*1024;
    }
    
    if (strlen($msg) > $maxmsgsize) {
        $msg = substr($msg, 0, $maxmsgsize);
    }
    
    return $msg;
}

//Setup VIM: ex: et ts=2 enc=utf-8 :
?>