Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Twit {
- const twit_addr = 'https://api.twitter.com/1/statuses/user_timeline.rss';
- const twit_num = 500;
- private $_db;
- private $lasterror='';
- //----------------------------------
- private function get_mysqli() {
- return new mysqli('','','','');
- }
- //----------------------------------
- private function check_sql_error($agent='') {
- if ($agent==='')
- $agent = $this->_db;
- if ($agent->errno!=0) {
- throw new Exception ('database error: '.$agent->error);
- }
- }
- //----------------------------------
- private function check_auth() {
- if (!$this->is_logged())
- throw new Exception('authorization error');
- }
- //----------------------------------
- public function mk_tables() {
- $this->check_auth();
- $sqls = array ('drop table if exists twit_lines',
- 'drop table if exists twit_twits',
- 'create table twit_lines (id int(11) not null auto_increment,
- line_name varchar(50), primary key(`id`))',
- 'create table twit_twits (id int(11) not null auto_increment,
- line_id int(11),
- title varchar(500), description varchar(500),
- link varchar(500), pubdate datetime, primary key(`id`))');
- while (list($key,$sq)= each($sqls)) {
- $this->_db->query($sq);
- $this->check_sql_error();
- }
- return 'operation completed';
- }
- //----------------------------------
- private function filt($s) {
- $s = preg_replace('/(https?:\/\/.*?)(\s|$)/i','<a href="$1" target="_blank">$1</a>',$s);
- return $s;
- }
- //----------------------------------
- private function date_rss2mysql($s) {
- preg_match('/(\S*?),\s(\d*?)\s(\D*?)\s(\d*?)\s(\d*?):(\d*?):(\d*?)\s/i', $s, $matches);
- $dayofweek = $matches[1];
- $day = $matches[2];
- $mon = $matches[3];
- $year = $matches[4];
- $hour = $matches[5];
- $minute = $matches[6];
- $second = $matches[7];
- switch ($mon) {
- case 'Jan': $mon4='01'; break;
- case 'Feb': $mon4='02'; break;
- case 'Mar': $mon4='03'; break;
- case 'Apr': $mon4='04'; break;
- case 'May': $mon4='05'; break;
- case 'Jun': $mon4='06'; break;
- case 'Jul': $mon4='07'; break;
- case 'Aug': $mon4='08'; break;
- case 'Sep': $mon4='09'; break;
- case 'Oct': $mon4='10'; break;
- case 'Nov': $mon4='11'; break;
- case 'Dec': $mon4='12'; break;
- }
- return $year.'-'.$mon4.'-'.$day.' '.$hour.':'.$minute.':'.$second;
- }
- //----------------------------------
- private function date_rss2mysql4($s) {
- // Thu, 27 Dec 2012 13:35:18 +0000
- // 2012-12-27 13:35:18
- $ver = phpversion();
- $ver = explode('.',$ver);
- $ver = implode(array_slice($ver,0,2));
- if ($ver>=53) {
- $date = DateTime::createFromFormat('D, d M Y H:i:s O',$s);
- $s = $date->format('Y-m-d H:i:s',$tm);
- } else {
- $tm = strtotime($s);
- $s = date('Y-m-d H:i:s',$tm);
- }
- return $s;
- }
- //----------------------------------
- private function is_logged() {
- if (isset($_SESSION['logged_in']))
- return $_SESSION['logged_in'];
- return false;
- }
- //----------------------------------
- private function get_twitline_num($name) {
- $res = $this->_db->query(
- "select min(id) from twit_lines where line_name='".
- $this->_db->real_escape_string($name)."'");
- $this->check_sql_error();
- if ($row = $res->fetch_array(MYSQL_NUM))
- $num = $row[0];
- else
- $num=false;
- $res->close();
- return $num;
- }
- //----------------------------------
- private function get_firstnum($id) {
- $res = $this->_db->query('select max(link) from twit_twits where line_id='.$id);
- $this->check_sql_error();
- if ($row = $res->fetch_array(MYSQL_NUM)) {
- $num = substr(strrchr($row[0],'/'),1);
- }
- else $num=0;
- $res->close();
- return $num;
- }
- //----------------------------------
- private function get_lastnum($id) {
- $res = $this->_db->query('select min(link) from twit_twits where line_id='.$id);
- $this->check_sql_error();
- if ($row = $res->fetch_row()) {
- $num = substr(strrchr($row[0],'/'),1);
- }
- else $num=0;
- $res->close();
- return $num;
- }
- //----------------------------------
- private function getNRows($id) {
- $res = $this->_db->query('select * from twit_twits where line_id='.
- $this->_db->real_escape_string($id));
- $this->check_sql_error();
- $nrows = $res->num_rows;
- $res->close();
- return $nrows;
- }
- //----------------------------------
- public function greeting() {
- return 'ready';
- }
- //----------------------------------
- public function show_twitlines() {
- $res = $this->_db->query('select id, line_name from twit_lines order by id desc');
- $this->check_sql_error();
- ob_start();
- echo '<form id="lineform"><ul class="twitlines">';
- while ($row = $res->fetch_object()) {
- echo '<li><input type="radio" name="line_name" value="'.$row->line_name.'" />'.
- '<a href="#" rel="_show_twitline" lnname="'.$row->line_name.'">'.$row->line_name.'</a></li>';
- }
- echo '</ul></form>';
- $s = ob_get_clean();
- return $s;
- }
- //----------------------------------
- public function show_controls() {
- $s = '<ul class="controls">
- <li><a href="#" rel="_add_twitline_form">add twitter feed</a></li>
- <li><a href="#" rel="_edit_twitline_form">edit twitter feed</a></li>
- <li><a href="#" rel="refill_twitline">fill twitter feed</a></li>
- <li><a href="#" rel="_update_twitline">update twitter feed</a></li>
- <li><a href="#" rel="_clear_twitline">clear twitter feed</a></li>
- <li><a href="#" rel="_delete_twitline_form">delete twitter feed</a></li>
- </ul>';
- return $s;
- }
- //----------------------------------
- public function edit_twitline_form($name='') {
- $this->check_auth();
- if ($name=='') {
- $isedit = false;
- $line_name = '';
- $line_id = 0;
- }
- else {
- $isdeit = true;
- $num = $this->get_twitline_num($name);
- if ($num===false)
- throw new Exception ('error getting twitter line');
- $res = $this->_db->query('select * from twit_lines where id='.$num);
- $this->check_sql_error();
- if (!$row = $res->fetch_assoc())
- throw new Exception ('error getting twitter line info');
- $res->close();
- $line_name = $row['line_name'];
- $line_id = $row['id'];
- }
- ob_start();
- echo '<form rel="_save_twitline" '.
- 'enctype="application/x-www-form-urlencoded">'.
- '<p> input twitter feed name: '.
- '<input type="text" name="line_name" value="'.$line_name.'" /></p>'.
- '<input type="hidden" name="line_id" value="'.$line_id,'" />'.
- '<p><input type="submit" name="submit" value="save"/>'.
- '<input type="button" rel="_greeting" value="cancel" /></p></form>';
- $s = ob_get_contents();
- ob_end_clean();
- return $s;
- }
- //----------------------------------
- public function add_twitline_form() {
- return $this->edit_twitline_form();
- }
- //----------------------------------
- public function delete_twitline_form($name) {
- $this->check_auth();
- if (!$name)
- throw new Exception('line_name parameter is empty');
- $num = $this->get_twitline_num($name);
- if ($num===false)
- throw new Exception ('error getting twitter line');
- $s = '<form rel="_delete_twitline" '.
- 'enctype="application/x-www-form-urlencoded">'.
- '<input type="hidden" name="line_id" value="'.$num.'" />'.
- '<p><input type="submit" name="submit" value="delete"/>'.
- '<input type="button" rel="_greeting" value="cancel"></p></form>';
- return $s;
- }
- //----------------------------------
- public function save_twitline() {
- $this->check_auth();
- if ($_POST['line_id']==0) {
- $stmt = $this->_db->prepare(
- 'insert into twit_lines(line_name) values(?)');
- $stmt->bind_param('s', $_POST['line_name']);
- $stmt->execute();
- $this->check_sql_error($stmt);
- $id = $stmt->insert_id;
- $stmt->close();
- return "record with number $id inserted";
- } else {
- $stmt = $this->_db->prepare(
- 'update twit_lines set line_name=? where id=?');
- $stmt->bind_param('si', $_POST['line_name'], $_POST['line_id']);
- $stmt->execute();
- $this->check_sql_error($stmt);
- $affected = $stmt->affected_rows;
- $stmt->close();
- return " $affected records updated";
- }
- }
- //----------------------------------
- public function delete_twitline() {
- $this->check_auth();
- $stmt = $this->_db->prepare(
- 'delete from twit_lines where id=?');
- $stmt->bind_param('i', $_POST['line_id']);
- $stmt->execute();
- $this->check_sql_error($stmt);
- $affected = $stmt->affected_rows;
- $stmt->close();
- return " deleted rows $affected";
- }
- //----------------------------------
- public function show_loginout_form() {
- if (!$this->is_logged()) {
- $frm ='<form rel="_loginout" '.
- 'enctype="application/x-www-form-urlencoded">'.
- '<p>input password <input type="text" name="pass" /></p>'.
- '<p><input type="submit" name="submit" value="login" />'.
- '<input type="button" rel="_greeting" value="cancel"></p></form>';
- }
- else {
- parse_str($_SERVER['QUERY_STRING'], $getvars);
- $action = $getvars['action'];
- $action = 'greeting';
- $frm = '<form rel="_loginout" '.
- 'enctype="application/x-www-form-urlencoded">'.
- '<p>log out, are you sure? '.
- '<input type="submit" name="logout" value="logout" />'.
- '<input type="button" rel="_'.$action.'" value="cancel" />'.
- '</p></form>';
- }
- return $frm;
- }
- //----------------------------------
- public function loginstatus() {
- $s = $this->is_logged() ? 'logged in' : 'logged out';
- $s4 = $this->is_logged() ? 'log out' : 'log in';
- return $s.'<br/><a href="#" rel="_show_loginout_form">'.$s4.'</a>';
- }
- //----------------------------------
- public function loginout() {
- if ($this->is_logged()===false) {
- if ($_POST['pass']=='password') {
- $_SESSION['logged_in']=true;
- return 'successfully authorized';
- } else {
- return 'invalid password, '.
- '<a href="#" rel="_show_loginout_form">try again</a>';
- }
- } else {
- if (isset($_SESSION['logged_in']))
- unset($_SESSION['logged_in']);
- }
- }
- //----------------------------------
- public function show_twitline($name) {
- $num = $this->get_twitline_num($name);
- $npages = ceil($this->getNRows($num)/100);
- if ($num===false)
- throw new Exception ('error getting twitter line');
- $stmt = $this->_db->prepare(
- 'select id, title, description, link, '.
- 'DATE_FORMAT(pubdate,\'%d.%m.%Y %H:%i\') from twit_twits '.
- ' where line_id=? order by link desc');
- $stmt->bind_param('i',$num);
- $stmt->execute();
- $stmt->bind_result($id, $title, $description, $link, $pubdate);
- //---------------------------
- if (isset($_GET['page'])) {
- if ($_GET['page']>1) {
- for ($i=0; $i<($_GET['page']-1)*100; $i++)
- $stmt->fetch();
- }
- }
- //---------------------------
- ob_start();
- echo '<ul class="pager">';
- for ($i=0; $i<$npages; $i++) {
- echo '<li><a href="#" rel="_show_twitline" pg="'.($i+1).
- '" lnname="'.$name.'">'.
- ($i+1).'</a></li>';
- }
- echo '</ul>';
- //---------------------------
- $j=0;
- echo '<ul class="twitfeed">';
- while (($stmt->fetch()) && ($j<100)) {
- printf ("<li>
- <div class=\"twitid\">%s</div>
- <div class=\"twittitle\">%s</div>
- <div class=\"twitdesc\">%s</div>
- <div class=\"twitlink\">%s</div>
- <div class=\"twitpubdate\">%s</div>
- </li>",
- $id, $this->filt($title), $description, $link, $pubdate);
- $j++;
- }
- echo '</ul>';
- $s = ob_get_clean();
- $stmt->close();
- return $s;
- }
- //----------------------------------------------------------------------
- public function clear_twitline($name) {
- $line_id = $this->get_twitline_num($name);
- if ($line_id===false)
- throw new Exception ('error getting twitter line');
- $this->_db->query('delete from twit_twits where line_id='.$line_id);
- $this->check_sql_error();
- return 'twit line cleared, '.$this->_db->affected_rows.' deleted';
- }
- //----------------------------------------------------------------------
- private function save_twits($url, $line_id, $exclude) {
- //--------------------------
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_TIMEOUT, 10);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
- curl_setopt($ch, CURLOPT_USERAGENT,
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $s = curl_exec($ch);
- if (curl_errno($ch)) {
- throw new Exception ('curl exception: '.curl_error($ch));
- }
- curl_close($ch);
- //--------------------------
- $tw = array();
- $xml = simplexml_load_string($s);
- foreach ($xml->channel->item as $item) {
- $f = array();
- $f['title'] = $item->title;
- $f['description'] = $item->description;
- $f['link'] = $item->link;
- $f['pubdate'] = $item->pubDate;
- array_push($tw, $f);
- }
- //--------------------------
- $stmt = $this->_db->prepare (
- 'insert into twit_twits(line_id, title, description, link, pubdate)'.
- 'values (?,?,?,?,?)');
- for ($i=0; $i<count($tw); $i++) {
- extract($tw[$i]);
- if (substr(strrchr($link,'/'),1)==$exclude)
- continue;
- $pubdate4 = $this->date_rss2mysql4($pubdate);
- $stmt->bind_param('issss', $line_id, $title, $description, $link, $pubdate4);
- $stmt->execute();
- $this->check_sql_error();
- }
- $stmt->close();
- return 'inserted '.count($tw).' twits : '.$url;
- }
- //----------------------------------------------------------------------
- public function fill_twitline($name) {
- $this->check_auth();
- $line_id = $this->get_twitline_num($name);
- if ($line_id===false)
- throw new Exception ('error getting twitter line');
- $last_num = $this->get_lastnum($line_id);
- $data = array (
- 'screen_name'=>$name,
- 'count'=>Twit::twit_num
- );
- if ($last_num!=0)
- $data['max_id']=$last_num;
- $url = Twit::twit_addr.'?'.http_build_query($data);
- return $this->save_twits($url, $line_id, $last_num);
- }
- //----------------------------------
- public function update_twitline($name) {
- $this->check_auth();
- $line_id = $this->get_twitline_num($name);
- if ($line_id===false)
- throw new Exception ('error getting twitter line');
- $first_num = $this->get_firstnum($line_id);
- if ($first_num==0) {
- throw new Exception ('cannot update empty line');
- }
- $data = array (
- 'screen_name'=>$name,
- 'count'=>Twit::twit_num,
- 'since_id'=>$first_num
- );
- $url = Twit::twit_addr.'?'.http_build_query($data);
- return $this->save_twits($url, $line_id, $first_num);
- }
- //----------------------------------
- public function refill_twitline($name) {
- $this->check_auth();
- $s = $this->fill_twitline($name);
- $f =ltrim(substr(strstr($s, 'inserted'),8));
- $f = substr_replace($f,'', strpos($f,' '));
- if ($f<200) {
- $s .= '<br/><br/>operation finished';
- return $s;
- }
- $s .= '
- <script type="text/javascript">
- var el = document.createElement("DIV");
- document.body.appendChild(el);
- el.num = 1;
- el.zz = setInterval (
- function() {
- el.innerHTML ="reload after "+el.num+"s";
- el.num--;
- if (el.num==0) {
- clearInterval(el.zz);
- location.replace(location.href);
- }
- }
- ,1000);
- </script>';
- return $s;
- }
- //----------------------------------
- public function exceptionHandler($e) {
- $this->lasterror .= 'exception: '.$e->getMessage().'<br/><br/>';
- }
- //----------------------------------
- public function errorHandler($errno, $errstr, $errfile, $errline) {
- $this->lasterror .= "error occured: errno:$errno errstr:$errstr
- errfile:$errfile errline:$errline<br/><br/>";
- return true;
- }
- //----------------------------------
- public function __construct() {
- session_start();
- set_exception_handler(array($this,'exceptionHandler'));
- set_error_handler(array($this, 'errorHandler'));
- $this->_db = $this->get_mysqli();
- }
- //----------------------------------
- public function __destruct() {
- $this->_db->close();
- echo $this->lasterror;
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement