<?php

require_once('class.stdModule.php');

define('WEBLOG_AUTHOR_GROUP', 'WBL');

class cwbl extends stdModule {

	function cwbl() {
		
		$this->stdModule('cwbl0100');

		$this->_settings->templates->message	= "message.tpl";
		$this->_settings->templates->overview	= "overview.tpl";
		$this->_settings->templates->history	= "history.tpl";
		$this->_settings->templates->edit_message= "edit_message.tpl";

		$this->_settings->reaction_states = array('NEW', 'ACK', 'NACK');

	}

	function _generateUrlTitle($title) {
		return str_replace(' ','-',trim(preg_replace('/[^a-z0-9-_ ]/i','', $title)));
	}

	function _cleanMessageText($text) {
		return $text;
		//return $this->_strip_tags_attributes($text, '<b><strong><i><em><u><ol><ul><li><br><span>');
	}

	function _strip_tags_attributes($string, $allowtags=null) {
		$string = preg_replace('/([^>]*) (.*)(=\'.*\'|=".*")(.*)/i', '$1$4', $string);
		return strip_tags($string,$allowtags);
	}

	function saveMessage($data) {

		$msg_db_data = array();

		if (isset($data['msg_id']) && is_numeric($data['msg_id'])) {
			$msg_db_data['msg_id'] = $data['msg_id'];
			$msg_db_data['msg_date_changed'] = 'NOW()';
		} else {
			$msg_db_data['msg_date_created'] = 'NOW()';
		}

		if (isset($this->_variables->public->usr_id) && is_numeric($this->_variables->public->usr_id)) $msg_db_data['msg_usr_id_lastchange'] = $this->_variables->public->usr_id;

		if (isset($data['msg_title']))	$msg_db_data['msg_title'] = "'". mysql_escape_string(stripslashes($data['msg_title'])) ."'";
		if (isset($data['msg_text']))	$msg_db_data['msg_text'] = "'". mysql_escape_string($this->_cleanMessageText(stripslashes($data['msg_text']))) ."'";
		if (isset($data['msg_usr_id']) && is_numeric($data['msg_usr_id']))	$msg_db_data['msg_usr_id'] = $data['msg_usr_id'];

		if (isset($data['msg_date'])) {
			list($d,$m,$y) = explode('-', $data['msg_date']);
			if (checkdate($m,$d,$y)) {
				$msg_db_data['msg_date'] = "'$y-$m-$d'";
			}
		}

		if (isset($data['msg_image_uri'])) {
			$msg_db_data['msg_image_uri'] = "'". $data['msg_image_uri'] ."'";
		}

		$sql = generate_query('wbl_message', $msg_db_data, 'msg_id');
		$this->_db->Execute($sql);

		$msg_id = is_numeric($data['msg_id']) ? $data['msg_id'] : $this->_db->lastInsertID();
		return $msg_id;
	}

	function saveMessageUpload($msg_id, $upload_data) {
		if (!is_numeric($msg_id)) return false;

		$this->_tcc->initializeSC($this->_settings->general->project->code, $this->_moduleCode, $this->_variables->public->org_id, $this->_variables->public->lng_code);

		$upload_data['data'] = file_get_contents($upload_data['tmp_name']);
		$upload_data['title'] = $upload_data['name'];

		$tmp_uri = $this->_tcc->_sc->putResource($upload_data);

		$this->_tcc->_sc->deleteResourceController('wbl_message', $msg_id, null, 'msg_image_uri');
		$this->_tcc->_sc->putResourceController($tmp_uri, 'wbl_message', $msg_id, null, 'msg_image_uri');

		return $this->saveMessage(array('msg_id'=>$msg_id, 'msg_image_uri'=>$tmp_uri));

	}
	function deleteMessageUpload($msg_id) {

		$this->_tcc->initializeSC($this->_settings->general->project->code, $this->_moduleCode, $this->_variables->public->org_id, $this->_variables->public->lng_code);
		$this->_tcc->_sc->deleteResourceController('wbl_message', $msg_id, null, 'msg_image_uri');
		return $this->saveMessage(array('msg_id'=>$msg_id, 'msg_image_uri'=>''));

	}

	function saveReaction($data) {
		
		$rea_db_data = array();

		if (isset($data['rea_id']) && is_numeric($data['rea_id'])) {
			$rea_db_data['rea_id'] = $data['rea_id'];
			if (isset($data['rea_state']) && in_array($data['rea_state'], $this->_settings->reaction_states)) $rea_db_data['rea_state'] = "'".$data['rea_state']."'";
		} else {
			$rea_db_data['rea_date'] = 'NOW()';
			$rea_db_data['rea_state'] = "'NEW'";
			if (isset($this->_variables->public->usr_id) && is_numeric($this->_variables->public->usr_id)) {
				$rea_db_data['rea_usr_id'] = $this->_variables->public->usr_id;
			} else {
				return false;
			}

			if (isset($data['rea_msg_id']) && is_numeric($data['rea_msg_id'])) {
				$rea_db_data['rea_msg_id'] = $data['rea_msg_id'];
			} else {
				return false;
			}
		}

		if (isset($data['rea_text'])) $rea_db_data['rea_text'] = "'". mysql_escape_string(stripslashes($data['rea_text'])) ."'";

		$sql = generate_query('wbl_reaction', $rea_db_data, 'rea_id');
		$this->_db->Execute($sql);

		$rea_id = is_numeric($data['rea_id']) ? $data['rea_id'] : $this->_db->lastInsertID();
		return $rea_id;
	}

	function deleteMessage($msg_id) {
		if (!is_numeric($msg_id)) return false;
		$this->_db->Execute("DELETE FROM wbl_message WHERE msg_id = ".$msg_id);
	}
	function deleteReaction($rea_id) {
		if (!is_numeric($rea_id)) return false;
		$this->_db->Execute("DELETE FROM wbl_reaction WHERE rea_id = ".$rea_id);
	}

	//--- getters

	function _getUser($usr_id) {
		if (!is_numeric($usr_id)) return false;
		$GLOBALS['g_obj_ti3a0365']->getUsers($users, array(array('USR_ID','='.$usr_id), 'USR_INITIALS', 'USR_INFIX', 'USR_FAMILYNAME', 'GET_USER_GREETING(USR_ID,0) as USR_GREETING'), array('GATT_CITY', 'GATT_TITLE', 'GATT_PHOTO'));
		$user = current($users);
		$user['USR_GREETING'] = ltrim($user['GATT_TITLE'] . ' ') . $user['USR_INITIALS'] .' '. ltrim($user['USR_INFIX'] . ' ') . $user['USR_FAMILYNAME'];
		return $user;
	}

	function getMessage($msg_id) {
		if (!is_numeric($msg_id)) return false;

		$rs = $this->_db->Query("SELECT wbl_message.*, count(rea_id) as reactions 
								FROM wbl_message 
								LEFT JOIN wbl_reaction ON rea_msg_id = msg_id AND rea_state = 'ACK'
								WHERE msg_id = ".$msg_id."
								GROUP BY msg_id");
		$message = $rs->Row();
		$message['url_title'] = $this->_generateUrlTitle($message['msg_title']);
		$rs->Close();

		return $message;
	}

	function getMessages($usr_id=null, $sort=null, $sort_direction=null, $limit=null, $offset=null) {

		$wheres = array();

		$wheres[] = 'msg_date <= CURDATE()';
		if (is_numeric($usr_id)) {
			$wheres[] = "msg_usr_id = " .$usr_id;
		}

		if ($sort) {
		
			$sort_direction = ($sort_direction == 'DESC') ? 'DESC' : 'ASC';

		} else {
			$sort = 'msg_date';
			$sort_direction = 'DESC';
		}

		$sql = "SELECT wbl_message.*, count(rea_id) as reactions 
				FROM wbl_message 
				LEFT JOIN wbl_reaction ON rea_msg_id = msg_id AND rea_state = 'ACK'
				".($wheres ? ' WHERE '.implode(' AND ', $wheres) : '')."
				GROUP BY msg_id
				ORDER BY ". $sort . " ".$sort_direction;
		$rs = $this->_db->Query($sql, $offset, $limit);

		$messages = array();
		while ($r = $rs->Row()) {
			$r['user'] = $this->_getUser($r['msg_usr_id']);
			$r['url_title'] = $this->_generateUrlTitle($r['msg_title']);
			$messages[] = $r;
			$rs->MoveNext();
		}
		$rs->Close();

		return $messages;
	}

	function getLastMessage() {
		$messages = $this->getMessages(null, 'msg_date', 'DESC', 1);
		return current($messages);
	}

	function getMessagesByUser($usr_id) {
		return $this->getMessages($usr_id, null, null, 5);
	}

	function getReaction($rea_id) {
		if (!is_numeric($rea_id)) return false;

		$rs = $this->_db->Query("
				SELECT *, date_format(rea_date, '%d-%m-%Y') as rea_date_fmt
				FROM wbl_reaction 
				LEFT JOIN wbl_message ON msg_id = rea_msg_id
				WHERE rea_id = ".$rea_id);

		$reaction = $rs->Row();
		$rs->Close();

		return $reaction;
	}

	function getReactions($msg_id=null, $state=null, $sort=null, $sort_direction=null, $limit=null, $offset=null) {
		
		$wheres = array();
		if ($state && in_array($state, $this->_settings->reaction_states)) {
			$wheres[] = "rea_state = '" .$state ."'";
		}

		if (is_numeric($msg_id)) {
			$wheres[] = "rea_msg_id = " .$msg_id;
		}

		if ($sort) {
		
			$sort_direction = ($sort_direction == 'DESC') ? 'DESC' : 'ASC';

		} else {
			$sort = 'rea_date';
			$sort_direction = 'ASC';
		}

		$sql = "SELECT *
				, date_format(rea_date, '%d-%m-%Y') as rea_date_fmt
				FROM wbl_reaction 
				LEFT JOIN wbl_message ON msg_id = rea_msg_id
				".($wheres ? ' WHERE '.implode(' AND ', $wheres) : '')."
				ORDER BY ". $sort . " ".$sort_direction;
		$rs = $this->_db->Query($sql, $offset, $limit);

		$reactions = array();
		while ($r = $rs->Row()) {
			$r['user'] = $this->_getUser($r['rea_usr_id']);
			$reactions[] = $r;
			$rs->MoveNext();
		}
		$rs->Close();

		return $reactions;
	}

	function getWeblogAuthors() {
		
		$q = array('AND'
			, array(I3A_FLD, 'USR_ID')
			, array(I3A_FLD, 'GET_USER_GREETING(USR_ID, 0) as USER_GREETING')
			, array(I3A_GRP, WEBLOG_AUTHOR_GROUP, true) # FO-group
		);

		$GLOBALS['g_obj_ti3a0365']->searchUsers($result, $q);
		$author_list = array(0 => 'KNMvD');
		foreach ($result as $r) {
			$author_list[$r['USR_ID']] = $r['USER_GREETING'];
		}
		return $author_list;
	}

	function printMessage($msg_id) {
		if (!is_numeric($msg_id)) return false;
		
		$message = $this->getMessage($msg_id);
		if ($message) {
			$this->_smrt->assign('message', $message);
			$this->_smrt->assign('user', $this->_getUser($message['msg_usr_id']));
			$this->_smrt->assign('reactions', $this->getReactions($msg_id, 'ACK'));
			$this->_smrt->assign('user_messages', $this->getMessagesByUser($message['msg_usr_id']));
		}

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->message);

	}

	function printOverview() {

		$this->_smrt->assign('messages', $this->getMessages(null, null, null, 50));

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->overview);
	}

	function printHistory($usr_id=null) {
		$this->_smrt->assign('messages', $this->getMessages($usr_id));

		if ($usr_id) {
			$this->_smrt->assign('user', $this->_getUser($usr_id));
		}

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->history);
	}

	function printEditMessageForm($msg_id=null) {

		if (is_numeric($msg_id)) {
			$message = $this->getMessage($msg_id);
			if ($message) {
				if ($message['msg_usr_id'] == $this->_variables->public->usr_id) {
					$this->_smrt->assign('message', $message);
				}
			}
		}

		$this->assignTemplateGlobals();
		$this->_smrt->display($this->_settings->templates->edit_message);
	}

}


if (!function_exists('rs2arr')) {
	function rs2arr(&$rs, $key_as_index=false, $single_row=false) {
	
		$new_arr = array();

		while ($r = $rs->row()) {

			$r = array_map('stripslashes', $r);

			if (count($r) == 1) {
				$value = current($r);
			} elseif (count($r) == 2 && $key_as_index !== false) {
				$tmp_r = $r;
				unset($tmp_r[$key_as_index]);
				$value = current($tmp_r);
			} else {
				$value = $r;
				
			}
			if ($key_as_index && isset($r[$key_as_index])) {
				$new_arr[$r[$key_as_index]] = $value;
			} else {
				$new_arr[] = $value;
			}		

			$rs->moveNext();
		}
		$rs->Close();

		return ($single_row) ? current($new_arr) : $new_arr;
	}
}

if (!function_exists('generate_query')) {

	function generate_query($tbl_name, $data, $key_field) {

		$fields = array();
		foreach ($data as $fld => $value) {
			if ($fld == $key_field) continue;
			$fields[] = $fld .' = ' . $value;
		}

		if (isset($data[$key_field]) && !empty($data[$key_field])) {
			//--- update
			$query = 'UPDATE '.$tbl_name.' SET ' . implode(', ',$fields) .' WHERE '.$key_field .' = '.$data[$key_field];
		} else {
			//--- insert
			$query = 'INSERT INTO '.$tbl_name.' SET ' . implode(', ',$fields);
		}

		return $query;
	}
}