Часть 10 из 12
Строки: 18001-20000 из 22262
================================================================================

            foreach ($value as $k => $v) {
                echo "[$k] = $v<br>";
            }
        }
        echo "<br>";
        echo "Stage:<br>";
        $listMission = Model::factory("stage")->getList(array("user_id" => $user_id));
        foreach ($listMission as $key => $value) {
            echo "[$key] = $value:<br>";
            foreach ($value as $k => $v) {
                echo "[$k] = $v<br>";
            }
        }

        
        echo "<br>";
        $mission_stat_id = 0;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";
        
        echo "<br>";
        $mission_stat_id = 1;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";

        echo "<br>";
        $mission_stat_id = 2;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";
        
        echo "<br>";
        $mission_stat_id = 3;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";
        
        echo "<br>";
        $mission_stat_id = 4;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";
        
        echo "<br>";
        $mission_stat_id = 5;
        echo "checkAllPreviousMissionCompleted [$mission_stat_id]:<br>";
        $check  = Model::factory("mission")->checkAllPreviousMissionCompleted($user_id, $mission_stat_id);
        echo "check = $check<br>";
        
        
        //m=|||uid||518141720992|||s_key||9736558|||m||0||0||mission.start|||m||0||1||{"mission_stat_id":"1"}&k=56325e3787e31d8
        /*
        echo "<br>";
        $mission_stat_id = 0;
        echo "mission.start [$mission_stat_id]:<br>";
        $resmission  = Model::factory("mission")->startMission($user_id, $mission_stat_id);
        echo "resmission = $resmission<br>";
        echo "count_resmission:". count($resmission)."<br>";
        foreach ($resmission as $key_mission => $value_mission) {
            echo "[$key_mission] = $value_mission:<br>";
            if(is_array($value_mission)){
                foreach ($value_mission as $key_1 => $value_1) {
                    echo "[$key_1] = $value_1<br>";
                }
            }
        }
        
         */
        
        
        
        
        
        echo <<<_END2
            </pre>
        </body
     </html>
_END2;
    }
} catch (Exception $e) {
    errors::$errorQueue [] = array('modul', $e->getMessage(), $e->getCode());
}
if (notifications::exist()) {
    $response = array_merge($response, notifications::getList());
}
if (count(errors::$errorQueue) > 0) {
    $response = array_merge($response, errors::$errorQueue);
}
//$viewClass = SConfig::$defaultView . "View";
//$view = new $viewClass ();
//$view->display ( $response );
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
LOG::printText("server_script_end");
LOG::printDate();
LOG::printLine();
LOG::printLine();
$viewClass = SConfig::$defaultView . "View";
$view = new $viewClass ();
$view->display ( $response );
//fclose( $f); 
?>


================================================================================
ФАЙЛ: index_server_send_mail_to_all.php
================================================================================

<?php   
                                 
require ("common.php");   
 
LOG::printLine(); 
LOG::printLine();  
LOG::printDate();
LOG::printText("server_script_mail_start");
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  ignore_user_abort ();
  set_time_limit ( 36000 );
     
  $socialId = SOCIAL_ID;
  
  $aCommand ['uid'] = 147784953;
  social::$authAPI = social::get ( SConfig::$social [$socialId] ['name'], SConfig::$social [$socialId] ['apiId'], SConfig::$social [$socialId] ['apiSecret'], $aCommand ['uid'] );
 
  $title = "Тест";
  $text = "Test Тест 1-9";
  Model::factory('mail')->sendMailToAll($title, $text, 1);

  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
  LOG::printText("server_script_mail_end");
  LOG::printDate();
  LOG::printLine();  
  LOG::printLine();  
    //$viewClass = SConfig::$defaultView . "View";
    //$view = new $viewClass ();
    //$view->display ( $response );

    //fclose( $f); 
?>


================================================================================
ФАЙЛ: lib/__cache_included.php
================================================================================

<?php

class CacheAccess {
	private static $mc;
	
	/**
	 * @return Memcached
	*/
	
	public static function getCache() 
    {   
       if (! self::$mc) {
			self::$mc = new Memcache();
        	self::$mc->addServer ( CACHE_SERVER, CACHE_PORT );
        	//self::$mc->setOption ( Memcached::OPT_COMPRESSION, false );
        }  
		return self::$mc;     
	}
	
	public static function getKey($key) 
    {
        if (is_array ( $key )) {
        	$keys = array ();
			foreach ( $key as $v ) {
        		$keys [] = CACHE_PREFIX . $v;
        	}
        	return $keys;
		} else {
        	return CACHE_PREFIX . $key;
		}   
        
        return CACHE_PREFIX . $key; 
	}
	
	public static function get($key) 
    {
        
        if (defined ( "CACHE_SERVER" )) {
        	$mc = self::getCache ();
        	return $mc->get ( self::getKey ( $key ) );
		} else {
        	return false;
		}     
        
        return false;
	}
	
	public static function getObject($key, $obj) 
    {
        
		if (($row = self::get ( $key )) !== false) {
			foreach ( $row as $k => $v ) {
				$obj->$k = $v;
			}
			return true;
		} else {
			return false;
		}   
        
        return false; 
	}
	
	public static function set($key, $val, $expire = 604800) 
    {      
        //1 ?????? = 604800
        if (defined ( "CACHE_SERVER" )) {
        	$mc = self::getCache ();
            $flag_compressed = 0;
        	return $mc->set ( self::getKey ( $key ), $val, $flag_compressed, $expire );
           // return $mc->set ( self::getKey ( $key ), $val); 
		} else {
        	return false;
		}   
        
        return false;  
	}
	
	public static function append($key, $val) 
    {      
        if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			$result = $mc->append ( self::getKey ( $key ), $val );
        	return $result && CacheAccess::getResultCode () != Memcached::RES_NOTSTORED;
		} else {
        	return false;
		}  
        
        return false;  
	}
	
	public static function getResultCode() 
    {
        
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->getResultCode ();
		} else {
			return false;
		}          
        
        return false; 
	}
	
	public static function delete($key) 
    {
        
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->delete ( self::getKey ( $key ) );
		} else {
			return false;
		}    
        
        return false; 
	}
	
	public static function flush() 
    {               
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->flush ();
		} else {
			return false;
		} 
        
        return false; 
	}
}

?>

================================================================================
ФАЙЛ: lib/db.php
================================================================================

<?php

/**
 * Работа с базой данных
 */
class DBAccess {
	private static $pdos = array ();
	
	/**
	 * Получение имени таблицы с префиксом
	 * @param string $table имя таблицы
	 * @return string
	 */
	public static function getTableName($table) {
		return DB_PREF . $table;
	}
	
	/**
	 * Получение экземпляра PDO
	 * @param array $params параметры коннекта к базе
	 * @return PDO
	 */
	public static function getDB($params = NULL) {
		if ($params == NULL) {
			$pdo_id = 0;
			$params ['host'] = DB_HOST;
			$params ['user'] = DB_USER;
			$params ['pass'] = DB_PASS;
			$params ['name'] = DB_NAME;
			$params ['port'] = DB_PORT;
			
		} else {
			$pdo_id = md5 ( 
					$params ['host'] . $params ['name'] . $params ['user'] . $params ['pass'] );
		}
		if (! isset ( self::$pdos [$pdo_id] )) {
			self::$pdos [$pdo_id] = new PDO ( 
			    //'mysql:host=' . $params ['host'] . ';dbname=' . $params ['name'] . '' .';port=3307', 
					'mysql:host=' . $params ['host'] . ';dbname=' . $params ['name'] . '' .';port=' . $params ['port'], 
					$params ['user'], $params ['pass'], array (PDO::ATTR_PERSISTENT => true ) );
			if (defined ( "DB_WARNING" )) {
				self::$pdos [$pdo_id]->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
			}
			if (defined ( "DB_EXCEPTION" )) {
				self::$pdos [$pdo_id]->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
			}
			self::$pdos [$pdo_id]->exec ( "SET NAMES 'utf8'" );
		}
		return self::$pdos [$pdo_id];
	}
	
	/**
	 * Строит where выражение 
	 * @param array $where массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * которые нужно искать. в случае использования % в начале или конце поиск производится по LIKE
	 * @return array массив из двух элементов - where-выражения sql запроса и значений, для передачи в execute
	 */
	private static function buildWhere(array $where) {
		$sets = array ();
		$vals = array ();
		foreach ( $where as $k => $v ) {
			if (substr ( $v, 0, 1 ) == "%" || substr ( $v, - 1 ) == "%") {
				$str = "`{$k}` LIKE :{$k}";
			} else {
				$str = "`{$k}`=:{$k}";
			}
			$sets [] = $str;
			$vals [":{$k}"] = $v;
		}
		$sets = implode ( " AND ", $sets );
		return array ($sets, $vals );
	}
	
	/**
	 * Строит set выражение
	 * @param array $update массив параметров для обновления где ключи - это имена полей, значения - значения
	 * @return array массив из двух элементов - set-выражения sql запроса и значений, для передачи в execute
	 */
	private static function buildSET(array $update) {
		$sets = array ();
		$vals = array ();
		foreach ( $update as $k => $v ) {
			$str = "`{$k}`=:s_{$k}";
			$sets [] = $str;
			$vals [":s_{$k}"] = $v;
		}
		$sets = implode ( ",", $sets );
		return array ($sets, $vals );
	}
	
	/**
	 * Строит insert выражение, в отличие от buildSET строит выражение для запроса insert ... on duplicate key update
	 * @param array $update массив параметров для обновления где ключи - это имена полей, значения - значения
	 * @param array $keys ключи, по которым нужно произвести обновление в случае существования
	 * @return array массив из трех элементов - set-выражение, update-выражение sql запроса и значений,
	 * для передачи в execute
	 */
	private static function buildSETUPD(array $update, array $keys) {
		$sets = array ();
		$upds = array ();
		$vals = array ();
		foreach ( $update as $k => $v ) {
			$str = "`{$k}`=:{$k}";
			$sets [] = $str;
			if (! in_array ( $k, $keys )) {
				$upds [] = $str;
			}
			$vals [":{$k}"] = $v;
		}
		$sets = implode ( ",", $sets );
		$upds = implode ( ",", $upds );
		return array ($sets, $upds, $vals );
	}
	
	/**
	 * Выполняет запрос к БД
	 * @param string $sql
	 * @param array $vals
	 * @param int $fetch_mode
	 * @return array|boolean
	 */
	public static function query($sql, $vals = array(), $fetch_mode = NULL, $fetch_all = true) {
		$db = self::getDB ();
		$st = $db->prepare ( $sql );
		$result = $st->execute ( $vals );
		if (! is_null ( $fetch_mode ))
			$result = $fetch_all ? $st->fetchAll ( $fetch_mode ) : $st->fetch ( $fetch_mode );
		if (! PRODUCTION)
			SDebug::log_sql ( $sql, $vals );
		return $result;
	}
	
	/**
	 * Производит выборку из таблицы
	 * @param string $table название таблицы
	 * @param array $where массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * которые нужно искать. в случае использования % в начале или конце поиск производится по LIKE
	 * @param array $fields массив полей, что необходимо получить
	 * @param string $order выражение, подставляющееся в ORDER BY (не экранируется!!!)
	 * @param int $fm режим получения данных PDO (PDO::FETCH_ASSOC,PDO::FETCH_COLUMN)
	 * @return array массив значений
	 */
	public static function select($table, array $where = array(), array $fields = null, $order = "", $limit = "", 
			$fm = PDO::FETCH_ASSOC) {
		list ( $sets, $vals ) = self::buildWhere ( $where );
		if (! $fields) {
			$fields = "*";
		} else {
			$fields = "`" . implode ( "`,`", $fields ) . "`";
		}
		
		$qur = "SELECT {$fields} FROM `" . self::getTableName ( $table ) . "`";
		if ($sets != "") {
			$qur .= " WHERE {$sets}";
		}
		if ($order != "") {
			$qur .= " ORDER BY {$order}";
		}
		if ($limit != "") {
			$qur .= " LIMIT {$limit}";
		}
		return self::query ( $qur, $vals, $fm );
	}
	
	/**
	 * Удаляет строки из таблицы
	 * @param string $table название таблицы
	 * @param array $where массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * по которым нужно найти записи. в случае использования % в начале или конце поиск производится по LIKE
	 * @return bool
	 */
	public static function delete($table, array $where) {
		if (count ( $where ) == 0) {
			return false;
		}
		list ( $sets, $vals ) = self::buildWhere ( $where );
		$qur = "DELETE FROM `" . self::getTableName ( $table ) . "` WHERE {$sets}";
		return self::query ( $qur, $vals );
	}
	
	/**
	 * Обновляет строки в таблице
	 * @param string $table название таблицы
	 * @param array $upd массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * которые нужно обновить.
	 * @param array $where массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * по которым нужно найти записи. в случае использования % в начале или конце поиск производится по LIKE
	 * @return bool
	 */
	public static function update($table, array $upd, array $where) {
		if (count ( $where ) == 0 || count ( $upd ) == 0) {
			return false;
		}
		list ( $wsets, $wvals ) = self::buildWhere ( $where );
		list ( $usets, $uvals ) = self::buildSET ( $upd );
		$vals = array_merge ( $wvals, $uvals );
		
		$qur = "UPDATE `" . self::getTableName ( $table ) . "` SET {$usets} WHERE {$wsets}";
		return self::query ( $qur, $vals );
	}
	
	/**
	 * Добавляет записи в таблицу
	 * @param string $table название таблицы
	 * @param array $sets массив параметров запроса, где ключи - это имена полей, значения - значения,
	 * которые нужно добавить или обновить в записи.
	 * @param array $keys ключи, по которым нужно произвести обновление в случае существования
	 * @return bool
	 */
	public static function insert($table, array $sets, array $keys) {
		if (count ( $sets ) == 0) {
			return false;
		}
		list ( $sets, $upds, $vals ) = self::buildSETUPD ( $sets, $keys );
		$qur = "INSERT INTO `" . self::getTableName ( $table ) . "` SET {$sets}" . ($upds ? " ON DUPLICATE KEY UPDATE {$upds}" : "");
		$result = self::query ( $qur, $vals );
		$lastId = self::getDB ()->lastInsertId ();
		return $lastId ? $lastId : $result;
	}
	
	/**
	 * Добавляет записи в таблицу
	 * @param string $table название таблицы
	 * @param string $object объект, из которого нужно брать параметры
	 * @param array $sets названия свойств объекта, что нужно сохранить
	 * @param array $keys ключи, по которым нужно произвести обновление в случае существования
	 * @return bool
	 */
	public static function insertFromObject($table, $object, array $keys, array $sets = null) {
		$newsets = array ();
		if ($sets && is_array ( $sets )) {
			foreach ( $sets as $k ) {
				if ($object->$k)
					$newsets [$k] = $object->$k;
			}
		} else {
			foreach ( $object as $k => $v ) {
				if ($v)
					$newsets [$k] = $v;
			}
		}
		
		return self::insert ( $table, $newsets, $keys );
	}
}

?>

================================================================================
ФАЙЛ: lib/notifications.php
================================================================================

<?php

class notifications {
	public static $notification = array ();
	
	public static function add($key, $value) {
		self::$notification [][$key] = $value;
	}
	
	public static function getList() {
		return array (array ('_notification', self::$notification ) );
	}
	
	public static function exist() {
		return ( boolean ) count ( self::$notification );
	}
}

?>

================================================================================
ФАЙЛ: lib/inputParser.php
================================================================================

<?php

abstract class inputAbsParser {
    protected $commands = array();

    public function getCmd() {
        $cmd = array_shift($this->commands);
        if ($cmd) {
            if (is_array($cmd) && count($cmd)==2) {
                return $cmd;
            }else{
                return errors::errorIncorrectCommand;
            }
        }else{
            return false;
        }
    }
}

class inputParser extends inputAbsParser {
    public function  __construct($req) {
        if (isset($req['m']) && is_array($req['m'])) 
            $this->commands = $req['m'];
            ksort($this->commands);
    }
}

class inputQueryParser extends inputAbsParser 
{
    public function  __construct( $qur, $req) 
	{
     //   $f = fopen("testadmin1.txt", "a");
            //    $qur = substr($qur, strlen(dirname($_SERVER['SCRIPT_NAME']))+1); 
        
        
	//------------------------------------------------------------------        
      //  fprintf( $f, ".................\n"); 
      //  fprintf( $f, $qur);                   
      //  fprintf( $f, "\n"); 
      //  fprintf( $f, $_SERVER['SCRIPT_NAME']); 
      //  fprintf( $f, "\n");  

       
        $zag =  explode("/", $qur); 
        $qur = "";    
        
      //  fprintf( $f, count($zag)); 
                              
        for( ;  count($zag) > 0; )
        {                
            $sEl = array_shift($zag);
       ///      fprintf( $f, $sEl);  
            if( $sEl == "admin" )
            {
         //       fprintf( $f, "-->\n"); 
                $qur = "";
                for( $i = 0; $i < count($zag); $i++)
                {
                    if( $i != 0)
                     $qur .= "/";
                    $qur .= $zag[$i];    
                }
            }   
        }
                         
                                     
       // if(count($qur) > 7)
         //   $qur = substr($qur, 7);  
            
     //    fprintf( $f, "<--\n"); 
     //   fprintf( $f, $qur);   
     //   fprintf( $f, "\n"); 
         
           // $zag =  explode("/", $qur);  
         
         //if($zag > )
        
        
//------------------------------------------------------------------ 
        
		list($qur) = explode("?",$qur);
                
        
		$cmd = explode("/", $qur);
		if (count($cmd)==1) 
		{
			if (!$cmd[0]) 
			{
				$cmd = "index.index";
			}
			else
			{
				$cmd = $cmd[0].".index";
			}
		}
		else
		{
			$cmd = $cmd[0].".".$cmd[1];
		}
        
     //   fprintf( $f, "\n");  

		$this->commands[] = array( $cmd, $req);
        
        
   //     fclose( $f);
    }
}

?>

================================================================================
ФАЙЛ: lib/cache.php
================================================================================

<?php

class CacheAccess {
	private static $mc;
	
	/**
	 * @return Memcached
	*/
	
	public static function getCache() 
    {   
       if (! self::$mc) {
			self::$mc = new Memcache();
        	self::$mc->addServer ( CACHE_SERVER, CACHE_PORT );
        	//self::$mc->setOption ( Memcached::OPT_COMPRESSION, false );
        }  
		return self::$mc;     
	}                                      
	
	public static function getKey($key) 
    {
        if (is_array ( $key )) {
        	$keys = array ();
			foreach ( $key as $v ) {
        		$keys [] = CACHE_PREFIX . $v;
        	}
        	return $keys;
		} else {
        	return CACHE_PREFIX . $key;
		}   
        
        return CACHE_PREFIX . $key; 
	}
	
	public static function get($key) 
    {
        
        if (defined ( "CACHE_SERVER" )) {
        	$mc = self::getCache ();
        	return $mc->get ( self::getKey ( $key ) );
		} else {
        	return false;
		}     
        
        return false;
	}
	
	public static function getObject($key, $obj) 
    {
        
		if (($row = self::get ( $key )) !== false) {
			foreach ( $row as $k => $v ) {
				$obj->$k = $v;
			}
			return true;
		} else {
			return false;
		}   
        
        return false; 
	}
	
	public static function set($key, $val, $expire = 604800) 
    {      
        //1 ?????? = 604800
        if (defined ( "CACHE_SERVER" )) {
        	$mc = self::getCache ();
            $flag_compressed = 0;
        	return $mc->set ( self::getKey ( $key ), $val, $flag_compressed, $expire );
           // return $mc->set ( self::getKey ( $key ), $val); 
		} else {
        	return false;
		}   
        
        return false;  
	}
	
	public static function append($key, $val) 
    {      
        if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			$result = $mc->append ( self::getKey ( $key ), $val );
        	return $result && CacheAccess::getResultCode () != Memcached::RES_NOTSTORED;
		} else {
        	return false;
		}  
        
        return false;  
	}
	
	public static function getResultCode() 
    {
        
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->getResultCode ();
		} else {
			return false;
		}          
        
        return false; 
	}
	
	public static function delete($key) 
    {
        
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->delete ( self::getKey ( $key ) );
		} else {
			return false;
		}    
        
        return false; 
	}
	
	public static function flush() 
    {               
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->flush ();
		} else {
			return false;
		} 
        
        return false; 
	}
}

?>

================================================================================
ФАЙЛ: lib/jsonCoder.php
================================================================================

<?php
/**
 * Работа с базой данных
 */
class JsonCoder {
    
    
    public static function jsonEncode($value) //альтернатива json_encode
    {
                if (is_int($value)) {
                    return (string)$value;
                } elseif (is_string($value)) {
        $value = str_replace(array('\\', '/', '"', "\r", "\n", "\b", "\f", "\t"),
        array('\\\\', '\/', '\"', '\r', '\n', '\b', '\f', '\t'), $value);
        $convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
        $result = "";
        for ($i = mb_strlen($value) - 1; $i >= 0; $i--) {
        $mb_char = mb_substr($value, $i, 1);
        if (mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match)) {
        $result = sprintf("\\u%04x", $match[1]) . $result;
        } else {
        $result = $mb_char . $result;
        }
        }
        return '"' . $result . '"';
                } elseif (is_float($value)) {
                    return str_replace(",", ".", $value);
                } elseif (is_null($value)) {
                    return 'null';
                } elseif (is_bool($value)) {
                    return $value ? 'true' : 'false';
                } elseif (is_array($value)) {
                    $with_keys = false;
                    $n = count($value);
                    for ($i = 0, reset($value); $i < $n; $i++, next($value)) {
                                if (key($value) !== $i) {
        $with_keys = true;
        break;
                        }
            }
        } elseif (is_object($value)) {
            $with_keys = true;
        } else {
            return '';
        }
        $result = array();
        if ($with_keys) {
            foreach ($value as $key => $v) {
                $result[] = self::jsonEncode((string)$key) . ':' . self::jsonEncode($v);
            }
            return '{' . implode(',', $result) . '}';
        } else {
            foreach ($value as $key => $v) {
                $result[] = self::jsonEncode($v);
            }
            return '[' . implode(',', $result) . ']';
        }
    } 
    
     public static function jsonDecode($json, $assoc = false)     {
              
         mb_internal_encoding("UTF-8");
         $i = 0;
         $n = strlen($json);
         try {
              $result = self::json_decode_value($json, $i, $assoc);
              while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
              if ($i < $n) {
                   return null;
                   }
              return $result;
              } catch (Exception $e) {
              return null;
           }
         }
         
        private function json_decode_value($json, &$i, $assoc = false){
            $n = strlen($json);
            while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;

            switch ($json[$i]) {
         // object
            case '{':
                $i++;
                $result = $assoc ? array() : new stdClass();
                while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                if ($json[$i] === '}') {
                    $i++;
                    return $result;
                }
                while ($i < $n) {
                    $key = self::json_decode_string($json, $i);
                  
                    while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                    if ($json[$i++] != ':') {
                        throw new Exception("Expected ':' on ".($i - 1));
                    }
                  
                    if ($assoc) {
                        $result[$key] = self::json_decode_value($json, $i, $assoc);
                    } else {
                        $result->$key = self::json_decode_value($json, $i, $assoc);
                    }
                    while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                    if ($json[$i] === '}') {
                        $i++;
                        return $result;
                    }
                    if ($json[$i++] != ',') {
                        throw new Exception("Expected ',' on ".($i - 1));
                    }
                    while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                }
                throw new Exception("Syntax error");
                       // array
            case '[':
                $i++;
                $result = array();
                while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                if ($json[$i] === ']') {
                    $i++;
                    return array();
                }
                while ($i < $n) {
                    $result[] = self::json_decode_value($json, $i, $assoc);
                    while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                    if ($json[$i] === ']') {
                    $i++;
                    return $result;
                    }
                    if ($json[$i++] != ',') {
                        throw new Exception("Expected ',' on ".($i - 1));
                    }
                    while ($i < $n && $json[$i] && $json[$i] <= ' ') $i++;
                }
                throw new Exception("Syntax error");
                            // string
            case '"':
                return self::json_decode_string($json, $i);
                // number
            case '-':
                return self::json_decode_number($json, $i);
                // true
            case 't':
                if ($i + 3 < $n && substr($json, $i, 4) === 'true') {
                    $i += 4;
                    return true;
                   }
               // false
            case 'f':
                if ($i + 4 < $n && substr($json, $i, 5) === 'false') {
                    $i += 5;
                    return false;
                }
            // null
            case 'n':
                if ($i + 3 < $n && substr($json, $i, 4) === 'null') {
                    $i += 4;
                    return null;
                }
            default:
             // number
                if ($json[$i] >= '0' && $json[$i] <= '9') {
                     return self::json_decode_number($json, $i);
                } else {
                      throw new Exception("Syntax error");
                };
            }
        }

        private static function json_decode_string($json, &$i)
        {
                $result = '';
                $escape = array('"' => '"', '\\' => '\\', '/' => '/', 'b' => "\b", 'f' => "\f", 'n' => "\n", 'r' => "\r", 't' => "\t");
                $n = strlen($json);
                if ($json[$i] === '"') {
                    while (++$i < $n) {
                        if ($json[$i] === '"') {
                            $i++;
                            return $result;
                        } elseif ($json[$i] === '\\') {
                            $i++;
                            if ($json[$i] === 'u') {
                                $code = "&#".hexdec(substr($json, $i + 1, 4)).";";
                                $convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
                                $result .= mb_decode_numericentity($code, $convmap, 'UTF-8');
                                $i += 4;
                            } elseif (isset($escape[$json[$i]])) {
                                $result .= $escape[$json[$i]];
                            } else {
                                break;
                            }
                        } else {
                            $result .= $json[$i];
                        }
                    }
                }
              throw new Exception("Syntax error");
        }

        public static function json_decode_number($json, &$i)
        {
                $result = '';
                if ($json[$i] === '-') {
                    $result = '-';
                    $i++;
                }
                $n = strlen($json);
                while ($i < $n && $json[$i] >= '0' && $json[$i] <= '9') {
                    $result .= $json[$i++];
                }
                
                if ($i < $n && $json[$i] === '.') {
                    $result .= '.';
                    $i++;
                    while ($i < $n && $json[$i] >= '0' && $json[$i] <= '9') {
                        $result .= $json[$i++];
                    }
                }
                if ($i < $n && ($json[$i] === 'e' || $json[$i] === 'E')) {
                    $result .= $json[$i];
                    $i++;
                    if ($json[$i] === '-' || $json[$i] === '+') {
                        $result .= $json[$i++];
                    }
                    while ($i < $n && $json[$i] >= '0' && $json[$i] <= '9') {
                        $result .= $json[$i++];
                    }
                }
            
            
                if(strlen($result) <= 9){
                     return (0 + $result); 
                } else {
                     return ($result);  
                }
        }    
   
}



================================================================================
ФАЙЛ: lib/social/social.php
================================================================================

<?php
/**
 * Фабрика для работы с API соц. сетей
 */
class Social {
	public static $authAPI = NULL;
	
	const errorConnectionTimeout = - 107;
	const errorUnknown = - 108;
	const errorAppDisabled = - 109;
	const errorUnknownMethod = - 110;
	const errorSig = - 111;
	const errorAuth = - 112;
	const errorTooManyRequest = - 113;
	const errorInvRequest = - 114;
	const errorInvUserId = - 115;
	const errorInvVotes = - 116;
	const errorPermDenied = - 117;
	const errorNotEnoughUserVotes = - 118;
	const errorNotEnoughAppVotes = - 119;
	const errorInvMessage = - 120;
	const errorInit = - 121;
	//https://api.vk.com/method/getProfiles?uid=46104264&client_secret=hz8sPcPyvrSrfuai86yJ&random=46104264&timestamp=155463215?access_token=8680ac058680ac0586d056b06986abace5886808680ac054e12d823a0aa1beb
	/**
	 * Получение экземпляра класса для работы с API
	 * @param string $name имя соц. сети
	 * @param string $apiId ID приложения
	 * @param string $apiSecret секретный ключ для общения с API
	 * @param string $userId ID пользователя
	 * @return Object
	 */
	public static function get($name, $apiId, $apiSecret, $userId = 0) 
    {
		$className = strtolower ( $name ) . 'Driver';
		if (! class_exists ( $className, false )) 
        {
			if (include ('social/' . $className . '.php')) 
            {
				if (! class_exists ( $className, false )) 
                {
					throw new Exception ( '', social::errorInit );
				}
			} 
            else 
            {
				throw new Exception ( '', social::errorInit );
			}
		}
		return new $className ( $apiId, $apiSecret, $userId );
	}
}

errors::$desc = array_merge ( errors::$desc, array (social::errorConnectionTimeout => 'Не удалось подключится к API', social::errorUnknown => 'Неизвестная ошибка API', social::errorAppDisabled => 'Приложение не активно', social::errorUnknownMethod => 'Попытка вызова неизвестного метода API', social::errorSig => 'Неправильная подпись запроса', social::errorAuth => 'Ошибка аторизации', social::errorTooManyRequest => 'Слишком много запросов в секунду', social::errorInvRequest => 'Неправильный запрос', social::errorInvUserId => 'Неправильный идентификатор пользователя', social::errorInvVotes => 'Неправильное количество голосов', social::errorPermDenied => 'Доступ к голосам запрещен', social::errorNotEnoughUserVotes => 'У пользователя не хватает голосов для данного действия', social::errorNotEnoughAppVotes => 'У приложения не хватает голосов для данного действия', social::errorInvMessage => 'Неправильное сообщение', social::errorInit => 'Ошибка инициализации API' ) );

================================================================================
ФАЙЛ: lib/social/abstractDriver.php
================================================================================

<?php
/**
 * Абстрактный класс драйвера работы с API соц. сетей
 */
abstract class abstractDriver {
	protected $userId;
	protected $appId;
	protected $apiSecret;
	protected $networkId;
	
	/**
	 * @param string $apiId ID приложения
	 * @param string $apiSecret секретный ключ для общения с API
	 * @param string $userId ID пользователя
	 */
	public function __construct($appId, $apiSecret, $userId = 0) 
    {
		$this->appId = $appId;
		$this->userId = $userId;
		$this->apiSecret = $apiSecret;
	}
	
	public function setUserId($userId) {
		$this->userId = $userId;
	}
	
	abstract public function checkAuth($auth_key);
	
	/**
	 * Посылка запроса API
	 * @param array $args переменные которые передадутся в запросе
	 * @return mixed
	 */
	//abstract protected function sendRequest($args = array());
	

	/**
	 * Обработка ошибок
	 * @param integer $errorCode код ошибки
	 * @return mixed
	 */
	abstract protected function processError($errorCode);
	
	public function getUserId($withNetworkId = false) {
		return ($withNetworkId ? $this->networkId : '') . $this->userId;
	}
}

================================================================================
ФАЙЛ: lib/social/vkDriver.php
================================================================================

<?php
/**
 * Драйвер для работы с API vkontakte.ru
 */
if (! class_exists ( 'abstractDriver' ))
    require 'abstractDriver.php';
class vkDriver extends abstractDriver {
    
    public function __construct($appId, $apiSecret, $userId = 0) 
    {
        parent::__construct ( $appId, $apiSecret, $userId );
        $this->networkId = 1;
    }
    
    /**
     * Вычисление подписи запроса
     * @param array $args массив переменных
     * @return string
     */
    protected function createSig($args = array()) 
    {
        ksort ( $args );
        $str = '';
        foreach ( $args as $k => $v ) {
            $str .= $k . "=" . $v;
        }
        return md5 ( $str . $this->apiSecret );
    }
    
    public function buyGold($id_user, $count, $price) 
    {
        //$count - votes
        //$price - gold
       
        $votes = $this->withdrawVotes ( $count );
       
        if($votes == -4 )
        {
            return array('result' => -4, "text" => 'uids error in withdraw');
        }
        else if($votes == -5 )
        {
            return array('result' => -5, "text" => 'response error');     
        }
        else if($votes == -6 )
        {
            return array('result' => -6, "text" => 'some response error');     
        }
              
          if ($votes == $count) 
        {
             $user = Model::factory ( 'user', $this->getUserId () );
               
             Model::factory('user', $id_user)->buyGold ( $price, $count);
            return array('result' => 1, "gold" => $price);    
            
        } 
        else 
        {
            return array('result' => -7, "text" => 'error unknown');      
            //errors::exc ( errors::errorUnknown );
        }
    
    }
        
    public function test()
    {
       LOG::printText("sendRequest"); 
       
       $uids = 3074750;
       //$friends = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       //$friends = $this->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       
       
       
       $uids = array(147784953);   //кокорев
      // $uids = implode ( ",", $uids );
      
       $message = 'text';
       
       $result = social::$authAPI->sendNotif($uids, $message);  
       //$result = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
       
       
        
       //$uids = 3074750;
       //$friends = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       
       return $result;  
    }
    
    
    public function  getFriends($id_user)
    {
        $out = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $id_user));   
        return $out['response'];
    }
    
    
    public function sendNoticeToAll($massage)   
    {
        ignore_user_abort ();
        set_time_limit ( 30 );
        
        $aUids = array();
        $listUser = Model::factory('user')->getList(array(), array('id'));
        
        $listCount = count($listUser);
        for($i = 0; $i < $listCount; $i++)
        {  
             $aUserBuf = $listUser[$i];
             $id_user = $aUserBuf["id"];
             LOG::printText("user_list[$i]:$id_user");
             $aUids[] = $id_user;
        }
        
        //$chunks = array_chunk ( $rows, 100 );
       /*
       while ( $chunk = array_shift ( $chunks ) ) {
       set_time_limit ( 30 );
       $res = $social->sendNotification ( $chunk, $text );
       if (is_array ( $res )) {
       foreach ( $res as $id ) {
            $q2 = "INSERT INTO `user_notify` SET `status`='1',`type` = 1,`id`=1{$id}";
            DBAccess::query($q2);
        }
        $res2 = array_diff ( $chunk, $res );
        foreach ( $res2 as $id ) {
            $q2 = "INSERT INTO `user_notify` SET `status`='0',`type` = 1,`id`=1{$id}";
            DBAccess::query($q2);
        }
    } else {
        echo ("Error: " . $res);
    }
    file_put_contents ( SConfig::$root_dir . 'tmp/notify.lock', time () );
    sleep ( 1 );
}
       */ 
       return $aUids;
    }  
    
    
    public function sendAll($text, $priority) 
    {
        //чистить кеш
        $result = array();
        $result["res"] = array();
        $db = DBAccess::getDB ();
        $offset = 0;
        ignore_user_abort ();
       
        //удаляем предыдущие логи 
        //$q5 = "delete FROM `user_notification`";
        //DBAccess::query($q5);
        
                 
        while ( true ) 
        {
            set_time_limit ( 30 );
            $st1 = $db->prepare ( 'SELECT id FROM users LIMIT 10000 OFFSET ' . $offset );
            $st1->execute ();
            
            $users = $st1->fetchAll ( PDO::FETCH_ASSOC );
            
            if (count ( $users ) == 0)
                break;
            
            //------------------------------------------------------------------------------------------------------------------------------------
            $chunks = array_chunk ( $users, 100 );   //разбиваем на части по 100 элементов
            
            $result['chunks_0'] = $chunks;   
            
            while ( $chunk = array_shift ( $chunks ) ) 
            {
                 set_time_limit ( 120 );
                
                 $uids_chunk = array();
                 foreach ( $chunk as $value )
                 {
                     $uids_chunk[] = $value['id'];
                     $iii = $value['id'];
                 }
                 
                 
                 $res = social::$authAPI->sendNotif($uids_chunk, $text);  
                 $result["res"][] = $res;
                 //------------------------------------------------------------
                 if (is_array ( $res )) 
                 {
                     $iCount = count($res);
                     foreach ( $res as $id ) 
                     {
                        if(count($res) != 0)
                        {
                            $today = date("Y.m.d H:i:s"); 
                           // $q2 = "INSERT INTO `user_notification` SET `time`='".$today."',`status`='1',`type` = 1,`id`={$id}";    
                           // DBAccess::query($q2);
                           LOG::printText("vkontakteDriver| sendAll || time=$today, id_user=$id, status = 1");   
                        }
                     }
                     
                     $res2 = array_diff ( $uids_chunk, $res );
                     
                     $iCount = count($res2);
                       
                     foreach ( $res2 as $id ) 
                     {
                        if(count($res2) != 0)
                        {
                            $today = date("Y.m.d H:i:s");  
                            // $q2 = "INSERT INTO `user_notification` SET `time`=".$today.",`status`='0',`type` = 1,`id`=1{$id}";
                            //$q2 = "INSERT INTO `user_notification` SET `time`='".$today."',`status`='0',`type` = 1,`id`={$id}";    
                            //DBAccess::query($q2);
                            LOG::printText("vkontakteDriver| sendAll || time=$today, id_user=$id, status = 0"); 
                        }
                     }
                 }
                 else 
                 {
                      //echo ("Error: " . $res);
                 }
             sleep ( 1 );
             
             //--------------------------------------------------------------------------------------------------
             $count = count($chunks);
             $count = count($users);
             
             $result['users_'] = $users;
             $result['chunks_'] = $chunks;
             //--------------------------------------------------------------------------------------------------
            }
        $offset += 10000;  
        }
        return $result;
    }
    
    public function setUserLevel($id_user, $level){
        try{
              $out = $this->sendRequest ( array ("method" => "secure.setUserLevel", "uid" => $id_user, "level" => $level ) );
              return 1;
        } catch ( Exception $e ){
            $test = $e->getMessage(); 
            return -1000;
        }
    }
                
    public function sendHello($id_user)
    {
          LOG::printText('<--------------------------------------------------------------------------------------');
          LOG::printText("sendHello:$id_user");
        
          $listUser = Model::factory('user')->getList(array("id" => $id_user), array("name"));  
          $aUser = $listUser['0']; 
          $sUser = $aUser['name'];
          $array = explode(' ', $sUser);
          $sFirstName = $array[0];
          
          $message = "Hi, $sFirstName :)";    
         
                // LOG::printText("message:$message");    
         
          $uids = array($id_user);
          $uids = implode ( ",", $uids );
          //$message = "Уважаемые игроки, произашло обнавление игры! теперь вы можетебе: ляляля, а еще тратата. пурум пум пум";
          
          //$this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
          
          $out = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => "147784953", "message" => "Text1" ) );
          
          LOG::printText('-------------------------------------------------------------------------------------->');  
      
         //---------------------------------------------------------------------------------------
        return $out['response'];
    }  
    
     protected function sendRequest($args = array()) 
    {          

            //LOG::printText('sendRequest');                
        $request = array ();
        ////$request ['api_id'] = $this->appId;
        ////$request ['v'] = "3.0";
        $request ['timestamp'] = time ();
        $request ['random'] = rand ( 0, 999999 );
        ////$request ['format'] = "JSON";
               // $request['client_id'] = '2632132';
                
                //////////////////////////////////////////////////////////////////////////////////////////////
                //как получить access_token
                //////////////////////////////////////////////////////////////////////////////////////////////
                $request['client_secret'] = CLIENT_SECRET;
                $request['access_token']  = ACCESS_TOKEN;
      
                 //пока так, потом сделать в инициализации сервера получения ключа ссессии
                //$request = array_merge ( $request, $args );
     
        /////$request ['sig'] = $this->createSig ( $request );
        
        
        //$example = "https://api.vk.com/method/secure.sendNotification?uid=46104264&message=test&random=46104264&timestamp=155463215&&client_secret=z7Y3nFvHIQOTZDGEvc6Q&access_token=f91c3551f91c3551f94ccfe4a8f93735b1ff91cf91c3551b7701c5e304cc05d";
        //$example = "https://api.vk.com/method/secure.sendNotification?uid=46104264&message=test&random=46104264&timestamp=155463215&&client_secret=xgt8zmZQdod7jVENVnAN&access_token=d31d0dc5d31d0dc5d34df77022d3352401dd31dd31d0dc594ce7078077a192e";
        $example = "https://api.vk.com/method/secure.getAppBalance?random=46104264&timestamp=155463215&&client_secret=z7Y3nFvHIQOTZDGEvc6Q&access_token=f91c3551f91c3551f94ccfe4a8f93735b1ff91cf91c3551b7701c5e304cc05d";
    
    
        //"https://api.vk.com/method/secure.getAppBalance?random=46104264&timestamp=155463215&client_secret=z7Y3nFvHIQOTZDGEvc6Q&access_token=f91c3551f91c3551f94ccfe4a8f93735b1ff91cf91c3551b7701c5e304cc05d"
       // "timestamp=1332592207&random=361816&client_secret=xgt8zmZQdod7jVENVnAN&access_token=d31d0dc5d31d0dc5d34df77022d3352401dd31dd31d0dc594ce7078077a192e&method=secure.getAppBalance"
        
       // random=46104264
        //random=361816
        
        
        //---------------------------------------
        ///////$pice = array();
        ///////foreach($request as $k=>$v) {
        ///////    $pice[] = $k.'='.urlencode($v);
        ///////}
        
        ///////$Param = implode('&',$pice);
        
        //$query = 'api.vk.com/api.php'.'?'.$Param;
        //$query = 'https://api.vk.com/method/'.$args['method'].'?'.$Param;
        // LOG::printText("query:$query");              
        $ch = curl_init ();
        ////$a = curl_setopt ( $ch, CURLOPT_URL, "http://api.vk.com/api.php" );
        
        //$a = curl_setopt ( $ch, CURLOPT_URL, "https://api.vk.com/method/secure.sendNotification?uids=3074750&message=%D0%98%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D0%B8%D1%8F+%D0%BA+%D1%80%D0%B0%D0%B7%D0%BC%D1%8B%D1%88%D0%BB%D0%B5%D0%BD%D0%B8%D1%8E&timestamp=1332761480&random=89630&client_secret=xgt8zmZQdod7jVENVnAN&access_token=d31d0dc5d31d0dc5d34df77022d3352401dd31dd31d0dc594ce7078077a192e" );
        
        
        
        $piceArgs = array();
        
        foreach($args as $k=>$v) {
       //     LOG::printText("a555:$k");   
       //     LOG::printText("a555:$v");   
            if($k != 'method')
            {
                 $piceArgs[] = $k.'='.urlencode($v);
            }
        }
        $http_query = "";  
      
        if(count($piceArgs) != 0)
        {
            $ParamArgs = implode('&',$piceArgs);
            $http_query = $args['method'].'?'.$ParamArgs.'&'.http_build_query ( $request );
        //     LOG::printText("a2:$http_query");     
        }
        else
        {
            $http_query = $args['method'].'?'.http_build_query ( $request );   
        //   LOG::printText("a3:$http_query");      
        }
        
        //LOG::printText("http_query:$http_query");   
        $a = curl_setopt ( $ch, CURLOPT_URL, "https://api.vk.com/method/".$http_query );
        
       
        
        //$b = curl_setopt ( $ch, CURLOPT_POST, 1 );    
       
        $d = curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        //    LOG::printText("d:$d"); 
        $e = curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
        //    LOG::printText("e:$e"); 
        $f = curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );            
        //    LOG::printText("f:$f"); 
            
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        //---------------------НАСТРОЙКИ ПРОКСИ--------------------
        //$proxy = 'http://proxy.tsure.ru:3128';
        //curl_setopt($ch, CURLOPT_PROXY, $proxy);
        //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
        //curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'jvv:chejvvhov1');
        //---------------------------------------------------------
         
        $result = curl_exec ( $ch );
        
        //LOG::printArray("result", $result);
        
        $error1 = curl_getinfo($ch);
        $error2 = curl_errno ($ch);
        $error3 = curl_error($ch);
        
           // LOG::printArray("error1",$error1);
           // LOG::printVar("error2",$error2);
           // LOG::printVar("error3",$error3);
        
        curl_close ( $ch );
        
        //$arr = json_decode ( $result, true );  
        //LOG::printArray("$arr",$arr);  
        
        if ($result) 
        {
            return json_decode ( $result, true );
        } 
        else 
        {
            LOG::printText("vkontacteDriver || social::errorConnectionTimeout");
            //throw new Exception ( '', social::errorConnectionTimeout );
        }
    }
    
    public function checkAuth($auth_key) 
    {
        return 1;
        return $auth_key == md5 ( $this->appId . '_' . $this->userId . '_' . $this->apiSecret );
    }
    
   
    
    protected function processError($errorCode) 
    {
        switch ($errorCode) 
        {
            case 1 :
                $exceptionCode = social::errorUnknown;
                break;
            case 2 :
                $exceptionCode = social::errorAppDisabled;
                break;
            case 3 :
                $exceptionCode = social::errorUnknownMethod;
                break;
            case 4 :
                $exceptionCode = social::errorSig;
                break;
            case 5 :
                $exceptionCode = social::errorAuth;
                break;
            case 6 :
                $exceptionCode = social::errorTooManyRequest;
                break;
            case 8 :
                $exceptionCode = social::errorInvRequest;
                break;
            case 113 :
                $exceptionCode = social::errorInvUserId;
                break;
            case 120 :
                $exceptionCode = social::errorInvMessage;
                break;
            case 151 :
                $exceptionCode = social::errorInvVotes;
                break;
            case 500 :
                $exceptionCode = social::errorPermDenied;
                break;
            case 501 :
                $exceptionCode = social::errorNotEnoughAppVotes;
                break;
            case 502 :
                $exceptionCode = social::errorNotEnoughUserVotes;
                break;
            default :
                $exceptionCode = social::errorUnknown;
                break;
        }
        throw new Exception ( '', $exceptionCode );
        return;
    }
    
    /**
     * Получение баланса пользователя в приложении
     * @param integer $uid ID пользователя
     * @return float
     */
    public function getBalance($uid = 0) 
    {
        $uid = $uid ? $uid : $this->userId;
        if (! $uid) {
            $this->processError ();
            return false;
        }
        $result = $this->sendRequest ( array ('method' => 'secure.getBalance', 'uid' => $uid ) );
        if ($result && ! isset ( $result ['error'] )) {
            return $result ['response'] / 100;
        } else {
            if (is_array ( $result ))
                $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
    
    /**
     * Получение баланса приложения
     * @return float
     */
    public function getAppBalance() 
    {
        $result = $this->sendRequest ( array ('method' => 'secure.getAppBalance' ) );
        if ($result && ! isset ( $result ['error'] )) {
            return $result ['response'] / 100;
        } else {
            if (is_array ( $result ))
                $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
    
    /**
     * Списание голосов с пользователя
     * @param integer $votes Количество голосов
     * @param integer $uid ID пользователя
     * @return float
     */
    public function withdrawVotes($votes, $uid = 0) 
    {
             LOG::printText("withdrawVotes: votes:$votes");
        $uid = $uid ? $uid : $this->userId;
             LOG::printText("withdrawVotes: uid:$uid"); 
        
        if (! $uid) 
        {
            return -4;  
            // $uid error
            // $this->processError ();
        }
        
        $result = $this->sendRequest ( 
                                       array ('method' => 'secure.withdrawVotes', 
                                             'votes'  => $votes * 100, 
                                             'uid'    => $uid ) );
                        
        if ($result && ! isset ( $result ['error'] )) 
        {
            return $result ['response'] / 100;
        } else 
        {
            if (is_array ( $result ))
            {
               return -5;
               //response error   
               //$this->processError ( $result ['error'] ['error_code'] );
             
            }   
            return -6;
            //response error
            //return false;  
          }    
    }
    
    /**
     * Добавление голосов пользователю
     * @param integer $votes Количество голосов
     * @param integer $uid ID пользователя
     * @return float
     */
    public function addVotes($votes, $uid = 0) 
    {
        $uid = $uid ? $uid : $this->userId;
        if (! $uid) {
            $this->processError ();
            return false;
        }
        $result = $this->sendRequest ( 
                array ('method' => 'secure.addVotes', 'votes' => $votes * 100, 'uid' => $uid ) );
        if ($result && ! isset ( $result ['error'] )) {
            return $result ['response'] / 100;
        } else {
            if (is_array ( $result ))
                $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
    
    /**
     * Посылка уведомления пользователям     
     * @param array $uids ID пользователе
     * @param string $message текст уведомления
     * @return array
     */
    public function sendNotification(Array $uids, $message) 
    {
        return true;
                                          
        $uids = implode ( ",", $uids );
        $result = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
                        
        if ($result && ! isset ( $result ['error'] )) {
            return $result ['response'] != '' ? explode ( ",", $result ['response'] ) : false;
        } else {
            if (is_array ( $result ))
                $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
    
    public function sendNotif(Array $uids, $message) 
    {
        $uids = implode ( ",", $uids );
        //LOG::printText("sendNotif_uids:$uids");
        //LOG::printText("sendNotif_message:$message");
        
        $result = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
                        
        if ($result && ! isset ( $result ['error'] )) 
        {
            LOG::printText("sendNotif_result = 1");    
            return $result ['response'] != '' ? explode ( ",", $result ['response'] ) : false;
        } 
        else 
        {
             LOG::printText("sendNotif_result = 0");   
            //if (is_array ( $result ))
            //    $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
    
    public function getFriendsInApp() 
    {
        return true;
               
                            
        // $result = $this->sendRequest ( array ("method" => "secure.getAppBalance" ) );
         
      //  $result = $this->sendRequest ( array ("method" => "friends.getAppUsers" ) );
      // $result = $this->sendRequest ( array ("method" => "secure.sendNotification", "timestamp" => 13009923321, "random" => 113213123213, "uids" => 3074750, "message" => $message ));    
    
    //$uids = "3074750,129468746";
    $uids = "3074750";




                            $message = "1112345";
        // $result = $this->sendRequest ( array ("method" => "secure.getAppBalance" ) );
        // $result = $this->sendRequest ( array ("method" => "secure.sendNotification" ) ); 
        // $result = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
        //$res1 = $this->sendRequest ( array ("method" => "friends.getAppUsers" ) );
        $res1 = $this->sendRequest ( array ("method" => "users.getGroupsFull" ) );
        // $res2 = $this->sendRequest ( array ("method" => "users.isAppUser", "uid" => 3074750));
        //$jsd = json_decode($res1);
        //$rd = json_encode((string)$res2, true );
         //$decode = json_decode ( $res1, true )
        $sRcount = "!!!^".$rd."";//"Count=". count($rd)."!";
         $result = $this->sendRequest ( array ("method" => "secure.sendNotification", "timestamp" => 13009923321, "random" => 113213123213, "uids" => $uids, "message" => $sRcount ) );
     //$result = $this->sendRequest ( array ("method" => "secure.getBalance", "timestamp" => 13009923321, "random" => 113213123213, "uids" => 3074750) );
     //  $result = $this->sendRequest ( array ("method" => "friends.getAppUsers" ) );
        
        
        
        reset($res1);
        $out = current($res1);
        return array("result" => 1, "myinfo" => $out);        

                        
        if ($result && ! isset ( $result ['error'] )) 
        {
            return $result ['response'] != '' ? explode ( ",", $result ['response'] ) : false;
        } 
        else 
        {
            if (is_array ( $result ))
                $this->processError ( $result ['error'] ['error_code'] );
            return false;
        }
    }
}

================================================================================
ФАЙЛ: lib/social/odDriver.php
================================================================================

<?php
/**
 * Драйвер для работы с API vkontakte.ru
 */
if (! class_exists ( 'abstractDriver' ))
    require 'abstractDriver.php';
class odDriver extends abstractDriver {
    
    public function __construct($appId, $apiSecret, $userId = 0) 
    {
        parent::__construct ( $appId, $apiSecret, $userId );
        $this->networkId = 1;
    }
    
    /**
     * Вычисление подписи запроса
     * @param array $args массив переменных
     * @return string
     */
    protected function createSig($args = array()) 
    {
        ksort ( $args );
        $str = '';
        foreach ( $args as $k => $v ) {
            $str .= $k . "=" . $v;
        }
        return md5 ( $str . $this->apiSecret );
    }
    
    public function buyGold($id_user, $count, $price) 
    {
        //$count - votes
        //$price - gold
       
        $votes = $this->withdrawVotes ( $count );
       
        if($votes == -4 )
        {
            return array('result' => -4, "text" => 'uids error in withdraw');
        }
        else if($votes == -5 )
        {
            return array('result' => -5, "text" => 'response error');     
        }
        else if($votes == -6 )
        {
            return array('result' => -6, "text" => 'some response error');     
        }
              
          if ($votes == $count) 
        {
             $user = Model::factory ( 'user', $this->getUserId () );
               
             Model::factory('user', $id_user)->buyGold ( $price, $count);
            return array('result' => 1, "gold" => $price);    
            
        } 
        else 
        {
            return array('result' => -7, "text" => 'error unknown');      
            //errors::exc ( errors::errorUnknown );
        }
    
    }
        
    public function test()
    {
       LOG::printText("sendRequest"); 
       
       $uids = 3074750;
       //$friends = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       //$friends = $this->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       
       
       
       $uids = array(147784953);   //кокорев
      // $uids = implode ( ",", $uids );
      
       $message = 'text';
       
       $result = social::$authAPI->sendNotif($uids, $message);  
       //$result = $this->sendRequest ( array ("method" => "secure.sendNotification", "uids" => $uids, "message" => $message ) );
       
       
        
       //$uids = 3074750;
       //$friends = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $uids));
       
       return $result;  
    }
    
    
    public function  getFriends($id_user)
    {
        $out = social::$authAPI->sendRequest(array ('method' => 'friends.get', 'uid' => $id_user));   
        return $out['response'];
    }
    
    
    public function sendNoticeToAll($massage)   
    {
        ignore_user_abort ();
        set_time_limit ( 30 );
        
        $aUids = array();
        $listUser = Model::factory('user')->getList(array(), array('id'));
        
        $listCount = count($listUser);
        for($i = 0; $i < $listCount; $i++)
        {  
             $aUserBuf = $listUser[$i];
             $id_user = $aUserBuf["id"];
             LOG::printText("user_list[$i]:$id_user");
             $aUids[] = $id_user;
        }
        
        //$chunks = array_chunk ( $rows, 100 );
       /*
       while ( $chunk = array_shift ( $chunks ) ) {
       set_time_limit ( 30 );
       $res = $social->sendNotification ( $chunk, $text );
       if (is_array ( $res )) {
       foreach ( $res as $id ) {
            $q2 = "INSERT INTO `user_notify` SET `status`='1',`type` = 1,`id`=1{$id}";
            DBAccess::query($q2);
        }
        $res2 = array_diff ( $chunk, $res );
        foreach ( $res2 as $id ) {
            $q2 = "INSERT INTO `user_notify` SET `status`='0',`type` = 1,`id`=1{$id}";
            DBAccess::query($q2);
        }
    } else {
        echo ("Error: " . $res);
    }
    file_put_contents ( SConfig::$root_dir . 'tmp/notify.lock', time () );
    sleep ( 1 );
}
       */ 
       return $aUids;
    }  
    
     public function sendMass($text               = NULL, 
                             $expires            = NULL, 
                             $status             = "PUBLIC", 
                             $gender             = NULL, 
                             $age_range          = NULL, 
                             $birthday_range     = NULL,
                             $city               = NULL,
                             $first_access_range = NULL,
                             $has_email          = NULL)  
    {                                                                                         //LOG::printText('sendRequest');                
        $request = array ();

        $args['method']               = "notifications/sendMass";
        //$request ['method']         = "notifications.sendMass";
        $request ['format']           = "JSON";
        
        if(empty($text)){
            return array( 'result' => '-1', 'text' => 'massage is empty');
        }
        
        if(empty($expires)){
            //expires = one day 
            $expires_time = SConfig::$time + 432000; // 604800 - неделя ;
            //$expires_time = 1415109600; // 604800 - неделя ;
            //$expires_time = 1415455200; // 604800 - неделя ;
            //$expires_time = 1415800800; // 604800 - неделя ;
            //$expires_time = 1416078000; // 604800 - неделя ;
