Advertisement
Guest User

Twitter -> Vkontakte status translator with debug v3

a guest
May 13th, 2010
2,483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.92 KB | None | 0 0
  1. <?php    
  2.  
  3. $path = "/home/user"; // Путь, где скрипт будет хранить файл с данными, а также куки
  4.  
  5. //В файле ниже хранятся две важные вещи: 1) ID последнего твита 2) Activity Hash, необходимый для изменения статуса вконтакте
  6. $data = file_exists("$path/data.inc") ? unserialize(implode('',file("$path/data.inc"))) : array();
  7.  
  8. //Тут записываем юзеров, твиты которых нужно транслировать
  9.  
  10. $users = array(
  11.   array('VK E-Mail','VK Password','Twitter Login','Twitter Password'),
  12. );
  13.  
  14. //------------------------------------------------------------------------------
  15.  
  16. $ch_vk = new cURL(false);
  17. $ch_twi = new cURL(false);
  18. $xml = xml_parser_create();
  19.  
  20. foreach ($users as $i => $v) {
  21.  
  22.   $ch_vk->cookie("$path/$v[0].txt"); //Устанавливаем нужные куки для контакта.
  23.  
  24.   debug("$v[0]:");
  25.  
  26.   if (!filesize("$path/$v[0].txt") || !$data[$v[0]]['ahash']) { //Авторизируемся вконтакте, если куки пустые.
  27.     debug(" Авторизируемся ВКонтакте...");
  28.     $r = $ch_vk->post('http://login.vk.com/',"act=login&try_to_login=1&email=$v[0]&pass=$v[1]");
  29.     if (preg_match("/<input type='hidden' name='s' id='s' value='(.*?)' \/>/si",$r,$m)) {
  30.       $ch_vk->post('http://vkontakte.ru/login.php',"op=slogin&redirect=0&s=$m[1]");
  31.       sleep(1);
  32.       $r = $ch_vk->get('http://vkontakte.ru/'); //Получим Activity Hash
  33.       if (preg_match("/<a href='\/login.php'>/si",$r,$m)) { debug("Авторизация не прошла."); continue; }
  34.       if (preg_match("/<input type='hidden' id='activityhash' value='(.*?)'>/si",$r,$m)) { $data[$v[0]]['ahash'] = $m[1]; debug("  Activity Hash: $m[1]"); } else { debug("  Не удалось получить Activity Hash!"); continue; }
  35.     }
  36.   } else {
  37.     if (!$data[$v[0]]['ahash']) continue;
  38.   }
  39.  
  40.   $ch_twi->auth = "$v[2]:$v[3]"; //Задаем логин и пароль для твиттера
  41.  
  42.   //Если еще ни один твит не транслировали
  43.   if (!$data[$v[0]]['lastid']) {
  44.     debug(" Транслируем первый твит...");
  45.     $r = $ch_twi->get("http://twitter.com/statuses/user_timeline/$v[2].xml?count=1"); //Получаем ид последнего твита, текст и сорс
  46.     if (!$r) { debug("Не удалось получить список твитов!"); continue; }
  47.     $d = new SimpleXMLElement($r);
  48.     if ($d->status) {
  49.       $data[$v[0]]['lastid'] = (string)($d->status->id); //Записываем ид последнего твита
  50.       vk_status($d->status->text,$d->status->source,$data[$v[0]]['ahash']);
  51.       debug(" ok.");
  52.     }
  53.   } else {
  54.     debug(" Ищем новые твиты...");
  55.     $r = $ch_twi->get("http://twitter.com/statuses/user_timeline/$v[2].xml?since_id=".$data[$v[0]]['lastid']); //Получаем все твиты позже
  56.     if (!$r) { debug("Не удалось получить список твитов!"); continue; }
  57.     $d = new SimpleXMLElement($r);
  58.     if (!$d->status) { debug("  новых нет."); continue; }//Нет твитов
  59.     if (count($d->status) > 1) { //Если твитов несколько
  60.       debug(" Постим новые твиты..."); $i = 0;
  61.       foreach ($d->status as $j => $s) {
  62.         if ($i == 0) { $data[$v[0]]['lastid'] = (string)$s->id; } else { sleep(65); } //Задержка. Да, более минуты, иначе контакт просто заменит предыдущий статус на новый.
  63.         vk_status($s->text,$s->source,$data[$v[0]]['ahash']);
  64.         debug("  ".$s->id); $i++;
  65.       }
  66.     } else { //1 твит
  67.       debug(" 1 новый твит, постим...");
  68.       $data[$v[0]]['lastid'] = (string)($d->status->id);
  69.       vk_status($d->status->text,$d->status->source,$data[$v[0]]['ahash']);
  70.     }
  71.   }
  72.   sleep(1);
  73.   debug("OK.");
  74. }
  75.  
  76. //Сохраняем табличку с данными
  77.  
  78. $f = fopen("$path/data.inc",'w+');
  79. fwrite($f,serialize($data));
  80. fclose($f);
  81.  
  82. //------------------------------------------------------------------------------
  83.  
  84. function vk_status($text,$src,$hash) { //Функция для изменения статуса
  85.   global $ch_vk;
  86.   $src = strip_tags($src);
  87.   $text = (string)$text;
  88.   if ($text[0] == '@') return false; //Отфильтруем реплаи. Врядли они будут интересны людям из контакта
  89.   $src = $src == 'web' ? 'via Twitter' : 'via '.$src; //Сделаем красивую пометку, откуда пришел наш твит
  90.   $ch_vk->post("http://vkontakte.ru/profile.php","setactivity=$text $src&activityhash=$hash");
  91. }
  92.  
  93. //------------------------------------------------------------------------------
  94.  
  95. function debug($msg) {
  96.   echo $msg."\n";
  97. }
  98.  
  99. //------------------------------------------------------------------------------
  100.    
  101. // Fast cURL Class
  102.  
  103. class cURL {
  104.   var $headers;
  105.   var $user_agent;
  106.   var $compression;
  107.   var $cookie_file;
  108.   var $proxy;
  109.   var $auth;
  110.  
  111.   function cURL($cookies=TRUE,$cookie='cookies.txt',$compression='gzip',$proxy='') {
  112.     $this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
  113.     $this->headers[] = 'Connection: Keep-Alive';
  114.     $this->headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
  115.     $this->user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/530.5 (KHTML, like Gecko) Chrome/2.0.172.30 Safari/530.5';
  116.     $this->compression=$compression;
  117.     $this->proxy=$proxy;
  118.     $this->cookies=$cookies;
  119.     if ($this->cookies == TRUE) $this->cookie($cookie);
  120.   }
  121.  
  122.   function cookie($cookie_file) {
  123.     $this->cookies = true;
  124.     if (file_exists($cookie_file)) {
  125.       $this->cookie_file=$cookie_file;
  126.     } else {
  127.       $f = fopen($cookie_file,'w');
  128.       fclose($f);
  129.       $this->cookie_file=$cookie_file;
  130.     }
  131.   }
  132.  
  133.   function get($url) {
  134.     $process = curl_init($url);
  135.     curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
  136.     curl_setopt($process, CURLOPT_HEADER, 0);
  137.     curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
  138.     if ($this->cookies == TRUE) {
  139.       curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
  140.       curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
  141.      }
  142.     if ($this->auth) curl_setopt($process, CURLOPT_USERPWD, $this->auth);
  143.     curl_setopt($process,CURLOPT_ENCODING , $this->compression);
  144.     curl_setopt($process, CURLOPT_TIMEOUT, 30);
  145.     if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
  146.     curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
  147.     curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
  148.     $return = curl_exec($process);
  149.     curl_close($process);
  150.     return $return;
  151.   }
  152.  
  153.   function post($url,$data) {
  154.     $process = curl_init($url);
  155.     curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
  156.     curl_setopt($process, CURLOPT_HEADER, 1);
  157.     curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
  158.     if ($this->cookies == TRUE) {
  159.       curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
  160.       curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
  161.     }
  162.     if ($this->auth) curl_setopt($process, CURLOPT_USERPWD, $this->auth);  
  163.     curl_setopt($process, CURLOPT_ENCODING , $this->compression);
  164.     curl_setopt($process, CURLOPT_TIMEOUT, 30);
  165.     if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
  166.     curl_setopt($process, CURLOPT_POSTFIELDS, $data);
  167.     curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
  168.     curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
  169.     curl_setopt($process, CURLOPT_POST, 1);
  170.     $return = curl_exec($process);
  171.     curl_close($process);
  172.     return $return;
  173.   }
  174.  
  175. }
  176.  
  177. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement