<?php

/************************************************************************/
/* DOCEBO CORE - Framework												*/
/* ============================================							*/
/*																		*/
/* Copyright (c) 2005													*/
/* http://www.docebo.com												*/
/*																		*/
/* 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.		*/
/************************************************************************/

/**
 * @package admin-core
 * @subpackage user
 * @version  $Id: lib.usernotifier.php 955 2007-02-03 15:19:40Z fabio $
 * @author   Emanuele Sandri <esandri@docebo.com>
 *
 * This is the class for ClassEvents in Docebo
**/

require_once( dirname(__FILE__).'/lib.event.php' );

class DoceboUserNotifier extends DoceboEventConsumer {

	function _getConsumerName() {
		return "DoceboUserNotifier";
	}

	function actionEvent( &$event ) {

		parent::actionEvent($event);

		// initializing
		require_once($GLOBALS["where_framework"]."/setting.php");
		require_once($GLOBALS["where_framework"]."/lib/lib.field.php");

		$acl_man =& $GLOBALS['current_user']->getACLManager();
		$field_man = new FieldList();
		$send_to_field = $GLOBALS['framework']['sms_cell_num_field'];

		$arr_mail_recipients = array();
		$arr_sms_recipients = array();

		// recover event information
		$arr_recipients 	= explode( ',', $event->getProperty('recipientid') );
		$msg_composer 		= unserialize(urldecode($event->getProperty('MessageComposer')));
		$msg_composer->after_unserialize();
		$force_email_send 	= $event->getProperty('force_email_send');

		if(!is_array($arr_recipients) || empty($arr_recipients)) return;

		// recover user info and convert to idst if required
		if(is_numeric($arr_recipients[0])) $idst_users =& $arr_recipients;
		else $idst_users = $acl_man->fromUseridToIdst($arr_recipients);
		$users_info = $acl_man->getUsers($idst_users);

		// recove setting
		$users_lang		= $acl_man->getSettingValueOfUsers('ui.language', false, true);
		$users_sms 		= $field_man->showFieldForUserArr($idst_users, array($send_to_field));

		// scan all users

		if(!is_array($users_info) || empty($users_info)) return;
		while(list(, $user_dett) = each($users_info)) {

			// recover media setting
			$idst_user = $user_dett[ACL_INFO_IDST];
			$media = usernotifier_getUserEventChannel( $idst_user, $event->getClassName() );

			$lang = ( isset($users_lang[$idst_user]) && $users_lang[$idst_user] !== NULL
				? $users_lang[$idst_user]
				: getDefaultLanguage() );

			if(in_array('email', $media) || $force_email_send == 'true')
				if($user_dett[ACL_INFO_EMAIL] != '')
					$arr_mail_recipients[$lang][$idst_user] = $user_dett[ACL_INFO_EMAIL];

			if(in_array('sms', $media))
				if($users_sms[$idst_user][$send_to_field] != '')
					$arr_sms_recipients[$lang][$idst_user] = $users_sms[$idst_user][$send_to_field];

		}

		if(!empty($arr_mail_recipients)) {

			$lang_mail = array_keys($arr_mail_recipients);
			foreach($lang_mail as $lang_code) {

				reset($arr_mail_recipients[$lang]);
				$this->_sendMail(	$msg_composer->getSubject('email', $lang_code),
									$msg_composer->getBody('email', $lang_code),
									$arr_mail_recipients[$lang] );
			}
		}
		if(!empty($arr_sms_recipients)) {

			$lang_sms = array_keys($arr_sms_recipients);
			foreach($lang_sms as $lang_code) {

				reset($arr_sms_recipients[$lang_sms]);
				$this->_sendSms(	$msg_composer->getBody('sms', $lang_code),
									$arr_sms_recipients[$lang_code] );
			}
		}
		return true;
	}

	function _sendMail($subject, $body, &$mail_recipients) {

		// prepare intestation for email
		$from = "From: ".$GLOBALS['framework']['sender_event'].$GLOBALS['mail_br'];
		$intestazione  = "MIME-Version: 1.0".$GLOBALS['mail_br']
			."Content-type: text/html; charset=".getUnicode().$GLOBALS['mail_br'];
		$intestazione .= "Return-Path: ".$GLOBALS['framework']['sender_event'].$GLOBALS['mail_br'];
		$intestazione .= "Reply-To: ".$GLOBALS['framework']['sender_event'].$GLOBALS['mail_br'];
		$intestazione .= "X-Sender: ".$GLOBALS['framework']['sender_event'].$GLOBALS['mail_br'];
		$intestazione .= "X-Mailer: PHP/". phpversion().$GLOBALS['mail_br'];

		// send mail
		while(list(, $recipient) = each($mail_recipients)) {

			@mail($recipient , stripslashes($subject), stripslashes(nl2br($body)), $from.$intestazione."\r\n");
		}
	}

	function _sendSms($body, &$sms_recipients) {

		// in the future, if we'll have more than one gateway, smsmarket
		// will became a class that will include all the smsmarket's methods
		// and we will just load the class and call $obj->sendsms(..)

		/* switch($GLOBALS['framework']['sms_gateway']) {
			case "smsmarket": {
				$this->_smsmarket_Send(strip_tags($body), $sms_recipients);
			} break;
		} */
		require_once($GLOBALS["where_framework"]."/lib/lib.sms.php");
		$sms_manager =new SmsManager();
		$sms_manager->sendSms(strip_tags($body), $sms_recipients);
	}


}

function usernotifier_getUserEventChannel( $idst, $event_class ) {

	$query = "SELECT em.channel, em.permission"
		." FROM ".$GLOBALS['prefix_fw']."_event_manager as em"
		." JOIN ".$GLOBALS['prefix_fw']."_event_class as ec"
		." WHERE ec.idClass = em.idClass "
		."   AND ec.class='".$event_class."'";

	$rs_manager = mysql_query( $query );
	if( $rs_manager === FALSE )
		return array();
	if( mysql_num_rows($rs_manager) == 0 )
		return array();

	list($channel, $permission) = mysql_fetch_row( $rs_manager );

	$media = array();

	if( $permission == 'not_used' ) {
		return array();
	} elseif( $permission == 'mandatory' ) {

		if( strlen($channel) > 0 ) {
			$media = explode( ',', $channel );
		}
	} else {

		$query = "SELECT eu.channel "
				." FROM ".$GLOBALS['prefix_fw']."_event_user as eu"
				." JOIN ".$GLOBALS['prefix_fw']."_event_manager as em"
				." JOIN ".$GLOBALS['prefix_fw']."_event_class as ec"
				." WHERE eu.idEventMgr=em.idEventMgr "
				."   AND ec.idClass = em.idClass "
				."   AND eu.idst='".(int)$idst."'"
				."   AND ec.class='".$event_class."'";
		$rs_user = mysql_query( $query );
		if( mysql_num_rows($rs_user) == 1 ) {
			list($channel) = mysql_fetch_row( $rs_user );

			if( strlen($channel) > 0 ) {
				$media = explode( ',', $channel );
			}
		} else {
			list($channel) = mysql_fetch_row( $rs_manager );
			if( strlen($channel) > 0 ) {
				$media = explode( ',', $channel );
			}
		}
		return $media;
	}
	return $media;
}

function usernotifier_getUserEventStatus( $idst, $event_class ) {
	$media = usernotifier_getUserEventChannel( $idst, $event_class );
	return (count($media) > 0);
}

?>
