<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: PushMessageModel.php, v 1.1 2012/11/06 20:52:11
//All functions -insert device tokens, send push message etc.
class PushmessageModel extends Model
{
	##### Insert Device Token ######
    public function logoutUser($userID) 
     {
        $deviceToken    = $_POST['deviceToken'];
     
        if ($sql != '') 
        {
            $delResult = $this->ObjDatabase->setQuery($sql);
        }
        return 1;
    }

	
	
	function sendMessage($deviceRegistrationId, $message='', $apiKey)
	{
			$data = array(
			'registration_ids' => $deviceRegistrationId,
			'data'	=>array( "message" => $message)
		);
                    
			$headers = array( 
			'Authorization: key=' . $apiKey,
			'Content-Type: application/json'
			);
			$ch = curl_init();
			$url = 'https://android.googleapis.com/gcm/send';
			curl_setopt( $ch, CURLOPT_URL, $url );
			curl_setopt( $ch, CURLOPT_POST, true );
			curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
			$result = curl_exec($ch);
			curl_close($ch);
			echo 'result starts-----'.$result.'-----android result'; 
	}
        
        /*  OLD FUNCTION WHICH IS NOT WORKING 
         *  I have replaced it with new one bellow
       
	function sendPushNotification($messages)
	{
                          
		$appid = '289-55244Be7r8RR32ro0M589o9r02h459255e28';
		// Password provided by RIM
		$password = 'toR339Ab';
		// Application device port
		$appport =32933;
		//Deliver before timestamp
		$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+10 minutes'));
		$addresses = '<address address-value="' .$messages['deviceToken']. '"/>';
		$message['dealTitle']= $messages['dealTitle'];
		$message['dealID']= $messages['dealID'];
		$message['cityName']= $messages['cityName'];
		$message['cityKeyID']= $messages['cityKeyID'];
		// For certificate   
		$message['userID']= $messages['userID'];
		$message['cityID']= $messages['cityID'];
		$message['pushID']= $messages['pushID'];
		$message['certificateID']= $messages['certificateID'];
		$message['certificateCode']= $messages['certificateCode'];
		$message['cerErtificateID']= $messages['certificateID'];
		$message['certificatxpiryDate']= $messages['cerExpiryDate'];
		$message['message']= $messages['message'];
		$message['notification_id']= $messages['notification_id'];
		$messages=json_encode($message);		
		//////////////////////////////////
		// create a new cURL resource
		$err = false;
		$ch = curl_init();
		$messageid = microtime(true);
		$data = '--asdwewe. "\r\n" .Content-Type: application/xml; charset=UTF-8' ."\r\n\r\n" .'<?xml version="1.0"?><!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd"><pap><push-message push-id="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'. $addresses .'<quality-of-service delivery-method="unconfirmed"/>        </push-message>        </pap>' . "\r\n" .        '--asdwewe' . "\r\n" .        'Content-Type: text/plain' . "\r\n" .                    'Push-Message-ID: ' . $messageid . "\r\n\r\n" .$messages. "\r\n" .        '--asdwewe--' . "\r\n";
		// set URL and other appropriate options
                
		curl_setopt($ch, CURLOPT_URL, "https://cp289.pushapi.na.blackberry.com/mss/PD_pushRequest");
		curl_setopt($ch, CURLOPT_PORT , 32933);
		curl_setopt($ch, CURLOPT_SSLVERSION, 3);
		curl_setopt($ch, CURLOPT_CAINFO, getcwd()."\cacert.pem");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_USERAGENT, "My BB Push Server\1.0");
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$__extra_Headers = array(
		"Content-Type: multipart/related; boundary=asdwewe; type=application/xml",
		"Accept: text/html, image/gif, image/jpeg, *; q=.2, *//*; q=.2",
		"Connection: keep-alive",
		"X-Rim-Push-Dest-Port: ".$appport,
		"X-RIM-PUSH-ID: ".$messageid,
		"X-RIM-Push-Reliability-Mode: APPLICATION"
		);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $__extra_Headers);
                
		// grab URL and pass it to the browser
		$xmldata = curl_exec($ch);
		if($xmldata === false){
		echo 'Error pada CURL : ' . curl_error($ch)."\n";
		}else{
		echo 'Operasi push berhasil'."\n";
		}
		// close cURL resource, and free up system resources
		curl_close($ch);
		//Start parsing response into XML data that we can read and output
		$p = xml_parser_create();
		xml_parse_into_struct($p, $xmldata, $vals);
		$errorcode = xml_get_error_code($p);
		if ($errorcode > 0) {
		echo xml_error_string($errorcode)."\n";
		$err = true;
		}
		xml_parser_free($p);
		echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
			if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
			echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
			echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
			echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
			echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
		} else {
			echo '<p>An error has occured</p>' . "\n";
			echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
			echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
		}
	//////////////////////////////////
	}
        */
        
               
        function sendPushNotification($messages)
	{
                          
		$appid = "289-s83l449379ri10y941cree086c643r620i28";
            // Password provided by RIM
            $password = "3S4T7u9m";
            // Application device port
            $appport = "32288";
            
            $addresstosendto[] = $messages['deviceToken'];

            $addresses = '';
            foreach ($addresstosendto as $value) {
                $addresses .= '<address address-value="' . $value . '"/>';
            }
            
            $deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+5 minutes'));
            
		$message['dealTitle']= $messages['dealTitle'];
		$message['dealID']= $messages['dealID'];
		$message['cityName']= $messages['cityName'];
		$message['cityKeyID']= $messages['cityKeyID'];
		// For certificate   
		$message['userID']= $messages['userID'];
		$message['cityID']= $messages['cityID'];
		$message['pushID']= $messages['pushID'];
		$message['certificateID']= $messages['certificateID'];
		$message['certificateCode']= $messages['certificateCode'];
		$message['cerErtificateID']= $messages['certificateID'];
		$message['certificatxpiryDate']= $messages['cerExpiryDate'];
		$message['message']= $messages['message'];
		$message['notification_id']= $messages['notification_id'];
		$messages=json_encode($message);		
		//////////////////////////////////
		// create a new cURL resource
		$err = false;
		$ch = curl_init();
		$messageid = microtime(true);
		$data = '--asdwewe. "\r\n" .Content-Type: application/xml; charset=UTF-8' ."\r\n\r\n" .'<?xml version="1.0"?><!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd"><pap><push-message push-id="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'. $addresses .'<quality-of-service delivery-method="unconfirmed"/>        </push-message>        </pap>' . "\r\n" .        '--asdwewe' . "\r\n" .        'Content-Type: text/plain' . "\r\n" .                    'Push-Message-ID: ' . $messageid . "\r\n\r\n" .$messages. "\r\n" .        '--asdwewe--' . "\r\n";
		// set URL and other appropriate options
                
		curl_setopt($ch, CURLOPT_URL, "https://cp289.pushapi.na.blackberry.com/mss/PD_pushRequest");
            curl_setopt($ch, CURLOPT_PORT , 443);
            curl_setopt($ch, CURLOPT_SSLVERSION, 3);
            curl_setopt($ch, CURLOPT_CAINFO, getcwd()."\cacert.pem");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, "My BB Push Server\1.0");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $__extra_Headers = array(
            "Content-Type: multipart/related; boundary=asdwewe; type=application/xml",
            "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
            "Connection: keep-alive",
            "X-Rim-Push-Dest-Port: ".$appport,
            "X-RIM-PUSH-ID: ".$messageid,
            "X-RIM-Push-Reliability-Mode: APPLICATION"
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $__extra_Headers);
                
		// grab URL and pass it to the browser
		$xmldata = curl_exec($ch);
		if($xmldata === false){
		echo 'Error pada CURL : ' . curl_error($ch)."\n";
		}else{
		echo 'Operasi push berhasil'."\n";
		}
		// close cURL resource, and free up system resources
		curl_close($ch);
		//Start parsing response into XML data that we can read and output
		$p = xml_parser_create();
		xml_parse_into_struct($p, $xmldata, $vals);
		$errorcode = xml_get_error_code($p);
		if ($errorcode > 0) {
		echo xml_error_string($errorcode)."\n";
		$err = true;
		}
		xml_parser_free($p);
		echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
			if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
			echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
			echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
			echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
			echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
                        echo "<br>Just For Testing Porpose - Showing Data Which is Passed in Message<br>".htmlentities($messages);
		} else {
			echo '<p>An error has occured</p>' . "\n";
			echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
			echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
		}
	//////////////////////////////////
	}
        
        
        
        //Bellow mentioned test method is working without errors on date 31-12-2013 //gaurav_kumar@ispg.in
        function testSendPushNotification($messages)
	{
            
            // APP ID provided by RIM
            $appid = "289-s83l449379ri10y941cree086c643r620i28";
            // Password provided by RIM
            $password = "3S4T7u9m";
            // Application device port
            $appport = "32288";
            
            $addresstosendto[] = $messages['deviceToken'];

            $addresses = '';
            foreach ($addresstosendto as $value) {
                $addresses .= '<address address-value="' . $value . '"/>';
            }
            
            
        // Message to send :
        $message['dealTitle']= $messages['dealTitle'];
    $message['dealID']= $messages['dealID'];
    $message['cityName']= $messages['cityName'];
    $message['cityKeyID']= $messages['cityKeyID'];
    // For certificate   
    $message['userID']= $messages['userID'];
    $message['cityID']= $messages['cityID'];
    $message['pushID']= $messages['pushID'];
    $message['certificateID']= $messages['certificateID'];
    $message['certificateCode']= $messages['certificateCode'];
    $message['cerErtificateID']= $messages['certificateID'];
    $message['certificatxpiryDate']= $messages['cerExpiryDate'];
    $message['message']= $messages['message'];
    $message['notification_id']= $messages['notification_id'];
    $messages=json_encode($message);

        //Deliver before timestamp
        $deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+5 minutes'));

        
         //   $addresses = '<address address-value="293C127B" />';

        // create a new cURL resource
        $err = false;
        $ch = curl_init();
        $messageid = microtime(true);
        $data = '--asdwewe'. "\r\n" .'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n".
        '<?xml version="1.0"?>
        <!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.1//EN" "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd">
        <pap>
        <push-message push-id="' . $messageid . '" deliver-before-timestamp="' . $deliverbefore . '" source-reference="' . $appid . '">'
        . $addresses .
        '<quality-of-service delivery-method="unconfirmed"/>
        </push-message>
        </pap>' . "\r\n" .
        '--asdwewe' . "\r\n" .
        'Content-Type: text/plain' . "\r\n" .
                //'Content-Encoding: binary'. "\r\n" .
        'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
        $messages . "\r\n" .
        '--asdwewe--' . "\r\n";
        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "https://cp289.pushapi.na.blackberry.com/mss/PD_pushRequest");
            curl_setopt($ch, CURLOPT_PORT , 443);
            curl_setopt($ch, CURLOPT_SSLVERSION, 3);
            curl_setopt($ch, CURLOPT_CAINFO, getcwd()."\cacert.pem");
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, "My BB Push Server\1.0");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $__extra_Headers = array(
            "Content-Type: multipart/related; boundary=asdwewe; type=application/xml",
            "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
            "Connection: keep-alive",
            "X-Rim-Push-Dest-Port: ".$appport,
            "X-RIM-PUSH-ID: ".$messageid,
            "X-RIM-Push-Reliability-Mode: APPLICATION"
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $__extra_Headers);
        

    // grab URL and pass it to the browser
    $xmldata = curl_exec($ch);
		if($xmldata === false){
		echo 'Error pada CURL : ' . curl_error($ch)."\n";
		}else{
		echo 'Operasi push berhasil'."\n";
		}
		// close cURL resource, and free up system resources
		curl_close($ch);
		//Start parsing response into XML data that we can read and output
		$p = xml_parser_create();
		xml_parse_into_struct($p, $xmldata, $vals);
		$errorcode = xml_get_error_code($p);
		if ($errorcode > 0) {
		echo xml_error_string($errorcode)."\n";
		$err = true;
		}
		xml_parser_free($p);
		echo 'Our PUSH-ID: ' . $messageid . "<br \>\n";
			if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
			echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "<br \>\n";
			echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "<br \>\n";
			echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "<br \>\n";
			echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "<br \> \n";
		} else {
			echo '<p>An error has occured</p>' . "\n";
			echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "<br \>\n";
			echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "<br \>\n";
		}
	//////////////////////////////////
	
                
                }
 
    public function getLocationNameByID($currentLanguageID, $locID)
    {
        $locSql = "SELECT BLD.locName 
                    FROM ".DB_PREFIX."business_locations BL
                    JOIN ".DB_PREFIX."business_location_details BLD ON BL.businessLocID = BLD.businessLocID AND BLD.languageID ='".$currentLanguageID."'
                    WHERE BL.locStatus = 'Active' AND BL.businessLocID = '".$locID."' AND BLD.locName != ''"; 
        return $this->ObjDatabase->readValue($locSql);
    }
    
    public function getLocationIDByName($currentLanguageID, $locName)
    {
        $locSql = "SELECT BL.businessLocID, BLD.locName 
                    FROM ".DB_PREFIX."business_locations BL
                    JOIN ".DB_PREFIX."business_location_details BLD ON BL.businessLocID = BLD.businessLocID AND BLD.languageID ='".$currentLanguageID."'
                    WHERE BL.locStatus = 'Active' AND BLD.locName = '".$this->escape($locName)."'"; 
        return $this->ObjDatabase->readValues($locSql);
    }
    
    public function getChildLocByParentID($currentLanguageID, $parentLocIDs)
    {
        $locSql = "SELECT BL.businessLocID
                    FROM ".DB_PREFIX."business_locations BL
                    JOIN ".DB_PREFIX."business_location_details BLD ON BL.businessLocID = BLD.businessLocID AND BLD.languageID ='".$currentLanguageID."'
                    WHERE BL.locStatus = 'Active' AND BL.businessLocParentID IN (".$parentLocIDs.")"; 
        return $this->ObjDatabase->readValues($locSql);
    }

    ##### Insert Device Token ######
    public function insertDeviceToken($deviceType,$userID='')
    {
            $deviceToken = $_POST['deviceToken'];
            $status      = $_POST['status'];
            $userID      = (empty($userID)) ? 0: $userID;
            $sql="
                    SELECT 
                            * 
                    FROM 
                            " . DB_PREFIX . "push_devicetoken 
                    WHERE 
                            deviceToken='".$deviceToken."' 
                            AND 
                            deviceType='".$deviceType."' 
                            AND 
                            userID='".$userID."' ";
            $checkToken       = $this->ObjDatabase->readValue($sql);
            if(!empty($checkToken))
            {
                    $updateSql = " UPDATE 
                                    ".DB_PREFIX."push_devicetoken 
                                   SET 
                                    `status`= '".$status."' 
                                   WHERE 
                                    id = '".$checkToken['id']."' ";
                    $ressql = $this->ObjDatabase->setQuery($updateSql);
                    if($ressql)
                    return 0;
            }
            else
            {
                    $sql="
                            INSERT INTO " . DB_PREFIX . "push_devicetoken 
                                    (
                                    deviceToken, 
                                    deviceType, 
                                    userID, 
                                    date,
                                    status
                                    ) 
                            VALUES
                                    (
                                    '".$deviceToken."', 
                                    '".$deviceType."', 
                                    '".$userID."', 
                                    NOW(), 
                                    '".$status."'
                                    )";
                    $ressqlInsertToken = $this->ObjDatabase->setQuery($sql);
                    if($ressqlInsertToken)
                    return 1;
            }
    }
    ##### Insert Business Device Token ######
    public function insertBusinessDeviceToken($deviceType,$userID='')
    {
            $deviceToken = $_POST['deviceToken'];
            $status      = $_POST['status'];
            $userID      = (empty($userID)) ? 0: $userID;
            $sql="
                    SELECT 
                            * 
                    FROM 
                            " . DB_PREFIX . "push_business_devicetoken 
                    WHERE 
                            deviceToken='".$deviceToken."' 
                            AND 
                            deviceType='".$deviceType."' 
                            AND 
                            userID='".$userID."' ";
            $checkToken       = $this->ObjDatabase->readValue($sql);
            if(!empty($checkToken))
            {
                    $updateSql = " UPDATE 
                                    ".DB_PREFIX."push_business_devicetoken 
                                   SET 
                                    `status`= '".$status."' 
                                   WHERE 
                                    id = '".$checkToken['id']."' ";
                    $ressql = $this->ObjDatabase->setQuery($updateSql);
                    if($ressql)
                    return 0;
            }
            else
            {
                    $sql="
                            INSERT INTO " . DB_PREFIX . "push_business_devicetoken 
                                    (
                                    deviceToken, 
                                    deviceType, 
                                    userID, 
                                    date,
                                    status
                                    ) 
                            VALUES
                                    (
                                    '".$deviceToken."', 
                                    '".$deviceType."', 
                                    '".$userID."', 
                                    NOW(), 
                                    '".$status."'
                                    )";
                    $ressqlInsertToken = $this->ObjDatabase->setQuery($sql);
                    if($ressqlInsertToken)
                    return 1;
            }
    }
    ##### Change Notification Read Status ######
    public function changeNotificationStatus($deviceType, $userID='', $notificationID)
    {
        $updateSql = " UPDATE 
                        ".DB_PREFIX."notification_to_devices 
                       SET 
                        `status`= 'read' 
                       WHERE 
                        notificationID = '".$notificationID."' "; 
        $ressql = $this->ObjDatabase->setQuery($updateSql);
        if($ressql > 0)
            return 1;
        else
            return 0;
    }
    
    public function listUnreadNotifications($deviceType, $deviceID='', $languageIDs = '', $limitFrom='', $limitTo='')
    {
        $sql = "
                SELECT 
                    PN.*,PND.* ,DATE_FORMAT(PN.notification_sent_date,'%d %b %Y') AS sent_date 
                FROM 
                    ".DB_PREFIX."notification_to_devices ND 
                JOIN 
                    ".DB_PREFIX."push_notifications PN ON (ND.notificationID = PN.notification_id) 
                JOIN 
                    ".DB_PREFIX."push_notification_details PND ON (PND.notification_id = PN.notification_id and languageID='".$languageIDs['Current']."') 
                WHERE 
                        PN.status!='delete' AND
                        ND.status='unread'
                        AND
                        ND.id IN (
                                SELECT id FROM ".DB_PREFIX."push_devicetoken WHERE deviceType='".$this->escape($deviceType)."' ";
        if($deviceID!='') {
           $sql .= " AND deviceToken='".$this->escape($deviceID)."' ";
        }
        $sql .= " )";
        $sql .= " 
				GROUP BY PN.notification_id
				ORDER BY ND.`date` DESC ";
        
        
        if(!empty($limitFrom) )
            $sql     .=" LIMIT  ".$limitFrom.",".$limitTo."";
    
        return $this->ObjDatabase->readValues($sql);
    }

}