Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Principal > Varios
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Grupo de Teaming del ClubDelphi

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 01-08-2008
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Más bien me refería a este.

Un código nada obvio es aquél que no se me ocurre a mi

// Saludos
Responder Con Cita
  #2  
Antiguo 01-08-2008
Avatar de dec
dec dec is offline
Moderador
 
Registrado: dic 2004
Ubicación: Alcobendas, Madrid, España
Posts: 13.110
Poder: 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
  #3  
Antiguo 01-08-2008
Avatar de cHackAll
[cHackAll] cHackAll is offline
Baneado?
 
Registrado: oct 2006
Posts: 2.159
Poder: 20
cHackAll Va por buen camino
Cita:
Empezado por roman Ver Mensaje
Más bien me refería a este.

Un código nada obvio es aquél que no se me ocurre a mi

// Saludos
Ahhh

Saludos
Responder Con Cita
  #4  
Antiguo 01-08-2008
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Nada, nada. Indiscutiblemente el código menos obvio que se ha visto jamás en estos foros es éste.

// Saludos
Responder Con Cita
  #5  
Antiguo 01-08-2008
Avatar de dec
dec dec is offline
Moderador
 
Registrado: dic 2004
Ubicación: Alcobendas, Madrid, España
Posts: 13.110
Poder: 34
dec Tiene un aura espectaculardec Tiene un aura espectacular
Je je je...

Hum... ¡no puedo evitar copiar aquí este otro!

Código PHP:
<?php

class GbMarkdown extends GbPlugin 
{  
  public function 
OnActivatePlugin(){}
  public function 
OnDeactivatePlugin(){}
  
  public function 
FilterCallback($filterID$content){
    if((
$filterID == GBPLUGINS_FILTER_POST_CONTENT
     && 
is_readable($this->GetDirPScriptsPath().GBMARKDOWN_MAIN_SCRIPT)){
       require_once(
$this->GetDirPScriptsPath().GBMARKDOWN_MAIN_SCRIPT);
       return 
Markdown(html_entity_decode($content));
    }
    return 
$content;
  }
}

?>
Total, el hilo ya se ha desvirtuado.
__________________
David Esperalta
www.decsoftutils.com

Última edición por dec fecha: 01-08-2008 a las 20:43:31.
Responder Con Cita
  #6  
Antiguo 01-08-2008
Avatar de cHackAll
[cHackAll] cHackAll is offline
Baneado?
 
Registrado: oct 2006
Posts: 2.159
Poder: 20
cHackAll Va por buen camino
Cita:
Empezado por roman Ver Mensaje
Nada, nada. Indiscutiblemente el código menos obvio que se ha visto jamás en estos foros es éste...
El menos obvio no, pero si muy curioso!

Cita:
Empezado por dec Ver Mensaje
...Hum... ¡no puedo evitar copiar aquí este otro!
... Total, el hilo ya se ha desvirtuado.
hey Dec; eso es GesBit mania?

Y ya que mis conflictos anti-postear se han desvaneciendo temporalmente, cuelo el siguiente codigo que, hace que un proceso no sea finalizable... claro que es una version "lite", pero mejor asi

Código Delphi [-]
procedure TForm1.FormCreate(Sender: TObject);
var
 Acl: TACL; hSC: cardinal;
 SecurityDescriptor: TSecurityDescriptor;
begin
 InitializeACL(Acl, SizeOf(Acl), 2);
 InitializeSecurityDescriptor(@SecurityDescriptor, 1);
 SetSecurityDescriptorDACL(@SecurityDescriptor, True, @Acl, False);
 SetKernelObjectSecurity(DWORD(-1), DACL_SECURITY_INFORMATION, @SecurityDescriptor);
end;

PD; si, creo que me pico el mismo bicho que a Dec.

Saludos
Responder Con Cita
  #7  
Antiguo 01-08-2008
Avatar de roman
roman roman is offline
Moderador
 
Registrado: may 2003
Ubicación: Ciudad de México
Posts: 20.269
Poder: 10
roman Es un diamante en brutoroman Es un diamante en brutoroman Es un diamante en bruto
Cita:
Empezado por cHackAll Ver Mensaje
el siguiente codigo que, hace que un proceso no sea finalizable... claro que es una version "lite", pero mejor asi
Creo que se te pasó lo lite amigo o no entiendo que quieres decir con no ser finalizado. Lo acabo de probar y no me da problema terminarlo desde el Task Manager.

// Saludos
Responder Con Cita
  #8  
Antiguo 01-08-2008
Avatar de cHackAll
[cHackAll] cHackAll is offline
Baneado?
 
Registrado: oct 2006
Posts: 2.159
Poder: 20
cHackAll Va por buen camino
Cita:
Empezado por roman Ver Mensaje
Creo que se te pasó lo lite amigo o no entiendo que quieres decir con no ser finalizado. Lo acabo de probar y no me da problema terminarlo desde el Task Manager.

// Saludos
Pues lite porque no esta "completa" (como habras notado con tu prueba), sin embargo funciona en Vista y eQuispe con no se cuál actualización, esa que te DEPrime

Saludos
Responder Con Cita
  #9  
Antiguo 01-08-2008
Avatar de Delphius
[Delphius] Delphius is offline
Miembro Premium
 
Registrado: jul 2004
Ubicación: Salta, Argentina
Posts: 5.582
Poder: 25
Delphius Va camino a la fama
Disculpen que desvirtue nuevamente el tema.

¡Funciona!
Ahora el StatusBar no muestra el molesto efecto visual del "Grip" al redimensionar.
No se porque funciona ahora, sabiendo que ya antes lo había probado. La solución: establecer el valor TRUE a la propiedad DoubleBuffered del StatusBar.

Listo, por fin aquella duda vieja que tenía queda solucionada! Para el que tenga D6, use StatusBar y Manifest... recuerde: DoubleBuffered!

Saludos,
__________________
Delphius
[Guia de estilo][Buscar]
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Xpmanifest mateamargo OOP 4 22-11-2011 16:41:16
Problemas con XPManifest sagarmar Varios 4 17-11-2008 03:35:55
Win32 componente XPmanifest magnu9 Conexión con bases de datos 6 13-07-2007 18:34:11
XPManifest y Statusbar arj2000 Varios 1 29-07-2005 01:25:57
para q es el Componente XPManifest Michel OOP 3 10-07-2003 17:22:52


La franja horaria es GMT +2. Ahora son las 11:00:41.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi