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.
- $filter = new Zend_Filter_Callback('strrev');
- // 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.
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é.
L'appel manuel à une telle fonction se serait fait comme cela:
- $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.
- // Utilisation des paramètres blowfish par défaut
- $filter = new Zend_Filter_Decrypt('myencryptionkey');
- // Utilisation du vecteur utilisé lors de l'encryptage
- $filter->setVector('myvector');
- $decrypted = $filter->filter('texte_encodé_non_lisible');
- 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.
Note: L'adaptateur
OpenSSLne 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().
- // Utilise OpenSSL avec une clé spécifiée
- 'adapter' => 'openssl',
- 'private' => '/path/to/mykey/private.pem'
- ));
- // Passage des clés enveloppe
- '/key/from/encoder/first.pem',
- '/key/from/encoder/second.pem'
- ));
- $filter->setPassphrase('mypassphrase');
Enfin, décryptez le contenu. Voici l'exemple complet:
- // Utilise OpenSSL avec une clé spécifiée
- 'adapter' => 'openssl',
- 'private' => '/path/to/mykey/private.pem'
- ));
- // Passage des clés enveloppe
- '/key/from/encoder/first.pem',
- '/key/from/encoder/second.pem'
- ));
- $filter->setPassphrase('mypassphrase');
- $decrypted = $filter->filter('texte_encodé_illisible');
- 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.
To set another adapter you can also use setAdapter(), and the getAdapter() method to receive the actual set adapter.
- // Use the Mcrypt adapter
- $filter = new Zend_Filter_Encrypt();
- $filter->setAdapter('openssl');
Note: When you do not supply the
adapteroption or do not use setAdapter, then theMcryptadapter 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
mcryptextension. -
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.
- // Use the default blowfish settings
- $filter = new Zend_Filter_Encrypt('myencryptionkey');
- // Set a own vector, otherwise you must call getVector()
- // and store this vector for later decryption
- $filter->setVector('myvector');
- // $filter->getVector();
- $encrypted = $filter->filter('text_to_be_encoded');
- print $encrypted;
- // 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.
- // Use openssl and provide a private key
- 'adapter' => 'openssl',
- 'private' => '/path/to/mykey/private.pem'
- ));
- // of course you can also give the public keys at initiation
- '/public/key/path/first.pem',
- '/public/key/path/second.pem'
- ));
Note: Note that the
OpenSSLadapter 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.
- // Use openssl and provide a private key
- 'adapter' => 'openssl',
- 'private' => '/path/to/mykey/private.pem'
- ));
- // of course you can also give the public keys at initiation
- '/public/key/path/first.pem',
- '/public/key/path/second.pem'
- ));
- $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.
- // Use openssl and provide a private key
- 'adapter' => 'openssl',
- 'private' => '/path/to/mykey/private.pem'
- ));
- // of course you can also give the public keys at initiation
- '/public/key/path/first.pem',
- '/public/key/path/second.pem'
- ));
- $filter->setPassphrase('mypassphrase');
- $encrypted = $filter->filter('text_to_be_encoded');
- $envelope = $filter->getEnvelopeKey();
- print $encrypted;
- // 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:
- // Initiate the filter
- $filter = new Zend_Filter_LocalizedToNormalized();
- $filter->filter('123.456,78');
- // 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:
- // Numeric Filter
- $filter->filter('123.456');
- // returns the value '123456.00'
- $filter->filter('123.456,78901');
- // 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.
- // Initiate the filter
- $filter = new Zend_Filter_LocalizedToNormalized();
- $filter->filter('12.April.2009');
- // 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.
- // Date Filter
- $filter = new Zend_Filter_LocalizedToNormalized(
- );
- $filter->filter('11:22:33');
- // 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:
- // Initiate the filter
- $filter = new Zend_Filter_NormalizedToLocalized();
- $filter->filter(123456.78);
- // 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:
- // Numeric Filter
- $filter->filter(123456);
- // returns the value '123.456,00'
- $filter->filter(123456.78901);
- // 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.
- // Initiate the filter
- $filter = new Zend_Filter_NormalizedToLocalized();
- // 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.
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.
- $filter = new Zend_Filter_RealPath();
- $path = '/www/var/path/../../mypath';
- $filtered = $filter->filter($path);
- // 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().
- $filter = new Zend_Filter_RealPath(false);
- $path = '/www/var/path/../../non/existing/path';
- $filtered = $filter->filter($path);
- // 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 |
