m7v
5/15/2014 - 8:25 AM

В данном классе реализованы две функции. Публикация на стену и загрузка изображения в альбом.

В данном классе реализованы две функции. Публикация на стену и загрузка изображения в альбом.

<?php

class classVkApi {

  private $user_id;
  private $access_token;
  private $user_agent;

  public function __construct($user_id, $access_token, $imagePath) {
    $this->user_id = $user_id;
    $this->access_token = $access_token;
    $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
    $this->imagePath = $imagePath;
  }

  public function api($method, $param) {
    $res = $this->curlPost("https://api.vkontakte.ru/method/$method?$param&access_token=$this->access_token", array());

    return json_decode($res);
  }

  public function wallMessage($msg, $url) {
    if (is_int($msg[0])) {
      $msg .= '%20' . $msg;
    }
    $msg = str_replace(' ', '%20', $msg);
    $server = $this->api("wall.post", "owner_id=$this->user_id&message=$msg&attachments=$url");
    //print_r($server);
  }

  public function uploadImg($aid, $url, $text) {
    $text = str_replace(' ', '%20', $text);
    $data = array("file1" => "@" . $this->saveImg($url));
    $server = $this->api("photos.getUploadServer", "aid=$aid");
    $res = $this->curlPost($server->response->upload_url, $data);
    $upload = json_decode($res);
    $save = $this->api("photos.save", "caption=$text&aid={$upload->aid}&server={$upload->server}&photos_list={$upload->photos_list}&hash={$upload->hash}");

    return $save->response[0]->id;
  }

  public function saveImg($url) {
    $upload_dir = $this->imagePath;
    $name = 'image.jpg';
    $file = file_get_contents($url);
    $openedfile = fopen($upload_dir . $name, "w");
    fwrite($openedfile, $file);
    fclose($openedfile);

    return $upload_dir . $name;
  }

  private function curlPost($url, $data = array()) {
    if (!isset($url)) {
      return FALSE;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, $this->user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);

    if (count($data) > 0) {
      curl_setopt($ch, CURLOPT_POST, TRUE);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
  }
}