Programmer's Reference Guide

Introduction

Classes de filtre standards

Zend Framework est fourni avec un jeu de filtres standards, qui sont directement utilisables.

Alnum

Retourne la chaîne $value, en retirant tout sauf les caractères alphabétiques et numériques. Ce filtre inclue une option permettant d'autoriser ou non les caractères espace.

Note: Les caractères alphabétiques comprennent les caractères destinés à constituer des mots dans chaque langue. Cependant l'alphabet anglais est aussi utilisé pour les langues suivantes : chinois, japonais et coréen. La langue est spécifiée par Zend_Locale.

Alpha

Retourne la chaîne $value, en retirant tout sauf les caractères alphabétiques. Ce filtre inclue une option permettant d'autoriser ou non les caractères espace.

BaseName

En passant une chaîne contenant un chemin vers un fichier, ce filtre retourne le nom de base du fichier.

Callback

Ce filtre vous permet d'utiliser votre propre fonction en tant que filtre de Zend_Filter. Nul besoin de créer un filtre si une fonction ou méthode fait déja le travail.

Par exemple un filtre qui inverse une chaine.

  1. $filter = new Zend_Filter_Callback('strrev');
  2.  
  3. print $filter->filter('Hello!');
  4. // retourne "!olleH"

C'est très simple de passer une fonction à appliquer comme filtre. Dans le cas de méthodes de classes, passez un tableau comme callback.

  1. // Notre classe
  2. class MyClass
  3. {
  4.     public function Reverse($param);
  5. }
  6.  
  7. // La définition du filtre
  8. $filter = new Zend_Filter_Callback(array('MyClass', 'Reverse'));
  9. print $filter->filter('Hello!');

Pour récupérer la fonction de filtrage actuelle, utilisez getCallback() et pour en affecter une nouvelle, utilisez setCallback().

Il est aussi possible de définir des paramètres par défaut qui sont alors passés à la méthode appelée lorsque le filtre est exécuté.

  1. $filter = new Zend_Filter_Callback(
  2.     'MyMethod',
  3.     array('key' => 'param1', 'key2' => 'param2')
  4. );
  5. $filter->filter(array('value' => 'Hello'));

L'appel manuel à une telle fonction se serait fait comme cela:

  1. $value = MyMethod('Hello', 'param1', 'param2');

Note: Notez que passer une fonction qui ne peut être appelée mènera à une exception.

Decrypt

Ce filtre va décrypter toute chaine grâce aux paramètres utilisés. Des adaptateurs sont utilisés. Actuellement des aptateurs existent pour les extensions Mcrypt et OpenSSL de php.

Pour plus de détails sur l'encryptage de contenu, voyez le filtre Encrypt. La documentation de celui-ci couvre les bases en matière de cryptage, nous n'aborderons ici que les méthodes utilisées pour le décryptage.

Décryptage avec Mcrypt

Pour décrypter une données cryptées avec Mcrypt, vous avez besoin des paramètres utilisés pour encrypter, ainsi que du vecteur.

Si vous n'aviez pas passé de vecteur spécifique à l'encryptage, alors vous devriez récupérer le vecteur utilisé grâce à la méthode getVector(). Sans ce vecteur, aucun décryptage de la données originale n'est possible.

Le décryptage s'effectue aussi simplement que l'encryptage.

  1. // Utilisation des paramètres blowfish par défaut
  2. $filter = new Zend_Filter_Decrypt('myencryptionkey');
  3.  
  4. // Utilisation du vecteur utilisé lors de l'encryptage
  5. $filter->setVector('myvector');
  6.  
  7. $decrypted = $filter->filter('texte_encodé_non_lisible');
  8. print $decrypted;

Note: Si l'extension mcrypt n'est pas présente dans votre environement, une exception sera levée.

Note: Vos paramètres sont vérifiés à la création de l'instance ou à l'appel de setEncryption(). Si mcrypt détecte des problèmes avec ces paramètres, une exception sera levée.

Decryptage avec OpenSSL

Le décryptage avec OpenSSL est aussi simple que l'encryptage. Mais vous aurez besoin de toutes les données concernant la personne ayant crypté la donnée de référence.

Pour décrypter avec OpenSSL vous devez posséder:

  • private: Votre clé privée. Ce peut être un nom de fichier ou juste le contenu de ce fichier : la clé.

  • envelope: La clé enveloppe cryptée de l'utilisateur qui a crypté le document. Un chemin de fichier ou une chaine peuvent être utilisés.

  1. // Utilise OpenSSL avec une clé spécifiée
  2. $filter = new Zend_Filter_Decrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // Passage des clés enveloppe
  8. $filter->setEnvelopeKey(array(
  9.     '/key/from/encoder/first.pem',
  10.     '/key/from/encoder/second.pem'
  11. ));

Note: L'adaptateur OpenSSL ne fonctionnera pas avec des clés non valides.

Optionnellement il peut être nécessaire de passer la passphrase pour décrypter les clés elles-mêmes. Utilisez alors setPassphrase().

  1. // Utilise OpenSSL avec une clé spécifiée
  2. $filter = new Zend_Filter_Decrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // Passage des clés enveloppe
  8. $filter->setEnvelopeKey(array(
  9.     '/key/from/encoder/first.pem',
  10.     '/key/from/encoder/second.pem'
  11. ));
  12. $filter->setPassphrase('mypassphrase');

Enfin, décryptez le contenu. Voici l'exemple complet:

  1. // Utilise OpenSSL avec une clé spécifiée
  2. $filter = new Zend_Filter_Decrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // Passage des clés enveloppe
  8. $filter->setEnvelopeKey(array(
  9.     '/key/from/encoder/first.pem',
  10.     '/key/from/encoder/second.pem'
  11. ));
  12. $filter->setPassphrase('mypassphrase');
  13.  
  14. $decrypted = $filter->filter('texte_encodé_illisible');
  15. print $decrypted;

Digits

Retourne la chaîne $value, en retirant tout sauf les caractères numériques.

Dir

Retourne la partie correspondant au nom de dossier dans le chemin spécifié.

Encrypt

This filter will encrypt any given string with the provided setting. Therefor it makes use of Adapters. Actually there are adapters for the Mcrypt and OpenSSL extensions from php.

As these two encryption methodologies work completely different, also the usage of the adapters differ. You have to select the adapter you want to use when initiating the filter.

  1. // Use the Mcrypt adapter
  2. $filter1 = new Zend_Filter_Encrypt(array('adapter' => 'mcrypt'));
  3.  
  4. // Use the OpenSSL adapter
  5. $filter2 = new Zend_Filter_Encrypt(array('adapter' => 'openssl'));

To set another adapter you can also use setAdapter(), and the getAdapter() method to receive the actual set adapter.

  1. // Use the Mcrypt adapter
  2. $filter = new Zend_Filter_Encrypt();
  3. $filter->setAdapter('openssl');

Note: When you do not supply the adapter option or do not use setAdapter, then the Mcrypt adapter will be used per default.

Encryption with Mcrypt

When you have installed the Mcrypt extension you can use the Mcrypt adapter. This adapter supports the following options at initiation:

  • key: The encryption key with which the input will be encrypted. You need the same key for decryption.

  • algorithm: The algorithm which has to be used. It should be one of the algorithm ciphers which can be found under » PHP's mcrypt ciphers. If not set it defaults to blowfish.

  • algorithm_directory: The directory where the algorithm can be found. If not set it defaults to the path set within the mcrypt extension.

  • mode: The encryption mode which has to be used. It should be one of the modes which can be found under » PHP's mcrypt modes. If not set it defaults to cbc.

  • mode_directory: The directory where the mode can be found. If not set it defaults to the path set within the mcrypt extension.

  • vector: The initialization vector which shall be used. If not set it will be a random vector.

  • salt: If the key should be used as salt value. The key used for encryption will then itself also be encrypted. Default is false.

If you give a string instead of an array, this string will be used as key.

You can get/set the encryption values also afterwards with the getEncryption() and setEncryption() methods.

Note: Note that you will get an exception if the mcrypt extension is not available in your environment.

Note: You should also note that all settings which be checked when you create the instance or when you call setEncryption(). If mcrypt detects problem with your settings an exception will be thrown.

You can get/set the encryption vector by calling getVector() and setVector(). A given string will be truncated or padded to the needed vector size of the used algorithm.

Note: Note that when you are not using an own vector, you must get the vector and store it. Otherwise you will not be able to decode the encoded string.

  1. // Use the default blowfish settings
  2. $filter = new Zend_Filter_Encrypt('myencryptionkey');
  3.  
  4. // Set a own vector, otherwise you must call getVector()
  5. // and store this vector for later decryption
  6. $filter->setVector('myvector');
  7. // $filter->getVector();
  8.  
  9. $encrypted = $filter->filter('text_to_be_encoded');
  10. print $encrypted;
  11.  
  12. // For decryption look at the Decrypt filter

Encryption with OpenSSL

When you have installed the OpenSSL extension you can use the OpenSSL adapter. This adapter supports the following options at initiation:

  • public: The public key of the user whom you want to provide the encrpted content. You can give multiple public keys by using an array. You can eigther provide the path and filename of the key file, or just the content of the key file itself.

  • private: Your private key which will be used for encrypting the content. Also the private key can be eighter a filename with path of the key file, or just the content of the key file itself.

You can get/set the public keys also afterwards with the getPublicKey() and setPublicKey() methods. The private key can also be get and set with the related getPrivateKey() and setPrivateKey() methods.

  1. // Use openssl and provide a private key
  2. $filter = new Zend_Filter_Encrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // of course you can also give the public keys at initiation
  8. $filter->setPublicKey(array(
  9.     '/public/key/path/first.pem',
  10.     '/public/key/path/second.pem'
  11. ));

Note: Note that the OpenSSL adapter will not work when you do not provide valid keys.

When you want to encode also the keys, then you have to provide a passphrase with the setPassphrase() method. When you want to decode content which was encoded with a passphrase you will not only need the public key, but also the passphrase to decode the encrypted key.

  1. // Use openssl and provide a private key
  2. $filter = new Zend_Filter_Encrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // of course you can also give the public keys at initiation
  8. $filter->setPublicKey(array(
  9.     '/public/key/path/first.pem',
  10.     '/public/key/path/second.pem'
  11. ));
  12. $filter->setPassphrase('mypassphrase');

At last, when you use OpenSSL you need to give the receiver the encrypted content, the passphrase when have provided one, and the envelope keys for decryption.

This means for you, that you have to get the envelope keys after the encryption with the getEnvelopeKey() method.

So our complete example for encrypting content with OpenSSL look like this.

  1. // Use openssl and provide a private key
  2. $filter = new Zend_Filter_Encrypt(array(
  3.     'adapter' => 'openssl',
  4.     'private' => '/path/to/mykey/private.pem'
  5. ));
  6.  
  7. // of course you can also give the public keys at initiation
  8. $filter->setPublicKey(array(
  9.     '/public/key/path/first.pem',
  10.     '/public/key/path/second.pem'
  11. ));
  12. $filter->setPassphrase('mypassphrase');
  13.  
  14. $encrypted = $filter->filter('text_to_be_encoded');
  15. $envelope  = $filter->getEnvelopeKey();
  16. print $encrypted;
  17.  
  18. // For decryption look at the Decrypt filter

HtmlEntities

Retourne la chaîne $value, en convertissant les caractères en leurs entités HTML correspondantes quand elles existent.

Int

Retourne la valeur (int) $value.

LocalizedToNormalized

This filter will change any given localized input to it's normalized representation. It uses in Background Zend_Locale to do this transformation for you.

This allows your user to enter informations in his own language notation, and you can then store the normalized value into your database for example.

Note: Please note that normalization is not equal to translation. This filter can not translate strings from one language into another like you could expect with months or names of days.

The following input types can be normalized:

  • integer: Integer numbers, which are localized, will be normalized to the english notation.

  • float: Float numbers, which are localized, will be normalized to the english notation.

  • numbers: Other numbers, like real, will be normalized to the english notation.

  • time: Time values, will be normalized to a named array.

  • date: Date values, will be normalized to a named array.

Any other input will be returned as it, without changing it.

Note: You should note that normalized output is always given as string. Otherwise your environment would transfor the normalized output automatically to the notation used by the locale your environment is set to.

Normalization for numbers

Any given number like integer, float or real value, can be normalized. Note, that numbers in scientific notation, can actually not be handled by this filter.

So how does this normalization work in detail for numbers:

  1. // Initiate the filter
  2. $filter = new Zend_Filter_LocalizedToNormalized();
  3. $filter->filter('123.456,78');
  4. // returns the value '123456.78'

Let's expect you have set the locale 'de' as application wide locale. Zend_Filter_LocalizedToNormalized will take the set locale and use it to detect which sort of input you gave. In our example it was a value with precision. Now the filter will return you the normalized representation for this value as string.

You can also control how your normalized number has to look like. Therefor you can give all options which are also used by Zend_Locale_Format. The most common are:

  • date_format

  • locale

  • precision

For details about how these options are used take a look into this Zend_Locale chapter.

Below is a example with defined precision so you can see how options work:

  1. // Numeric Filter
  2. $filter = new Zend_Filter_LocalizedToNormalized(array('precision' => 2));
  3.  
  4. $filter->filter('123.456');
  5. // returns the value '123456.00'
  6.  
  7. $filter->filter('123.456,78901');
  8. // returns the value '123456.79'

Normalization for date and time

Input for date and time values can also be normalized. All given date and time values will be returned as array, where each date part is given within a own key.

  1. // Initiate the filter
  2. $filter = new Zend_Filter_LocalizedToNormalized();
  3. $filter->filter('12.April.2009');
  4. // returns array('day' => '12', 'month' => '04', 'year' => '2009')

Let's expect you have set the locale 'de' again. Now the input is automatically detected as date, and you will get a named array in return.

Of course you can also control how your date input looks like with the date_format and the locale option.

  1. // Date Filter
  2. $filter = new Zend_Filter_LocalizedToNormalized(
  3.     array('date_format' => 'ss:mm:HH')
  4. );
  5.  
  6. $filter->filter('11:22:33');
  7. // returns array('hour' => '33', 'minute' => '22', 'second' => '11')

NormalizedToLocalized

This filter is the reverse of the filter Zend_Filter_LocalizedToNormalized and will change any given normalized input to it's localized representation. It uses in Background Zend_Locale to do this transformation for you.

This allows you to give your user any stored normalised value in a localized manner, your user is more common to.

Note: Please note that localization is not equal to translation. This filter can not translate strings from one language into another like you could expect with months or names of days.

The following input types can be localized:

  • integer: Integer numbers, which are normalized, will be localized to the set notation.

  • float: Float numbers, which are normalized, will be localized to the set notation.

  • numbers: Other numbers, like real, will be localized to the set notation.

  • time: Time values, will be localized to a string.

  • date: Date values, will be normalized to a string.

Any other input will be returned as it, without changing it.

Localization for numbers

Any given number like integer, float or real value, can be localized. Note, that numbers in scientific notation, can actually not be handled by this filter.

So how does localization work in detail for numbers:

  1. // Initiate the filter
  2. $filter = new Zend_Filter_NormalizedToLocalized();
  3. $filter->filter(123456.78);
  4. // returns the value '123.456,78'

Let's expect you have set the locale 'de' as application wide locale. Zend_Filter_NormalizedToLocalized will take the set locale and use it to detect which sort of output you want to have. In our example it was a value with precision. Now the filter will return you the localized representation for this value as string.

You can also control how your localized number has to look like. Therefor you can give all options which are also used by Zend_Locale_Format. The most common are:

  • date_format

  • locale

  • precision

For details about how these options are used take a look into this Zend_Locale chapter.

Below is a example with defined precision so you can see how options work:

  1. // Numeric Filter
  2. $filter = new Zend_Filter_NormalizedToLocalized(array('precision' => 2));
  3.  
  4. $filter->filter(123456);
  5. // returns the value '123.456,00'
  6.  
  7. $filter->filter(123456.78901);
  8. // returns the value '123.456,79'

Localization for date and time

Normalized for date and time values can also be localized. All given date and time values will be returned as string, with the format defined by the set locale.

  1. // Initiate the filter
  2. $filter = new Zend_Filter_NormalizedToLocalized();
  3. $filter->filter(array('day' => '12', 'month' => '04', 'year' => '2009');
  4. // returns '12.04.2009'

Let's expect you have set the locale 'de' again. Now the input is automatically detected as date, and will be returned in the format defined by the locale 'de'.

Of course you can also control how your date input looks like with the date_format, and the locale option.

  1. // Date Filter
  2. $filter = new Zend_Filter_LocalizedToNormalized(
  3.     array('date_format' => 'ss:mm:HH')
  4. );
  5.  
  6. $filter->filter(array('hour' => '33', 'minute' => '22', 'second' => '11'));
  7. // returns '11:22:33'

Int

Retourne la valeur $value en enlevant les caractères représentant une nouvelle ligne.

RealPath

Ce filtre va résoudre un lien ou un chemin en chemin absolu canonique. Toutes références à '/./', '/../' et tout ajout supplémentaire de '/' sera résolu ou supprimé. Aucun caractère de lien symbolique ne sera présent dans le résultat ('/./' ou '/../')

Zend_Filter_RealPath retourne FALSE en cas d'echec par exemple si le fichier n'existe pas. Sur les systems BSD, Zend_Filter_RealPath n'échoue pas si seule la dernière partie du chemin n'existe pas, les autres systèmes retourneront FALSE.

  1. $filter = new Zend_Filter_RealPath();
  2. $path   = '/www/var/path/../../mypath';
  3. $filtered = $filter->filter($path);
  4.  
  5. // retourne '/www/mypath'

Il peut être nécessaire quelques fois de vouloir utiliser ce filtre sur des chemins inexistants. Par exemple récupérer le realpath d'un chemin à créer. Dans ce cas vous pouvez passer FALSE au constructeur, ou utiliser setExists().

  1. $filter = new Zend_Filter_RealPath(false);
  2. $path   = '/www/var/path/../../non/existing/path';
  3. $filtered = $filter->filter($path);
  4.  
  5. // retourne '/www/non/existing/path' même si file_exists ou realpath retourneraient false

StringToLower

Retourne la chaîne $value, en convertissant les caractères alphabétiques en minuscules si nécessaire.

StringToUpper

Retourne la chaîne $value, en convertissant les caractères alphabétiques en majuscules si nécessaire.

StringTrim

Retourne la chaîne $value en supprimant les caractères vides en début et fin de chaîne.

StripTags

Ce filtre retourne une chaîne, où toutes les balises HTML et PHP sont supprimées, exceptées celles qui sont explicitement autorisées. En plus de pouvoir spécifier quelles balises sont autorisées, les développeurs peuvent spécifier quels attributs sont autorisés soit pour toutes les balises autorisées soit pour des balises spécifiques seulement. Pour finir, ce filtre permet de contrôler si les commentaires (par exemple <!-- ... -->) sont refusés ou autorisés.


Introduction
blog comments powered by Disqus

Select a Version

Languages Available

Components

Search the Manual