Advertisement
Guest User

Untitled

a guest
Oct 17th, 2017
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.92 KB | None | 0 0
  1. <?php
  2. /**
  3. Usage:
  4. require_once 'kclick_client.php';
  5. $client = new KClickClient('http://tds.com/api.php', 'CAMPAIGN_TOKEN');
  6. $client->sendUtmLabels(); # send only utm labels
  7. $client->sendAllParams(); # send all params
  8. $client
  9. ->keyword('[KEYWORD]')
  10. ->execute(); # use executeAndBreak() to break the page execution if there is redirect or some output
  11.  
  12. */
  13. class KClickClient
  14. {
  15. private $_token;
  16.  
  17. const UNIQUENESS_COOKIE = 'uniqueness_cookie';
  18. /**
  19. * @var KHttpClient
  20. */
  21. private $_httpClient;
  22. private $_debug = false;
  23. private $_site;
  24. private $_params = array();
  25. private $_log = array();
  26. private $_excludeParams = array('api_key', 'token', 'language', 'ua', 'ip', 'referrer', 'uniqueness_cookie');
  27. private $_result;
  28.  
  29. const VERSION = 2;
  30. const ERROR = '[KTrafficClient] Something is wrong. Enable debug mode to see the reason.';
  31.  
  32. public function __construct($site, $token)
  33. {
  34. $this->site($site);
  35. $this->token($token);
  36. $this->version(self::VERSION);
  37. $this->fillParams();
  38. }
  39.  
  40. public function fillParams()
  41. {
  42. $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  43. $this->setHttpClient(new KHttpClient())
  44. ->ip($this->_findIp())
  45. ->ua(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null)
  46. ->language((isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : ''))
  47. ->seReferrer($referrer)
  48. ->referrer($referrer)
  49. ->setUniquenessCookie($this->_getUniquenessCookie())
  50. ;
  51. }
  52.  
  53. public function currentPageAsReferrer()
  54. {
  55. $this->referrer($this->_getCurrentPage());
  56. return $this;
  57. }
  58.  
  59. public function debug($state = true)
  60. {
  61. $this->_debug = $state;
  62. return $this;
  63. }
  64.  
  65. public function seReferrer($seReferrer)
  66. {
  67. $this->_params['se_referrer'] = $seReferrer;
  68. return $this;
  69. }
  70.  
  71. public function referrer($referrer)
  72. {
  73. $this->_params['referrer'] = $referrer;
  74. return $this;
  75. }
  76.  
  77. public function setHttpClient($httpClient)
  78. {
  79. $this->_httpClient = $httpClient;
  80. return $this;
  81. }
  82.  
  83. public function setUniquenessCookie($value)
  84. {
  85. $this->_params[self::UNIQUENESS_COOKIE] = $value;
  86. return $this;
  87. }
  88.  
  89. public function site($name)
  90. {
  91. $this->_site = $name;
  92. }
  93.  
  94. public function token($token)
  95. {
  96. $this->_params['token'] = $token;
  97. return $this;
  98. }
  99.  
  100. public function version($version)
  101. {
  102. $this->_params['version'] = $version;
  103. return $this;
  104. }
  105.  
  106. public function ua($ua)
  107. {
  108. $this->_params['ua'] = $ua;
  109. return $this;
  110. }
  111.  
  112. public function language($language)
  113. {
  114. $this->_params['language'] = $language;
  115. return $this;
  116. }
  117.  
  118. public function keyword($keyword)
  119. {
  120. $this->_params['keyword'] = $keyword;
  121. return $this;
  122. }
  123.  
  124. public function ip($ip)
  125. {
  126. $this->_params['ip'] = $ip;
  127. return $this;
  128. }
  129.  
  130. public function sendUtmLabels()
  131. {
  132. foreach ($_GET as $name => $value) {
  133. if (strstr($name, 'utm_')) {
  134. $this->_params[$name] = $value;
  135. }
  136. }
  137. }
  138.  
  139. public function sendAllParams()
  140. {
  141. foreach ($_GET as $name => $value) {
  142. if (empty($this->_params[$name]) && !in_array($name, $this->_excludeParams)) {
  143. $this->_params[$name] = $value;
  144. }
  145. }
  146. }
  147.  
  148. public function saveUniquenessCookie($value)
  149. {
  150. if (!headers_sent()) {
  151. setcookie($this->getCookieName(), $value, $this->_getCookiesExpireTimestamp(), '/', $this->_getCookieHost());
  152. }
  153. $_COOKIE[$this->getCookieName()] = $value;
  154. }
  155.  
  156. public function param($name, $value)
  157. {
  158. if (!in_array($name, $this->_excludeParams)) {
  159. $this->_params[$name] = $value;
  160. }
  161. return $this;
  162. }
  163.  
  164. public function params($value)
  165. {
  166. if (!empty($value)) {
  167. if (is_string($value)) {
  168. parse_str($value, $result);
  169. foreach ($result as $name => $value) {
  170. $this->param($name, $value);
  171. }
  172. }
  173. }
  174.  
  175. return $this;
  176. }
  177.  
  178. public function reset()
  179. {
  180. $this->_result = null;
  181. }
  182.  
  183. public function performRequest()
  184. {
  185. if ($this->_result) {
  186. return $this->_result;
  187. }
  188. $request = $this->_buildRequestUrl();
  189. $this->_log[] = 'Request: ' . $request;
  190. try {
  191. $result = $this->_httpClient->request($request);
  192. $this->_log[] = 'Response: ' . $result;
  193. } catch (KTrafficClientError $e) {
  194. if ($this->_debug) {
  195. throw $e;
  196. } else {
  197. return self::ERROR;
  198. }
  199. }
  200. $this->_result = json_decode($result);
  201. return $this->_result;
  202. }
  203.  
  204. public function execute($break = false, $print = true)
  205. {
  206. $content = $this->getContent();
  207.  
  208. if ($print) {
  209. $this->updateCookies();
  210. $headers = $this->sendHeaders();
  211. echo $content;
  212. } else {
  213. return $content;
  214. }
  215.  
  216. if ($break && (!empty($content) || $this->checkHeadersHasRedirect($headers))) {
  217. exit;
  218. }
  219. }
  220.  
  221. public function checkHeadersHasRedirect($headers)
  222. {
  223. if (empty($headers)) {
  224. return;
  225. }
  226. foreach ($headers as $header) {
  227. if (strpos($header, 'Location:') == 0) {
  228. return true;
  229. }
  230. }
  231. return false;
  232. }
  233.  
  234. public function getContent()
  235. {
  236. $result = $this->performRequest();
  237. $content = '';
  238. if (!empty($result)) {
  239. if (!empty($result->error)) {
  240. $content .= $result->error;
  241. }
  242.  
  243. if (!empty($result->body)) {
  244. $content .= $result->body;
  245. }
  246. }
  247.  
  248. if ($this->_debug) {
  249. $content .= $this->showLog();
  250. }
  251. return $content;
  252. }
  253.  
  254. public function showLog($separator = '<br />')
  255. {
  256. $this->performRequest();
  257. return implode($separator, $this->_log);
  258. }
  259.  
  260. public function getCookieName()
  261. {
  262. return hash('sha1', $this->_site);
  263. }
  264.  
  265. public function executeAndBreak()
  266. {
  267. $this->execute(true);
  268. }
  269.  
  270. public function getParams()
  271. {
  272. return $this->_params;
  273. }
  274.  
  275. public function updateCookies()
  276. {
  277. $result = $this->performRequest();
  278.  
  279. if (!empty($result->info) && !empty($result->info->sub_id)) {
  280. $startSession = (!function_exists('session_status') || !session_status());
  281. if ($startSession && !headers_sent()) {
  282. @session_start();
  283. }
  284. $_SESSION['sub_id'] = $result->info->sub_id;
  285. $_SESSION['subid'] = $result->info->sub_id;
  286. }
  287.  
  288. if (!empty($result->uniqueness_cookie)) {
  289. $this->saveUniquenessCookie($result->uniqueness_cookie);
  290. }
  291. }
  292.  
  293. public function sendHeaders()
  294. {
  295. $result = $this->performRequest();
  296. $headers = [];
  297.  
  298. if (!empty($result->status)) {
  299. http_response_code($result->status);
  300. }
  301.  
  302. if (!empty($result->headers)) {
  303. foreach ($result->headers as $header) {
  304. $headers[] = $header;
  305. if (!headers_sent()) {
  306. header($header);
  307. }
  308. }
  309. }
  310.  
  311. if (!empty($result->contentType)) {
  312. $header = 'Content-Type: ' . $result->contentType;
  313. $headers[] = $header;
  314. if (!headers_sent()) {
  315. header($header);
  316. }
  317. }
  318. return $headers;
  319. }
  320.  
  321. // @deprecated
  322. public function updateHeaders()
  323. {
  324. $this->sendHeaders();
  325. }
  326.  
  327. public function getOffer($params = array())
  328. {
  329. $result = $this->performRequest();
  330. if (empty($result->info->token)) {
  331. $this->_log[] = 'Campaign hasn\'t returned offer';
  332. return 'no_offer';
  333. }
  334. $params['_lp'] = 1;
  335. $params['_token'] = $result->info->token;
  336. return $this->_buildOfferUrl($params);
  337. }
  338.  
  339. public function getSubId()
  340. {
  341. $result = $this->performRequest();
  342. if (empty($result->info->sub_id)) {
  343. $this->_log[] = 'Campaign hasn\'t returned sub_id';
  344. return 'no_subid';
  345. }
  346. return $result->info->sub_id;
  347. }
  348.  
  349. public function isBot()
  350. {
  351. $this->param('info', true);
  352. $result = $this->performRequest();
  353. if (isset($result->info)) {
  354. return isset($result->info->is_bot) ? $result->info->is_bot : false;
  355. }
  356. }
  357.  
  358. public function isUnique($level = 'campaign')
  359. {
  360. $this->param('info', true);
  361. $result = $this->performRequest();
  362. if (isset($result->info) && $result->info->uniqueness) {
  363. return isset($result->info->uniqueness->$level) ? $result->info->uniqueness->$level : false;
  364. }
  365. }
  366.  
  367. public function getBody()
  368. {
  369. $result = $this->performRequest();
  370. return $result->body;
  371. }
  372.  
  373. public function getHeaders()
  374. {
  375. $result = $this->performRequest();
  376. return $result->headers;
  377. }
  378.  
  379. private function _buildOfferUrl($params = array())
  380. {
  381. $request = parse_url($this->_site);
  382. $lastChar = substr($request['path'], -1);
  383. if ($lastChar != '/' && $lastChar != '\\') {
  384. $path = str_replace(basename($request['path']), '', $request['path']);
  385. } else {
  386. $path = $request['path'];
  387. }
  388. $path = ltrim($path, "\\\/");
  389. $params = http_build_query($params);
  390. return "{$request['scheme']}://{$request['host']}/{$path}?{$params}";
  391. }
  392.  
  393.  
  394. private function _getCurrentPage()
  395. {
  396. if ((isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443) || !empty($_SERVER['HTTPS'])) {
  397. $scheme = 'https';
  398. } else {
  399. $scheme = 'http';
  400. }
  401. return $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  402. }
  403.  
  404. private function _buildRequestUrl()
  405. {
  406. $this->param('info', true);
  407. $request = parse_url($this->_site);
  408. $params = http_build_query($this->getParams());
  409. return "{$request['scheme']}://{$request['host']}/{$request['path']}?{$params}";
  410. }
  411.  
  412.  
  413. private function _findIp()
  414. {
  415. $ip = null;
  416. $headers = array('HTTP_X_FORWARDED_FOR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'REMOTE_ADDR');
  417. foreach ($headers as $header) {
  418. if (!empty($_SERVER[$header])) {
  419. $tmp = explode(',', $_SERVER[$header]);
  420. $ip = trim($tmp[0]);
  421. break;
  422. }
  423. }
  424. if (strstr($ip, ',')) {
  425. $tmp = explode(',', $ip);
  426. if (stristr($_SERVER['HTTP_USER_AGENT'], 'mini')) {
  427. $ip = trim($tmp[count($tmp) - 2]);
  428. } else {
  429. $ip = trim($tmp[0]);
  430. }
  431. }
  432.  
  433. if (empty($ip)) {
  434. $ip = $_SERVER['REMOTE_ADDR'];
  435. }
  436.  
  437. return $ip;
  438. }
  439.  
  440. private function _getUniquenessCookie()
  441. {
  442. return !empty($_COOKIE[$this->getCookieName()]) ? $_COOKIE[$this->getCookieName()] : '';
  443. }
  444.  
  445. private function _getCookiesExpireTimestamp()
  446. {
  447. return time() + 60 * 60 * 24 * 31;
  448. }
  449.  
  450. private function _getCookieHost()
  451. {
  452. if (isset($_SERVER['HTTP_HOST']) && substr_count($_SERVER['HTTP_HOST'], '.') < 3) {
  453. $host = '.' . str_replace('www.', '', $_SERVER['HTTP_HOST']);
  454. } else {
  455. $host = null;
  456. }
  457. return $host;
  458. }
  459. }
  460.  
  461. class KHttpClient
  462. {
  463. const UA = 'KHttpClient';
  464.  
  465. public function request($url)
  466. {
  467. $ch = curl_init();
  468. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  469. curl_setopt($ch, CURLOPT_URL, $url);
  470. curl_setopt($ch, CURLOPT_HEADER, 0);
  471. curl_setopt($ch, CURLOPT_NOBODY, 0);
  472. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  473. curl_setopt($ch, CURLOPT_USERAGENT, self::UA);
  474. $result = curl_exec($ch);
  475. if (curl_error($ch)) {
  476. throw new KTrafficClientError(curl_error($ch));
  477. }
  478.  
  479. if (empty($result)) {
  480. throw new KTrafficClientError('Empty response');
  481. }
  482. return $result;
  483. }
  484. }
  485.  
  486. class KTrafficClientError extends \Exception {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement