Ver Mensaje Individual
  #15  
Antiguo 01-08-2008
Avatar de dec
dec dec is offline
Moderador
 
Registrado: dic 2004
Ubicación: Alcobendas, Madrid, España
Posts: 13.112
Reputación: 34
dec Tiene un aura espectaculardec Tiene un aura espectacular
Hola,

¿Un código nada obvio? ¡Marchando!

Código PHP:
<?php

class GbDefensio extends GbPlugin 
{  
  private 
$statsCache;
  
  public function 
__construct($pluginData){
    
$this->statsCache = array();
    
parent::__construct($pluginData);
  }
  
  public function 
OnActivatePlugin(){
    if(
$this->PrepareDatabase()){
      
$this->SetOptions($this->GetDefaultOptions(), 1);
    }else{
      return new 
GbError(
        
$this->_rp('Sorry, GbDefensio cannot be install')
      );
    }
  }
  
  public function 
OnDeactivatePlugin(){
    if(!
$this->DeleteDatabase()){
      return new 
GbError(
        
$this->_rp('Sorry, GbDefensio cannot be uninstall')
      );
    }
  }

  public function 
ActionCallback($actionID$args){
    if(
$actionID == GBPLUGINS_ACTION_COMMENT_NEW){
      
$this->CheckNewComment($args);
    }elseif(
$actionID == GBPLUGINS_ACTION_COMMENTS_UPDATE){
      
$this->CheckUpdateComments($args);          
    }
    return 
null;
  }
    
  public function 
ShowStats(){
    
$stats $this->GetStats();
    if(!empty(
$stats)){
      
$falsePos sprintf(
        
$this->_rp('%s false positives'), 
        
$stats['false-positives']
      );      
      
$falseNeg sprintf(
        
$this->_rp('%s false negatives'), 
        
$stats['false-negatives']
      );      
      
$accuracy sprintf(
        
$this->_rp('%s %% accuracy'), 
        
round($stats['accuracy'] * 1002)
      );
      
$spam sprintf(
        
$this->_rp('%s spam'), $stats['spam']
      );
      
$ham sprintf(
        
$this->_rp('%s innocents'), $stats['ham']
      );
      
$ham StrUtils::SafeHtm($ham);      
      
$spam StrUtils::SafeHtm($spam);
      
$accuracy StrUtils::SafeHtm($accuracy);
      
$falsePos StrUtils::SafeHtm($falsePos);
      
$falseNeg StrUtils::SafeHtm($falseNeg);
      echo
"
       <div class=\"gbdefensiostats\">
        <ul>
         <li class=\"accuracy\">
{$accuracy}</li>
         <li class=\"spam\">
{$spam}</li>
         <li class=\"ham\">
{$ham}</li>
         <li class=\"falsepos\">
{$falsePos}</li>
         <li class=\"falseneg\">
{$falseNeg}</li>
        </ul>                  
       </div>"
;
    }
    return 
true;    
  }
  
  public function 
ShowCounter($args = array()){    
    
$stats $this->GetStats();
    if(!empty(
$stats)){
      
$defaultArgs = array(
        
'skin' => 'light'
      
);
      
$args array_merge($defaultArgs$args);      
      
$imgPath $this->GetDirImagesPath().GBDEFENSIO_COUNTER_IMAGE;
      if(
is_readable($imgPath)){
        
$query http_build_query(array(
          
'skin' => $args['skin'],
          
'number' => $stats['spam']
        ));
        
$imgDir $this->GetDirImagesUrl();
        
$imgUrl $imgDir.GBDEFENSIO_COUNTER_IMAGE.'?'.$query;
        
$imgText StrUtils::SafeHtm(
         
$this->_rp('%s SPAM caught by GbDefensio'));
        
$imgText sprintf($imgText$stats['spam']);
        
printf(
          
'<div class="gbdefensiocounter">
            <a href="http://www.defensio.com/" title="%s"><img 
             src="%s" alt="%s" width="120" height="50" /></a>
           </div>'
$imgText$imgUrl$imgText
        
);
      }
    }
    return 
true;
  }  
  
  public function 
OptionsCallback(){
    
$errors $success = array();
    
$options $this->FillOptions();
    
$apikey $options[GBDEFENSIO_OPT_APIKEY];    
    if(
G::GetVar(INPUT_REQUEST_FORMSUBMIT)){
      
$apikey trim(G::GetVar(GBDEFENSIO_OPT_APIKEY));
      if(
$this->ValidateApikey($apikey)){
        
$options[GBDEFENSIO_OPT_APIKEY] = $apikey;
        
$this->SetOptions($options1);
        
$success[] = $this->_rp('Options saved, API key validated');
      }else{
        
$errors[] = $this->_rp('The API key cannot be validated');
      }
      
XHtmlAdmin::FormResults($errors$successtrue);
    }
    
?>
    <p>
     <?php echo StrUtils::SafeHtm(
      
$this->_rp('Visit the Defensio website to obtain your own API Key')) ?>
     <a href="http://www.defensio.com/" 
      title="<?php echo StrUtils::SafeHtm($this->_rp('click here')) ?>">
       <?php echo StrUtils::SafeHtm($this->_rp('click here')) ?></a>
    </p>
    <p>
     <label>
      <input value="<?php echo StrUtils::SafeHtm($apikey?>
       style="width: 30%" type="text" name="<?php echo GBDEFENSIO_OPT_APIKEY ?>" />
        <?php echo StrUtils::SafeHtm($this->_rp('Your Defensio API Key')) ?>
     </label>
    </p>
    <p>
     <input type="submit" id="submit" name="submit" 
      value="<?php echo StrUtils::SafeHtm($this->_rp('Save options')) ?>" />
    </p>
    <?php
    
return true;
  }
  
  private function 
GetStats(){
    if(empty(
$this->statsCache)){
      
$options $this->FillOptions();
      
$apikey $options[GBDEFENSIO_OPT_APIKEY];
      if(
$this->ValidateApikey($apikey)){
        
$blogUrl GbUrls::GetBlogRootUrl();
        
$params = array('owner-url' => $blogUrl);      
        
$defensio = new Defensio($apikey$blogUrl);
        
$response $defensio->get_stats($params); 
        if(
$this->IsDefensioSuccessResponse($response)){
          
$this->statsCache $response;
          return 
$response;
        }
      }
      return 
null;
    }else{
      return 
$this->statsCache;  
    }
  }
  
  private function 
GetComments($commentIDs){
    global 
$gbdb;
    
$idsToSql '';
    
$sqlLimit count($commentIDs);
    foreach(
$commentIDs as $commentID){
      
$commentID $gbdb->Escape($commentID);
      if(
$idsToSql == ''){
        
$idsToSql .= sprintf('"%s"'$commentID);
      }else{
        
$idsToSql .= sprintf(',"%s"'$commentID);
      }
    }
    return 
$gbdb->GetResults(sprintf(
      
GBDEFENSIO_SQL_GET_COMMENTS
      
$idsToSql$gbdb->Escape($sqlLimit)
    ));
  }
  
  private function 
CheckNewComment($comment){
    
$options $this->FillOptions();
    
$apikey $options[GBDEFENSIO_OPT_APIKEY];
    if((
trim($apikey) != '') && $this->ValidateApikey($apikey)){
      
$blogUrl GbUrls::GetBlogRootUrl();
      
$params = array(
        
'owner-url' => $blogUrl,
        
'article-date' => date('Y/m/d'),
        
'user-ip' => G::GetVar('REMOTE_ADDR'),
        
'comment-type' => $comment['commenttype'],
        
'trusted-user' => G::UserIsAuthenticated(),
        
'comment-content' => $comment['commentcontent'],
        
'comment-author' => $comment['commentauthorname'],
        
'comment-author-url' => $comment['commentauthorurl'],
        
'comment-author-email' => $comment['commentauthoremail']
      );
      
$defensio = new Defensio($apikey$blogUrl);
      
$response $defensio->audit_comment($params);
      if(
$this->IsDefensioSuccessResponse($response)){
        
$this->UpdateComment($comment['commentid'],$response);
      }
    }
    return 
true;  
  }
  
  public function 
CheckUpdateComments($commentsIDs){
    
$options $this->FillOptions();    
    
$apikey $options[GBDEFENSIO_OPT_APIKEY];
    if((
trim($apikey) != '') && $this->ValidateApikey($apikey)){    
      
$falsePositives $falseNegatives = array();
      
$commentsData $this->GetComments($commentsIDs);
      if(!empty(
$commentsData)){
        foreach(
$commentsData as $comment){
          if(!empty(
$comment->comment_defensio)){
            
$commentType $comment->comment_type;            
            
$defensioData unserialize($comment->comment_defensio);
            
$defensioSign $defensioData['signature'];
            
$isDefensioSpam = ($defensioData['spam'] == 'true');
            
$isCommentSpam = ($commentType == GBDB_COMMENT_TYPE_SPAM);
            if(!
$isCommentSpam && $isDefensioSpam){
              
$falsePositives[] = $defensioSign;
            }elseif(
$isCommentSpam && !$isDefensioSpam){
              
$falseNegatives[] = $defensioSign;
            }
          }
        }
        if(!empty(
$falsePositives
         || !empty(
$falseNegatives)){
           
$this->ReportUpdates(array(
             
$falsePositives
             
$falseNegatives
           
));          
        }
      }
    }
    return 
true;
  }
  
  private function 
ReportUpdates($reportData){
    
$options $this->FillOptions();
    
$blogUrl GbUrls::GetBlogRootUrl();
    
$apikey $options[GBDEFENSIO_OPT_APIKEY];
    
$defensio = new Defensio($apikey$blogUrl);
    if(!empty(
$reportData[0])){
      
$signatures $this->PrepareSignatures(
       
$reportData[0]);
      
$defensio->report_false_positives(
       array(
'signatures' => $signatures));
    }
    if(!empty(
$reportData[1])){
      
$signatures $this->PrepareSignatures(
       
$reportData[1]);            
      
$defensio->report_false_negatives(
       array(
'signatures' => $signatures));           
    }
    return 
true;    
  }

  private function 
PrepareSignatures($signatures){
    
$result '';
    foreach(
$signatures as $signature){
      if(
$result ''){
        
$result .= $signature;
      }else{
        
$result .= sprintf(',%s'$signature);
      }
    }
    return 
$result;
  }
  
  
  private function 
UpdateComment($commentID$defensioData){
    global 
$gbdb;
    
$storeData serialize(array(
      
'spam' => $defensioData['spam'],
      
'spaminess' => $defensioData['spaminess'],
      
'signature' => $defensioData['signature']
    ));
    if(
$defensioData['spam'] == 'true'){
      
$affectedRow $gbdb->Execute(sprintf(
        
GBDEFENSIO_SQL_UPDATE_COMMENT,
        
GBDB_COMMENT_TYPE_SPAM,
        
$gbdb->Escape($storeData), 
        
$gbdb->Escape($commentID)
      ));
    }else{
      
$affectedRow $gbdb->Execute(sprintf(
        
GBDEFENSIO_SQL_UPDATE_DEFENSIO,
        
$gbdb->Escape($storeData), 
        
$gbdb->Escape($commentID)
      ));
    }
    return (
$affectedRow == 1);
  }
  
  private function 
ValidateApikey($apikey){
    if(
$this->RequireDefensioClass()){
      
$blogUrl GbUrls::GetBlogRootUrl();
      
$defensio = new Defensio($apikey$blogUrl);
      
$params = array('owner-url' => $blogUrl);
      
$response $defensio->validate_key($params);
      return 
$this->IsDefensioSuccessResponse($response);
    }else{
      return 
false;  
    }
  }
  
  private function 
IsDefensioSuccessResponse($response){
    return 
is_array($response
     && isset(
$response['status']) 
      && (
$response['status'] == 'success');  
  }
  
  private function 
RequireDefensioClass(){
    
$script $this->GetDirPScriptsPath()
               .
GBDEFENSIO_CLASS_SCRIPT;
    if(
is_readable($script)){
      require_once(
$script);
      return 
true;
    }else{
      return 
false;  
    }
  }  
  
  private function 
FillOptions(){
    
$options $this->GetOptions();
    if(
is_array($options)){
      return 
$options;
    }else{
      return 
$this->GetDefaultOptions();
    }    
  }
  
  private function 
GetDefaultOptions(){
    return array(
      
GBDEFENSIO_OPT_APIKEY => ''
    
);    
  }

  private function 
PrepareDatabase(){
    if(
$this->DatabaseExists()){
      if(
$this->DeleteDatabase()){
        return 
$this->CreateDatabase();  
      }else{
        return 
false;  
      }
    }else{
      return 
$this->CreateDatabase();
    }
  }
  
  private function 
CreateDatabase(){
    
$GLOBALS['gbdb']->Execute(
     
GBDEFENSIO_SQL_INSTALL_DEFENSIO);
    return 
$this->DatabaseExists();
  }
  
  private function 
DeleteDatabase(){
    
$GLOBALS['gbdb']->Execute(
     
GBDEFENSIO_SQL_DELETE_DEFENSIO);
    return !
$this->DatabaseExists();
  }
  
  private function 
DatabaseExists(){
    global 
$gbdb;
    
$usingCache $gbdb->IsQueriesCacheOn();
    if(
$usingCache){
      
$gbdb->SetQueriesCacheOff();  
    }
    
$fields $gbdb->GetResults(
      
GBDEFENSIO_SQL_DESCRIBE_COMMENTS);
    if(
$usingCache){
      
$gbdb->SetQueriesCacheOn();    
    }
    if(!empty(
$fields)){
      foreach(
$fields as $field){
        if(
$field->Field 
         
== GBDEFENSIO_TABLE_FIELD_NAME){
           return 
true;
        }
      }
      return 
false;
    }else{
      return 
false;
    }
  }  
}

?>
No lo quería poner, por lo de no desvirtuar los hilos...
__________________
David Esperalta
www.decsoftutils.com

Última edición por dec fecha: 01-08-2008 a las 20:19:19.
Responder Con Cita