Advertisement
terorama

twit / twit.inc.php

Dec 27th, 2012
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 17.34 KB | None | 0 0
  1. <?php
  2.  
  3.  
  4.  class Twit {
  5.  
  6.  
  7.     const twit_addr = 'https://api.twitter.com/1/statuses/user_timeline.rss';
  8.     const twit_num = 500;
  9.    
  10.     private $_db;
  11.     private $lasterror='';
  12.    
  13.     //----------------------------------
  14.     private function get_mysqli() {
  15.    
  16.        return new mysqli('','','','');
  17.     }
  18.  
  19.     //----------------------------------
  20.     private function check_sql_error($agent='') {
  21.    
  22.        if ($agent==='')
  23.           $agent = $this->_db;
  24.          
  25.        if ($agent->errno!=0) {
  26.           throw new Exception ('database error: '.$agent->error);
  27.        }
  28.     }
  29.    
  30.     //----------------------------------
  31.     private function check_auth() {
  32.    
  33.        if (!$this->is_logged())
  34.           throw new Exception('authorization error');
  35.     }
  36.  
  37.     //----------------------------------
  38.     public function mk_tables() {
  39.    
  40.        $this->check_auth();
  41.        
  42.        $sqls = array ('drop table if exists twit_lines',
  43.        
  44.        'drop table if exists twit_twits',
  45.        
  46.        'create table twit_lines (id int(11) not null auto_increment,
  47.        line_name varchar(50), primary key(`id`))',
  48.  
  49.        'create table twit_twits (id int(11) not null auto_increment,
  50.        line_id int(11),
  51.        title varchar(500), description varchar(500),
  52.        link varchar(500), pubdate datetime, primary key(`id`))');
  53.      
  54.        while (list($key,$sq)= each($sqls)) {
  55.           $this->_db->query($sq);
  56.           $this->check_sql_error();
  57.           }
  58.          
  59.        return 'operation completed';
  60.     }
  61.  
  62.     //----------------------------------
  63.     private function filt($s) {
  64.        
  65.        $s = preg_replace('/(https?:\/\/.*?)(\s|$)/i','<a href="$1" target="_blank">$1</a>',$s);
  66.        
  67.        return $s;
  68.     }
  69.     //----------------------------------
  70.     private function date_rss2mysql($s) {
  71.        
  72.        preg_match('/(\S*?),\s(\d*?)\s(\D*?)\s(\d*?)\s(\d*?):(\d*?):(\d*?)\s/i', $s, $matches);
  73.        
  74.        $dayofweek = $matches[1];
  75.        $day = $matches[2];
  76.        $mon = $matches[3];
  77.        $year = $matches[4];
  78.        $hour = $matches[5];
  79.        $minute = $matches[6];
  80.        $second = $matches[7];
  81.        
  82.         switch ($mon) {
  83.           case 'Jan': $mon4='01'; break;
  84.           case 'Feb': $mon4='02'; break;
  85.           case 'Mar': $mon4='03'; break;
  86.           case 'Apr': $mon4='04'; break;
  87.           case 'May': $mon4='05'; break;         
  88.           case 'Jun': $mon4='06'; break;
  89.           case 'Jul': $mon4='07'; break;
  90.           case 'Aug': $mon4='08'; break;
  91.           case 'Sep': $mon4='09'; break;
  92.           case 'Oct': $mon4='10'; break;   
  93.           case 'Nov': $mon4='11'; break;   
  94.           case 'Dec': $mon4='12'; break;         
  95.        }
  96.        
  97.        return $year.'-'.$mon4.'-'.$day.' '.$hour.':'.$minute.':'.$second;  
  98.     }
  99.     //----------------------------------
  100.     private function date_rss2mysql4($s) {
  101.    
  102.        //   Thu, 27 Dec 2012 13:35:18 +0000
  103.        
  104.        //   2012-12-27 13:35:18
  105.        
  106.        $ver = phpversion();
  107.        $ver = explode('.',$ver);
  108.        $ver = implode(array_slice($ver,0,2));
  109.  
  110.        if ($ver>=53) {
  111.        
  112.          $date =  DateTime::createFromFormat('D, d M Y H:i:s O',$s);
  113.          $s = $date->format('Y-m-d H:i:s',$tm);
  114.          
  115.        } else {
  116.           $tm = strtotime($s);   
  117.           $s = date('Y-m-d H:i:s',$tm);
  118.        }
  119.        
  120.        return $s;
  121.     }
  122.     //----------------------------------
  123.     private function is_logged() {
  124.    
  125.        if (isset($_SESSION['logged_in']))
  126.           return $_SESSION['logged_in'];
  127.          
  128.        return false;
  129.     }
  130.    
  131.     //----------------------------------
  132.     private function get_twitline_num($name) {
  133.    
  134.        $res = $this->_db->query(
  135.           "select min(id) from twit_lines where line_name='".
  136.           $this->_db->real_escape_string($name)."'");
  137.        
  138.        
  139.        $this->check_sql_error();
  140.        
  141.        if ($row = $res->fetch_array(MYSQL_NUM))
  142.           $num = $row[0];
  143.        else
  144.           $num=false;
  145.      
  146.        $res->close();
  147.        return $num;
  148.     }
  149.    
  150.  
  151.     //----------------------------------
  152.     private function get_firstnum($id) {
  153.    
  154.        $res = $this->_db->query('select max(link) from twit_twits where line_id='.$id);
  155.        $this->check_sql_error();
  156.        
  157.        if ($row = $res->fetch_array(MYSQL_NUM)) {
  158.           $num = substr(strrchr($row[0],'/'),1);
  159.        }
  160.        else $num=0;
  161.        
  162.        $res->close();
  163.        return $num;
  164.     }
  165.     //----------------------------------
  166.     private function get_lastnum($id) {
  167.    
  168.        $res = $this->_db->query('select min(link) from twit_twits where line_id='.$id);
  169.        $this->check_sql_error();
  170.        
  171.        if ($row = $res->fetch_row()) {
  172.           $num = substr(strrchr($row[0],'/'),1);
  173.        }
  174.        else $num=0;
  175.        
  176.        $res->close();
  177.        return $num;
  178.     }
  179.    
  180.     //----------------------------------
  181.     private function getNRows($id) {
  182.    
  183.  
  184.        $res = $this->_db->query('select * from twit_twits where line_id='.
  185.        $this->_db->real_escape_string($id));
  186.        
  187.        $this->check_sql_error();
  188.        
  189.        $nrows = $res->num_rows;
  190.        $res->close();
  191.        
  192.        return $nrows;
  193.     }
  194.     //----------------------------------
  195.     public function greeting() {
  196.        return 'ready';
  197.     }
  198.    
  199.     //----------------------------------
  200.     public function show_twitlines() {
  201.    
  202.    
  203.        $res = $this->_db->query('select id, line_name from twit_lines order by id desc');
  204.        $this->check_sql_error();
  205.        
  206.        ob_start();
  207.        echo '<form id="lineform"><ul class="twitlines">';
  208.        while ($row = $res->fetch_object()) {
  209.           echo '<li><input type="radio" name="line_name" value="'.$row->line_name.'" />'.
  210.           '<a href="#" rel="_show_twitline" lnname="'.$row->line_name.'">'.$row->line_name.'</a></li>';
  211.        }
  212.        echo '</ul></form>';    
  213.        
  214.        $s = ob_get_clean();
  215.        return $s;
  216.     }
  217.    
  218.     //----------------------------------
  219.     public function show_controls() {
  220.    
  221.        $s = '<ul class="controls">
  222.        <li><a href="#" rel="_add_twitline_form">add twitter feed</a></li>
  223.        <li><a href="#" rel="_edit_twitline_form">edit twitter feed</a></li>
  224.        <li><a href="#" rel="refill_twitline">fill twitter feed</a></li>
  225.        <li><a href="#" rel="_update_twitline">update twitter feed</a></li>
  226.        <li><a href="#" rel="_clear_twitline">clear twitter feed</a></li>       
  227.        <li><a href="#" rel="_delete_twitline_form">delete twitter feed</a></li>
  228.  
  229.        </ul>';
  230.        
  231.        return $s;
  232.     }
  233.    
  234.     //----------------------------------
  235.     public function edit_twitline_form($name='') {
  236.        
  237.        $this->check_auth();
  238.        
  239.        if ($name=='') {
  240.           $isedit = false;
  241.          
  242.           $line_name = '';
  243.           $line_id = 0;
  244.        }
  245.        else {
  246.           $isdeit = true;
  247.           $num = $this->get_twitline_num($name);
  248.          
  249.           if ($num===false)
  250.              throw new Exception ('error getting twitter line');
  251.          
  252.           $res = $this->_db->query('select * from twit_lines where id='.$num);
  253.           $this->check_sql_error();
  254.          
  255.           if (!$row = $res->fetch_assoc())
  256.              throw new Exception ('error getting twitter line info');
  257.              
  258.           $res->close();
  259.           $line_name = $row['line_name'];
  260.           $line_id = $row['id'];
  261.        }
  262.        
  263.        ob_start();     
  264.        echo '<form rel="_save_twitline" '.
  265.        'enctype="application/x-www-form-urlencoded">'.
  266.        '<p> input twitter feed name: '.
  267.        '<input type="text" name="line_name" value="'.$line_name.'" /></p>'.
  268.        '<input type="hidden" name="line_id" value="'.$line_id,'" />'.
  269.        '<p><input type="submit" name="submit" value="save"/>'.
  270.        '<input type="button" rel="_greeting" value="cancel" /></p></form>';
  271.        
  272.        $s = ob_get_contents();
  273.        ob_end_clean();
  274.        
  275.        return $s;
  276.     }  
  277.    
  278.     //----------------------------------
  279.     public function add_twitline_form() {
  280.    
  281.        return $this->edit_twitline_form();
  282.     }
  283.    
  284.     //----------------------------------
  285.     public function delete_twitline_form($name) {
  286.    
  287.        $this->check_auth();
  288.        
  289.        if (!$name)
  290.           throw new Exception('line_name parameter is empty');
  291.          
  292.        $num = $this->get_twitline_num($name);
  293.        if ($num===false)
  294.           throw new Exception ('error getting twitter line');
  295.          
  296.        $s = '<form rel="_delete_twitline" '.
  297.        'enctype="application/x-www-form-urlencoded">'.
  298.        '<input type="hidden" name="line_id" value="'.$num.'" />'.
  299.        '<p><input type="submit" name="submit" value="delete"/>'.
  300.        '<input type="button" rel="_greeting" value="cancel"></p></form>';
  301.        
  302.        return $s;
  303.     }
  304.    
  305.     //----------------------------------
  306.     public function save_twitline() {
  307.    
  308.        $this->check_auth();
  309.        
  310.        if ($_POST['line_id']==0) {
  311.        
  312.           $stmt = $this->_db->prepare(
  313.              'insert into twit_lines(line_name) values(?)');
  314.              
  315.           $stmt->bind_param('s', $_POST['line_name']);
  316.           $stmt->execute();
  317.           $this->check_sql_error($stmt);
  318.           $id = $stmt->insert_id;
  319.           $stmt->close();
  320.           return "record with number $id inserted";
  321.          
  322.          
  323.        } else {
  324.          
  325.           $stmt = $this->_db->prepare(
  326.              'update twit_lines set line_name=? where id=?');
  327.              
  328.           $stmt->bind_param('si', $_POST['line_name'], $_POST['line_id']);
  329.           $stmt->execute();
  330.           $this->check_sql_error($stmt);
  331.           $affected = $stmt->affected_rows;
  332.           $stmt->close();
  333.           return " $affected records updated";
  334.        }
  335.        
  336.     }
  337.    
  338.     //----------------------------------
  339.     public function delete_twitline() {
  340.        
  341.        $this->check_auth();
  342.        
  343.        $stmt = $this->_db->prepare(
  344.           'delete from twit_lines where id=?');
  345.          
  346.        $stmt->bind_param('i', $_POST['line_id']);
  347.        $stmt->execute();
  348.        $this->check_sql_error($stmt);
  349.        $affected = $stmt->affected_rows;
  350.        $stmt->close();
  351.        return " deleted rows $affected";
  352.        
  353.     }
  354.    
  355.     //----------------------------------
  356.     public function show_loginout_form() {
  357.    
  358.        if (!$this->is_logged()) {
  359.           $frm ='<form rel="_loginout" '.
  360.           'enctype="application/x-www-form-urlencoded">'.
  361.           '<p>input password <input type="text" name="pass" /></p>'.
  362.           '<p><input type="submit" name="submit" value="login" />'.
  363.           '<input type="button" rel="_greeting" value="cancel"></p></form>';
  364.        }
  365.        else {
  366.           parse_str($_SERVER['QUERY_STRING'], $getvars);
  367.           $action = $getvars['action'];
  368.          
  369.           $action = 'greeting';
  370.          
  371.           $frm = '<form rel="_loginout" '.
  372.           'enctype="application/x-www-form-urlencoded">'.
  373.           '<p>log out, are you sure? '.
  374.           '<input type="submit" name="logout" value="logout" />'.
  375.           '<input type="button" rel="_'.$action.'" value="cancel" />'.
  376.           '</p></form>';
  377.      
  378.        
  379.        }
  380.        
  381.        return $frm;
  382.     }
  383.    
  384.     //----------------------------------
  385.     public function loginstatus() {
  386.    
  387.        $s = $this->is_logged() ? 'logged in' : 'logged out';
  388.        $s4 = $this->is_logged() ? 'log out' : 'log in';
  389.      
  390.        return $s.'<br/><a href="#" rel="_show_loginout_form">'.$s4.'</a>';
  391.     }
  392.     //----------------------------------
  393.     public function loginout() {
  394.      
  395.        if ($this->is_logged()===false) {
  396.           if ($_POST['pass']=='password') {
  397.              $_SESSION['logged_in']=true;
  398.              return 'successfully authorized';
  399.           } else {
  400.              return 'invalid password, '.
  401.              '<a href="#" rel="_show_loginout_form">try again</a>';
  402.           }
  403.          
  404.        } else {
  405.           if (isset($_SESSION['logged_in']))
  406.              unset($_SESSION['logged_in']);
  407.        }
  408.     }
  409.    
  410.     //----------------------------------
  411.     public function show_twitline($name) {
  412.    
  413.        $num = $this->get_twitline_num($name);
  414.        $npages = ceil($this->getNRows($num)/100);
  415.        
  416.        if ($num===false)
  417.           throw new Exception ('error getting twitter line');
  418.          
  419.        $stmt = $this->_db->prepare(
  420.           'select id, title, description, link, '.
  421.           'DATE_FORMAT(pubdate,\'%d.%m.%Y  %H:%i\') from twit_twits '.
  422.           ' where line_id=? order by link desc');
  423.          
  424.        $stmt->bind_param('i',$num);
  425.        $stmt->execute();       
  426.        $stmt->bind_result($id, $title, $description, $link, $pubdate);
  427.        //---------------------------
  428.        if (isset($_GET['page'])) {
  429.           if ($_GET['page']>1) {
  430.              for ($i=0; $i<($_GET['page']-1)*100; $i++)
  431.                 $stmt->fetch();
  432.              }
  433.        }
  434.        //---------------------------
  435.        ob_start();
  436.    
  437.        echo '<ul class="pager">';
  438.        for ($i=0; $i<$npages; $i++) {
  439.           echo '<li><a href="#" rel="_show_twitline" pg="'.($i+1).
  440.           '" lnname="'.$name.'">'.
  441.           ($i+1).'</a></li>';
  442.        }
  443.        echo '</ul>';
  444.        //---------------------------       
  445.        
  446.        $j=0;
  447.        echo '<ul class="twitfeed">';
  448.        while (($stmt->fetch()) && ($j<100)) {
  449.           printf ("<li>
  450.               <div class=\"twitid\">%s</div>
  451.               <div class=\"twittitle\">%s</div>
  452.               <div class=\"twitdesc\">%s</div>
  453.               <div class=\"twitlink\">%s</div>
  454.               <div class=\"twitpubdate\">%s</div>
  455.              
  456.              </li>",
  457.           $id, $this->filt($title), $description, $link, $pubdate);
  458.          
  459.           $j++;
  460.        }
  461.        echo '</ul>';
  462.  
  463.        $s = ob_get_clean();
  464.        $stmt->close();
  465.        
  466.        return $s;
  467.  
  468.     }
  469.    
  470.     //----------------------------------------------------------------------
  471.     public function clear_twitline($name) {
  472.    
  473.        $line_id = $this->get_twitline_num($name);
  474.        
  475.        if ($line_id===false)
  476.           throw new Exception ('error getting twitter line');
  477.  
  478.        $this->_db->query('delete from twit_twits where line_id='.$line_id);
  479.        $this->check_sql_error();
  480.        
  481.        return 'twit line cleared, '.$this->_db->affected_rows.' deleted';
  482.     }
  483.    
  484.     //----------------------------------------------------------------------
  485.     private function save_twits($url, $line_id, $exclude) {
  486.        
  487.        //--------------------------
  488.        $ch = curl_init();
  489.        curl_setopt($ch, CURLOPT_URL, $url);
  490.        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  491.        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  492.        curl_setopt($ch, CURLOPT_USERAGENT,
  493.           "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");
  494.        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  495.        
  496.        $s = curl_exec($ch);
  497.        
  498.        if (curl_errno($ch)) {
  499.           throw new Exception ('curl exception: '.curl_error($ch));      
  500.        }       
  501.        curl_close($ch);
  502.        //--------------------------
  503.        
  504.        $tw = array();
  505.        $xml = simplexml_load_string($s);
  506.        
  507.        foreach ($xml->channel->item as $item) {
  508.        
  509.           $f = array();
  510.           $f['title'] = $item->title;
  511.           $f['description'] = $item->description;
  512.           $f['link'] = $item->link;
  513.           $f['pubdate'] = $item->pubDate;
  514.          
  515.           array_push($tw, $f);
  516.        }
  517.        //--------------------------
  518.        
  519.        $stmt = $this->_db->prepare (
  520.        'insert into twit_twits(line_id, title, description, link, pubdate)'.
  521.        'values (?,?,?,?,?)');
  522.        
  523.        for ($i=0; $i<count($tw); $i++) {
  524.          
  525.           extract($tw[$i]);
  526.           if (substr(strrchr($link,'/'),1)==$exclude)
  527.              continue;
  528.              
  529.           $pubdate4 = $this->date_rss2mysql4($pubdate);
  530.           $stmt->bind_param('issss', $line_id, $title, $description, $link, $pubdate4);
  531.          
  532.           $stmt->execute();
  533.           $this->check_sql_error();
  534.          
  535.        }
  536.        $stmt->close();
  537.        
  538.        return 'inserted '.count($tw).' twits : '.$url;
  539.     }
  540.  
  541.     //----------------------------------------------------------------------
  542.  
  543.     public function fill_twitline($name) {
  544.    
  545.        $this->check_auth();
  546.        
  547.        $line_id = $this->get_twitline_num($name);
  548.        if ($line_id===false)
  549.           throw new Exception ('error getting twitter line');
  550.        
  551.        $last_num = $this->get_lastnum($line_id);
  552.        
  553.        $data = array (
  554.           'screen_name'=>$name,
  555.           'count'=>Twit::twit_num
  556.        );
  557.        if ($last_num!=0)
  558.           $data['max_id']=$last_num;
  559.          
  560.        $url = Twit::twit_addr.'?'.http_build_query($data);
  561.        
  562.        return $this->save_twits($url, $line_id, $last_num);
  563.        
  564.     }
  565.     //----------------------------------
  566.     public function update_twitline($name) {
  567.    
  568.        $this->check_auth();
  569.        
  570.        $line_id = $this->get_twitline_num($name);
  571.        if ($line_id===false)
  572.           throw new Exception ('error getting twitter line');
  573.        
  574.        $first_num = $this->get_firstnum($line_id);
  575.        
  576.        if ($first_num==0)  {
  577.           throw new Exception ('cannot update empty line');
  578.        }
  579.        
  580.        $data = array (
  581.              'screen_name'=>$name,
  582.              'count'=>Twit::twit_num,
  583.              'since_id'=>$first_num
  584.           );
  585.            
  586.        $url = Twit::twit_addr.'?'.http_build_query($data);
  587.        
  588.        return $this->save_twits($url, $line_id, $first_num);
  589.  
  590.     }
  591.     //----------------------------------
  592.     public function refill_twitline($name) {
  593.        
  594.  
  595.        $this->check_auth();
  596.  
  597.        $s = $this->fill_twitline($name);
  598.        
  599.        $f =ltrim(substr(strstr($s, 'inserted'),8));
  600.        $f = substr_replace($f,'', strpos($f,' '));
  601.        
  602.        if ($f<200) {
  603.           $s .= '<br/><br/>operation finished';
  604.           return $s;
  605.        }
  606.        
  607.        $s .= '
  608.        <script type="text/javascript">
  609.           var el = document.createElement("DIV");
  610.           document.body.appendChild(el);
  611.          
  612.           el.num = 1;
  613.           el.zz = setInterval (
  614.              function() {
  615.                 el.innerHTML ="reload after "+el.num+"s";
  616.                 el.num--;
  617.                 if (el.num==0) {
  618.                    clearInterval(el.zz);
  619.                    location.replace(location.href);
  620.                 }
  621.              }
  622.           ,1000);
  623.        </script>';
  624.        
  625.        return $s;
  626.        
  627.     }
  628.    
  629.     //----------------------------------
  630.     public function exceptionHandler($e) {
  631.    
  632.        $this->lasterror .= 'exception: '.$e->getMessage().'<br/><br/>';
  633.     }
  634.     //----------------------------------   
  635.     public function errorHandler($errno, $errstr, $errfile, $errline) {
  636.    
  637.        $this->lasterror .= "error occured: errno:$errno errstr:$errstr
  638.         errfile:$errfile errline:$errline<br/><br/>";
  639.        
  640.        return true;
  641.     }
  642.    
  643.     //----------------------------------
  644.     public function __construct() {
  645.    
  646.        session_start();
  647.        set_exception_handler(array($this,'exceptionHandler'));
  648.        set_error_handler(array($this, 'errorHandler'));
  649.        
  650.        $this->_db = $this->get_mysqli();
  651.        
  652.     }
  653.    
  654.     //----------------------------------
  655.     public function __destruct() {
  656.    
  657.        $this->_db->close();
  658.        echo $this->lasterror;
  659.     }
  660.    
  661.    
  662.  }
  663.  
  664.  
  665. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement