Guest User

Untitled

a guest
Jul 27th, 2015
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.46 KB | None | 0 0
  1. <?php
  2. class td_social_api {
  3.  
  4.  
  5. private $log_buffer = '';
  6. private $log_last_get_url_page_data = '';
  7.  
  8.  
  9.  
  10.  
  11. //the name of the field in the table that holds the cache array
  12. private $cache_var_name_last_val = 'td_social_api_v3_last_val';
  13.  
  14. private $do_transient_save = false;
  15.  
  16. //the cache holding the last value > 0
  17. public $td_cache_last_val = array();
  18.  
  19.  
  20. function __construct() {
  21. $this->td_cache_last_val = get_option($this->cache_var_name_last_val, '');
  22. $this->log(__FUNCTION__, 'New class instance');
  23. }
  24.  
  25.  
  26. //check to see if we have the cache
  27. private function in_cache($service_id, $user_id) {
  28. //se poate sa dea worning aici cind nu exista array-ul cache in tabela
  29. //echo '<br>'.$service_id. ": ". (time() - $this->td_cache_last_val[$service_id]['timestamp']) .' > ' . $this->td_cache_last_val[$service_id]['expires'].'<br>';
  30. //e pus asa ( < )ca sa dea false la verificare
  31. if (is_array($this->td_cache_last_val) and isset($this->td_cache_last_val[$service_id]['uid']) and $this->td_cache_last_val[$service_id]['uid'] == $user_id and (time() - $this->td_cache_last_val[$service_id]['timestamp'] < $this->td_cache_last_val[$service_id]['expires']) ) {
  32. return true;
  33. } else {
  34. return false;
  35. }
  36. }
  37.  
  38. //extract the value for a service_id, and return it to the service_id function
  39. private function get_cache($service_id, $user_id) {
  40. if (is_array($this->td_cache_last_val) and isset($this->td_cache_last_val[$service_id]['uid']) and $this->td_cache_last_val[$service_id]['uid'] == $user_id) {
  41. return $this->td_cache_last_val[$service_id];
  42. } else {
  43. return false;
  44. }
  45. }
  46.  
  47. //save the cache array to the database
  48. private function save_cache($service_id, $data) {
  49. if($this->do_transient_save == true) {
  50. $this->td_cache_last_val[$service_id] = $data;
  51.  
  52. //update the database
  53. update_option($this->cache_var_name_last_val, $this->td_cache_last_val);
  54. }
  55.  
  56. $this->do_transient_save = false;
  57. }
  58.  
  59.  
  60. public function get_url_wordpress($url) {
  61.  
  62. $this->log(__FUNCTION__, "Fatching url: $url");
  63.  
  64. $response = wp_remote_get($url, array(
  65. 'timeout' => 10,
  66. 'sslverify' => false,
  67. 'user-agent' => 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0'
  68. ));
  69.  
  70. if (is_wp_error($response)) {
  71. $this->log(__FUNCTION__, 'got wp_error, get_error_message: ' . $response->get_error_message());
  72. return false;
  73. }
  74.  
  75. // do not kill at response code != 200, it may still work
  76. if (wp_remote_retrieve_response_code($response) != 200) {
  77. $this->log(__FUNCTION__, 'Response code != 200: ' . wp_remote_retrieve_response_code($response));
  78. }
  79.  
  80. $td_request_result = wp_remote_retrieve_body($response);
  81.  
  82. if ($td_request_result == '') {
  83. $this->log(__FUNCTION__, 'Empty response via wp_remote_retrieve_body, Quitting.');
  84. return false;
  85. }
  86.  
  87.  
  88. $this->log_last_get_url_page_data = $td_request_result;
  89. return $td_request_result;
  90. }
  91.  
  92.  
  93.  
  94. public function get_url_file_get_contents($url) {
  95. $this->log(__FUNCTION__, "Fatching url: $url");
  96.  
  97. $opts = array(
  98. 'http'=>array(
  99. 'method'=>"GET",
  100. 'header'=>"Accept-language: en\r\n" .
  101. "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0\r\n"
  102. )
  103. );
  104. $context = stream_context_create($opts);
  105.  
  106. $td_data = file_get_contents($url, false, $context);
  107.  
  108. if (empty($td_data)) {
  109. $this->log(__FUNCTION__, 'file_get_contents returned empty result');
  110. return false;
  111. } else {
  112. return $td_data;
  113. }
  114.  
  115.  
  116. }
  117.  
  118.  
  119.  
  120. private function get_url_curl($url) {
  121. $this->log(__FUNCTION__, "Fatching url: $url");
  122.  
  123.  
  124. $ch = curl_init();
  125. curl_setopt ($ch, CURLOPT_URL, $url);
  126. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  127. //mergem dupa redirecturi
  128. curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
  129. curl_setopt ($ch, CURLOPT_MAXREDIRS, 3); //max redirects
  130. curl_setopt ($ch, CURLOPT_ENCODING, ''); //folosim compresia - daca e empty trimite toate formele de compresie suportate
  131. //timeout? - 300 sec = 5 min
  132. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10); //Fail if a web server doesn’t respond to a connection within a time limit (seconds).
  133. curl_setopt($ch, CURLOPT_TIMEOUT, 10); //Fail if a web server doesn’t return the web page within a time limit (seconds).
  134. curl_setopt($ch, CURLOPT_HEADER, false);
  135. // misc
  136. curl_setopt($ch,CURLOPT_AUTOREFERER,true); //The referer is a URL for the web page that linked to the requested web page. When following redirects, set this to true and CURL automatically fills in the URL of the page being redirected away from.
  137. curl_setopt($ch,CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0');
  138. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  139. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  140. $data = curl_exec($ch);
  141.  
  142.  
  143.  
  144. $this->log(__FUNCTION__, 'curl_error: ' . curl_error($ch));
  145. $this->log(__FUNCTION__, 'curl_getinfo: ' . curl_getinfo($ch));
  146.  
  147.  
  148. /***************************************************************
  149. * html cache checks
  150. */
  151. $results['data'] = $data;
  152. curl_close($ch);
  153. return $data;
  154. }
  155.  
  156.  
  157. /*
  158. *
  159. */
  160. private function get_url($url) {
  161.  
  162. /*
  163. if( ini_get('safe_mode') ){
  164. echo 'xxxxxxxxxxxx';
  165. }
  166.  
  167.  
  168. if( ini_get('open_basedir') ){
  169. echo 'xxxxxsadsdadsasadxxxxxxx';
  170. }
  171. die;
  172. */
  173. //return $this->get_url_curl($url);
  174.  
  175. return $this->get_url_wordpress($url);
  176. //return $this->get_url_file_get_contents($url);
  177.  
  178.  
  179.  
  180.  
  181.  
  182. }
  183.  
  184. private function get_json($url) {
  185. $td_json = json_decode($this->get_url($url), true);
  186. return $td_json;
  187. }
  188.  
  189. private function extract_numbers_from_string($td_string) {
  190. $buffy = '';
  191. foreach (str_split($td_string) as $td_char) {
  192. if (is_numeric($td_char)) {
  193. $buffy .= $td_char;
  194. }
  195. }
  196. return $buffy;
  197. }
  198.  
  199.  
  200.  
  201. public function get_social_counter($service_id, $user_id, $disable_cache = false) {
  202. $buffy_array = 0;
  203.  
  204.  
  205.  
  206. //use in g+
  207. $expl_maches = '';
  208.  
  209. if ($this->in_cache($service_id, $user_id) === false or $disable_cache === true) { //disable cache here
  210.  
  211. try {
  212. switch ($service_id) {
  213. case 'facebook':
  214.  
  215. $td_data = $this->get_url("http://facebook.com/$user_id");
  216.  
  217. if ($td_data === false) {
  218. $this->log(__FUNCTION__, 'The get_url method FAILED, returning 0');
  219. $buffy_array = 0;
  220. break;
  221. }
  222.  
  223. $pattern = "/id=\"PagesLikesCountDOMID\">(.*?)<\/span><\/span>/i";
  224.  
  225. //first match - get the string with number of likes and the `likes` word
  226. preg_match_all($pattern, $td_data, $matches);
  227.  
  228. //replace all the classes in the sting returned by first regular expression
  229.  
  230. $sub_string = preg_replace('/class=\"(.*?)\"/i', '', $matches[1][0]);
  231.  
  232. //extract only the numbers
  233. $buffy_array = $this->extract_numbers_from_string($sub_string);
  234.  
  235.  
  236.  
  237.  
  238. break;
  239.  
  240. case 'twitter':
  241.  
  242. $twitter_worked = false;
  243.  
  244. //check 1 via https
  245. $td_data = $this->get_url("https://twitter.com/$user_id");
  246.  
  247. if ($td_data === false) {
  248. $this->log(__FUNCTION__, 'The get_url method FAILED, we are trying again via the api');
  249. } else {
  250. $pattern = "/title=\"(.*)\"(.*)data-nav=\"followers\"/i";
  251. preg_match_all($pattern, $td_data, $matches);
  252. if (!empty($matches[1][0])) {
  253. //$td_buffer_counter_fix = str_replace(array('.', ',', ' ', '&nbsp;'), '', htmlentities($matches[1][0])); //old radu hack to filter numbers 2/2/2015
  254. $td_buffer_counter_fix = $this->extract_numbers_from_string(htmlentities($matches[1][0]));
  255.  
  256. // $td_buffer_counter_fix = str_replace(',','', $matches[1][0]);
  257. $buffy_array = (int) $td_buffer_counter_fix;
  258.  
  259. if (!empty($buffy_array) and is_numeric($buffy_array)) {
  260. $twitter_worked = true; //skip twitter second check it worked!
  261. }
  262. }
  263.  
  264. }
  265.  
  266.  
  267.  
  268. //check 2 via twitter api client - we only get here if the first check did not returned anything
  269. if ($twitter_worked === false) {
  270. if (!class_exists('TwitterApiClient')) {
  271. require_once 'twitter-client.php';
  272. $Client = new TwitterApiClient;
  273. $Client->set_oauth (YOUR_CONSUMER_KEY, YOUR_CONSUMER_SECRET, SOME_ACCESS_KEY, SOME_ACCESS_SECRET);
  274. try {
  275. $path = 'users/show';
  276. $args = array ('screen_name' => $user_id);
  277. $data = @$Client->call( $path, $args, 'GET' );
  278. if (!empty($data['followers_count'])) {
  279. $buffy_array = (int) $data['followers_count']; //set the buffer
  280. }
  281. }
  282. catch( TwitterApiException $Ex ){
  283. //twitter rate limit will show here
  284. //print_r($Ex);
  285. }
  286. }
  287. }
  288.  
  289.  
  290. break;
  291.  
  292. case 'vimeo':
  293. //$td_data = @$this->get_json("http://vimeo.com/api/v2/channel/$user_id/info.json");
  294. //if (!empty($td_data['total_subscribers'])) {
  295. // $buffy_array = (int) $td_data['total_subscribers'];
  296. //} else {
  297. $td_data = @$this->get_url("http://vimeo.com/$user_id");
  298. $pattern = "/<b class=\"stat_list_count\">(.*?)<\/b>(\s+)<span class=\"stat_list_label\">likes<\/span>/";
  299. preg_match($pattern, $td_data, $matches);
  300. if (!empty($matches[1])) {
  301. $buffy_array = (int) $matches[1];
  302. }
  303. //}
  304. break;
  305.  
  306. case 'youtube':
  307.  
  308. // // channel string, if it's present it is not necessary for getting data
  309. // $user_id = str_replace("channel/", "", $user_id);
  310. //
  311. // $td_data = @$this->get_json("http://gdata.youtube.com/feeds/api/users/$user_id?alt=json");
  312. // if (!empty($td_data['entry']['yt$statistics']['subscriberCount'])) {
  313. // $buffy_array = (int) $td_data['entry']['yt$statistics']['subscriberCount'];
  314. // }
  315.  
  316.  
  317. $url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&key=AIzaSyBneuqXGHEXQiJlWUOv23_FA4CzpsHaS6I";
  318.  
  319. $search_id = str_replace("channel/", "", $user_id);
  320.  
  321. if (strpos($user_id, "channel/") === 0) {
  322. $url .= "&id=$search_id";
  323. } else {
  324. $url .= "&forUsername=$search_id";
  325. }
  326.  
  327. $td_data = @$this->get_json($url);
  328.  
  329. $subscriberCount = @$td_data['items'][0]['statistics']['subscriberCount'];
  330.  
  331. if (!empty($subscriberCount)) {
  332. $buffy_array = (int) $subscriberCount;
  333. }
  334. break;
  335.  
  336. case 'googleplus':
  337. $td_data = @$this->get_json("https://www.googleapis.com/plus/v1/people/$user_id?key=AIzaSyA1hsdPPNpkS3lvjohwLNkOnhgsJ9YCZWw");
  338. if (!empty($td_data['plusOneCount'])) {
  339. $buffy_array = (int) $td_data['plusOneCount'];
  340. }else{
  341. $td_data = @$this->get_url("https://plus.google.com/$user_id/posts");
  342. $pattern = "/<span role=\"button\" class=\"d-s o5a\" tabindex=\"0\">(.*?)<\/span>/";
  343. preg_match($pattern, $td_data, $matches);
  344. if (!empty($matches[1])) {
  345. $expl_maches = explode(' ', trim($matches[1]));
  346. $buffy_array = str_replace(array('.', ','), array(''), $expl_maches[0]);
  347. }
  348. }
  349. break;
  350.  
  351. case 'instagram':
  352. $td_data = @$this->get_url("http://instagram.com/$user_id#");
  353. //$pattern = "/followed_by\":(.*?),\"follows\":/";
  354. $pattern = "/followed_by\"\:\{\"count\"\:(.*?)\}\,\"/";
  355. preg_match($pattern, $td_data, $matches);
  356. if (!empty($matches[1])) {
  357. $buffy_array = (int) $matches[1];
  358. }
  359. break;
  360.  
  361. case 'soundcloud':
  362. $td_data = @$this->get_json("http://api.soundcloud.com/users/$user_id.json?client_id=97220fb34ad034b5d4b59b967fd1717e");
  363. if (!empty($td_data['followers_count'])) {
  364. $buffy_array = (int) $td_data['followers_count'];
  365. }
  366. break;
  367.  
  368. case 'rss':
  369. $buffy_array = (int) $user_id;
  370. break;
  371. }
  372.  
  373.  
  374. // if the cache is disable, do not run the cache things
  375. if ($disable_cache === true) {
  376. return $buffy_array;
  377. }
  378.  
  379. //case 1; we have response from service; write the cache arrya with new values
  380. if ($buffy_array > 0) {
  381.  
  382. $local_cash['count'] = $buffy_array;
  383. if($buffy_array > 0){
  384. $local_cash['ok_count'] = $buffy_array;
  385. }
  386. $local_cash['timestamp'] = time();
  387. $local_cash['expires'] = 10800;
  388. $local_cash['uid'] = $user_id;
  389.  
  390. //set to true the flag to save
  391. $this->do_transient_save = true;
  392.  
  393. //send the service array to save the cache
  394. $this->save_cache($service_id, $local_cash);
  395.  
  396. /*
  397. * case 2; we DON'T have response from service, then get the cache array for this service,
  398. * and rewrite the array in cache, with default values
  399. */
  400. } else {
  401. $local_cash = $this->get_cache($service_id, $user_id);
  402.  
  403. if (is_array($local_cash) and isset($local_cash['ok_count']) > 0) {
  404. $buffy_array = intval($local_cash['ok_count']);
  405. }else{
  406. $buffy_array = 0;
  407. }
  408.  
  409. $local_cash['timestamp'] = time();
  410. $local_cash['count'] = 0;
  411. $local_cash['uid'] = $user_id;
  412. $local_cash['expires'] = 10800;
  413.  
  414. //set to true the flag to save
  415. $this->do_transient_save = true;
  416.  
  417. //send the service array to save the cache
  418. $this->save_cache($service_id, $local_cash);
  419. }
  420. } catch (Exception $e) {
  421.  
  422. }
  423. return $buffy_array;
  424. //case 3, the cache is true; time < expire
  425. } else {
  426.  
  427. $local_cash = $this->get_cache($service_id, $user_id);
  428.  
  429.  
  430.  
  431. if (is_array($local_cash) and array_key_exists('ok_count', $local_cash)) {
  432. $this->log(__FUNCTION__, "$service_id - $user_id found in cache (ok_count): " . intval($local_cash['ok_count']));
  433. return intval($local_cash['ok_count']);
  434. } else {
  435. $this->log(__FUNCTION__, "$service_id - $user_id found in cache but the cache is empty or something");
  436. return 0;
  437. }
  438. }
  439. }
  440.  
  441.  
  442.  
  443.  
  444. private function log($function_name, $message) {
  445. $this->log_buffer .= str_pad($function_name, 30, '.') . " - $message <br>";
  446. }
  447.  
  448.  
  449. function get_log() {
  450. return $this->log_buffer;
  451. }
  452.  
  453. function get_log_last_get_url_page_data() {
  454. return $this->log_last_get_url_page_data;
  455. }
  456. }
Advertisement
Add Comment
Please, Sign In to add comment