Файл: OctobirdClient.php
Строк: 229
<?php
/**
*
* @author Vitaly Gridasov <support@octobird.com>
*/
class OctobirdClient {
const VERSION = 'php_2.0';
const HTML_LABEL = '<!-- fe34er3 -->';
const SERVER_URI = 'http://show.octobird.com/show.php';
const CONNECTION_TIMEOUT_MS = 1000;
const TIMEOUT_MS = 1000;
const TYPE_BANNER_IMAGE = 1;
const TYPE_BANNER_TEXT = 2;
const DISALLOW = 0;
const ALLOW = 1;
/**
*
* @var OctobirdClient
*/
private static $_instance = null;
protected $is_initialized = false;
protected $site_id,
$unique_id,
$number = null,
$type = null,
$blocks = array(),
$timeout = self::TIMEOUT_MS,
$connection_timeout = self::CONNECTION_TIMEOUT_MS,
$default_block = '';
protected $configuration_params = array('number', 'type', 'blocks', 'timeout', 'connection_timeout');
protected $ads = array();
protected function __construct() {
}
/**
* Настройка клиента
*
* Пример настроек
* <code>
* $configuration = array(
* 'site_id' => 568,
* 'unique_id' => 'f54ggghj6pfg',
* 'alarm' => OctobirdClient::ALLOW,
* 'number' => 5,
* 'type' => OctobirdClient::TYPE_BANNER_IMAGE | OctobirdClient::TYPE_BANNER_TEXT,
* 'blocks' => array(
* 'top' => array(
* 'number' => 1,
* 'type' => OctobirdClient::TYPE_BANNER_TEXT
* ),
* 'bottom' => array(
* 'number' => 2,
* 'type' => OctobirdClient::TYPE_BANNER_IMAGE
* )
* )
* ));
* </code>
*
* @param array $configuration
* @return OctobirdClient
*/
public function initialize($configuration) {
if (!is_array($configuration)) {
throw new OctobirdClientException('Для инициализации нужно передать настройки в массиве');
}
if (empty($configuration['site_id'])) {
throw new OctobirdClientException('Не указан site_id');
}
$this->site_id = $configuration['site_id'];
if (empty($configuration['unique_id'])) {
throw new OctobirdClientException('Не указан unique_id');
}
$this->unique_id = $configuration['unique_id'];
//необязательные параметры
foreach ($this->configuration_params as $param) {
if (!empty($configuration[$param])) {
$this->{$param} = $configuration[$param];
}
}
$this->is_initialized = true;
return $this;
}
/**
*
* @return OctobirdClient
*/
public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function sendRequest() {
$this->checkInitialized();
$url = self::SERVER_URI;
$data = $this->getData();
$headers = array(
'User-Agent: OctobirdClient/2.1 php',
'X-Adsformobi-Id-Site: ' . $this->site_id,
'Content-Type: application/x-www-form-urlencoded',
'Connection: Close'
);
if (function_exists('curl_init')) {
$response = $this->curlRequest($url, $data, $headers);
} else {
$response = $this->fsockopenRequest($url, $data, $headers);
}
$this->parseResponse($response);
return $this;
}
public function get($block_id = null, $default = null) {
if(is_null($default)){
$default = $this->default_block;
}
if($block = $this->_get($block_id)){
return $block;
}else{
return $default . self::HTML_LABEL;
}
}
private function _get($block_id = null){
if (!count($this->ads) || ($block_id && empty($this->ads[$block_id])))
return false;
$ads = '';
if ($block_id) {
$ads = $this->ads[$block_id];
} else {
$ads = current($this->ads);
}
if(trim($ads) == self::HTML_LABEL){
return false;
}else{
return $ads;
}
}
public function has($block_id = null){
if($this->_get($block_id)){
return true;
}else{
return false;
}
}
/**
* Устанавливаем рекламный блок по умолчанию, при отсуствии рекламы
*
* @param string $html
* @return OctobirdClient
*/
public function setDefaultBlock($html){
$this->default_block = $html;
return $this;
}
protected function checkInitialized() {
if (!$this->is_initialized) {
throw new OctobirdClientException('Не указаны настройки');
}
}
protected function parseResponse($response) {
if (empty($response))
return;
list($header, $content) = explode("rnrn", $response, 2);
if (false === strpos($content, self::HTML_LABEL))
return;
try {
$ads = @json_decode($content, true);
if (is_array($ads)) {
$this->ads = $ads;
}
} catch (Exception $e) {
}
}
private function curlRequest($url, $data, $headers) {
$ch = curl_init($url);
unset($headers[2]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, $this->timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connection_timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
return $response;
}
private function fsockopenRequest($url, $data, $headers) {
$content = '';
foreach ($data as $k => $v) {
$content .= $k . '=' . urlencode($v) . '&';
}
$content = substr($content, 0, -1);
$crlf = "rn";
$request = 'POST ' . parse_url($url, PHP_URL_PATH) . ' HTTP/1.0' . $crlf;
$request .= 'Host: ' . parse_url($url, PHP_URL_HOST) . $crlf;
$request .= join($crlf, $headers) . $crlf;
$request .= 'Content-Length: ' . strlen($content) . $crlf;
$request .= $crlf;
$request .= $content;
$socket = @fsockopen(parse_url($url, PHP_URL_HOST), 80, $errno, $errstr, ceil($this->connection_timeout / 1000));
if ($socket) {
stream_set_timeout($socket, ceil($this->timeout / 1000));
fwrite($socket, $request);
$meta = stream_get_meta_data($socket);
$response = '';
while (!feof($socket) && !$meta['timed_out']) {
$response .= fread($socket, 256);
$meta = stream_get_meta_data($socket);
}
fclose($socket);
if (!$meta['timed_out']) {
return $response;
}
}
return null;
}
private function getData() {
$data = array(
'ip' => $_SERVER['REMOTE_ADDR'],
'uid' => $this->unique_id,
'type' => $this->type,
'version' => self::VERSION,
);
if(!empty($this->number)){
$data['number'] = $this->number;
}
if (!empty($this->blocks)) {
$data['blocks'] = json_encode($this->blocks);
}
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$data['ua'] = $_SERVER['HTTP_USER_AGENT'];
}
if (!empty($_SERVER['HTTP_REFERER'])) {
$data['referer'] = $_SERVER['HTTP_REFERER'];
}
if (!empty($_SERVER['HTTP_ACCEPT'])) {
$data['accept'] = $_SERVER['HTTP_ACCEPT'];
}
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$data['accept-language'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
}
$protocol = 'http';
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
$protocol .= 's';
$data['request_uri'] = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$http_x = array();
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_X') === 0) {
$key = str_replace('_', '-', strtolower(substr($key, 5)));
$http_x[$key] = $value;
}
}
$data['http_x'] = serialize($http_x);
return $data;
}
}
class OctobirdClientException extends Exception {
}