Часть 11 из 12
Строки: 20001-22000 из 22262
================================================================================

            //$expires_time = 1416423600; // 604800 - неделя ;
            
            $year          = date("Y", $expires_time);
            $month         = date("m", $expires_time);
            $day           = date("d", $expires_time);
            $hour          = date("h", $expires_time);
            $minute        = date("i", $expires_time);

            $expires = $year.".".$month.".".$day." ".$hour.":".$minute;
        }
        
        //вернуть из настроек-------------------------------------
        $request ['application_key']        = APP_KEY;
        //--------------------------------------------------------
        $request ['text']                   = $text;
        $request ['expires']                = $expires;
        if(!empty($status)){
            $request ['status']             = $status;
        }
	if(0){
           if(!empty($gender)){
              $request ['gender']             = $gender;
           } else {
              $request ['gender']             = "MALE";
           }
	}        
	if(!empty($age_range)){
            $request ['age_range']          = $age_range;
        }
        else {
            $request ['age_range']             = "14-65";
            //$request ['age_range']             = "16-55";
            //$request ['age_range']             = "11-17";
        }
        if(!empty($birthday_range)){
            $request ['birthday_range']     = $birthday_range;
        }
        if(!empty($city)){
            $request ['city']                = $city;
        }
        if(!empty($first_access_range)){
            $request ['first_access_range'] = $first_access_range;
        }
        if(!empty($has_email)){
            $request ['has_email']          = $has_email;
        }

        $str = $this->createSig($request);
        $request ['sig'] = mb_strtolower($str, 'UTF-8');
        
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        $ch = curl_init ();
        $piceArgs = array();
        foreach($args as $k=>$v) {
            if($k != 'method' && $k != 'sig')
            {
                 $piceArgs[] = $k.'='.urlencode($v);
            }
        }
        $http_query = "";  
        if(count($piceArgs) != 0)
        {
            $ParamArgs = implode('&',$piceArgs);
            $http_query = $args['method'].'?'.$ParamArgs.'&'.http_build_query ( $request );
        }
        else
        {
            $http_query = $args['method'].'?'.http_build_query ( $request );   
        }
        
        //$a = curl_setopt ( $ch, CURLOPT_URL, "http://api.odnoklassniki.ru/fb.do".$http_query );
        //$a = curl_setopt ( $ch, CURLOPT_URL, "http://api.odnoklassniki.ru/api/".$http_query );
         $a = curl_setopt ( $ch, CURLOPT_URL, "http://api.ok.ru/api/".$http_query );
        $d = curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $e = curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
        $f = curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );            
            
        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 );
        
        $error1 = curl_getinfo($ch);
        $error2 = curl_errno ($ch);
        $error3 = curl_error($ch);
        
        curl_close ( $ch );
        
        if ($result) 
        {
            return json_decode ( $result, true );
        } 
        else 
        {
        }
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
    }
    
    
    public function sendSimple($uid =                NULL,
                               $text               = NULL)  
    {                                                                                         //LOG::printText('sendRequest');                
        $request = array ();

        $args['method']               = "notifications/sendSimple";
        
        $request ['method']         = "notifications.sendSimple";
        //$request ['format']           = "JSON";
        $request ['format']           = "json";
        
        if(empty($text)){
            return array( 'result' => '-1', 'text' => 'massage is empty');
        }
        if(empty($uid)){
            return array( 'result' => '-2', 'text' => 'uid is empty');
        }
        
        //вернуть из настроек-------------------------------------
        $request ['application_key']        = APP_KEY;
        //--------------------------------------------------------
        $request ['text']                   = $text;
        $request ['uid']                    = $uid;
     
        $str = $this->createSig($request);
        ksort ( $request );
        $request ['sig'] = mb_strtolower($str, 'UTF-8');
        //$request ['sig'] = mb_strtoupper($str, 'UTF-8');
        
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        $ch = curl_init ();
        $piceArgs = array();
        foreach($args as $k=>$v) {
            if($k != 'method' && $k != 'sig')
            {
                 $piceArgs[] = $k.'='.urlencode($v);
            }
        }
        $http_query = "";  
        if(count($piceArgs) != 0)
        {
            $ParamArgs = implode('&',$piceArgs);
            //$http_query = $args['method'].'?'.$ParamArgs.'&'.http_build_query ( $request );
            $http_query = '?'.$ParamArgs.'&'.http_build_query ( $request );
        }
        else
        {
            //$http_query = $args['method'].'?'.http_build_query ( $request ); 
            $http_query = '?'.http_build_query ( $request );   
        }
        
        //$a = curl_setopt ( $ch, CURLOPT_URL, "http://api.odnoklassniki.ru/fb.do".$http_query );
        //$a = curl_setopt ( $ch, CURLOPT_URL, "http://api.odnoklassniki.ru/api/".$http_query );
        $a = curl_setopt ( $ch, CURLOPT_URL, "https://api.ok.ru/fb.do".$http_query );
        $d = curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        $e = curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
        $f = curl_setopt ( $ch, CURLOPT_TIMEOUT, 10 );   
        
        //echo ("CURLOPT_URL: " . "https://api.ok.ru/fb.do".$http_query);
        //echo "строка1 \n";
            
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        $result = curl_exec ( $ch );
        
        echo "$uid : $result \n";
                
        $error1 = curl_getinfo($ch);
        $error2 = curl_errno ($ch);
        $error3 = curl_error($ch);
        
        curl_close ( $ch );
        
        if ($result) 
        {
            return json_decode ( $result, true );
        } 
        else 
        {
        }
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
        //----------------------------------------------------------------------------------    
    }
    
    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'];
                     $res = social::$authAPI->sendNotif($value['id'], $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($uid, $message) 
    {
        $result = $this->sendSimple( $uid, $message );
                        
        if ($result && ! isset ( $result ['error'] )) 
        {
            LOG::printText("sendNotif_result = 1");    
            return $result;
        } 
        else 
        {
            LOG::printText("sendNotif_result = 0");   
            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/odnoklassDriver.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)  
    {                                                                                         //LOG::printText('sendRequest');                
        $request = array ();
        ////$request ['api_id'] = $this->appId;
        ////$request ['v'] = "3.0";
        
        $args['method']               = "notifications/sendMass";
        $request ['application_key']  = "CBAGKQABABABABABA";
        $request ['text']             = $text;
        $request ['expires']          = "2013.07.05 12:00";
        $request ['status']          = "PUBLIC";
        $request ['gender']          = "MALE";
        $request ['age_range']        = "10-30";
        
        //-----------------------------------------
        //format=JSON&method=photos.getAlbums
        $request ['method']        = "notifications.sendMass";
        $request ['format']        = "JSON";
        
        ksort ( $request );
        $str = '';
        foreach ( $request as $k => $v ) {
            $str .= $k . "=" . $v;
        }
        
        $apiSecret = "E7A58037D8DB68E3CE552BA6";
        //$request ['sig'] = md5 ( $str . $this->apiSecret );;
        $str             = md5 ( $str . $apiSecret );
        $request ['sig'] = mb_strtolower($str, 'UTF-8'); 
        
         
        
        
        ////$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' && $k != 'sig')
            {
                 $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, " http://api.odnoklassniki.ru/".$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 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/errors.php
================================================================================

<?php
set_error_handler ( "errors::handler" );
class errors {
	public static $errorQueue = array ();
	
	const errorUnknown           = - 1;
    const errorPHPError          = - 2;
	const errorPHPWarning        = - 3;
	const errorPHPNotice         = - 4;
    const errorIncorrectInput    = - 5;
    const errorIncorrectCommand  = - 6;
	const errorException         = - 7;
    const errorNoController      = - 8;
    const errorNoAction          = - 9;
    const errorIncorrectDBValue  = - 10;
    const errorIncorrectOutput   = - 11; 
    const errorUnexpectedEnd     = - 12; 
    const errorLogic             = - 13; 
	
	
	public static $desc = array (self::errorPHPError          => "PHP Error", 
			                     self::errorPHPWarning        => "PHP Warning", 
                                 self::errorPHPNotice         => "PHP Notice", 
                                 self::errorException         => "Exception", 
                                 self::errorIncorrectInput    => "Incorrect input data", 
                                 self::errorIncorrectCommand  => "Incorrect command", 
                                 self::errorNoController      => "Controller not exist", 
			                     self::errorNoAction          => "Action not exist", 
                                 self::errorUnknown           => "Unknow error",
			                     self::errorIncorrectDBValue  => "DB error",
                                 self::errorIncorrectOutput   => "Incorrect output data",
                                 self::errorUnexpectedEnd     => "Unexpected end of function",
                                 self::errorLogic             => "Safety catch",
                                 );
	
	public static function exc($code = 0, $message = '') {
		$back = debug_backtrace ( false );
		if (PRODUCTION) {
			throw new Exception ( $message, $code );
		} else {
			throw new Exception ( 
		    	    $message . ' ' . $back [0] ['file'] . ' - ' . $back [0] ['line'], $code 
                    );
		}
	}
	
	public static function handler($errno, $errstr, $errfile, $errline) {
		switch ($errno) {
			case E_STRICT :
				if (! PRODUCTION) {
			//		notifications::add ( 'Strict', $errstr . ' ' . $errfile . ' ' . $errline );
				}
				return true;
				break;
			case E_NOTICE :
			case E_USER_NOTICE :
				if (! PRODUCTION) {
				//notifications::add ( 'Notice', $errstr . ' ' . $errfile . ' ' . $errline );
				}
				return true;
				break;
			case E_WARNING :
			case E_USER_WARNING :
				$code = errors::errorPHPWarning;
				break;
			case E_ERROR :
			case E_USER_ERROR :
				$code = errors::errorPHPError;
				break;
			default :
				$code = errors::errorUnknown;
				break;
		}
		if (PRODUCTION) {
			throw new ErrorException ( '', $code, $errno, $errfile, $errline );
		} else {
			throw new ErrorException ( 
					htmlspecialchars ( $errstr ) . ' ' . $errfile . ' - ' . $errline, $code, 
					$errno, $errfile, $errline );
		}
	
	}
	
	public static function dictGen() {
		return json_encode ( self::$desc );
	}
    
    public static function return_error() {
        
        
        //errors::$errorQueue [] = array ('', $e->getMessage (), $e->getCode () );
        $viewClass = SConfig::$defaultView . "View";
        $view = new $viewClass ();
        $view->display ( array ('test_error0', 'test_error1', 'test_error3' ) );
        //return json_encode ( self::$desc );
        
    }
}

?>

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

<?php

class CacheAccess {
	private static $mc;
	
	/**
	 * @return Memcached
	 */
	public static function getCache() 
    {        /*
		if (! self::$mc) {
			self::$mc = new Memcached();
			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 = 0) 
    {          /*
		if (defined ( "CACHE_SERVER" )) {
			$mc = self::getCache ();
			return $mc->set ( self::getKey ( $key ), $val, $expire );
		} 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/log.php
================================================================================

<?php

/**
 * Работа с базой данных
 */
class LOG {
	                       
    /**
     * Пишет в лог-файл дату
     * @return bool
     */  
    public static function printLine() {
        /*
        $fh = fopen("1argLog.txt", "a+");
        fwrite($fh, "----------------------------------------------------------------------------\r\n");
        fclose($fh);
        return 1;
        */
    }
    
    
    /**
     * Пишет в лог-файл дату
     * @return bool
     */  
    public static function printDate() {
        
        /*
        $fh = fopen("1argLog.txt", "a+");
       // fwrite($fh, "Date:".date("Y, F, d(D)|h:m:s")."\r\n");
        fwrite($fh, "Date:".date("U: r")."\r\n");
        fclose($fh);
        return 1;
        */
    }
    
    /**
     * Пишет в лог-файл текст
     * @return bool
     */  
    public static function printText($text) {
  
        /*
        $fh = fopen("1argLog.txt", "a+");
        fwrite($fh, "".$text."\r\n");
        fclose($fh);
        return 1;
        */
        
    }
    
    /**
	 * Пишет в лог-файл переменную с пояснением
	 * @param string $text текст пояснения
	 * @param string $var  пкременная 
	 * @return bool
	 */  
	public static function printVar($text,$var) {
	    /*
        $fh = fopen("1argLog.txt", "a+");
        fwrite($fh, "".$text.":".$var."\r\n");
        fclose($fh);
		return 1;
        */
	}
    
    /**
     * Пишет в лог-файл переменную с пояснением
     * @param string $text текст пояснения
     * @param string $var  пкременная 
     * @return bool
     */  
    public static function printArray($text, array $array) {
       /*
       $fh = fopen("1argLog.txt", "a+");      
       fwrite($fh, "array_out:".$text."\r\n");  
       $mass = $array;
            //###-----------------------------------------#
           
            fwrite($fh, "C:".count($mass)."\r\n");
            $i = 0;
            while($i < count($mass))
            {
                fwrite($fh, "C".$i.":".key($mass)."\r\n");
                fwrite($fh, "C".$i.":".current($mass)."\r\n");
                next($mass);
                $i++;
            }
            fclose($fh);
            //###-----------------------------------------#
            //###-----------------------------------------#
        */ 
    }
}

?>

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

<?php
if (! isset ( $root_dir )) {
	$root_dir = realpath ( dirname ( __FILE__ ) . "/.." ) . "/";
}

class SConfig {
	public static $root_dir;
	public static $logs_dir;
	public static $app_dir;
	public static $conf_dir;
	public static $htdocs_dir;
	public static $debug_log_file;
	public static $img_dir;
	public static $img_url;
	public static $time;
	public static $paypal_user;
	public static $paypal_email;
	public static $paypal_password;
	public static $paypal_signature;
	
	public static $defaultView;
	public static $defaultViewTemplate;
    
    public static $test_flag;
    
    public static $session_key_flag;
    public static $log_money_flag;
    public static $request_signature_flag;

	
	public static $social = array ();
}

if (! defined ( "HTDOCS_NAME" )) {
	define ( "HTDOCS_NAME", "htdocs" );
}
if (! defined ( "LOGS_NAME" )) {
	define ( "LOGS_NAME", "logs" );
}
if (! defined ( "APP_NAME" )) {
	define ( "APP_NAME", "app" );
}
if (! defined ( "CONF_NAME" )) {
	define ( "CONF_NAME", "conf" );
}
if (! defined ( "DEFAULT_VIEW" )) {
	define ( "DEFAULT_VIEW", "json" );
}

SConfig::$root_dir = $root_dir;
SConfig::$htdocs_dir = SConfig::$root_dir . HTDOCS_NAME . "/";
SConfig::$conf_dir = SConfig::$root_dir . CONF_NAME . "/";
SConfig::$logs_dir = SConfig::$root_dir . LOGS_NAME . "/";
SConfig::$app_dir = SConfig::$root_dir . APP_NAME . "/";
SConfig::$debug_log_file = SConfig::$logs_dir . "sdebug.log";
SConfig::$img_dir = SConfig::$htdocs_dir . 'img/';
SConfig::$img_url = '/img/';
SConfig::$time = time();

SConfig::$defaultView = DEFAULT_VIEW;

class SMail {
	public static $fromemail;
	public static $fromname;
	
	public static function send($email, $name, $topic, $message) {
		$hdrs = "Content-Type: text/plain; charset=UTF-8\r\n";
		$hdrs .= "From: \"=?UTF-8?B?" . base64_encode ( SMail::$fromname ) . "?=\" <" . SMail::$fromemail . ">\r\n";
		if (! empty ( $name )) {
			$hdrs .= "To: \"=?UTF-8?B?" . base64_encode ( $name ) . "?=\" <" . $email . ">\r\n";
		} else {
			$hdrs .= "To: {$email}\r\n";
		}
		
		$topic_c = "=?UTF-8?B?" . base64_encode ( $topic ) . "?=";
		try {
			$r = mail ( $email, $topic_c, $message, $hdrs );
		} catch ( Exception $e ) {
			return false;
		}
		return ( boolean ) $r;
	}
}

abstract class View 
{
	protected $contentType = null;
	protected $tpl = null;
	
	abstract public function fetch($res);
	
	public function __construct($contentType = null, $tpl = null) {
		if ($contentType == null) {
			$this->contentType = "text/plain; charset=utf-8";
		}
	}
	
	public function display($res) {
		header ( "Content-Type: " . $this->contentType );
		echo $this->fetch ( $res );
	}
}

date_default_timezone_set('Europe/Moscow');
require 'config.php';
?>

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

<?php

/**
 * Работа с базой данных
 */
class LOG_CRASH {
                           
    /**
     * Пишет в лог-файл в мазу
     * @return bool
     */  
