Diary, artworks and codes
July 26th, 2009

Le regard

regard

Ce regard était effrayant. On aurait dit que sans cesse il scrutait en nous le relief d’une existence que nous voulions cesser d’espérer. Je me suis souvent demandé ce qu’aurait été l’écoulement de notre temps si il n’avait pas été là. Il fixait sans rien attendre, nous seuls attendions de pouvoir le soutenir. Certains, beaucoup même, finir par prétendre qu’il ne regardait rien. Ce regard, peut être n’était-il ici que pour nous faire sentir un peu de notre masse, un peu de cette notion de matière qui dramatise notre existence.”

R.L

Bookmark and Share
by Raphael Leray | Posted in Textes | No Comments » |
July 25th, 2009

Space fish…

space fish

Bookmark and Share
by Raphael Leray | Posted in Artwoks, Dessins | No Comments » |
July 22nd, 2009

Interactions BD avec MadeSimple

Si vous êtes amené à travailler à l’écriture d’un module ou bien d’une customisation au moyen des UDT (User Defined Tag), vous serez sans doute interressé par la présentation des quelques fonctions suivantes qui vous familiariseront avec les opérations de base entre votre BD et l’API MadeSimple.

Avant toute chose si vous êtes dans le cas d’une création d’UDT n’oubliez pas de mettre dans votre fonction :

  global $gCms;

Créez l’objet qui pointera vers votre base de donnée :

  $db =& $gCms->GetDB();

A partir de là vous effectuerez toutes vos requêtes SQL à l’aide de l’objet $db. L’API MadeSimple est en fait basé sur l’abstraction de base de donnée ADObd, dont voici les principales méthodes :

  $res = $db->Execute($sql);

Tout les types de requêtes (SELECT, INSERT, UPDATE etc) pourront être effectuées avec la méthode Execute(), cette fonction renvoie en résultat un objet possédant plusieurs méthodes de traitement des données qui s’avèrent fort pratiques :

La fonction RecordCount() vous renvoie le nombre de résultats.

$nb = $res->RecordCount();

Pour ranger les résultats de votre requète dans un tableau, vous procéderez ainsi :

$result = array();
while($res && $line = $res->FetchRow()){
  $result[] = $line;
}

Et enfin nous terminons par une méthode importante puisqu’elle permet d’échapper automatiquement vos variables et rend ainsi toutes attaques pirates par injection SQL impossibles, la méthode qstr() (quoted string).

$res = $db->Execute("SELECT * FROM auth WHERE login=".
 $db->qstr($login)." AND password=".$db->qstr($password));

Ici la fonction qstr permet donc d’échapper les variables login et password.

C’est tout pout le moment, je vous invite à poursuivre votre découverte de ADOdb avec la documentation officielle de cette bibliothèque : http://phplens.com/lens/adodb/docs-adodb.htm

Bookmark and Share
by Raphael Leray | Posted in Coding | No Comments » |
July 21st, 2009

Nietzsche et les maths

Mathématiques – Nous voulons faire entrer à tout prix la finesse et la rigueur des mathématiques dans toute science, autant qu’il est en notre pouvoir; non pas dans la croyance que nous connaîtrions mieux les choses par cette voie, mais afin d’établir notre relation humaine aux choses. Les mathématiques ne sont que le moyen de l’universelle et dernière connaissance de l’humain.

Le gai savoir #246

Bookmark and Share
by Raphael Leray | Posted in Extraits de lectures | No Comments » |
July 20th, 2009

Récupérer vos variables GET en javascript

Une fonction bien pratique qui permet de récupérer les variables GET en javascript :

 function getVar(name)
         {
         get_string = document.location.search;
         return_value = '';

         do { //cette boucle va capturer toutes les instances des variables GET.
            name_index = get_string.indexOf(name + '=');

            if(name_index != -1)
              {
              get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);

              end_of_value = get_string.indexOf('&');
              if(end_of_value != -1)
                value = get_string.substr(0, end_of_value);
              else
                value = get_string;                

              if(return_value == '' || value == '')
                 return_value += value;
              else
                 return_value += ', ' + value;
              }
            } while(name_index != -1)

         space = return_value.indexOf('+');
         while(space != -1)
              {
              return_value = return_value.substr(0, space) + ' ' +
              return_value.substr(space + 1, return_value.length);

              space = return_value.indexOf('+');
              }

         return(return_value);
         }
Bookmark and Share
by Raphael Leray | Posted in Coding | No Comments » |
July 19th, 2009

Du plaisir de palper.

buto

Il se palpa, toucha, pinça puis tournoya sur lui même. Tombant à genoux, il ouvrit la bouche mais avorta son cris. Il est énivrant, ne serait-ce qu’un brève instant de ne gouter qu’au trés subtil plaisir d’être là. Eprouver sa matière, le temps qui l’emporte puis ce frisson glaciale qui nous pousse irresistiblement sous le regard des autres.

R.L

Bookmark and Share
by Raphael Leray | Posted in Artwoks, Textes | No Comments » |
July 19th, 2009

Le tri alphabétique en php

Il arrive parfois de devoir mettre automatiquement dans l’ordre alphabétique les élements d’un tableau, pour cela inutile de se lancer dans la mise en place d’un algorithme du type tri à bulle/rapide ou autre, il existe en effet la fonction usort en php, cette dernière accepte en premier argument votre tableau à trier, et en deuxième une fonction de comparaison (existante ou de votre cru), dans notre cas nous utiliserons la fonction strcasecmp qui permet une comparaison insensible à la casse de chaînes binaires.

// Le tableau :
$tab = array('arbitre', 'Zoo','koala','glop','Alcool');
usort($tab, "strcasecmp");    // Pas d'affectation de variable !

//Resultat :
/* array(
 *            0=>'Alcool',
 *            1=>'arbitre',
 *            2=>'glop',
 *            3=>'koala',
 *            4=>'Zoo'
 *          );
 */

Attention usort renvoie un booléen, évitez donc d’écrire :

$tab = usort($tab, "strcasecmp");
Bookmark and Share
by Raphael Leray | Posted in Coding | No Comments » |
July 17th, 2009

Au bord de la sumidagawa

sumigawa

Bookmark and Share
by Raphael Leray | Posted in Japon, Photographies | No Comments » |
July 6th, 2009

Une class php pour visualiser les fichiers .psd

Pour ceux qui auraient besoin de développer une fonctionnalité de preview pour psd dans le cadre d’une appli web, voici une classe développée par un certain Tim de Koning qui leur fera certainement gagner beaucoup de temps :

/* This file is released under the GPL, any version you like
 *    PHP PSD reader class, v1.3
 *    By Tim de Koning
 *    Kingsquare Information Services, 22 jan 2007
 */

class PhpPsdReader
{
    var $infoArray;
    var $fp;
    var $fileName;
    var $tempFileName;
    var $colorBytesLength;

    function PhpPsdReader($fileName)
    {
        set_time_limit(0);
        $this->infoArray = array ();
        $this->fileName = $fileName;
        $this->fp = fopen($this->fileName, ‘r’);

        if (fread($this->fp, 4) == ‘8BPS’)
        {
            $this->infoArray['version id'] = $this->_getInteger(2);
            fseek($this->fp, 6, SEEK_CUR); // 6 bytes of 0’s
            $this->infoArray['channels'] = $this->_getInteger(2);
            $this->infoArray['rows'] = $this->_getInteger(4);
            $this->infoArray['columns'] = $this->_getInteger(4);
            $this->infoArray['colorDepth'] = $this->_getInteger(2);
            $this->infoArray['colorMode'] = $this->_getInteger(2);

            /* COLOR MODE DATA SECTION */ //4bytes Length The length of the following color data.
            $this->infoArray['colorModeDataSectionLength'] = $this->_getInteger(4);
            fseek($this->fp, $this->infoArray['colorModeDataSectionLength'], SEEK_CUR); // ignore this snizzle

            /*  IMAGE RESOURCES */
            $this->infoArray['imageResourcesSectionLength'] = $this->_getInteger(4);
            fseek($this->fp, $this->infoArray['imageResourcesSectionLength'], SEEK_CUR); // ignore this snizzle

            /*  LAYER AND MASK */
            $this->infoArray['layerMaskDataSectionLength'] = $this->_getInteger(4);
            fseek($this->fp, $this->infoArray['layerMaskDataSectionLength'], SEEK_CUR); // ignore this snizzle

            /*  IMAGE DATA */
            $this->infoArray['compressionType'] = $this->_getInteger(2);
            $this->infoArray['oneColorChannelPixelBytes'] = $this->infoArray['colorDepth']/8;
            $this->colorBytesLength = $this->infoArray['rows']*$this->infoArray['columns']*$this->infoArray['oneColorChannelPixelBytes'];

            if ($this->infoArray['colorMode'] == 2)
            {
                $this->infoArray['error'] = ‘images withindexedcoloursarenotsupportedyet ’;
                return false;
            }
        } else
        {
            $this->infoArray['error'] = ‘invalid or unsupportedpsd ’;
            return false;
        }
    }

    function getImage()
    {
        // decompress image data if required
        switch($this->infoArray['compressionType'])
        {
            // case 2:, case 3: zip not supported yet..
            case 1:
                // packed bits
                $this->infoArray['scanLinesByteCounts'] = array ();
                for ($i = 0; $i < ($this->infoArray['rows']*$this->infoArray['channels']); $i++)$this->infoArray['scanLinesByteCounts'][] = $this->_getInteger(2);
                $this->tempFileName = tempnam(realpath( ‘/tmp’),‘decompressedImageData’);
                $tfp = fopen($this->tempFileName, ‘wb’);
                foreach ($this->infoArray['scanLinesByteCounts'] as $scanLinesByteCount)
                {
                    fwrite($tfp, $this->_getPackedBitsDecoded(fread($this->fp, $scanLinesByteCount)));
                }
                fclose($tfp);
                fclose($this->fp);
                $this->fp = fopen($this->tempFileName, ‘r’);
            default:
                // continue with current file handle;
                break;
    }

    // let’s write pixel by pixel….
    $image = imagecreatetruecolor($this->infoArray['columns'], $this->infoArray['rows']);

    for ($rowPointer = 0; ($rowPointer < $this->infoArray['rows']); $rowPointer++)
    {
        for ($columnPointer = 0; ($columnPointer < $this->infoArray['columns']); $columnPointer++)
        {
            /*     The color mode of the file. Supported values are: Bitmap=0;
             Grayscale=1; Indexed=2; RGB=3; CMYK=4; Multichannel=7;
             Duotone=8; Lab=9.
             */
            switch($this->infoArray['colorMode'])
            {
                case 2: // indexed… info should be able to extract from color mode data section. not implemented yet, so is grayscale
                    exit ;
                    break;
                case 0:
                    // bit by bit
                    if ($columnPointer == 0)$bitPointer = 0;
                    if ($bitPointer == 0)$currentByteBits = str_pad(base_convert(bin2hex(fread($this->fp, 1)), 16, 2), 8, ‘0′,STR_PAD_LEFT);
                    $r = $g = $b = (($currentByteBits[$bitPointer] == ‘1′)?0:255);
                    $bitPointer++;
                    if ($bitPointer == 8)$bitPointer = 0;
                    break;

                case 1:
                case 8: // 8 is indexed with 1 color…, so grayscale
                    $r = $g = $b = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    break;

                case 4: // CMYK
                    $c = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    $currentPointerPos = ftell($this->fp);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $m = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $y = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $k = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $currentPointerPos);
                    $r = round(($c*$k)/(pow(2, $this->infoArray['colorDepth'])-1));
                    $g = round(($m*$k)/(pow(2, $this->infoArray['colorDepth'])-1));
                    $b = round(($y*$k)/(pow(2, $this->infoArray['colorDepth'])-1));

                    break;

                case 9: // hunter Lab
                    // i still need an understandable lab2rgb convert algorithm… if you have one, please let me know!
                    $l = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    $currentPointerPos = ftell($this->fp);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $a = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $b = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $currentPointerPos);

                    $r = $l;
                    $g = $a;
                    $b = $b;

                    break;
                default:
                    $r = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    $currentPointerPos = ftell($this->fp);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $g = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $this->colorBytesLength-1, SEEK_CUR);
                    $b = $this->_getInteger($this->infoArray['oneColorChannelPixelBytes']);
                    fseek($this->fp, $currentPointerPos);
                    break;

            }

            if (($this->infoArray['oneColorChannelPixelBytes'] == 2))
            {
                $r = $r>>8;
                $g = $g>>8;
                $b = $b>>8;
            } elseif (($this->infoArray['oneColorChannelPixelBytes'] == 4))
            {
                $r = $r>>24;
                $g = $g>>24;
                $b = $b>>24;
            }

            $pixelColor = imagecolorallocate($image, $r, $g, $b);
            imagesetpixel($image, $columnPointer, $rowPointer, $pixelColor);
        }
    }
    fclose($this->fp);
    if ( isset ($this->tempFileName))unlink($this->tempFileName);
    return $image;
}

/**
 *
 * PRIVATE FUNCTIONS
 *
 */

function _getPackedBitsDecoded($string)
{
    /*
     The PackBits algorithm will precede a block of data with a one byte header n, where n is interpreted as follows:
     n Meaning
     0 to 127 Copy the next n + 1 symbols verbatim
     -127 to -1 Repeat the next symbol 1 - n times
     -128 Do nothing
     Decoding:
     Step 1. Read the block header (n).
     Step 2. If the header is an EOF exit.
     Step 3. If n is non-negative, copy the next n + 1 symbols to the output stream and go to step 1.
     Step 4. If n is negative, write 1 - n copies of the next symbol to the output stream and go to step 1.
     */

    $stringPointer = 0;
    $returnString = ”;

    while (1)
    {
        if ( isset ($string[$stringPointer]))$headerByteValue = $this->_unsignedToSigned(hexdec(bin2hex($string[$stringPointer])), 1);
        else return $returnString;
        $stringPointer++;

        if ($headerByteValue >= 0)
        {
            for ($i = 0; $i <= $headerByteValue; $i++)
            {
                $returnString .= $string[$stringPointer];
                $stringPointer++;
            }
        } else
        {
            if ($headerByteValue != -128)
            {
                $copyByte = $string[$stringPointer];
                $stringPointer++;

                for ($i = 0; $i < (1-$headerByteValue); $i++)
                {
                    $returnString .= $copyByte;
                }
            }
        }
    }
}

function _unsignedToSigned($int, $byteSize = 1)
{
    switch($byteSize)
    {
        case 1:
            if ($int < 128) return $int;
            else return -256+$int;
            break;

        case 2:
            if ($int < 32768) return $int;
            else return -65536+$int;

        case 4:
            if ($int < 2147483648) return $int;             else return -4294967296+$int;         default:             return $int;     } } function _hexReverse($hex) {     $output = ”;     if (strlen($hex)%2) return false;     for ($pointer = strlen($hex); $pointer >= 0; $pointer -= 2)$output .= substr($hex, $pointer, 2);
    return $output;
}

function _getInteger($byteCount = 1)
{
    switch($byteCount)
    {
        case 4:
            // for some strange reason this is still broken…
            return @reset(unpack( ‘N’,fread($this->fp,4)));
            break;

        case 2:
            return @reset(unpack( ‘n’,fread($this->fp,2)));
            break;

        default:
            return hexdec($this->_hexReverse(bin2hex(fread($this->fp, $byteCount))));
    }
}
}

/**
 * Returns an image identifier representing the image obtained from the given filename, using only GD, returns an empty string on failure
 *
 * @param string $fileName
 * @return image identifier
 */

function imagecreatefrompsd($fileName)
{
    $psdReader = new PhpPsdReader($fileName);
    if ( isset ($psdReader->infoArray['error'])) return ”;
    else return $psdReader->getImage();
}

Un exemple d’utilisation :

      include_once('classPhpPsdReader.php')
      header("Content-type: image/jpeg");
      print imagejpeg(imagecreatefrompsd('test.psd'));
Bookmark and Share
by Raphael Leray | Posted in Uncategorized | No Comments » |
July 6th, 2009

Carnet de dessins #2

carnet_dessin2

Bookmark and Share
by Raphael Leray | Posted in Artwoks, Dessins | No Comments » |