2009-05-15 9 views
0

이전에이 작업을 수행하는 방법을 물었습니다. 그러나 실제로 답변을 얻으려면 코드를 추가해야했습니다.Repost : PHP로 RSS 피드 만들기

은 내가 레딧 유형의 사이트를 가지고 있고, 나는 RSS이이 코드 먹이를 만들려고하고 있어요,하지만 난 치명적인 오류 얻을 : 메시지와 함께 catch되지 않은 예외 '예외'여기 그것

'쿼리 실패' 코드 :

<?php 
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php'); 
require_once(SITE_ROOT.'includes/exceptions.php'); 
require_once(SITE_ROOT.'data/model.php'); 
require_once(SITE_ROOT.'data/comment.php'); 

class Article extends Model 
{ 
    private $id; 
    private $user_id; 
    private $url; 
    private $title; 
    private $description; 
    private $ranking; 
    private $points; 

    function __construct($title = ' ', $description = ' ', $url = ' ', $username = ' ', $created = ' ', $modified = '') { 

     $this->setId(0); 
     $this->setCreated($created); 
     $this->setModified($modified); 
     $this->setUsername($username); 
     $this->setUrl($url); 
     $this->setTitle($title); 
     $this->setDescription($description); 
     $this->setRanking(0.0); 
     $this->setPoints(0); 
    } 

    function getId(){ 
     return $this->id; 
    } 

    private function setId($value){ 
     $this->id = $value; 
    } 

    function getUsername(){ 
     return $this->username; 
    } 

    function setUsername($value){ 
     $this->username = $value; 
    } 

    function getUrl(){ 
     return $this->url; 
    } 

    function setUrl($value){ 
     $this->url = $value; 
    } 

    function getTitle() 
    { 
     return $this->title; 
    } 

    function setTitle($value) { 

     $this->title = $value; 
    } 

    function getDescription() { 
     return $this->description; 
    } 

    function setDescription($value) 
    { 
     $this->description = $value; 
    } 

    function getPoints() 
    { 
     return $this->points; 
    } 

    function setPoints($value) { 
     $this->points = $value; 
    } 

    function getRanking() 
    { 
     return $this->ranking; 
    } 

    function setRanking($value) 
    { 
     $this->ranking = $value; 
    } 

    function calculateRanking() 
    { 
     $created = $this->getCreated(); 
     $diff = $this->getTimeDifference($created, date('F d, Y h:i:s A')); 
     $time = $diff['days'] * 24; 
     $time += $diff['hours']; 
     $time += ($diff['minutes']/60); 
     $time += (($diff['seconds']/60)/60); 

     $base = ($time + 2); 

     if($base > 0) 
     { 
      $this->ranking = ($this->points - 1)/pow($base, 1.5); 
     } 
     else 
     { 
      $this->ranking = 0; 
     } 
     $this->save(); 
    } 

    function vote($user,$amount=1) 
    { 
     if($this->has_voted($user) == false) 
     {    
      $this->points += $amount; 
      $this->save(); 
      $this->log_vote($user); 
     } 
    } 

    function log_vote($user) 
    { 
     try 
     { 
      $db = parent::getConnection(); 
      $query = "insert into votes (article_id, username) values ($this->id, '$user')";   
      $results = parent::execSql($query); 
     } 
     catch(Exception $e){ 
      throw $e; 
     }   
    } 

    function has_voted($user) 
    { 
     try 
     { 
      $db = parent::getConnection(); 
      $query = "select id from votes where username = '$user' and article_id = $this->id"; 
      $results = parent::execSQL($query); 
      if($results->num_rows == 1) { 
       return true;     
      } 
      else 
      { 
       return false; 
      }    
      parent::closeConnection($db); 

     } 
     catch(Exception $e){ 
      throw $e; 
     }  
    } 
    function getUrlDomain() 
    { 
     /* We extract the domain from the URL 
     * using the following regex pattern 
     */ 

     $url = $this->getUrl(); 
     $matches = array(); 
     if(preg_match('/http:\/\/(.+?)\//', $url, $matches)) 
     { 
      return $matches[1]; 
     } 
     else 
     { 
      return $url; 
     } 
    } 

    function getTimeDifference($start, $end) 
    { 
     //echo "start is $start, end is $end"; 
     $uts['start']  = strtotime($start); 
     $uts['end']  = strtotime($end); 
     if($uts['start']!==-1 && $uts['end']!==-1) 
     { 
      if($uts['end'] >= $uts['start']) 
      { 
       $diff = $uts['end'] - $uts['start']; 
       if($days=intval((floor($diff/86400)))) 
        $diff = $diff % 86400; 
       if($hours=intval((floor($diff/3600)))) 
        $diff = $diff % 3600; 
       if($minutes=intval((floor($diff/60)))) 
        $diff = $diff % 60; 
       $diff = intval($diff); 
       return(array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff)); 
      } 
      else 
      { 
       echo("Ending date/time is earlier than the start date/time"); 
      } 
     } 
     else 
     { 
      echo("Invalid date/time data detected"); 
     } 
     return(false); 
    } 

    function getElapsedDateTime() 
    { 
     $db = null; 
     $record = null; 

     $record = Article::getById($this->id); 
     $created = $record->getCreated();   

     $diff = $this->getTimeDifference($created, date('F d, Y h:i:s A')); 
     //$diff = $this->getTimeDifference($created, date_add(date('F d, Y h:i:s A'),new DateInterval("5H"))); 
     //echo 'new date is '.date('F d, Y h:i:s A'); 
     //print_r($diff); 

     if($diff['days'] > 0) 
     { 
      if($diff['days'] < 2) { return sprintf("%d dia", $diff['days']); } 

      else return sprintf("%d dias", $diff['days']); 
     } 
     else if($diff['hours'] > 0) 
     { 
      if($diff['hours'] < 2) { return sprintf("%d hora", $diff['hours']); } 

      else return sprintf("%d horas", $diff['hours']); 
     } 
     else if($diff['minutes'] > 0) 
     { 
      if($diff['minutes'] < 2) { return sprintf("%d minuto", $diff['minutes']); } 

      else return sprintf("%d minutos", $diff['minutes']); 
     } 
     else 
     { 
      if($diff['seconds'] < 2) { return sprintf("%d segundo", $diff['seconds']); } 

      else return sprintf("%d segundos", $diff['seconds']); 
     } 
    } 

    function save() { 

    /* 
      Here we do either a create or 
      update operation depending 
      on the value of the id field. 
      Zero means create, non-zero 
      update 
    */ 

     if(!get_magic_quotes_gpc()) 
     { 
      $this->title = addslashes($this->title); 
      $this->description = addslashes($this->description); 
     } 

     try 
     { 
      $db = parent::getConnection(); 
      if($this->id == 0) 
      { 
       $query = 'insert into articles (modified, username, url, title, description, points)'; 
       $query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)"; 
       createRSS(); // ++++++ rss +++++++ 
      } 
      else if($this->id != 0) 
      { 
       $query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id"; 
      } 

      $lastid = parent::execSql2($query); 

      if($this->id == 0) 
       $this->id = $lastid; 

     } 
     catch(Exception $e){ 
      throw $e; 
     } 
    } 


    function delete() 
    { 
     try 
     { 
      $db = parent::getConnection(); 
      if($this->id != 0) 
      {    ; 
       /*$comments = $this->getAllComments(); 
       foreach($comments as $comment) 
       { 
        $comment->delete(); 
       }*/ 
       $this->deleteAllComments(); 
       $query = "delete from articles where id = $this->id"; 
      } 
      parent::execSql($query); 


     } 
     catch(Exception $e){ 
      throw $e; 
     } 
    } 

    static function getAll($conditions = ' ') 
    { 
     /* Retrieve all the records from the 
     * database according subject to 
     * conditions 
     */ 

     $db = null; 
     $results = null; 
     $records = array(); 
     $query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions"; 
     try 
     { 
      $db = parent::getConnection(); 
      $results = parent::execSql($query); 

      while($row = $results->fetch_assoc()) 
      { 
       $r_id = $row['id']; 
       $r_created = $row['created']; 
       $r_modified = $row['modified']; 

       $r_title = $row['title']; 
       $r_description = $row['description']; 

       if(!get_magic_quotes_gpc()) 
       { 
        $r_title = stripslashes($r_title); 
        $r_description = stripslashes($r_description); 
       } 

       $r_url = $row['url']; 
       $r_username = $row['username']; 
       $r_points = $row['points']; 
       $r_ranking = $row['ranking']; 

       $article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified); 
       $article->id = $r_id; 
       $article->points = $r_points; 
       $article->ranking = $r_ranking; 
       $records[] = $article; 
      } 
      parent::closeConnection($db); 
     } 
     catch(Exception $e) 
     { 
      throw $e; 
     } 

     return $records; 
    } 

    static function getById($id) 
    {/* 
    * Return one record from the database by its id */ 

     $db = null; 
     $record = null; 

     try 
     { 
      $db = parent::getConnection(); 
      $query = "select id, username, created, modified, title, url, description, points, ranking from articles where id = $id"; 
      $results = parent::execSQL($query); 
      if(!$results) { 
       throw new Exception ('Record not found', EX_RECORD_NOT_FOUND); 
      } 

      $row = $results->fetch_assoc(); 
      parent::closeConnection($db); 

      if(!get_magic_quotes_gpc()) 
      { 
       $row['title'] = stripslashes($row['title']); 
       $row['description'] = stripslashes($row['description']); 
      } 


      $article = new Article($row['title'], $row['description'], $row['url'], $row['username'], $row['created'], $row['modified']); 
      $article->id = $row['id']; 
      $article->points = $row['points']; 
      $article->ranking = $row['ranking']; 
      return $article; 

     } 
     catch (Exception $e){ 
      throw $e; 
     } 
    } 

    static function getNumberOfComments($id) 
    {/* 
    * Return one record from the database by its id */ 

     $db = null; 
     $record = null; 

     try 
     { 
      $db = parent::getConnection(); 
      $query = "select count(*) as 'total' from comments where article_id = $id"; 
      $results = parent::execSQL($query); 
      if(!$results) { 
       throw new Exception ('Comments Count Query Query Failed', EX_QUERY_FAILED); 
      } 

      $row = $results->fetch_assoc(); 
      $total = $row['total']; 
      parent::closeConnection($db);  

      return $total; 


     } 
     catch (Exception $e){ 
      throw $e; 
     } 
    } 

    function deleteAllComments() 
    {/* 
    * Return one record from the database by its id */ 

     $db = null; 
     try 
     { 
      $db = parent::getConnection(); 
      $query = "delete from comments where article_id = $this->id"; 
      $results = parent::execSQL($query); 
      if(!$results) { 
       throw new Exception ('Deletion Query Failed', EX_QUERY_FAILED); 
      } 
      parent::closeConnection($db); 
     } 
     catch (Exception $e){ 
      throw $e; 
     } 
    } 


    function getAllComments($conditions = ' ') 
    { 
     /* Retrieve all the records from the 
     * database according subject to 
     * conditions 
     */ 
     $conditions = "where article_id = $this->id"; 
     $comments = Comment::getAll($conditions); 
     return $comments; 
    } 


    static function getTestData($url) 
    { 
     $page = file_get_contents($url); 

    } 

} 

    function createRSS() 
    { 
     $articles = Article::getAll("order by created desc limit $offset, $num_items"); 
     $num_articles = count($articles);  

     // open a file pointer to an RSS file 
     $fp = fopen ("rss.xml", "w"); 
     if (!$fp) { 
      // Can't write to a file 
      return; 
      } 

     fwrite ($fp, "<?xml version='1.0' encoding='iso-8859-1' ?>\n"); 
     fwrite ($fp, "<rss version='2.0' xmlns:atom=\"http://www.kiubbo.com/rss.xml\"><channel>\n"); 
     fwrite ($fp, "<title>Kiubbo.com</title>\n"); 
     fwrite ($fp, "<atom:link href='http://www.kiubbo.com/rss.xml' rel='self' type='application/rss+xml' />\n"); 
     fwrite ($fp, "<link>http://www.kiubbo.com/</link>\n"); 
     fwrite ($fp, "<description>Todas las Noticias Fotos y Videos.</description>\n"); 
     fwrite ($fp, "<language>es-mx</language>\n"); 
     fwrite ($fp, "<docs>http://www.kiubbo.com/rss.xml</docs>\n"); 
     fwrite ($fp, "<image>\n"); 
     fwrite ($fp, " <title>Kiubbo.com</title>\n"); 
     fwrite ($fp, " <url>http://www.kiubbo.com/Logot.png</url>\n"); 
     fwrite ($fp, " <link>http://www.kiubbo.com</link>\n"); 
     fwrite ($fp, "</image>\n"); 

     for($index = 0; $index < $num_articles; $index++){ 

     $url = $articles[$index]->getUrl(); 
     $title = $articles[$index]->getTitle(); // ok? 


     $search = array(
     '@<script[^>]*?>.*?</script>@si', // Strip out javascript 
     '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags 
     '@([\r\n])[\s][email protected]', // Strip out white space 
     '@&(quot|#34);@i', // Replace HTML entities 
     '@&(amp|#38);@i', 
     '@&(lt|#60);@i', 
     '@&(gt|#62);@i', 
     '@&(nbsp|#160);@i', 
     '@&(iexcl|#161);@i', 
     '@&(cent|#162);@i', 
     '@&(pound|#163);@i', 
     '@&(copy|#169);@i', 
     '@&(acento|#0027);@i', 
     '@&#(\d+);@e'); // evaluate as php 
     $replace = array(
     '', 
     '', 
     '\1', 
     '"', 
     '&', 
     '<', 
     '>', 
     ' ', 
     'chr(161)', 
     'chr(162)', 
     'chr(163)', 
     'chr(169)', 
     'chr(\1)'); 

     $content = preg_replace($search, $replace, $content); 
     $title = preg_replace("/&/", 'y', $title); 
     $content = preg_replace("/&/", 'y', $content); 

     fwrite ($fp, "<item>\n"); 
     fwrite ($fp, " <title>$title</title>\n"); 
     fwrite ($fp, " <link>$url</link>\n"); 
     fwrite ($fp, "<guid>http://www.kiubbo.com</guid>\n"); 
     fwrite ($fp, "</item>\n"); 
     } 
     fwrite ($fp, "</channel></rss>\n"); 
     fclose ($fp); 
    } 

?> 

들으

감사 카를로스

+1

당신은 브래킷 또는 객체를 사용하는 경우 연결할 필요가 있다고 확신한다 코드 어떤 함수가 오류를 생성하는지 알고 있습니까? 또한 준비된 문을 사용해야합니다. –

답변

2

내가 이것을 테스트하기 위해 PHP로 기계에 아니지만, 당신이 querie이 로 다음과 변수들 ...

"select id from votes where username = '$user' and article_id = $this->id" 

나는 많은 있다는 ...

"select id from votes where username = '$user' and article_id = ${this->id}" 

또는

"select id from votes where username = '$user' and article_id = " . $this->id 
+1

내가 쿼리에 사용 된 변수는 SQL 주입이나 다른 나쁜 일들이 일어나지 않도록 어디서나 검사/파싱되지 않는다는 것을 알 수 있습니까? – giorgio

+0

@ giorgio - 개발자가 입력 내용을 살폈는 지 여부는 분명하지 않으므로 답변을 통해 개발자는 의심의 이익을 얻을 수있었습니다. 즉, 그것은 일반적인 경고이며 유용한 경고입니다. –

+1

나는 당신의 anwer (정확하고 도움이되는!)에 대한 것이 아니라 포스터 자신에 대해 언급하고있는 것이 아닙니다. 보시다시피 사용 된 데이터는 생성자 또는 설정자를 통해 삽입됩니다. 생성자는 setter도 사용합니다 (이는 좋은 일입니다!)하지만 setters는 단순히 vars를 복사하는 것 이상을 수행하지 않습니다. 그의 부모 메소드'execSQL'은 명시 적으로 vars를 sanitize 할 수 없습니다. (또는 이전에 발견하지 못했던 정말 똑똑한 소독자 여야합니다.) 이렇게하면 입력이 전혀 소독되지 않습니다. 포스터에; 어떻게 좀 해 봐! 세터에서 mysql_real_escape()을 사용하면 어떨까요? – giorgio