Last active
September 19, 2017 00:35
-
-
Save exileed/9da2badc0b91676ae91aff6a3658763b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Vk { | |
private $vk; | |
private $owner; | |
public function __construct( vk $vk, $user = null, $group = null ) { | |
$this->vk = $vk; | |
if ( ! $user && ! $group ) { | |
throw new \Exception( 'Not found group or user' ); | |
} | |
$this->owner = [ | |
'type' => $user ? 'owner_id' : 'group_id', | |
'value' => $user ? $user : $group, | |
]; | |
$this->owner[ 'value' ] = (int) preg_replace( '/([^\d]+)/', '', $this->owner[ 'value' ] ); | |
} | |
public function post( $text, $img = null ) { | |
if ( $img ) { | |
$img = 'photo'.$this->owner[ 'value' ].'_'.$this->load( $img )->response[ 0 ]->id; | |
} | |
$data = [ | |
'message' => $text, | |
'owner_id' => $this->owner[ 'value' ], | |
]; | |
if ( $img ) { | |
$data[ 'attachments' ] = $img; | |
} | |
if ( $this->owner[ 'type' ] === 'group_id' ) { | |
$data[ 'owner_id' ] = '-' . $data[ 'owner_id' ]; | |
} | |
var_dump($data); | |
die(); | |
$data = $this->vk->get( 'wall.post', $data ); | |
if ( isset( $data->error ) ) { | |
throw new \Exception( $data->error->error_msg ); | |
} | |
return $data; | |
} | |
private function load( $src ) { | |
$photo = (array) $this->getPhoto( $src ); | |
$photo[ $this->owner[ 'type' ] ] = $this->owner[ 'value' ]; | |
$data = $this->vk->get( 'photos.saveWallPhoto', $photo ); | |
return $data; | |
} | |
private function getPhoto( $src ) { | |
$name = __DIR__ . DIRECTORY_SEPARATOR . '1.png'; | |
file_put_contents( $name, file_get_contents( $src ) ); | |
$ch = curl_init( $this->getServer() ); | |
curl_setopt( $ch, CURLOPT_POST, true ); | |
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); | |
curl_setopt( $ch, CURLOPT_HTTPHEADER, [ 'Content-Type: multipart/form-data; charset=UTF-8' ] ); | |
curl_setopt( $ch, CURLOPT_POSTFIELDS, [ | |
'photo' => '@' . $name | |
// 'photo' => new \CURLFile( '/' . $name ), | |
] ); | |
$response = curl_exec( $ch ); | |
curl_close( $ch ); | |
return json_decode( $response ); | |
} | |
private function getServer() { | |
$data = $this->vk->get( 'photos.getWallUploadServer', [ | |
$this->owner[ 'type' ] => $this->owner[ 'value' ], | |
] ); | |
return $data->response->upload_url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment