<?php
/*
	+-----------------------------------------------------------------------------+
	| ILIAS open source                                                           |
	+-----------------------------------------------------------------------------+
	| Copyright (c) 1998-2009 ILIAS open source, University of Cologne            |
	|                                                                             |
	| This program is free software; you can redistribute it and/or               |
	| modify it under the terms of the GNU General Public License                 |
	| as published by the Free Software Foundation; either version 2              |
	| of the License, or (at your option) any later version.                      |
	|                                                                             |
	| This program is distributed in the hope that it will be useful,             |
	| but WITHOUT ANY WARRANTY; without even the implied warranty of              |
	| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
	| GNU General Public License for more details.                                |
	|                                                                             |
	| You should have received a copy of the GNU General Public License           |
	| along with this program; if not, write to the Free Software                 |
	| Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. |
	+-----------------------------------------------------------------------------+
*/

/**
* Class ilObjTest
* 
* @author Stefan Meyer 
* @version $Id: class.ilObjChat.php 19587 2009-04-09 15:08:42Z jposselt $
*
* @extends ilObject
*/

require_once "classes/class.ilObjectGUI.php";
require_once "Modules/Chat/classes/class.ilChatServerConfig.php";
require_once "Modules/Chat/classes/class.ilChatServerCommunicator.php";
require_once "Modules/Chat/classes/class.ilChatUser.php";
require_once "Modules/Chat/classes/class.ilChatRoom.php";
require_once "Modules/Chat/classes/class.ilFileDataChat.php";

class ilObjChat extends ilObject
{
	var $server_conf;
	var $server_comm;
	var $chat_room;
	var $chat_user;
	var $chat_recording = null;

	/**
	* Constructor
	* @access	public
	* @param	integer	reference_id or object_id
	* @param	boolean	treat the id as reference_id (true) or object_id (false)
	*/
	public function __construct($a_id = 0,$a_call_by_reference = true)
	{
		$this->type = "chat";
		$this->ilObject($a_id,$a_call_by_reference);

		$this->server_conf =& new ilChatServerConfig();
		$this->server_comm =& new ilChatServerCommunicator($this);
		$this->chat_user =& new ilChatUser();
		$this->chat_room =& new ilChatRoom($this->getId());
	}
	
	/**
	 * Lookup moderator role
	 *
	 * @access public
	 * @static
	 * @param int ref_id of forum
	 * 
	 */
	public static function _lookupModeratorRole($a_ref_id)
	{
		global $ilDB;
		
		$mod_title = 'il_chat_moderator_'.$a_ref_id;

		$res = $ilDB->queryf('SELECT * FROM object_data WHERE title = %s',
			array('text'), array($mod_title));
		
	 	while($row = $res->fetchRow(DB_FETCHMODE_OBJECT))
	 	{
	 		return $row->obj_id;
	 	}
	 	return 0;
	}
	
	
	
	/**
	 * Clone Object
	 *
	 * @access public
	 * @param int source_id
	 * @apram int copy id
	 * 
	 */
	public function cloneObject($a_target_id,$a_copy_id = 0)
	{
		global $ilDB,$ilUser;
		
	 	$new_obj = parent::cloneObject($a_target_id,$a_copy_id);
	 	$this->cloneAutoGeneratedRoles($new_obj);
	}
	
	/**
	 * Clone forum moderator role 
	 *
	 * @access public
	 * @param object forum object
	 * 
	 */
	public function cloneAutoGeneratedRoles($new_obj)
	{
		global $ilLog,$rbacadmin,$rbacreview;
		
		$moderator = ilObjChat::_lookupModeratorRole($this->getRefId());
		$new_moderator = ilObjChat::_lookupModeratorRole($new_obj->getRefId());
	 	$source_rolf = $rbacreview->getRoleFolderIdOfObject($this->getRefId());
	 	$target_rolf = $rbacreview->getRoleFolderIdOfObject($new_obj->getRefId());
	 	
		if(!$moderator || !$new_moderator || !$source_rolf || !$target_rolf)
		{
			$ilLog->write(__METHOD__.' : Error cloning auto generated role: il_chat_moderator');
		}
	 	$rbacadmin->copyRolePermissions($moderator,$source_rolf,$target_rolf,$new_moderator,true);
		$ilLog->write(__METHOD__.' : Finished copying of role il_chat_moderator.');
	}
	

	public function read()
	{
		// USED ilObjectFactory::getInstance...
		parent::read();

		$this->server_conf =& new ilChatServerConfig();
		$this->server_comm =& new ilChatServerCommunicator($this);
		$this->chat_user =& new ilChatUser();
		$this->chat_room =& new ilChatRoom($this->getId());
	}

	/**
	* init default roles settings
	* @access	public
	* @return	array	object IDs of created local roles.
	*/
	public function initDefaultRoles()
	{
		global $rbacadmin;
		
		// create a local role folder
		$rolf_obj =& $this->createRoleFolder();

		// create moderator role and assign role to rolefolder...
		$role_obj = $rolf_obj->createRole("il_chat_moderator_".$this->getRefId(),"Moderator of chat obj_no.".$this->getId());

		// grant permissions: visible,read,write,chat_moderate
		$permissions = ilRbacReview::_getOperationIdsByName(array('visible','read','moderate'));
		$rbacadmin->grantPermission($role_obj->getId(),
									$permissions,
									$this->getRefId());

		unset($rolf_obj);

		return array($role_obj->getId());
	}

	public function delete()
	{
		global $ilDB;
				
		if(!parent::delete())
		{
			return false;
		}
		$rooms = $this->chat_room->getAllRoomsOfObject();
		foreach($rooms as $room)
		{
			$this->chat_room->delete($room["room_id"]);
		}

		// FINALLY DELETE MESSAGES IN PUBLIC ROOM
		$res = $ilDB->manipulateF('
			DELETE FROM chat_room_messages WHERE chat_id = %s',
			array('integer'),array($this->getRefId()));
		

		// AND ALL USERS
		$res = $ilDB->manipulateF('
			DELETE FROM chat_user WHERE chat_id = %s', 
			array('integer'), array($this->getRefId()));


		// AND ALL RECORDINGS
		$res = $ilDB->queryf('
			SELECT record_id FROM chat_records 
			WHERE chat_id = %s',
			array('integer'), array($this->getId()));
			
		if (ilDB::isDbError($res)) die("ilObjChat::delete(): " . $res->getMessage() . "<br>SQL-Statement: ".$res);
		//if (($num = $ilDB->numRows($res)) > 0)
		if (($num = $res->numRows()) > 0)
		{
			for ($i = 0; $i < $num; $i++)
			{
				$rec_data = $res->fetchRow(DB_FETCHMODE_ASSOC);
				$res = $ilDB->manipulateF('
					DELETE FROM chat_record_data WHERE record_id = %s',
					array('integer'), array($rec_data['record_id']));

			}
			
		}
			$res = $ilDB->manipulateF('
			DELETE FROM chat_records WHERE chat_id = %s',
			array('integer'), array($this->getId()));
			
		return true;
	}

	public function sendMessage($a_id)
	{
		include_once "Services/Mail/classes/class.ilMail.php";

		$tmp_mail_obj = new ilMail($_SESSION["AccountId"]);

		// GET USER OBJECT
		$tmp_user = ilObjectFactory::getInstanceByObjId($a_id);

		// GET USERS LANGUAGE
		$tmp_lang =& new ilLanguage($tmp_user->getLanguage());
		$tmp_lang->loadLanguageModule("chat");

		$message = $tmp_mail_obj->sendMail($this->formatRecipient($tmp_user),"","",$this->formatSubject($tmp_lang),
										   $this->formatBody($tmp_user,$tmp_lang),array(),array("normal"));

		unset($tmp_mail_obj);
		unset($tmp_lang);
		unset($tmp_user);

		return true;
	}

	public function sendMessageForRoom($a_id, $room)
	{
		include_once "Services/Mail/classes/class.ilMail.php";

		$tmp_mail_obj = new ilMail($_SESSION["AccountId"]);

		// GET USER OBJECT
		$tmp_user = ilObjectFactory::getInstanceByObjId($a_id);

		// GET USERS LANGUAGE
		$tmp_lang =& new ilLanguage($tmp_user->getLanguage());
		$tmp_lang->loadLanguageModule("chat");

		$message = $tmp_mail_obj->sendMail(self::formatRecipient($tmp_user),"","",self::formatSubject($tmp_lang),
										   $this->formatBodyForRoom($tmp_user,$tmp_lang, $room),array(),array("normal"));

		unset($tmp_mail_obj);
		unset($tmp_lang);
		unset($tmp_user);

		return true;
	}
	
	public function getHTMLDirectory()
	{
		$tmp_tpl =& new ilTemplate("tpl.chat_export.html",true,true);
		
		$this->chat_room->setRoomId(0);

		$tmp_tpl->setVariable("CHAT_NAME",$this->getTitle());
		$tmp_tpl->setVariable("CHAT_DATE",strftime("%c",time()));
		$tmp_tpl->setVariable("CONTENT",$this->chat_room->getAllMessages());

		$file_obj =& new ilFileDataChat($this);
		
		// return directory name of index.html
		return $file_obj->addFile('index.html',$tmp_tpl->get());
	}

	private function formatRecipient(&$user)
	{
		if(is_object($user))
		{
			return $user->getLogin();
		}
		return false;
	}

	private function formatSubject(&$lang)
	{
		return $lang->txt("chat_invitation_subject");
	}

	private function formatBody(&$user,&$lang)
	{
		global $ilClientIniFile;
		
		$room_id = $this->chat_room->getRoomId();
		$room_title = $this->chat_room->getTitle();

		$body = sprintf($this->lng->txt("chat_notification_intro"), $ilClientIniFile->readVariable("client","name"), ILIAS_HTTP_PATH)."\n\n";
		$body .= $lang->txt("chat_invitation_body")." ";
		$body .= $this->ilias->account->getFullname();
		$body .= "\n";
		$body .= $lang->txt("chat_chatroom_body").' '.$this->getTitle();
		if ($room_title != '')
		{
			$body .= ', '.$room_title;
		}
		$body .= "\n\n";
		$body .= $lang->txt('chat_to_chat_body');
		$body .= ': '.ILIAS_HTTP_PATH."/ilias.php?baseClass=ilChatPresentationGUI&room_id=".$room_id."&ref_id=".$this->getRefId();

		return $body;
	}
	
	private function formatBodyForRoom(&$user,&$lang, $room)
	{
		global $ilClientIniFile, $lng, $ilias;
		
		$room_id = $room->getRoomId();
		$room_title = $room->getTitle();

		$body = sprintf($lng->txt("chat_notification_intro"), $ilClientIniFile->readVariable("client","name"), ILIAS_HTTP_PATH)."\n\n";
		$body .= $lang->txt("chat_invitation_body")." ";
		$body .= $ilias->account->getFullname();
		$body .= "\n";
		$body .= $lang->txt("chat_chatroom_body").' '.$this->getTitle();
		if ($room_title != '')
		{
			$body .= ', '.$room_title;
		}
		$body .= "\n\n";
		$body .= $lang->txt('chat_to_chat_body');
		$body .= ': '.ILIAS_HTTP_PATH."/ilias.php?baseClass=ilChatPresentationGUI&room_id=".$room_id."&ref_id=".$room->getObjId();

		return $body;
	}

	// Protected
	// must be pubic
	public function __initChatRecording()
	{
		if(!is_object($this->chat_recording))
		{
			include_once 'Modules/Chat/classes/class.ilChatRecording.php';

			$this->chat_recording = new ilChatRecording($this->getId());

			return true;
		}
		return false;
	}

	static function _getPublicChatRefId()
	{
		static $public_chat_ref_id = 0;

		global $tree;

		if($public_chat_ref_id)
		{
			return $public_chat_ref_id;
		}
		else
		{
			foreach($tree->getSubTree($tree->getNodeData(SYSTEM_FOLDER_ID)) as $node)
			{
				if($node['type'] == 'chat')
				{
					return $public_chat_ref_id = $node['child'];
				}
			}
		}
		return false;
	}
			
	// SET/GET
} // END class.ilObjTest
?>
