Advertisement
terorama

PHP / rss.inc.php

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