Synopsis - theopenunderground.de
Transcrição
Synopsis - theopenunderground.de
PEAR-Handbuch Herausgegeben von Daniel Convissor Martin Jansen Alexander Merz 22-01-2006 Copyright © 2001, 2002, 2003, 2004, 2005, 2006 von The PEAR Documentation Group Copyright Copyright © 2001 - 2006 by the PEAR Documentation Group. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. The PEAR Documentation Group consists of all the people that have contributed documentation to the PEAR manual. Representatives are listed on the front page of this manual. In case you would like to contact the group, please write to [email protected]. Copyright for the XML_RPC documentation The documentation of the XML_RPC package has originally been written by Edd Dumbill as an independent document on his homepage and is published as part of the PEAR Manual under the following license restrictions: Copyright © 1999,2000,2001 by Edd Dumbill, Useful Information Company All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. • • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the "XML-RPC for PHP" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Inhaltsverzeichnis Vorwort Über dieses Handbuch Der Aufbau des Handbuchs Autoren und Beteiligte I. Über PEAR 1. Einführung 2. Installation 3. Support 4. Coding Standards 5. Contributing 6. FAQ - Frequently Asked Questions II. Leitfaden für neue Entwickler 7. Introduction 8. When to contribute (and when not to contribute) 9. Getting started with the community 10. The formal proposal process 11. Taking over an unmaintained package III. Entwickler-Leitfaden 12. Introduction 13. PEAR's meaning for developers 14. Contributing your own code 15. The package definition file package.xml 16. The package definition file package.xml, version 2.0 17. Releasing A Package 18. Supporting PEAR development 19. Recommendations 20. Writing documentation IV. Neue Funktionen in PEAR 1.4 21. Introduction 22. Channels 23. Custom File Roles 24. Custom File Tasks 25. Post-installation Scripts V. Core-Bestandteile 26. PEAR base classes 27. PEAR Installer classes VI. Packages 28. Authentication 29. Benchmarking 30. Caching 31. Configuration 32. Console 33. Database 34. Date and Time 35. Encryption 36. Event 37. File Formats 38. File System 39. Gtk 40. HTML 41. HTTP 42. Images 43. Internationalization 44. Logging 45. Mail 46. Math 47. Networking 48. Numbers 49. Payment 50. PEAR 51. PHP 52. Science 53. Streams 54. Structures 55. System 56. Text 57. Tools and Utilities 58. XML 59. Web Services VII. PECL Packages I. Imagick II. KADM5 III. Radius IV. Net_Gopher V. PostScript document creation VI. Satellite CORBA client extension VII. PostgreSQL Session Save Handler VIII. SPPLUS Payment System IX. Net_Gopher X. oggvorbis Vorwort PEAR ist die Abkürzung für: PHP Extension and Application Repository. Über dieses Handbuch Dieses Handbuch wird gepflegt in XML unter Benutzung der DocBook XML DTD und formatiert mit DSSSL (Document Style and Semantics Specification Language). Um die HTML-Versionen zu erzeugen, wird benutzt: Jade, von James Clark und die Modular DocBook Stylesheets von Norman Walsh. Die Struktur für das Handbuch basiert auf den Arbeiten der PHP Documentation Group. Lesen Sie dazu für mehr Information About the PHP manual. Der Aufbau des Handbuchs Diese Einführung erklärt die allgemeine Struktur, das Layout und die Konventionen im PEAR-Handbuch. Es ist unterteilt in sechs große Teile, die sind: • Über PEAR Dieser Teil enthält eine Einführung darüber, was PEAR ist und was es bietet. Dazu kommen allgemeine Informationen über die Installation und die Benutzung von PEAR, Support-Möglichkeiten und beantwortet häufig gestellte Fragen zu PEAR. • Entwickler-Leitfaden Allgemeine Informationen über die Entwicklung und Herausgabe von PEAR- Packages. • Core-Bestandteile Dieser Teil dokumentiert die PEAR-Core-Klassen. Sie sind die Basis für jede Klasse in PEAR - wenn Sie die Core-Klassen kennen, dürfte das Arbeiten mit den übrigen keine Schwierigkeit sein. Themen sind u.a.: PEAR, PEAR verwalten, die Fehlerbehandlung über die PEAR_Error-Klasse, und system-nahe Kommandos. Die hier beschriebenen Funktionen sind Bestandteil jeder orginalen PHP-Distribution. • Packages Es gibt eine wachsende Anzahl von PEAR-Packages. Viele sind hier dokumentiert aber standardmäßig nicht installiert. Für die Installation von PEAR Packages lesen Sie bitte das Installation chapter. Die Dokumentation für jede Klasse enthält zumindest eine Beschreibung aller öffentlichen Methoden. Häufig sind zusätzlich verfügbar: eine Einführung, eine Auflistung definierter Konstanten und Anwendungs-Beispiele. Daneben gibt es natürlich noch Informationen im Quellcode der Klassen selbst. Die Beschreibung jeder Methode enthält einige oder alle folgenden Teile: • Synopsis Zeigt den Aufbau der Methode • Beschreibung Beschreibt, was die Methode tut • Parameter Beschreibt jeden Parameter der Methode mit ihrem Namen und Datentyp. Es werden erforderliche und optionalen Parameter aufgeführt • Rückgabewert Beschreibt den Rückgabewert, wenn kein Fehler auftritt • Fehler-Meldungen Beschreibt das zurückgelieferte PEAR_Error-Objekt wenn ein Fehler auftritt • Hinweise Zusätzliche Hinweise über eine Methode. Z.B. ist hier vermerkt, wenn eine Methode statisch aufgerufen werden kann. • Siehe auch Links zu zugehörigen Methoden oder Handbuch-Seiten • Beispiel Ein Benutzungs-Beispiel für die Methode oder Klasse • PECL Packages PECL Packages sind normale PHP-Erweiterungen in C. Die Dokumentations-Struktur sollte denen des Package-Teils gleichen • An PEAR mitarbeiten Enthält Information zum Schreiben eigener PEAR-Packages Autoren und Beteiligte Die folgende Liste enthält die Namen derjenigen, die an diesem Handbuch beteiligt sind. Wenn Sie einen kontaktieren möchten, schreiben Sie bitte an [email protected]. • Lorenzo Alberton • Gregory Beaver • Daniel Convissor • David Costa • Thomas V.V. Cox • Martin Jansen • Alan Knowles • Clay Loveless • Alexander Merz • Stefan Neufeind • Jon Parise • Tobias Schlitt • Stephan Schmidt • Mika Tuupola • Michael Wallner (In alphabetischer Reihenfolge) I. Über PEAR Inhaltsverzeichnis 1. Einführung 2. Installation 3. Support 4. Coding Standards 5. Contributing 6. FAQ - Frequently Asked Questions Kapitel 1. Einführung Das PEAR-Manifest PEAR ist Malin Bakken gewidmet, sie wurde geboren am 21.11.1999. Was ist PEAR? PEAR ist die Abkürzung für „PHP Extension and Application Repository“ und wird ausgesprochen wie die englische übersetzung von "Birne". Der Zweck von PEAR ist es anzubieten: • Eine aufgeräumte Bibliothek von offenem Quellcode für PHP-Programmierer • Eine Infrastruktur für den Vertrieb von Quellcode und deßen Betreuung • Einen einheitlichen Stil für Quellcode in PHP, wie er hier beschrieben wird • Die PHP Extension Community Library (PECL), mehr hier • Eine Webseite, Mailing-Listen und ein Netz von Download-Servern um die PHP/PEAR-Gemeinschaft zu unterstützen PEAR ist ein Gemeinschafts-Projekt mit der PEAR Group als Normen-gebende Kraft. Das Projekt wurde begründete 1999 von Stig S. Bakken, seit dem schloßen sich dem Projekt viele weitere an. Eine aufgräumte Bibliothek für PHP-Code Der Quellcode in PEAR ist aufgeteilt in „Packages“. Jedes Package ist ein selbständiges Projekt mit eigenem Entwickler-Team, Versionierung, Herausgabe-Zyklen und festgelgten Beziehungen zu anderen Packages (einschließlich äbhängigkeiten) Packages werden verteilt in Form von gepackten Daten (mit Hilfe von Tar und GZip). Jedes enthält eine beschreibende Datei; die Installation erfolgt auf dem eigenem Computer über den PEARInstaller Es gibt zwei Arten von Packages: • • "source packages" enthalten nur Quellcode. Dabei handelt es sich entweder um PHP-Quellcode oder C-Quellcode. Zum Einsatz letzterer benötigten Sie die entsprechenden Werkzeuge zur Erzeugung lauffähiger Dateien. "binary packages" enthalten ausführbare Dateien und eventuell Quellcode. Sie sind typischerweise plattform-spezifisch. Die Packages sind in PEAR in Form eines Baumes organisiert. Die „Knoten“ des Baums finden sich wieder im Namen des Packages. Die Knoten dienen als Beschreibungen; und die Knoten im Name sind durch einen Unterstrich abgegrenzt. Beispiele für Package-Namen sind: „MP3_Id“, „Archive_Tar“ und „HTTP_Post“. Sind Packages von einander abhängig, so muß das ausdrücklich angegeben werden - es gibt keine automatische Beziehung zwischen Packages auf Grund des Namens. Z.B. gibt es keine Abhängigkeit zwischen einen Package und seinem „Vater“ im Package-Baum: das Package „HTTP_Post“ ist unabhängig von dem Package „HTTP“. Einige obere Knoten im Package-Baum haben eine spezielle Funktion und werden deshalb „Sub-Repository“ genannt, aktuell sind das: PECL und Gtk. Für jedes dieser gelten abweichende Regeln, beachten Sie die Beschreibungen zu diesen Sub-Repositorys weiter unten. Der Stil-Leitfaden, die PEAR Coding Standards (kurz PCS), wurde geschaffen, um die Zusammenarbeit zwischen den PEAR-Entwicklern zu vereinfachen, Qualität zu sichern und portablen Quellcode zu schreiben - und um allen Beteiligten einheitliche Schnittstellen zu bieten. Quellcode-Vertrieb und Package-Betreuung Alle PEAR-Packages werden in einer zentralen Datenbank verwaltet und sind von dort verfügbar. Diese Datenbank befindet sich auf pear.php.net. Quellcode-offene Packages können ebenfalls dort registriert und bereitgestellt werden. Nicht-offene Packages können über den PEAR-Installer installiert werden, die PEAR-Datenbank steht aber allein offenen Packages zur Verfügung. Pear.php.net bietet eine HTML-basierte Benutzeroberfläche für die PEAR-Datenbank, und eine eine (aktuell) XML-RPC-basierte Schnittstelle für den maschinellen Zugriff. Das Herunterladen von Packages geschieht über HTTP. Andere Funktionen von pear.php.net sind bzw. werden sein: • die Verwaltung der Konten der PEAR-Beteiligten (einschließlich des CVS-Zugriffs) • Die Package-Verwaltung • Die Release-Verwaltung von Packages Packages werden vertrieben als gezippte Tar-Dateien, in dem sich auf jeden Fall eine XML-basierte Beschreibungs-Datei befindet. Diese Datei enthält Informationen über das Package, eine Liste der entahlten Dateien und ihrer Funktion, und Package-Abhängigkeiten. Die PHP Extension Community Library (PECL) PECL PECL (englisch ausgesprochen „pickle“) ist ein Sub-Repository von PEAR für Erweiterungen in C, wie sie mit PHP4 vertrieben werden. PECL entstand u.a. deshalb, um Erweiterungem aus der Entwicklung von PHP heraus zu ziehen. PECL-Packages müßen den PHP-Coding Standards enstprechen; sie werden aber als normale PEAR-Packages vertrieben und installiert. Das Verschieben einer Erweiterung von PHP zu PECL wird auch als „pickling“ bezeichnet. Oktober 2003 wurde PECL eine eigenständiges Projekt, das nicht mehr Bestandteil von PEAR ist - mit Ausnahme der Infrastruktur, die sich von PEAR ausgeliehen wurde. Mehr Informationen und alle PECL-Packages können auf der PECL Homepage gefunden werden. Während der Ausgliederung wurde PECL umbenannt von „PHP Extension Code Library“ in „PHP Extension Community Library“. Gtk-Packages Gtk Gtk-Packages sind Programme, die auf dem PHP-GTK- Projekt basieren. Quellcode in diesem Sub-Repository folgt den PEAR Coding-Standards. Kapitel 2. Installation Diese Kapitel beschreibt, wie man Packages von PEAR installiert Einführung Bevor Sie dieses Kapitel lesen, sollten Sie mit der Idee von PEAR vertraut sein. Die PHP-Distribution enthält bereits alles, um die PEAR-Werkzeuge für die Installation zu nutzen. Mit einer einer aktuellen PHP-Installation können Sie sich zurücklegen: Die PEAR-Basis-Installation ist bereits vorhanden - es sei denn Sie haben PHP installiert mt der ./configure-Einstellung --without-pear. Bei einigen Unix/Linux/BSD-Distributionen liefern PHP-Versionen mit, bei denen PEAR erst noch manuell installiert werden muss. Beachten Sie in diesem Fall die entsprechende Dokumentation zur Distribution. Die Packages, die nicht bereits mit zur Distribution gehören, können Sie mit dem PEARPackage-Manager installieren. Er ist vergleichbar mit Debian's „apt-get“. Zur Wiederholung: Mit einer aktuellen PHP-Installation (> 4.3.0) können Sie den nächsten Abschnitt überspringen. Nur wenn Sie die PHP-Version 4.2.* oder frühere benutzen, müsssen Sie den Manager von Hand installieren. Neben der Package-Installation übernimmt der PEAR-Package-Manager weitere Aufgaben: Er kann neue Packages erzeugen auf ihrem Computer, verwaltet eine Datenbank der installierten PAckages, überprüft Abhängigkeiten; und er kann über den XML-RPCService auf pear.php.net einige weitere Aufgaben übernehmen. Den Manager herunterladen Unix/Linux/BSD Mit PHP >= 4.3.0 ist der PEAR-Package-Manager bereits installiert, ausser es wurde bei ./configure die Einstellung --without-pear angegeben. Für alle Versionen vor 4.3.0 oder für eine erneute Installation des Package-Managers können Sie folgerdermaßen vorgehen: $ lynx -source http://go-pear.org/ | php Anmerkung: Einige Linux-Distributionen (z.B. Redhat) benutzen links anstatt lynx als Namen für den Kommandozeilen-HTML-Browser. ändern Sie in diesem Fall die obige Anweisung entsprechend um. Windows Nach dem Herunterladen und der Installation von PHP müssen Sie die Batch-Datei gopear.bat ausführen. Diese befindet sich im Verzeichnis ihrer PHP-Installation, z.B.: c:\php\go-pear.bat. Es werden ihnen einige Fragen gestellt, danach wird der PEARPackage-Manager installiert in einem Pfad entsprechend ihrer Angaben. Zum Schluß müssen Sie den Installations-Pfad, der auf ihre PEAR-Installation zeigt, der Umgebungsvariable PATH zuweisen (Start > Einstellungen > System > Umgebungsvariablen). Oder Sie führen die Datei PEAR_ENV.reg aus (üblicherweise einfach per Doppelklick). Danach können Sie den PEAR-Package-Manager über die Kommandozeile unter Windows benutzen mit dem Aufruf von pear. Um ihre PEAR-Installation auf den neusten Stand zu bringen, rufen Sie in ihrem Browser die URL http://go-pear.org/ auf und speichern die Ausgabe in der Datei go-pear.php. Danach rufen Sie auf: php go-pear.php auf der Kommandozeile, um das Update durchzuführen. PEAR und Web-Hoster Wenn Sie eine Webseite bei eiem Web-Hoster betreiben und keinen direkten Zugriff auf den Server haben (lokal, Telnet oder SSH), dann können Sie den Manager nicht benutzen, wenn Sie nicht zumindest Version 1.4.x und FTP-Zugang haben (SFTP wird derzeit noch nicht unterstützt). Warnung Achtung: Bei FTP werden Passwörter unverschlüsselt übertragen! FTP as a protocol is inherently insecure, as passwords are sent unencrypted. Wenn Sie Kunden bei einem guten Web-Hoster sind, haben Sie gute Chancen, das häufig genutzte PEAR-Packages bereits installiert sind. Ist das nicht der Fall bzw. benötigen Sie weitere Packages, frageb Sie ihren Hoster, ob er sie installieren will. Sollte er sich weigern, schauen Sie sich nach einem neuen Anbieter um, oder versuchen Sie die Packages manuell zu installieren. Der Kommandozeilen-Installer Vorrausetzungen Die folgende Beschreibung geht davon aus, dass die neuste Version des PEAR-PackageManagers installiert ist. Die Installation über die Kommandozeile ist der schnellste Weg PEAR-Packages auf ihrem System zu installieren: Dazu verbindet sich der Manager mit dem PEAR-Package-Server über HTTP, lädt das Package herunter und installiert das Package gemäß ihren Einstellungen. Die voll-automatische Installation Der CLI-Installer ist einfach zu benutzen. Tippen Sie folgendes in ihre Kommandozeile: $ pear install <package> <package> müß durch den Namen des Packages ersetzt werden, dass Sie installieren wollen (z.B. HTTP_Upload). Um eine Liste aller verfügbaren Packages zu bekommen, schauen Sie entweder auf die PEAR-Package-übersicht oder führen Sie diesen Befehl aus: $ pear remote-list Dieses Kommando holt sich die Liste aller Packages, die zur Zeit in PEAR verfügbar sind. Halb-automatische Installation Wenn Sie ein Package von http://pear.php.net/ heruntergeladen haben als gezipptes TarArchiv, können Sie es ebenfalls lokal installieren, dazu geben Sie auf der Kommandozeile ein: $ pear install <file>.tgz Dieses Kommando wird das Package installieren ohne dass eine Online-Verbindung notwendig ist. <file>.tgz muss durch den Namen der heruntergeladenen Datei ersetzt werden. Befehle und Konfigurationsvariablen Hier finden Sie eine Auflistung der verfügbaren Befehle für das PEAR KommandozeilenProgramm. Einige Befehle benötigen Root-Zugriff auf dem Server. Befehl Beschreibung build Erzeugt eine Erweiterung aus dessen Quellcode. bundle Lädt und entpackt eine PECL Erweiterung. channel-add Fügt einen Channel der internen Channel-Liste hinzu. (PEAR 1.4+) channel-alias Definiert einen Aliasnamen für einen Channel (PEAR 1.4+) channel-delete Entfernt einen Channel von der internen Channel-Liste. (PEAR 1.4+) channel-discover Initialisert einen Channel auf Basis des Server-Namens. (PEAR 1.4+) channel-info Zeigt Informationen über einen Channel an. (PEAR 1.4+) channel-update Erneut die Informationen über eine Channel in der internen ChannelListe. (PEAR 1.4+) clear-cache Löscht den XML-RPC-Cache. config-create Erzeugt eine PEAR-Konfigurationsdatei. (PEAR 1.4+) config-get Zeigt eine bestimmte Konfigurationseinstellung an. config-help Zeigt Informationen zur Konfiguration an. config-set Setzt eine bestimmte Konfigurationseinstellung. config-show Zeigt alle Konfigurationseinstellungen an. convert Konvertiert eine package.xml-Datei der Version 1.0 in das Format für Version 2.0. (betrifft nur Package-Entwickler) (PEAR 1.4+) cvsdiff Führt ein "cvs diff -u" über alle Dateien eines Packages aus und zeigt das Resultat an. Befehl Beschreibung cvstag Setzt ein CVS-Release-Tag download Lädt ein Package herunter, installiert es aber nicht. download-all Lädt alle verfügbaren Packages vom Package-Server. info Zeigt Informationen über ein Package an. install Installiert ein Package und liefert eine entsprechende Erfolgsmeldung list Zeigt alle installierten Packages an. list-all Zeigt alle verfügbaren Packages an. list-channels Listet die verfügbaren Channels auf. (PEAR 1.4+) list-files Listet die Dateien eines installierten Packages auf. (PEAR 1.4+) list-upgrades Zeigt alle installierten Packages an, für die Upgrades verfügbar sind. login Stellt eine Verbindung mit einem PEAR-Packageserver her und authentifiziert den Nutzer am Server. logout Logt einen angemeldeten Nutzer an einem PEAR-Packageserver aus. makerpm Erzeugt eine RPM-Specification-Datei von einem PEAR-Package. package Erzeugt ein Package-Archiv. packagedependencies Zeigt Abhängigkeiten eines Packages an. package-validate Prüft, ob eine Package-Archiv konsistent und korrekt ist. remote-info Zeigt Informationen über ein installiertes Package einer entfernten Installation an. remote-list Zeigt alle installierten Packages auf einer entfernten Installation an. run-scripts Startet die Post-Installationsskripte eines Packages. (PEAR 1.4+) Befehl Beschreibung run-tests Startet die Testskripte in einem Verzeichnis. search Durchsucht die Package-Datenbank eines Packageservers. shell-test Testet ob ein Package installiert ist. sign Signiert ein Package-Archiv. uninstall Deinstalliert ein Package und löscht alle installierten Dateien des Packages. update-channels Erneuert die Informationen aller Channels in der internen Channel-Liste. (PEAR 1.4+) upgrade Installiert die aktuelle Version eines Packages. (Siehe auch: preferred_state) upgrade-all Installiert die aktuelle Version, wenn verfügbar, für jedes installierte Packages (Siehe auch: list-upgrades) Und hier finden Sie die Liste der verfügbaren PEAR-Konfigurationsvariablen. Benutzen Sie config-get-, config-help-, config-set- und config-show-Befehle um die entsprechenden Werte zu lesen und zu setzen. Die meisten Werte werden bei der PEARInstallation auf Standardwerte gesetzt, die Sie eventuell anpassen müssen. Variablenname Beschreibung Standardwert bin_dir Verzeichnis, in dem sich die ausführbaren Programme befinden. /usr/bin doc_dir Verzeichnis für die Dokumentation eines Packages. /usr/lib/php/docs ext_dir Verzeichnis, in dem sich die PHPErweiterungen befinden. ./ php_dir Verzeichnis, in dem PHP-Dateien eine Packages installiert werden. /usr/lib/php cache_dir Verzeichnis für Cache-Daten des PEAR- /tmp/pear/cache Variablenname Beschreibung Standardwert Installers. data_dir Verzeichnis, in dem Daten-Dateien eines Packages installiert werden. php_bin Der Pfad und Name des PHP-Interpreters (CLI /usr/bin/php bzw. CGI-Version) um Skripte auszuführen. test_dir Verzeichnis für die Testskripte eines Packages. /usr/lib/php/tests cache_ttk Zeitdauer (Anzahl der Sekunden), während der lokale Cache nicht erneuert wird. („Time To Kill“) 3600 preferred_stat Bevorzugter Packagestatus: stable, beta, e alpha, devel, oder snapshot. /usr/lib/php/data stable umask Zu verwendende umask bei der Installation von Dateien (betrifft nur UNIX-artige Systeme). verbose Gesprächigkeit des PEAR-Installers: 0-3, 1 wobei 3 die umfangreichste Ausgabe darstellt. http_proxy Die optionale Angabe eines HTTP-Proxys (host:port), der beim Herunterladen eines Packages benutzt werden soll. 22 Die Konfigurationsdatei, die benutzt wird um eine lokale PEAR-Installation auf einem remote_config entfernten Server per FTP zu spiegeln. (PEAR 1.4+) auto_discover Automatische Ermittlung unbekannter Channels, aufgrund von Angaben in Befehlen oder bei Abhängigkeiten. 0 pear.php.net (bzw. default_channe Standardmäßig benutzter Channel (PEAR 1.4+) pecl.php.net bei PECLl bezogenen Befehlen) Variablenname Beschreibung Standardwert preferred_mirr Benvorzugter Channel-Mirror (PEAR 1.4+) or pear.php.net (bzw. pecl.php.net bei PECLbezogenen Befehlen) Der standardmäßig zu verwendende Packagemaster_server Server. (Sollte ab 1.4.x nicht mehr benutzt werden.) pear.php.net password Login-Passwort für den Package-Server (betrifft nur Package-Entwickler). sig_bin Der Pfad und der Programmname zum Umgang mit Signaturen. /sw/bin/gpg sig_keydir Das Verzeichnis mit den Signatur-Schlüsseln. /etc/pearkeys sig_keyid Der Name des zu verwendenden SignaturSchlüssels. sig_type Der Type der Signatur (derzeit wird nur gpg unterstützt) username Der Benutzername zur Anmeldung am PackageServer (betrifft nur Package-Entwickler) gpg Installation eines lokalen PEAR-Verzeichnisses bei fremden WebHostern Viele Benutzer sind bei Web-Hostern mit einer system-weiten PEAR-Installation. In einigen Fällen kann es notwendig sein, eine eigene PEAR-Installation zu verwalten, z.B. zur Installation nicht vorhandener Packages. Das ist möglich entweder über Telnet/SSH oder allein per FTP. Ein lokales PEAR-Verzeichnis über SSH Um ein lokales PEAR über SSH zu installieren, führen Sie folgende Befehle aus: PEAR 1.3.5 und frühere Versionen $ pear -s -c ~/.pearrc -d doc_dir=~/pear/docs -d ext_dir=~/pear/ext -d php_dir=~/pear/lib PEAR 1.4 und Neuere $ pear config-create /home/user/pear .pearrc Damit erzeugen Sie eine lokales Konfigurations-Datei in ihrem Home-Verzeichnis sie heißt .pearrc. Wenn Sie dann in .bashrc im Path-Eintrag das Verzeichnis ~/pear/bin hinzufügen, müsste nachfolgender Aufruf funktionieren. Die Path-Angabe muß an erster Stelle in der Datei stehen! (Lautet ihr Startup-Datei anders, müssen Sie den Eintrag natürlich dort machen.) PEAR 1.3.2 und frühere Versionen $ pear -c ~/.pearrc install Archive_Tar PEAR Console_Getopt XML_RPC PEAR 1.3.3 und Neuere $ pear install -o PEAR Damit wird in ihrem Home-Verzeichnis ein Verzeichnis pear erzeugt, dass die zukünftigen Packages aufnimmt. Damit erzeugen Sie eine lokale PEAR-Installation, die oberhalb der systemweiten liegt. Damit die lokalen Packages auch benutzt werden, müssen Sie die include_path-Einstellung von PHP anpassen: <?php ini_set('include_path', '~/pear/lib' . PATH_SEPARATOR . ini_get('include_path')); ?> Alternativ können Sie dies auch in der .htaccess für Apache vornehmen über die Einstellung php_value. Ein lokales PEAR-Verzeichnis über FTP Es gibt zwei Wege eine lokale PEAR-Installation per FTP auf einen anderen Server zu spiegeln: den alten, schweren Weg und den neuen, einfachen Weg. Der neue Weg erfordert unbedingt ein Upgrade von PEAR auf Version 1.4.x. Die neue, verbesserte Methode mit PEAR 1.4.0 und Net_FTP Die Installation einer Kopie einer bestehenden PEAR-Installation über FTP würde mit PEAR 1.4.0 vereinfacht. Häufig ist es problematisch PEAR auf einem Server zu installieren, zu dem man keinen Shell-Zugang besitzt. Die einzige Möglichkeit ist auf FTP zurückzugreifen. Das führt aber bei manchen Packages zu Problemen, wenn diese auf fortgeschrittene Funktionen des Installers aufsetzen, wie z.B. der Einsatz von systemspezifischen Ersetzungen im Quelltext. Der grundlegende Ablauf für die FTP-Variante ist folgender: 1. Sie benötigen eine lauffähige CLI-Version von PEAR auf dem lokalen System. Damit ist das pear-Kommando gemeint, nicht das Web-Interface. 2. Stellen Sie sicher, dass der FTP-Zugang zum Server funktioniert und Sie die erforderlichen Zugriffsrechte zum Schreiben besitzen. 3. Merken Sie sich den vollständigen Pfad zu Ihrem Home-Verzeichnis. 4. Erzeugen Sie eine angepasste Konfigurationsdatei für das lokale System und den Server. 5. Laden Sie die angepasste Konfigurationsdatei für den Server eben dorthin. 6. In der lokalen Konfigurationsdatei setzen Sie den Wert remote_config auf den Pfad der Konfigurationsdatei auf dem Server. 7. Installieren Sie die Packages, die Sie benötigen. 1. Sie benötigen eine lauffähige CLI-Version von PEAR auf dem lokalen System. Damit ist das pear-Kommando gemeint, nicht das Web-Interface! Mehr dazu finden Sie in der Installationsanleitung. 2. Stellen Sie sicher, dass der FTP-Zugang zum Server funktioniert und Sie die erforderlichen Zugriffsrechte zum Schreiben besitzen. Das ist unbedingt notwendig - wenn Sie sich mit einem FTP-Programm auf ihrem Webspace einloggen können, dann haben Sie FTP-Zugang. Der Zugang über SecureFTP (SFTP) wird derzeit nicht unterstützt, das wird aber funktionieren, wenn das Package Net_FTP SFTP unterstützt. Merken Sie sich den Benutzernamen und das Passwort, mit dem Sie sich einloggen, Sie werden es nachher benötigen. Der Test, ob Sie Schreibrechte besitzen ist einfach: Wenn Sie eine Datei hochladen können, dann besitzen Sie Schreibrechte. 3. Merken Sie sich den vollständigen Pfad zu Ihrem Home-Verzeichnis. Wenn Sie den Pfad nicht wissen, dann laden Sie dieses kleine Skript auf Ihren Webspace und rufen es auf: <?php echo dirname(__FILE__); ?> Dann sollten Sie eine Ausgabe erhalten wie z.B. /home/username/htdocs. 4. Erzeugen Sie eine angepasste Konfigurationsdatei für das lokale System und den Server. Die Dateien erzeugen Sie mit dem PEAR-Installer: Unter Windows: Wählen Sie zuerst ein Verzeichnis für die lokale Installationskopie von PEAR, z.B. C:\remote\pear. Auf der Kommandozeile geben Sie ein (wenn Sie sich direkt im WurzelVerzeichnis befinden): C:\> mkdir remote C:\> cd remote C:\remote\> mkdir pear C:\remote\> cd pear C:\remote\pear> pear config-create -w C:\remote\pear remote.ini C:\remote\pear> pear config-create /home/username/pear .pearrc Unter Linux/Unix funktioniert es analog: $ $ $ $ $ $ $ cd mkdir remote cd remote mkdir pear cd pear pear config-create /home/mylocaluser remote.conf pear config-create /home/username/pear .pearrc 5. Laden Sie die angepasste Konfigurationsdatei für den Server eben dorthin. Benutzen Sie einfach ein FTP-Programm Ihrer Wahl zum Hochladen der gerade erzeugten Datei .pearrc in das zu erzeugende Verzeichnis /home/username/pear/ 6. In der lokalen Konfigurationsdatei setzen Sie den Wert remote_config auf den Pfad der Konfigurationsdatei auf dem Server. Unter Windows: C:\remote\pear\> pear -c remote.ini config-set remote_config ftp://user:pass@myremotehost. Unter Linux/Unix: $ pear -c remote.conf config-set remote_config ftp://user:[email protected]/.pearrc 7. Installieren Sie die Packages, die Sie benötigen. Sie können den PEAR-Installer von nun an regulär benutzen. Die lokale und die entfernte PEAR-Installation werden automatisch synchroniziert, wenn neue Packages installiert/geupdatet werden. Wie funktioniert dass? Der Installer installiert ein Package zuerst lokal und benutzt dann Net_FTP, um eine Kopie jeder installierten Datei auf den Server an die korrekte Position hochzuladen. Alle Befehle, welche die Installation betreffen (wie z.B. install, upgrade, selbst upgrade-all) können genutzt werden. Die Option remote_config teilt dem Installer mit, dass die lokale Installation automatisch auf dem Server gespiegelt werden soll. Eine Besonderheit ist, dass die Einstellungen der Konfigurationsdatei auf dem Server für Ersetzungen bei der Installation auf dem Server benutzt werden. Z.B. wenn in einer Datei der Pfad zum PEAR-Daten-Verzeichnis (data_dir-Eintrag in der Konfiguration) gesetzt werden soll, dann wird der Pfad auf dem Server eingetragen (z.B. /home/username/pear/data) anstatt dem lokalem Pfad (hier: C:\remote\pear\data). Das hat allerdings den Nebeneffekt, dass die lokale Installation u.U. nicht auf dem lokalen Rechner läuft. Die lokale Installation fungiert hier eher als Back-up-System. Dies hat allerdings den Vorteil, das bei Problemen auf dem Server, die lokale PEAR-Installation 1:1 auf den Server kopiert werden kann, um wieder einen stabilen Zustand herzustellen. Warnung Einige Packages konfigurieren sich bei der Installation abhängig vom zugrundeliegenden Betriebssystem (Windows vs. Linux). Prüfen Sie vor der Installation, ob dies der Fall ist, bzw. stellen Sie sicher, dass das lokale System und der Server mit dem selben Betriebssystem laufen. Der traditionelle Weg um PEAR per FTP zu installieren. Die Vorrausetzung für die Installation über FTP ist ein FTP-Programm, dass die Zugriffsrechte setzten kann. Erzeugen Sie zuerst ein Verzeichnis, das NICHT in ihrem öffentlich zugänglichen Web-Verzeichnis liegt; die Benennung ist egal. Es muß für jeden les- und schreibbar sein (Zugriffsrechte: 0777). Holen Sie sich dann das go-pear.phpSkript von http://go-pear.org/ und laden Sie es in ein öffentlich zugängliches UnterVerzeichnis Ihres Web-Verzeichnisses. Sie sollten dieses Verzeichnis unbedingt über die .htaccess mit einem Passwort schützen. Rufen Sie als zweites über den Browser das go-pear.php-Skript auf. Ist die URL ihrer Webseite http://www.example.com/, und befindet sich das Skript in public_html/install/go-pear.php; und http://www.example.com/ zeigt die Inhalte von public_html/, dann rufen Sie auf: http://www.example.com/install/go-pear.php. Folgen Sie den Installations-Anweisungen. Wenn Sie gefragt werden, wohin Sie PEAR installieren wollen, wählen Sie das Verzeichnis, das für jeden les- und schreibbar ist. Ausserdem werden Sie gefragt, wo sich die Kommandozeilen-Version von PHP befindet. Führen Sie dazu auf dem Server folgendes PHP-Skript über den Browser aus und übernehmen die Ausgabe: <?php echo `which php`; // if this does not work, also try echo PHP_BIN; ?> Nachdem PEAR installiert wurde, können Sie über den Web-Installer Packages installieren und aktualisieren wie mit jeder anderen PEAR-Installation. Um die installierten Packages zu benutzen, müssen Sie ebenfalls den Include-Path anpassen. <?php ini_set('include_path', '~/pear/lib' . PATH_SEPARATOR . ini_get('include_path')); ?> Manuelle Installation Packages manuell zu installieren ist nicht empfohlen, aber viele haben immer wieder Probleme mit der automatischen Installation, besonders wenn es sich um die Installation bei Web-Hoster handelt. In den nächsten Absätzen werden wir demonstrieren wie Sie Packages von Hand auf ihrer Webseite installieren. Wir gehen von diesem Schema aus: Der Document-Root der Seite ist /var/www/www.example.com/htdocs/. Auf der gleichen Ebene von htdocs befindet sich ein Verzeichnis includes. Auf dieses Verzeichnis kann nicht über HTTP zugegriffen, aber über FTP oder WebDAV. Die Installation besteht aus den folgenden Schritten. 1. Das Package herunterladen: Sie können das Package herunterladen von der PEAR-Homepage über den WebBrowser. Wenn Sie die URL der Package-Seite nicht kennen, gehen Sie über den Package-Browser. 2. Hochladen des Package-Quellcodes Nach dem Sie die .tgz-Datei des Packages heruntergeladen haben, müssen Sie den Inhalt der Datei auf ihrem eigenem Computer entpacken. Laden Sie danach den entpackten Quellcode über FTP, WebDAV oder eine andere Methode in das Verzeichnis /var/www/www.example.com/includes/. Der Quellcode für Mail_Mime z.B. sollte sich dann befinden in /var/www/www.example.com/includes/Mail/. 3. Anpassen des include_path Jetzt müssen Sie den include-path von PHP so anpassen, dass er den Namen des Verzeichnise enthält, in dem der Quellcode liegt. Wenn Sie Zugriff auf die php.ini für ihre Webseite haben, müssen Sie das Verzeichnis /var/www/www.example.com/includes/ in der Einstellung ergänzen. Wenn Sie keinen Zugriff darauf haben, müssen Sie diese Einstellung in jedem Ihrer Skripte setzen, um das Package zu benutzen: ini_set("include_path", '/var/www/www.example.com/includes/' . PATH_SEPARATOR . ini_ 4. Nach dem Sie diese Schritte durchgeführt haben, können Sie das Package ein ihre Skripte einbinden: require_once 'Mail/mime.php'; $mime = ... Wenn Sie weiter Fragen zur manuellen Installation haben, fragen Sie auf der MailingListe für PEAR-User. CVS installer Dieser Abschnitt beschreibt, wie Sie ein PEAR-Package aus dem CVS heraus installieren. Sie sollten keine Packages direkt aus dem CV heraus in Produktions-Umgebungen laufen lassen! Es sind keine offiziellen Releases, deshalb: • • können Sie weder mit Hilfe vom Maintainer rechnen, noch von irgendjemand anderem. können diese den PEAR-Installer _durcheinanderbringen_ bei Updates, da CVSReleases keine eindeutigen Versionsnummer besitzen. Sie sollten ein Package aus dem CVS heraus nur benutzen, wenn: • Der Maintainer ist ihnen empfohlen hat. • Sie bei der Entwicklung des Packages helfen wollen. • Sie wirklich einen bestimmten Patch oder eine Funktion benötigen, die in einem Release nicht enthalten ist. Wenn Sie immer noch ein Package aus dem CVS installieren wollen, müssen die selben Schritte gehen, die auch ein Package-Maintainer tut, wenn er ein neues Release erzeugt. Wenn Sie Probleme bei den nächsten Punkten haben, werfen Sie einen Blick in den Entwickler-Leitfaden des Handbuchs. 1. Holen Sie sich die zum Package gehörenden Dateien wie es auf http://www.php.net/anoncvs.php beschrieben ist. Der _Name_ des Moduls zum auschecken lautet pear/<packagename>, z.B. cvs -d :pserver:[email protected]:/repository checkout pear/HTTP_Client. 2. überprüfen Sie die Datei package.xml, inbesondere die fileset benannten Einträge. Sie müssen die existierenden Dateien und Verzeichnisse wiederspiegeln. Wenn sie es nicht tun, nehmen Sie Kontakt mit dem Maintainer auf, und bitten ihn die package.xml anzupassen. 3. Erzeugen Sie ein korrektes PEAR-Package mit dem PEAR-Installer pear package <path to package.xml> 4. ist das Package bereits installiert: entfernen Sie es, um Versions-Probleme zu vermeiden. pear uninstall <package> 5. Installieren Sie die erzeugte Package-Datei Install your package archive: pear install <package-file> Jetzt ist die CVS-Version installiert! So früh wie möglich sollten Sie wieder ein offizielles Release installieren. Achten Sie darauf vor dem Installieren, die CVS-Version zu deinstallieren. PECL-Packages installieren Die Installation von PECL-Packages ist im PHP-Handbuch beschrieben: http://www.php.net/manual/en/install.pecl.php. Kapitel 3. Support This chapter describes, how you can get support, if you have questions concerning PEAR. The mailing lists Overview As in most other open-source projects, the support is done via mailing lists. In our case, we currently have five PEAR related mailing lists: • General list • Developers list • Documentation list • Webmaster list • CVS commit list • Core list • Quality Assurance list The first four lists are intended to help you, if you have questions. Please read below to get to know, what list fits to your needs. The CVS commit list is intended for people that are contributing to PEAR: All commits to our revision control system (CVS) are send to this list. The core and QA lists are intended for people that want to take part in the development of PEAR. You can subscribe to the PEAR mailing lists via this website. The General mailing list The PEAR general mailing list is the mailing list, where you ask, if you have a question about installing PEAR, using a certain PEAR package etc. The list is no support forum for question concerning the usage of PHP. Please use [email protected] instead. The Developers mailing list As the name already tells you, this list is the place where the developers of PEAR come together to make decisions, to discuss about code and to handle things that are related to this. If you are no developer of PEAR itself, this list is of no real interest for you, unless • you want to get to know what's going on behind PEAR • you want to contribute code to PEAR • you have found a bug in a PEAR package and want to supply a patch for that. The adress for this list is [email protected]. The documentation mailing list This list is the place, where all the things concerning the PEAR documentation, the manual etc. are discussed. If you want to help out documenting PEAR packages, don't hesitate to drop a mail there. The QA mailing list People being interested in improving the overall quality of PEAR come together on the QA list. The Quality Insurance team is always seeking people that want to help. If you are interested, just sign up and announce yourself on the mailing list. The Webmaster mailing list If you have found a problem on our website or have a question concerning the site, you can email the guys on [email protected] . The core mailing list This list is the place, where the core infrastructure of PEAR is discussed. Members of this list also come from other PHP projects such as PECL and PHP QA, since the PEAR infrastructure is also relevant to these projects (like the PEAR installer, the PEAR website etc.). Specifically the list is concerned with the following topics: • New main features for the PEAR website • PEAR installer development • PEAR standards definition Web resources There are a number of web sites that deal with PEAR. We have compiled a list of them here. If a site is missing, you can email the webmaster. #PEAR on IRC The PEAR project has its own IRC channel #PEAR, which is available on EFnet. Come along and meet the gurus, which don't have to pay for their internet connection and can hang around in IRC the whole day. Kapitel 4. Coding Standards Anmerkung: The PEAR Coding Standards apply to code that is part of the official PEAR distribution (that is, either distributed with PHP or available for download from the PHP PEAR repository). Indenting and Line Length Use an indent of 4 spaces, with no tabs. If you use Emacs to edit PEAR code, you should set indent-tabs-mode to nil. Here is an example mode hook that will set up Emacs according to these guidelines (you will need to ensure that it is called when you are editing PHP files): (defun php-mode-hook () (setq tab-width 4 c-basic-offset 4 c-hanging-comment-ender-p nil indent-tabs-mode (not (and (string-match "/\\(PEAR\\|pear\\)/" (buffer-file-name)) (string-match "\.php$" (buffer-file-name)))))) Here are vim rules for the same thing: set set set set expandtab shiftwidth=4 softtabstop=4 tabstop=4 It is recommended that you break lines at approximately 75-85 characters. There is no standard rule for the best way to break a line, use your judgment and, when in doubt, ask on the PEAR Quality Assurance mailing list. Control Structures These include if, for, while, switch, etc. Here is an example if statement, since it is the most complicated of them: if ((condition1) || (condition2)) { action1; } elseif ((condition3) && (condition4)) { action2; } else { defaultaction; } Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls. You are strongly encouraged to always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added. For switch statements: switch (condition) { case 1: action1; break; case 2: action2; break; default: defaultaction; break; } Function Calls Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example: $var = foo($bar, $baz, $quux); As displayed above, there should be one space on either side of an equals sign used to assign the return value of a function to a variable. In the case of a block of related assignments, more space may be inserted to promote readability: $short = foo($bar); $long_variable = foo($baz); Function Definitions Function declarations follow the „one true brace“ convention: function fooFunction($arg1, $arg2 = '') { if (condition) { statement; } return $val; } Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate. Here is a slightly longer example: function connect(&$dsn, $persistent = false) { if (is_array($dsn)) { $dsninfo = &$dsn; } else { $dsninfo = DB::parseDSN($dsn); } if (!$dsninfo || !$dsninfo['phptype']) { return $this->raiseError(); } } return true; Comments Complete inline documentation comment blocks (docblocks) must be provided. Please read the Sample File and Header Comment Blocks sections of the Coding Standards to learn the specifics of writing docblocks for PEAR packages. Further information can be found on the phpDocumentor website. Non-documentation comments are strongly encouraged. A general rule of thumb is that if you look at a section of code and think „Wow, I don't want to try and describe that“, you need to comment it before you forget how it works. C style comments (/* */) and standard C++ comments (//) are both fine. Use of Perl/shell style comments (#) is discouraged. Including Code Anywhere you are unconditionally including a class file, use require_once. Anywhere you are conditionally including a class file (for example, factory methods), use include_once. Either of these will ensure that class files are included only once. They share the same file list, so you don't need to worry about mixing them - a file included with require_once will not be included again by include_once. Anmerkung: include_once and require_once are statements, not functions. Parentheses should not surround the subject filename. PHP Code Tags Always use <?php ?> to delimit PHP code, not the <? ?> shorthand. This is required for PEAR compliance and is also the most portable way to include PHP code on differing operating systems and setups. Header Comment Blocks All source code files in the PEAR repository shall contain a „page-level“ docblock at the top of each file and a „class-level“ docblock immediately above each class. Below are examples of such docblocks. <?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Short description for file * * Long description for file (if any)... * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 * that is available through the world-wide-web at the * http://www.php.net/license/3_0.txt. If you did not * the PHP License and are unable to obtain it through * send a note to [email protected] so we can mail you a * * @category CategoryName * @package PackageName * @author Original Author <[email protected]> * @author Another Author <[email protected]> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP * @version CVS: $Id:$ * @link http://pear.php.net/package/PackageName * @see NetOther, Net_Sample::Net_Sample() * @since File available since Release 1.2.0 * @deprecated File deprecated in Release 2.0.0 */ of the PHP license following URI: receive a copy of the web, please copy immediately. License 3.0 /* * Place includes, constant defines and $_GLOBAL settings here. * Make sure they have appropriate docblocks to avoid phpDocumentor * construing they are documented by the page-level docblock. */ /** * Short description for class * * Long description for class (if any)... * * @category CategoryName * @package PackageName * @author Original Author <[email protected]> * @author Another Author <[email protected]> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/PackageName * @see NetOther, Net_Sample::Net_Sample() * @since Class available since Release 1.2.0 * @deprecated Class deprecated in Release 2.0.0 */ class foo { } ?> Required Tags That Have Variable Content Short Descriptions Short descriptions must be provided for all docblocks. They should be a quick sentence, not the name of the item. Please read the Coding Standard's Sample File about how to write good descriptions. PHP Versions One of the following must go in the page-level docblock: . * PHP version 4 * PHP version 5 * PHP versions 4 and 5 @license There are several possible licenses. One of the following must be picked and placed in the page-level and class-level docblocks: . * * * * * * * @license @license @license @license @license @license @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 http://www.freebsd.org/copyright/freebsd-license.html BSD License (2 C http://www.debian.org/misc/bsd.license BSD License (3 Clause) http://www.freebsd.org/copyright/license.html BSD License (4 Clause) http://www.opensource.org/licenses/mit-license.html MIT License http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 http://www.php.net/license/3_0.txt PHP License 3.0 For more information, see the PEAR Group's Licensing Announcement. @link The following must be used in both the page-level and class-level docblocks. Of course, change „PackageName“ to the name of your package. This ensures the generated documentation links back your package. . * @link http://pear.php.net/package/PackageName @author There's no hard rule to determine when a new code contributor should be added to the list of authors for a given source file. In general, their changes should fall into the "substantial" category (meaning somewhere around 10% to 20% of code changes). Exceptions could be made for rewriting functions or contributing new logic. Simple code reorganization or bug fixes would not justify the addition of a new individual to the list of authors. @since This tag is required when a file or class is added after the package's initial release. Do not use it in an initial release. @deprecated This tag is required when a file or class is no longer used but has been left in place for backwards compatibility. Optional Tags @copyright Feel free to apply whatever copyrights you desire. When formatting this tag, the year should be in four digit format and if a span of years is involved, use a hyphen between the earliest and latest year. The copyright holder can be you, a list of people, a company, the PHP Group, etc. Examples: . * * * * @copyright @copyright @copyright @copyright 2003 John 2001-2004 1997-2004 2001-2004 Doe and Jennifer Buck John Doe The PHP Group XYZ Corporation License Summary If you are using the PHP License, use the summary text provided above. If another license is being used, please remove the PHP License summary. Feel free to substitute it with text appropriate to your license, though to keep things easy to locate, please preface the text with LICENSE: . @see Add a @see tag when you want to refer users to other sections of the package's documentation. If you have multiple items, separate them with commas rather than adding multiple @see tags. Order and Spacing To ease long term readability of PEAR source code, the text and tags must conform to the order and spacing provided in the example above. This standard is adopted from the JavaDoc standard. @package_version@ Usage There are two ways to implement the @package_version@ replacements. The procedure depends on whether you write your own package.xml files or if you use the PackageFileManager. For those authoring package.xml files directly, add a <replace> element for each file. The XML for such would look something like this: <file name="Class.php"> <replace from="@package_version@" to="version" type="package-info" /> </file> Maintainers using the PackageFileManager need to call addReplacement() for each file: $pkg->addReplacement('filename.php', 'package-info', '@package_version@', 'version'); Transition Policy Existing Small Packages Existing packages that have only a few files are required to adopt these docblocks before the next release. Existing Large Packages Existing packages with many files are encouraged to adopt the new headers as soon as possible. When such packages come out with a new major version upgrade, these docblocks must be implemented therein. New and Unreleased Packages New packages and existing packages which have no releases yet must include these docblocks before their first release. Using CVS This section applies only to packages using CVS at cvs.php.net. Include the $Id$ CVS keyword in each file. As each file is edited, add this tag if it's not yet present (or replace existing forms such as „Last Modified:“, etc.). The rest of this section assumes that you have basic knowledge about CVS tags and branches. CVS tags are used to label which revisions of the files in your package belong to a given release. Below is a list of the required and suggested CVS tags: RELEASE_n_n_n (required) Used for tagging a release. If you don't use it, there's no way to go back and retrieve your package from the CVS server in the state it was in at the time of the release. QA_n_n_n (branch, optional) If you feel you need to roll out a release candidate before releasing, it's a good idea to make a branch for it so you can isolate the release and apply only those critical fixes before the actual release. Meanwhile, normal development may continue on the main trunk. MAINT_n_n_n (branch, optional) If you need to make „micro-releases“ (for example 1.2.1 and so on after 1.2.0), you can use a branch for that too, if your main trunk is very active and you want only minor changes between your micro-releases. Only the RELEASE tag is required, the rest are recommended for your convenience. Below is an example of how to tag the 1.2.0 release of the Money_Fast package: $ $ T T T cd pear/Money_Fast cvs tag RELEASE_1_2_0 Fast.php README package.xml By doing this you make it possible for the PEAR web site to take you through the rest of your release process. Here's an example of how to create a QA branch: $ cvs tag QA_2_0_0_BP ... $ cvs rtag -b -r QA_2_0_0_BP QA_2_0_0 $ cvs update -r QA_2_0_0 $ cvs tag RELEASE_2_0_0RC1 ...and then the actual release, from the same branch: $ cvs tag RELEASE_2_0_0 The QA_2_0_0_BP tag is a „branch point“ tag, which is the start point of the tag. It's always a good idea to start a CVS branch from such branch points. MAINT branches may use the RELEASE tag as their branch point. Example URLs Use example.com, example.org and example.net for all example URLs and email addresses, per RFC 2606. Naming Conventions Classes Classes should be given descriptive names. Avoid using abbreviations where possible. Class names should always begin with an uppercase letter. The PEAR class hierarchy is also reflected in the class name, each level of the hierarchy separated with a single underscore. Examples of good class names are: Log Net_Finger HTML_Upload_Error Functions and Methods Functions and methods should be named using the „studly caps“ style (also referred to as „bumpy case“ or „camel caps“). Functions should in addition have the package name as a prefix, to avoid name collisions between packages. The initial letter of the name (after the prefix) is lowercase, and each letter that starts a new „word“ is capitalized. Some examples: connect() getData() buildSomeWidget() XML_RPC_serializeData() Private class members (meaning class members that are intended to be used only from within the same class in which they are declared; PHP does not yet support truly- enforceable private namespaces) are preceded by a single underscore. For example: _sort() _initTree() $this->_status Anmerkung: The following applies to PHP5. Protected class members (meaning class members that are intended to be used only from within the same class in which they are declared or from subclasses that extend it) are not preceded by a single underscore. For example: protected $somevar protected function initTree() Constants Constants should always be all-uppercase, with underscores to separate words. Prefix constant names with the uppercased name of the class/package they are used in. For example, the constants used by the DB:: package all begin with DB_. Anmerkung: The true, false and null constants are excepted from the alluppercase rule, and must always be lowercase. Global Variables If your package needs to define global variables, their name should start with a single underscore followed by the package name and another underscore. For example, the PEAR package uses a global variable called $_PEAR_destructor_object_list. File Formats All scripts contributed to PEAR must: • Be stored as ASCII text • Use ISO-8859-1 character encoding • Be Unix formatted „Unix formatted“ means two things: 1) Lines must end only with a line feed (LF). Line feeds are represented as ordinal 10, octal 012 and hex 0A. Do not use carriage returns (CR) like Macintosh computers do or the carriage return/line feed combination (CRLF) like Windows computers do. 2) There should be one line feed after the closing PHP tag (?>). This means that when the cursor is at the very end of the file, it should be one line below the closing PHP tag. Sample File (including Docblock Comment standards) The source code of PEAR packages are read by thousands of people. Also, it is likely other people will become developers on your package at some point in the future. Therefore, it is important to make life easier for everyone by formatting the code and docblocks in standardized ways. People can then quickly find the information they are looking for because it is in the expected location. Your cooperation is appreciated. Each docblock in the example contains many details about writing Docblock Comments. Following those instructions is important for two reasons. First, when docblocks are easy to read, users and developers can quickly ascertain what your code does. Second, the PEAR website now contains the phpDocumentor generated documentation for each release of each package, so keeping things straight here means the API docs on the website will be useful. Please take note of the vertical and horizontal spacing. They are part of the standard. The „fold markers“ (// {{{ and // }}}) are optional. If you aren't using fold markers, remove foldmethod=marker from the vim header. <?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Short description for file * * Long description for file (if any)... * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 * that is available through the world-wide-web at the * http://www.php.net/license/3_0.txt. If you did not * the PHP License and are unable to obtain it through * send a note to [email protected] so we can mail you a * * @category CategoryName * @package PackageName * @author Original Author <[email protected]> * @author Another Author <[email protected]> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP * @version CVS: $Id:$ of the PHP license following URI: receive a copy of the web, please copy immediately. License 3.0 * @link * @see * @since * @deprecated */ http://pear.php.net/package/PackageName NetOther, Net_Sample::Net_Sample() File available since Release 1.2.0 File deprecated in Release 2.0.0 /** * This is a "Docblock Comment," also known as a "docblock." The class' * docblock, below, contains a complete description of how to write these. */ require_once 'PEAR.php'; // {{{ constants /** * Methods return this if they succeed */ define('NET_SAMPLE_OK', 1); // }}} // {{{ GLOBALS /** * The number of objects created * @global int $GLOBALS['NET_SAMPLE_Count'] */ $GLOBALS['NET_SAMPLE_Count'] = 0; // }}} // {{{ Net_Sample /** * An example of how to write code to PEAR's standards * * Docblock comments start with "/**" at the top. Notice how the "/" * lines up with the normal indenting and the asterisks on subsequent rows * are in line with the first asterisk. The last line of comment text * should be immediately followed on the next line by the closing asterisk * and slash and then the item you are commenting on should be on the next * line below that. Don't add extra lines. Please put a blank line * between paragraphs as well as between the end of the description and * the start of the @tags. Wrap comments before 80 columns in order to * ease readability for a wide variety of users. * * Docblocks can only be used for programming constructs which allow them * (classes, properties, methods, defines, includes, globals). See the * phpDocumentor documentation for more information. * http://phpdoc.org/docs/HTMLSmartyConverter/default/phpDocumentor/tutorial_phpDocumentor * * The Javadoc Style Guide is an excellent resource for figuring out * how to say what needs to be said in docblock comments. Much of what is * written here is a summary of what is found there, though there are some * cases where what's said here overrides what is said there. * http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#styleguide * * The first line of any docblock is the summary. Make them one short * sentence, without a period at the end. Summaries for classes, properties * and constants should omit the subject and simply state the object, * because they are describing things rather than actions or behaviors. * * Below are the tags commonly used for classes. @category through @access * are required. The remainder should only be used when necessary. * Please use them in the order they appear here. phpDocumentor has * several other tags available, feel free to use them. * * @category CategoryName * @package PackageName * @author Original Author <[email protected]> * @author Another Author <[email protected]> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/PackageName * @see NetOther, Net_Sample::Net_Sample() * @since Class available since Release 1.2.0 * @deprecated Class deprecated in Release 2.0.0 */ class Net_Sample { // {{{ properties /** * The status of foo's universe * * Potential values are 'good', 'fair', 'poor' and 'unknown'. * * @var string */ var $foo = 'unknown'; /** * The status of life * * Note that names of private properties or methods must be * preceeded by an underscore. * * @var bool * @access private */ var $_good = true; // }}} // {{{ setFoo() /** * Registers the status of foo's universe * * Summaries for methods should use 3rd person declarative rather * than 2nd person imperative, begining with a verb phrase. * * Summaries should add description beyond the method's name. The * best method names are "self-documenting", meaning they tell you * basically what the method does. If the summary merely repeats * the method name in sentence form, it is not providing more * information. * * Summary Examples: * + Sets the label (preferred) * + Set the label (avoid) * + This method sets the label (avoid) * * Below are the tags commonly used for methods. A @param tag is * required for each parameter the method has. The @return and * @access tags are mandatory. The @throws tag is required if the * method uses exceptions. @static is required if the method can * be called statically. The remainder should only be used when * necessary. Please use them in the order they appear here. * phpDocumentor has several other tags available, feel free to use * them. * * The @param tag contains the data type, then the parameter's * name, followed by a description. By convention, the first noun in * the description is the data type of the parameter. Articles like * "a", "an", and "the" can precede the noun. The descriptions * should start with a phrase. If further description is necessary, * follow with sentences. Having two spaces between the name and the * description aids readability. * * When writing a phrase, do not capitalize and do not end with a * period: * + the string to be tested * * When writing a phrase followed by a sentence, do not capitalize the * phrase, but end it with a period to distinguish it from the start * of the next sentence: * + the string to be tested. Must use UTF-8 encoding. * * Return tags should contain the data type then a description of * the data returned. The data type can be any of PHP's data types * (int, float, bool, string, array, object, resource, mixed) * and should contain the type primarily returned. For example, if * a method returns an object when things work correctly but false * when an error happens, say 'object' rather than 'mixed.' Use * 'void' if nothing is returned. * * Here's an example of how to format examples: * <code> * require_once 'Net/Sample.php'; * * $s = new Net_Sample(); * if (PEAR::isError($s)) { * echo $s->getMessage() . "\n"; * } * </code> * * Here is an example for non-php example or sample: * <samp> * pear install net_sample * </samp> * * @param string $arg1 the string to quote * @param int $arg2 an integer of how many problems happened. * Indent to the description's starting point * for long ones. * * @return int the integer of the set mode used. FALSE if foo * foo could not be set. * @throws exceptionclass [description] * * @access public * @static * @see Net_Sample::$foo, Net_Other::someMethod() * @since Method available since Release 1.2.0 * @deprecated Method deprecated in Release 2.0.0 */ function setFoo($arg1, $arg2 = 0) { /* * This is a "Block Comment." The format is the same as * Docblock Comments except there is only one asterisk at the * top. phpDocumentor doesn't parse these. */ if ($arg1 == 'good' || $arg1 == 'fair') { $this->foo = $arg1; return 1; } elseif ($arg1 == 'poor' && $arg2 > 1) { $this->foo = 'poor'; return 2; } else { return false; } } } // }}} // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */ ?> Kapitel 5. Contributing This chapter describes the different ways in which one could contribute to PEAR. Introduction PEAR is an open source project, which means that everyone can help improving it. Improving doesn't always mean writing code. It can also mean reporting bugs, giving feedback, submitting feature requests and even financial support. Writing New Packages Explanations about submitting new packages can be found in the Developers' Guide. Submitting Patches If you have modified a package to expand its functionality or to fix a bug, you should contribute your changes back to the community (some licenses force you to do so, and it is generally considered immoral not to). Before creating the patch, you must first obtain the latest sources of the package you wish to patch from CVS by running the commands (the package in this example is Foo_Bar): cvs -d:pserver:[email protected]:/repository login password is phpfi cvs -d:pserver:[email protected]:/repository co pear/Foo_Bar Now that you have the latest sources, you can edit the relevant file(s). Make sure that your patch is fully compatible with the PEAR-Coding Standards. After you have finished adding/changing the code, TEST it: We will not accept code that hasn't been carefully tested. When you are absolutely sure the new code doesn't introduce bugs, create a unified diff by running: cd pear/Foo_Bar cvs diff -u >Foo_Bar.diff The resulting .diff file contains your patch. This diff makes it easy for us to see what has been changed. Next step is to submit the patch. Send a mail to [email protected] and Cc the maintainer(s) of the package. The subject of the mail should be prefixed with '[Patch]' to make it clear you are submitting a patch. Also include a verbose explanation of what the patch does. Don't forget to attach the .diff file to the mail. The maintainers of the package are usually listed in the header of each source file. Apart from that their email adresses are available on the package information page on http://pear.php.net/. Anmerkung: If you are using Outlook or Outlook Express, please change the file extension of the diff file to .txt, because Outlook's MIME-Type detection depends on the file extension and attachments with a MIME-Type not equal to text/plain will be rejected by our mailinglist software. Anmerkung: If your patch does break backwards compatibility, the chances are fairly good that the maintainers won't be happy about it. Thus you should always try to fix a bug in a way that does not seriously change the public API. But if there is absolutely no way to keep backwards compatibility and/or if your patch contains a groundbraking improvement, even API changes are fine. Reporting Bugs If you think that you have found a bug in a PEAR package, please take care that you are using the latest version of the package and that your system does meet the packages' requirements. If the bug still persists with the latest version of the package, don't hesitate to fill out a bug report. The easiest way is to click to link „Package Bugs“ on the package information page for the package on the PEAR Homepage, which you think contains a bug. This will take you to a list of existing bugs of the package. Please double check if the bug hasn't already been reported! If you are unable to find it in the list, you can click on „Report a new bug“ to fill out the bug form. More information and tips on how to report bugs in a proper way can be found at http://bugs.php.net/how-to-report.php. If you have already fixed a bug that you have found in a package, please read this. Writing & Translating Documentation Good documentation is essential for users to fully understand any software. Several PEAR packages lack documentation or have docs which need improvement. Writing documentation provides more information about helping out on this front. Translating documentation is another important task. Not only does new documentation need to be translated into the existing languages, additional languages are welcome. Also, existing translations need to be brought up to date because the English versions have been changed. Help on how to perform the translation process is in the Revision Tracking section of the manual. Wishlists Some of the PEAR developers have wishlists at Amazon or a similar service. If you appreciate the work of a certain developer, feel free to buy something for her from her wishlist. To find out if a developer has one of those wishlists, go to the account browser, look for the details of the developer and there you'll see if she has a wishlist. Buying something from people's wishlists may even speed up the time in which annoying bugs are fixed ;-). Kapitel 6. FAQ - Frequently Asked Questions What is PEAR? This is described here. How do I install a package when I get the error message "No release with state equal to: 'stable' found for 'Packagename'"? answer by Greg Beaver The package in question does have releases, but none that are stable. There are two solutions. 1. Set preferred_state to alpha or beta and then install $ pear config-set preferred_state alpha $ pear install Packagename 2. Find out the stability or version number of the latest release and install it directly. $ pear install Packagename-alpha $ pear install Packagename-1.5.3 How do I become a PEAR contributor and/or how do I get CVS access to PEAR? This is described here. I have written a PHP module in C. What are the rules of including this in PEAR? The PECL project (a spin-off from PEAR) is the place where C extensions for PHP are published. Why is PEAR separated into pear/ and pear-core/? The first elements of PEAR were stored in the directory pear-core (once php-src/pear) and so they were bundled with each new PHP release. For future releases of PEAR this isn't workable because PEAR will become too big to be bundled with every release of PHP. So there was a decision to commit all new elements to an own top level directory pear. The other elements which are currently remaining in phpsrc/pear will be moved to the new top level directory soon. Only the PEAR package manager code will be bundled with every new release automatically. Why does the directory structure of pear/ and pear-core/ differ? The directory structure of pear-core/ matches that of the install tree (by default /usr/local/lib/php), and are organized as a simple hierarchy. However, the directory structure of pear/ is based on what package the files belong to. Where files are located in each package directory is completely independent from where they end up being installed, this is all determined by the package description file. Why a flat directory structure instead of a deep? In CVS, PEAR code is organized by package instead of hierarchical like it would finally be installed. For example, if you want to use the XML_RPC class, you include "XML/RPC.php". It's easy to think that in CVS, this file should be in pear/XML/RPC.php, but that's not the case. XML_RPC is an independent package with its own directory in CVS, in this case the RPC.php file is actually located at pear/XML_RPC/RPC.php. The package description file (package.xml) is used to say where the files should finally be installed. The reason CVS is organized this way is that it makes package administration much easier. Can I commit experimental/unstable stuff? Yes. But make sure, that you mark up the experimental/unstable status of the project in the documentation. The best place to do this is in the package.xml in the <state>-tag. The values for this tag are alpha early stages of development, all things could change (API, behavoir) without notice, expect lots of bugs beta API should normally not change, usable software, expect bugs devel a release for other developers who want early access to test and give feedback, code quality may vary from pre-alpha to stable stable the software has a fixed API, it has undergone tests, and documentation exists. This release is a recommended release for use in production environments. snapshot a CVS snapshot from a certain date Am I expected to add examples and/or test files to my package and where to store them? Examples are a good idea, especially when your class has a complex API. But examples are only a part of a documentation. Don't create examples instead of a documentation. You should store the documentation and the examples in a sub directory 'docs' of the package directory. Test scripts are recommended when your class has to be compiled, requires special extentions/programs or needs correctly installed additional files (i.e. templates, graphics). Store them in sub directory called 'tests'. Are different packages or classes with similar features allowed? There is no problem with competitive packages, but we want to avoid pollution with 10 template classes, 7 different mail classes, and 3 different layers for databases doing the same only with different function names. First of all, do a reality check: Why do I want to commit a new package? Really bad answers are „To see my name in PEAR“ or „I didn't understand the API of the existing class“. A good reason for a new class is often, that you are missing a function, behaviour or speed in an existing implementation. In this case, you should take a look at this class, if it possible to extend this class. If not, then you have a good reason to commit a new class. „If not“ means, it isn't possible to add the required functionality without changing the basics of this class. If you write a new class, try to keep API compatibility with existing classes as far as possible! If it isn't possible to keep the class compatible himself, try to create a wrapper class to keep compatibility. Don't care, if this wrapper needs a lot of time or memory, a wrapper class only has to keep compatibility and make migration easier. Committing a competitive class has to be announced on the PEAR developers mailinglist! I have a question about PEAR. Where should I ask? • • General questions about the usage of PEAR components should be posted to the mailing list [email protected]. All technical discussions concerning the development of PEAR components should be posted to [email protected]. • Question concerning the website can be sent to [email protected]. Information on subscribing this mailing lists can be found here. On all mailing lists mentioned above the language is english and the way you ask questions should always be polite :-). A required package includes a package, my package needs it too. Should I include it again? Yes. You should include every package, you need with require_once() or include_once (), also when it is included already by another package. Does PEAR work on windows? To make PEAR work on Windows, you simple need to add the PEAR installation dir (e.g. c:\php\pear) to the include_path directive in your php.ini. Note: There are some classes (like Schedule/At.php), that do not work on Windows, because they use *nix specific commands. What licenses are allowed in PEAR/PECL? Currently PEAR supports the following list of licenses: • PHP License • Apache License • LGPL • BSD style • MIT License Other licenses may be added to this list on a case-by-case basis. Please get in touch with the PEAR developers mailing list for this. For PECL extensions that are linked into PHP, the license must be compatible with the PHP license. That means you can not GPL a PECL extension or you would be violating the GPL. Note also that if you write an extension that links against a GPL'ed library you will be violating the GPL. If you need to link against a GPL'ed library, get permission from the author of the library. To set the license of you PEAR/PECL package, put it in the head of all source code files of your package and also the type of it inside the <license> tag of your package description file (package.xml). Why does the PEAR coding standard insist on space-only indentation? Using spaces and avoiding tabs is the only way to ensure that a piece of code is rendered consistently in all editors and viewers. Many editors render tabs as 4 spaces, and a lot of editors, terminal programs and utilities render tabs as 8 spaces. Example: printf("%s", $arg); Here, there are 7 spaces before "$arg". If this code was written in an editor with 4-space tabs, it would store it as one tab and three spaces. Now, if another developer edits the same file in an editor with 8-space tabs, it will look like this: printf("%s", $arg); Likewise, consider this code written with 8-space tabs: if ($foo && $bar) { } If viewed in a 4-space-tab editor, it will look like this: if ($foo && $bar) { } In a community like PEAR where people use lots of different systems and editors, using tabs simply doesn't work. People will end up doing whitespace commits fixing rendering in their editor, while breaking it for others. With only spaces it will look the same to everyone. Jamie Zawinski has written a piece on the subject too. There is also a tool called Astyle which can help you convert your code to the appropriate style. go-pear.php or bundled packages in the windows build of PHP 4.3.x is out of date! Unlike other aspects of PEAR development, the windows build of PHP 4.3.x is not tracked in CVS. Instead, it is located on the machine that builds windows snapshots. Often, this will not be updated when the rest of PEAR is updated. Note that PHP 5.x releases use a different build system and are automatically updated to the latest versions of PEAR. If you find that PHP 4.3.x has out-of-date versions of packages, or no longer works, then please report that the windows bundle of PEAR is out of date to [email protected] Is there a tool to help PEAR manual translators to track files changes? Working on the translations is not just translating an English file and commiting the results. Much of the work is needed to update the already translated ones, to get in sync with the content of the English files. To follow the modifications in the English tree, you should subscribe to the PEAR documentation mailing list to get CVS commit messages, or read the archives. If you never update your files, the translations can get useless. Updating a foreign language file can get difficult, as you may not know when and who translated that file, so you may not know where you should look for the updates needed. We have one system for tracking the revisions and modification dates of the files in peardoc. The Revision Comments Instead of storing all responsibilities in a central file, the revision comment system stores them in the files they provide information about. Information about translator, revision numbers, and status information is stored in the revision comment. Let's see what would be in the header of the example file bookinfo.xml file in this case: <!-- EN-Revision: 1.16 Maintainer: jane Status: ready --> We can see the revision number for the last english file used to update the translation (EN-Revision: 1.16), the translator cvs account name. But we can also add some other status information in the case it is needed (eg. "partial" for incomplete translations). This revision comment system is basically about storing the information in the XML files, and not in a central place. This is extremely convenient now, as there are more than 2400 files in the English tree. Currently, all three fields (English revision, Maintainer, Status) are needed. Maintainer is intended to be a CVS user name, or some nickname without a space, status can be anything without a space. Note, that this header is not updated by CVS (in contrast with $Revision, which is updated automatically). This is only updated when you edit the contents of the comment yourself. You may see this as a good thing, but using these comments, you lose the quick look on the whole list of your files. No, you do not lose this, but get much more! If you would like to build a full list of you files, you can go to the /peardoc/ directory and run: ./scripts/revcheck_pear.php xx > revcheck.html Here xx is the imaginary language code. After running this script you'll get a revcheck.html in the same directory. You can find revision comparisions and links to diffs for all the files in this language. You can also add a further restriction parameter, the maintainer name, so the script will only list the files corresponding to the given maintainer. There are some optional extensions introduced for this script, to be available in this generated HTML page. This is why the translation.xml files are introduced. Here comes a simple translation.xml file for the imaginary xx language : <?xml version="1.0" encoding="iso-8859-1" ?> <!DOCTYPE translation SYSTEM "../dtds/translation.dtd"> <translation> <intro> This is some introductory text for the xx language translators about who is the manager of the translation, and where to find more information. This paragraph is printed on the top of the generated revcheck.html page. </intro> <translators> <person name="Joe Doe" email="[email protected]" nick="joedoe" cvs="yes" editor="yes"/> <person name="Jane Smith" email="[email protected]" nick="jane" cvs="yes"/> <person name="Joe Forever" email="[email protected]" nick="joefo" cvs="no"/> </translators> <work-in-progress> <file name="appendices/aliases.xml" person="joedoe" type="working"/> <file name="functions/dbx.xml" person="joefo" type="working"/> </work-in-progress> </translation> In this file, you can add users without a CVS account, and can assign ready documents or work-in-progress files to them. The biggest advantage of using this addon is that all this information is used to generate dynamic tables of translators and files in the revcheck.html file. All translators are linked to from the individual files they are assigned to, and there is a nice table showing the state of files for all the translators. Assigning ready files may be needed if a time consuming update is in progress on that file. There are two optional parameters you can add to a <file>, if you would like to record it: the date and revision. Date is assumed to be the date when the work was started, revision is the checked out revision of the English file used to start the work (denoted as CO-Revision in the generated table). There is currently no fixed format for the date parameter. Another addon to this system is just to give credit to all people who worked on one file, and not just the current maintainer. To achieve this goal, we added the credit comments. One credit comment in eg. history.xml may look like this (in case Joe Doe translated the file initially, but Jane followed him to be the maintainer): <!-- CREDITS: joedoe --> The credits comment can contain a comma-separated list. These comments only affect the display of the translators table in revcheck.html. Why does my browser show strange warnings when logging in to the website? You are seeing the warnings because pear.php.net uses a SSL key that is signed by CAcert, whose root certificate is unfortunately not bundled with most browser. If you are using a Mozilla browser, you can import the certificate on this site by clicking on the link „Root Certificate (PEM Format)“. When asked if you want to trust the new Certificate Authority, you need to check at least the „Trust this CA to identify web sites.“ box and click "Ok". People using Internet Explorer may find help here. Mac OS X users must download the above mentioned PEM file. The certificate can then be imported with the „Keychain Access“ utility via „Import“ in the „File“ menu. II. Leitfaden für neue Entwickler Inhaltsverzeichnis 7. Introduction 8. When to contribute (and when not to contribute) 9. Getting started with the community 10. The formal proposal process 11. Taking over an unmaintained package Kapitel 7. Introduction If you are planning to contribute a new package to the PEAR project, this guide will provide you with the necessary information to get you started The Right Way (tm) . We will start by describing the cases in which it makes sense to contribute and in which not. After we have ensured that the package you want to contribute fits into PEAR, we will describe how to get started with the community. Once you are confident about the inner workings of the PEAR developer community, we will explain how to start the formal process of proposing a new package and we will give some tips for making your first package as successful as possible. Kapitel 8. When to contribute (and when not to contribute) In this chapter we describe the cases in which it makes sense to contribute code to PEAR and in which it does not. This description is by no means complete. If you are unsure, if your contribution could be included into PEAR, contact the developers mailing list. Cases in which it makes sense to contribute As you may have already noticed while browsing the list of existing packages, the PEAR packages provide a (often abstract) solution for a general problem. Thus your code will most likely fit into PEAR if it solves a problem that will not only occur in one (e.g. your) specific application, but that occurs in a lot of (web) applications. Examples are: • • • Support for Network protocols Object oriented wrappers that provide easy access to otherwise complicated or less intuitive PHP extensions. Parsing different XML dialects. The PEAR packages that provide XML parsing functionalities can be found in the category browser. No matter which area is covered by a package, the API should be as abstract as possible (while not becoming too complex), so that it can be utilized painlessly in as much use cases as possible. Cases in which it does not make sense to contribute A rough rule of thumb is that code which solves a problem that exists in one or only very few projects is not convenient for inclusion into PEAR because most people will not benefit from it. However, this does not mean that „niche software“ cannot be included in PEAR. In the Math section we have a number of elaborate packages that solve different kinds of algebraic problems. While those problems do not occur in average applications, the packages are very abstract and scientific projects benefit a lot. Apart from code that does not fit into PEAR because of a lack of abstractness, there is another type of code that currently cannot be contributed to PEAR: Full web applications. Despite the fact that the "A" in PEAR stands for "Application" there is a simple reason why applications are not yet supported: Until now nobody has gotten around to make the infrastructure like the PEAR installer capable of handling packages that provide complete web applications. When the situation changes, this site will be updated. Kapitel 9. Getting started with the community Upon determining your code fits into PEAR, you should get started with the PEAR community. In this chapter we will provide several ways, in which you can establish a first contact with the other PEAR developers, which will hopefully be your future open source fellows. Additionally we will tell you the different places, where you can find more information about the inner workings and rules of PEAR. Communication with other PEAR developers Mailing lists naturally are the most important way to communicate in projects like PEAR. We are running a number of public mailing lists, which are listed on the PEAR website. For starters the PEAR developers mailing list [email protected] is of major importance for you: This mailing list is the place where the maintainers get together to discuss various aspects of their packages and this list is also the place where new packages are discussed. If you would like to get started with maintaining packages in PEAR, you are expected to be subscribed to this mailing list. (Subscription instructions) Anmerkung: During your first steps in the PEAR community, you may stumble across the term „pear-dev“, which is the abbreviation for the developers mailing list in PEAR's lingo. Some people enjoy communicating via IRC channels. We are running the channel #pear in the server network of EFnet. At this channel some of the most active PEAR developers hang out regularly. However for serious inquiries or discussions, you should mail to the developers mailing list. More written information • • • The PEAR Group occasionally publishes so called Administrative Documents, which describe the Group's decisions. You are expected to read those documents before starting serious contributions to PEAR, because they contain important information about the inner workings of PEAR. The developers mailing list will be informed, when new documents are added, so you do not need to visit the site frequently. This manual contains the Developer Guide, which provides valueable information as well. The Coding Standards describe the standards which PEAR code must adhere to. Kapitel 10. The formal proposal process In the early times of PEAR, all new packages were proposed by an informal email to the PEAR developers mailing list. Over the time, the number of new proposals increased quite dramatically, making it hard to keep track of all the proposals. A web-based proposal handling system was established to solve these problems. The system is called PEPr. It is pronounced like the spice and stands for „PEAR Proposal system“. This chapter describes the requirements and the workflow for a PEPr-based proposal. After that we will provide you with information, on how to actually start a proposal. Finally, you will learn what to do once the proposal is finished. After reading this chapter, you will will be able to start a proposal for your code right away. Step 1: Requirements for a proposal The following enumeration lists the most important things that need to be done or be made available before starting a new proposal. • Finding a name for the package It is obvious that each package needs to have a unique name. To get a „feeling“ for proper package names, you should browse the list of existing packages. Choosing a name for the package is an iterative process and it is likely that you will change the name at a later stage of the proposal process. • Finding a category for the package Similar to each package having a unique name, it has to be placed in one of the categories, which are listed in the package browser as well. • Writing a package description For starting the proposal you will need to write a description of the package. This description does not need to mention every detail of the package, but it should at least outline the basic concept and feature set. When your package has been accepted, you will have to come up with a single-line summary and a fulltext description. • Choosing a license for the package Each package has to be licensed under an accepted OpenSource license. If you are unsure about the license, you should opt for the PHP License. The PEAR Group has issued a License Announcement, which provides further details concerning this topic. • Writing examples and documentation Without proper usage examples and documentation, neither will the PEAR developers be able to evaluate your package nor will users be able to make use of your package. • Listing dependencies Making a list of dependencies basically means that you write down all external entities such as other PEAR packages, certain operating systems or external applications, which are required to use your proposed package. Beispiel 10-1. Example for a dependency list If your package does only work on Linux, requires the DB package, version 1.8.4 or higher of the Log package and at least PHP 4.3.0, your dependency list looks like this: Linux DB Log >= 1.8.4 PHP >= 4.3.0 Step 2: Initiating a discussion For every package you should start a proposal in PEPr as a draft to initiate dicussion on the developers mailing list. By discussing the package with the PEAR developers you will easily be able to find out if: • there are technical issues with the package/code • a package with similar functionality already exists • there are people working on something similar, so you can join forces • etc. By reading between the lines, you should also be able to find out if you will be able to gather enough positive votes in the formal proposal process. Be aware that people will scrutinize your code, so be prepared for criticism (both positive and negative) and save everybody a bunch of time by making sure your scripts adhere to the Coding Standards. Please note that PEAR is an international project. People come from different cultural backgrounds where english may not be their native tongue. Misunderstandings may happen because of that, so assume the person is trying to do good. Do not worry if your English is not perfect but do try to be as clear as possible and do not hesitate to ask for advice. Step 3: Using PEPr To be able to use the proposal tool (PEPr), you have to apply for a PEAR website account. This account will usually be granted within one or two days. After that you can open a new proposal using the „New Package Proposal“ interface. The package proposal process is divided into 4 stages: „Draft“, „Proposal“, „Call for Votes“ and „Finished“. Every proposal has to run through all of these stages. During each stage (except for the draft stage) an email is send to you (the proposer) and the PEAR developers mailing list for any action. Stage 1: Creating a draft At first your proposal is a draft. This simply means you can edit it, view it and it is shown up on the PEPr overview page as a draft. This stage is for you to play around with PEPr, to shape your proposal nicely and to prepare it for the proposal process. You can switch to the next stage when ever you want to publish your proposal and get feedback from the PEAR community. Stage 2: Moving to the Proposal stage After switching to the stage Proposal you have a real proposal. Either through email or through PEPr itself the community will give you hints and ask questions about the proposed package. Generally it is a good idea to follow these suggestions, but sometimes people in the community will have different visions for your package, which should be sorted out during this stage. After a week of comments you may switch to the next phase. You should only switch to the next stage, if you are sure that the PEAR community will accept your package. Stage 3: Calling for votes The next stage is the voting stage, during which you may not change your proposal anymore. You may not edit nor delete the proposal from now on. During the proposal stage, „Call for Votes,“ every active PEAR maintainer may give one vote on the proposal. Votes are given using the numbers -1, 0 and +1, where -1 means „I'm against this package to be added to PEAR in the current form,“ +1 says „I'm in favour of getting this package into PEAR in the current form“ and 0 means „I have looked at your package, but I am undecided.“ The time to vote for a package is 7 calendar days. If after this time less than 5 votes have been cast, the developers get another 7 days to cast their votes. After this time the voting is ended, whether there are 5 votes or not. Votes on proposals can be bound to a condition. These conditional votes indicate that you have to fulfil a certain condition the voters expect to be fulfilled. If there are conditional votes you are expected to read and follow them! The conditions on a vote will be provided in the votes comment. Each vote may have comments. Reading those is always a good idea! Stage 4: Proposal Finished Now your proposal is finished. To determine if the proposal was successful or not, the sum of all votes is computed. If the result is greater or equal to 5 the proposal has been accepted. Otherwise we are sorry to say, that the community has decided to reject it. Have a look at their comments during proposal and vote stage to find out why. Maybe you can rework your package and propose it again, but please do not try to hand in a proposal the same way twice. If your proposal has been accepted, you may put your package into PEAR. If this is your first proposal, please contact the PEAR Group via email to get your current PEAR website account upgraded to a full featured developer account. After that, you can register your package and upload releases. The process of preparing and uploading a release is described in the Developer Guide. Changing a proposal In general you may not edit or delete your proposal after it has left the Proposal stage. In urgent cases you can contact the PEAR community via the developers mailing list to reach a PEAR website administrator to do a change. This is heavily discouraged however! You should have made everything clear to the community during the Proposal stage to ensure a hassle free voting process. Even if the voting has a negative result, this is no reason to delete it. Kapitel 11. Taking over an unmaintained package If you want to become the new lead maintainer of a package that is marked as unmaintained on the PEAR website, the following section will explain to you the necessary steps for this to happen. 1. The first thing is to inform the PEAR Quality Assurance mailing list about your intention. If you have not been involved in PEAR prior to that, it is a good idea to write a few words about you and your motivations. 2. The QA team will then state whether you can take over the package or not, eventually explaining why. You can then apply for an account for the PEAR website unless you already have one. The PEAR Group will have to grant this account, and afterwards the QA team will assign you as the new lead maintainer for the package. 3. If the sources of the package are kept in the PHP CVS repository, you will also need an account for this. You can sign up for it on the PHP website. Please mention in the purpose field of the request form that the PEAR QA team has told you to get an account, so that your request can be processed faster. CVS accounts are managed by the PHP Group, so PEAR unfortunately has only limited influence on this process. Anmerkung: In case you already have a CVS account for cvs.php.net, it is only necessary for you to get additional „karma“ for the module where the package resides. You can request this karma by sending an email to the PEAR Group. (Please also mention in this mail that you have already talked to the QA team.) 4. If everything has worked out well, you should by now be the lead maintainer of the previously unmaintained package. If not, don't hesitate to ask the people on the QA mailing list for help. III. Entwickler-Leitfaden Inhaltsverzeichnis 12. Introduction 13. PEAR's meaning for developers 14. Contributing your own code 15. The package definition file package.xml 16. The package definition file package.xml, version 2.0 17. Releasing A Package 18. Supporting PEAR development 19. Recommendations 20. Writing documentation Kapitel 12. Introduction A guide to PEAR written for developers by developers. Purpose of this text The intention of this guide is to provide people, who want to contribute to PEAR, with all necessary information to start working effectively. The first part of this guide will cover the advantages a developer will have when using PEAR code in his every-day work. After that we will show you how to contribute your own code to PEAR. Finally the guide will point out, in which ways a developer can support the PEAR project. Kapitel 13. PEAR's meaning for developers Code of high quality PEAR only accepts contributed code which is of high quality and which is compliant to the PEAR Coding Standards. For you this means that you are using code that has a more or less consistent API, is based on the same standard components and provides the same error reporting mechanism everywhere. Note that this does not apply for code that is contributed to PECL: In PECL all code has to follow the PHP coding standards. Chance to release your own code PEAR gives you the chance to contribute your code to an enormous number of PHP developers: To get more information about how to contribute your code in PEAR, read here. Kapitel 14. Contributing your own code PEAR is driven by an open source oriented developer community. Thus there is a chance for everybody to contribute code (in form of a new package or as an improvement for an existing package) to the project. However PEAR aims to keep the quality of the packages at a very high level. Because of that there are certain requirements for contributions, which are listed below. Requirements for contributing code We are making certain demands on both the code and the maintainers of packages: 1. Code must be conforming to the Coding Standards. If you want to contribute your code to PEAR in form of a new package or as an addition to an existing package, it has to be compliant to a set of Coding Standards. There have been numerous discussions about whether those standards are good or not and the decision has been made that they are absolutely necessary. There is no sense in discussing about this. 2. Extensible and „forward-compatible“ code. Always keep in mind that your code should be extensible and that it has to be easy to add new features in the future. If it is easily predictable for you that there is no clean way to add new functionality to the codebase without breaking backwards compatibility, you should consider to review the code and to adapt it, before contributing it to PEAR. In this context it may be helpful to become familiar with the basics of object oriented programming. Eventhough PHP 4 does not come with full object oriented support yet, the knowledge will possibly help you in maintaining an extensible state for your package code. There are numerous resources about object oriented programming all around the web and you will also find tons of books available for your reading pleasure. However we can can recommend Object-Oriented Programming Concepts on Sun's Java Homepage for a quick start. 3. Documentation in an appropriate format (plain text, docbook) Your code must come with appropriate documentation in one of the following formats: • Docbook XML • Plain Text If you write the documentation in Docbook XML and if the markup is valid, the documentation can be easily added to the official PEAR Manual, which you are reading right now. Anmerkung: As of August 2003, phpDocumentor is fully capable of converting in-code API documentation and external tutorials into Docbook XML. PhpDocumentor version 1.2.2 or greater is required. Install with pear install phpDocumentor. Use the XML:DocBook/peardoc2:default converter on your source code to generate output. The output should be generated directly into the peardoc/lang/package directory, where lang is en, or fr, etc. Be aware though that only shipping the API documentation does not suffice! Additionally your package has to come with usage examples and (even better) tutorials about its usage. More information can be found in the section describing how to write documentation 4. Regression tests in .phpt or PHPUnit format All developers have experienced the frustration of bugs. They are a fact of life in programming, but fortunately there are a few systems that can be used to catch them, kill them, and prevent their return. Regression tests should be included with every stable release, so that users can run them if a bug occurs to help you debug the package. Examples of .phpt regression tests can be found as part of the PFC DB package. For examples of PHPUnit tests, see the Auth package. 5. The contributor („you“) must be willing to provide support for the package and must be willing to release future versions that at the very least fix bugs. If you are not willing to maintain your code over a long period of time, it makes little sense to contribute it. PEAR is the standard repository of PHP packages, and this comes with great responsibility. Maintaining means more than just providing support via the various mailing lists: You must be willing to not only fix bugs, but also integrate useful enhancements contributed by users of your packages, if they fit the design specifications of your package. You should expect to release new versions of your package regularly with bug fixes. If you will be unable to maintain your package for an extended period of time, it is expected that you will announce this to the PEAR developer mailing list, and assign another temporary lead maintainer or publicly document the fact that your package is temporarily unmaintained, and the approximate date that users can expect to receive support and bug fixes, if possible. Warnung Code can be removed from PEAR if the lead maintainers are not willing to maintain the code anymore and if there is no other person that is willing to take over the maintainership. How to contribute code in practice 1. Finding an appropriate package name One of the most important tasks while contributing a new package to PEAR is finding an appropriate name for your package. The general syntax for package names is <Category>_<Name>. The value for <Category> should be chosen from a predefined list of categories that are available in PEAR (e.g. „HTTP“, „Net“, „HTML“). The second part is the name of the package (like „Upload“, „Portscan“, „Table“). The categories that are currently available in PEAR are represented by the bold headings at the Package Browser. If you think that your package does not fit in any of the existing categories, you can ask the on the mailing list to create a new category. (PEAR is usually reluctant to do that.) Apart from this general syntax, the package names can also contain more than one category name. An example for this is HTML_Template_PHPLIB: The multiple categories indicate that the package PHPLIB is part of the category Template, that again is part of the HTML category. This naming scheme is necessary here since it's possible that there are Template systems in PEAR that don't work with HTML but with another technology. (The cases where more than one „category“ is used are pretty rare.) If you need further advice or help for finding a name for your package, you should ask on the developers mailing list. 2. Announcing to the PEAR developers The second step while contributing is to announce your package in PEPr. Usually this announcement will spawn some discussion. After one week you may call for votes with PEPr and the developers will then start to vote for or against your proposal. (You are of course urged to join the upcoming discussion.) Announcing a package does of course not mean that it is already accepted! That will still take some time and likely some more efforts from your side. Anmerkung: The following passages are taken from the administrative document Handling Package Proposals, which describes proposing new packages in more details. Reading this document should be a mandatory step for PEAR newbies. Only the votes of active members of the PEAR community (must have a PEAR web account, however the proposer himself is not counted) are counted, however anyone may vote. Votes require that a final choiceof package name is specified. The votes are added up, which means that one -1 offsets a +1. However -1 vote should always be considered to be serious and may lead to decisions being made on a case by case basis by the PEAR Group who reserves a veto (it is intended that in the future the PEAR QA team will assist the PEAR Group in such situations). Therefore a -1 vote *must* contain a comment explaining that decision, it is desirable that votes in favour (+1) should also be accompanied with an explanation when appropriate. A vote is accepted if the total of all votes exceeds +5. In case the proposal is not accepted the package can be further discussed on the list and the proposer may attempt to make another "call for vote" (it is expected that this is only done for sensible reasons). 3. Getting the necessary accounts Right now one can distinguish between two types of accounts related to PEAR: a. Pear.php.net account This account is always necessary for you, if you want to release your package through PEAR. With this account you have access to the necessary infrastructure on pear.php.net in order to propose, upload and roll new releases. The PEAR Group manages PEAR accounts and pearweb karma levels (i.e.: karma to use the web site to maintain packages). b. PHP CVS account If you want to administrate your code via CVS , you can also apply for a CVS account to have access to the pear CVS module on cvs.php.net. This makes it easier for other users to contribute to your code. The PHP Group ([email protected]) manage the PHP CVS server, which is used for maintaining PEAR packages. If you already have a PHP CVS account you will ask the PEAR Group for Karma for a given package or set of packages. Please send an email to [email protected] specifying what packages you need commit access along with credentials (e.g.: the package "lead" email giving you his go or a QA member email announcing you are to be given access). If you already have a CVS repository somewhere else (e.g. on SourceForge), or if you don't want to maintain your code via CVS, you don't need the PHP CVS account. It is highly recommended to use some kind of public repository, so that users can try out any bug fixes you apply to the code, before a new release is rolled. To sign up for your pear.php.net account, go to the PEAR account request page and fill out the form there. The PEAR Group will then receive your request and someone will open your account, if the request sounds reasonable. You will be notified about that via email. Please note that you do NOT need a pear.php.net account to download packages from there. To get a PHP CVS account, go here to sign up for it. The PHP CVS account has to be approved by the PHP Group. 4. Registering the package Once you successfully went through the contribution procedure and got your pear.php.net account, you finish with registering your package. Registering does not mean that you are going to release a first version of your package. It just means that some basic information about the package will be added to the PEAR package database. The registration process is quite straightforward: Fill out the form on this site and submit the information. After you have done that, the PEAR Group has to finally approve your submission. This usually happens in a few hours and you will be notified about it via email. After having registered your package, you can create a first release, which is described here. How to document code in practice Writing documentation is covered in a dedicated section. Kapitel 15. The package definition file package.xml Introduction to the package definition file package.xml The package definition file package.xml is, as the name already implies, a well-formed XML file that contains all information about a PEAR package. This chapter will describe the allowed elements of the package definition file and it will discuss how to create such a file for your package. The PEAR_PackageFileManager package simplifies the creation of package.xml. You can install PEAR_PackageFileManager via the usual command $ pear install PEAR_PackageFileManager Allowed elements The toplevel element in package.xml is the element <package version="1.0">. The allowed sub elements are: • <name>: The name of the package. • <summary>: Short summary of the package's description. • <description>: Full length description of the package. • <license>: The license of the package (LGPL, PHP License etc.). • <maintainers>: Information about the maintainers of the package. • maintainer: Information about a single maintainer. (May be used multiple times.) • • <user>: The account name of the user. <role>: The role the user has during package development. (Can be either lead, developer, helper.) • <name>: The realname of the user. • <email>: The email address of the user. • <release>: Information about the current release. • • <version>: The version number of the release. <state>: The state of the release. (Can be one of stable, beta, alpha, devel, or snapshot.) • <date>: The date when the release has been rolled. • <license>: The license under which the code is available. • <notes>: Releasenotes • <filelist> • • • <dir name="xxx" [role="xxx"]>: Name of a subdirectory. This subdirectory can again contain <file role="xxx"> entries. <deps>: List of dependencies of the package. • • <file name="xxx" role="xxx" />: Filename <dep type="xxx" rel="yyy" optional="yes">name</dep> : For more information about dependencies, please see below. <changelog>: Changelog-like information about the package. • <release> • <version>: Version of the specific release. • <state>: State of the specific release. • <date>: Date when the specific release has been rolled. • <notes>: Changelog information Allowed characters The letters allowed inside elements are A-Z and a-z. Other characters, such as é must use entities (in this case: é). If you create your package.xml files using the PEAR_PackageFileManager, upgrade your PEAR installation to version 1.4.0a2 or greater and you won't have to worry about this because the file manager takes care of this automatically. If you write your package.xml files manually, you will need to enter the entities yourself. A list of the most common entities can be found at: http://www.evolt.org/article/A_Simple_Character_Entity_Chart/17/21234/ If the characters you need aren't in that list, go to http://www.oasisopen.org/docbook/xmlcharent/0.1/index.shtml and look at the other entity lists. Validing In order to validate package.xml files one can use the xmllint tool that comes with libxml2. xmllint --dtdvalid http://pear.php.net/dtd/package-1.0 --noout package.xml Creating a package definition file Beispiel 15-1. Basic package.xml <?xml version="1.0" encoding="ISO-8859-1" ?> <package version="1.0"> <name>Money_Fast</name> <summary>Make money fast.</summary> <description> This package helps you to make money pretty fast. </description> <license>PHP License</license> <maintainers> <maintainer> <user>foo</user> <name>Joe Foo</name> <email>[email protected]</email> <role>lead</role> </maintainer> </maintainers> <release> <version>1.0</version> <date>2002-05-27</date> <state>stable</state> <notes> This is the first release. </notes> <filelist> <dir name="/" baseinstalldir="Money"> <file role="php">Fast.php</file> </dir> </filelist> </release> </package> This package.xml can serve as a template for you as it already contains all necessary elements. In most cases you only need to change the character data between the tags in order to use the example in your package. Beispiel 15-2. Example for nested directories <?xml version="1.0" encoding="ISO-8859-1" ?> [...] <release> <version>1.0</version> <date>2002-07-23</date> <state>stable</state> <notes> This is the first release. </notes> <filelist> <dir name="/" baseinstalldir="Money"> <file role="php">Fast.php</file> <dir name="Calculator" role="php"> <file>Calculator.php</file> <file>Currency.php</file> <file>Stocks.php</file> </dir> <dir name="docs" role="doc"> <file>README.txt</file> <file>tutorial.txt</file> <dir name="examples" role="doc"> <file role="php">NASDAQ.php</file> <file role="php">DAX.php</file> </dir> </dir> </dir> </filelist> </release> </package> In this example you get to know a very handy feature: When you have a directory in your package that only contains files of the same type, you can add to role attribute even to the <dir> tag instead of adding it to every single <file> tag. With the knowledge you aquired during this chapter you should now be able to produce a package definition file for your own package. If you still have questions concerning the topic, don't hesitate to ask on the mailinglist. The file roles The role-attribute in the <file> tag defines what type the file has and in which location it should be installed. Tabelle 15-1. Possible values Value Destination dir php PHP source file the directory is determined by the package name ext Extension, dynamically loadable library the PHP extension directory or PHP_PEAR_EXTENSION_DIR if defined doc Documentation file {PEAR_documentation_dir}/Package_Name/ data Package related data files (graphics, data tables etc) {PEAR_data_dir}/Package_Name/ test Package related test files (unittests etc) {PEAR_test_dir}/Package_Name/ script Package related shell scripts the PHP binary directory or PHP_PEAR_BIN_DIR if defined src and extsrc C or C++ source code not copied directly - used to build a extension Defining Dependencies The PEAR Package Manager supports checking for different system capabilities. You define those dependencies with the <dep> tag: Beispiel 15-3. package.xml with dependencies The following example shows how to specificy dependencies for PHP 4.3.0 or better and XML_Parser 1.0. <?xml version="1.0" encoding="ISO-8859-1" ?> [...] </release> <deps> <dep type="php" rel="ge" version="4.3.0" /> <dep type="pkg" rel="has" version="1.0">XML_Parser</dep> </deps> </package> The type-attribute The following types are supported: Tabelle 15-2. type values Value Meaning Example pkg Package depends on a certain Package „HTML_Flex y“ ext Extension depends on a certain PHP extension „curl“ php PHP depends on a certain PHP version „4.2“ prog Program depends on a certain Program available in the system path. This is not supported in the PEAR installer. „latex“ os Operating System depends on a certain OS version „Linux“ sapi Server API depends on a certain Server API. This is not supported „Apache“ in the PEAR installer. zend Zend depends on a certain version of the Zend API. This is not supported in the PEAR installer. „2“ Warnung The DTD for the package definition file supports further types, but those are not supported yet. The rel-attribute The rel-attribute defines the relationship between the existing capability and the required. Tabelle 15-3. rel values Value has has Meaning Can be used with the existing capability must have the requirement - version-attribute is ignored pkg, ext, php, prog, os, sapi, Value Meaning Can be used with zend pkg, ext, php, prog, os, sapi, zend eq equal the the existing capability must exactly match the version value lt less than the existing capability must be less than the pkg, ext, php, version value zend le less than or equal the existing capability must be less than or equal to the version value gt greater than the existing capability must be greater than pkg, ext, php, the version value zend ge greater than or the existing capability must greater than or equal equal to the version value pkg, ext, php, zend not conflicting dependency ext, php the dependency conflicts with the package, the two cannot co-exist. version is ignored. pkg, ext, php, zend Has will be used if no other value has been defined. Note that rel is required in PEAR 1.4.0 and newer. The version-attribute The attribute version defines the version that is used to compare. The optional-attribute The attribute optional can be used when a dependency is not required but having the package installed can bring enhanced functionalities. The only legal values are "yes" and "no". If the optional attribute is not present, a dependency is required. When optional="yes" is used, this attribute will result in installation messages similar to the following messages: $ pear install <package> Optional dependencies: Package `XML_Tree' is recommended to utilize some features. Package `MDB' is recommended to utilize some features. Kapitel 16. The package definition file package.xml, version 2.0 A quick and dirty guide to version 2.0 of the package definition file package.xml The package definition file package.xml is, as the name already implies, a well-formed XML file that contains all information about a PEAR package. Version 2.0 contains several important enhancements over version 1.0, including • Channel support • Binary PECL packages support (not fully implemented in PEAR 1.4.0) • More specific dependency resolution For those of you with an existing package.xml version 1.0, you can create an approximate equivalent package using the $ pear convert command. Note that as of version 1.6.0a1, PEAR_PackageFileManager supports package.xml 2.0 with the PEAR_PackageFileManager2 class. PECL developers: for more information on pecl-specific features, read here. An example file with all elements <?xml version="1.0"?> <package version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>PEAR</name> <channel>pear.php.net</channel> <summary>Any one-line summary</summary> <description>any static long description. This text should not change very much between releases, use the "notes" tag for release notes </description> <lead> <name>Greg Beaver</name> <user>cellog</user> <email>[email protected]</email> <active>yes</active> </lead> <date>2005-02-26</date> <time>20:30:13</time> <-- note: <time> is optional --> <version> <release>1.4.0a2</release> <api>1.4.0</api> </version> <stability> <release>alpha</release> <api>alpha</api> </stability> <license uri="http://www.php.net/license">PHP License</license> <notes> Put release notes here. They can be multi-line </notes> <contents> <dir name="/"> <dir name="PEAR"> <dir name="ChannelFile"> <file name="Parser.php" role="php" /> </dir> <!-- /PEAR/ChannelFile --> <file name="Dependency2.php" role="php"> <tasks:replace from="@PEAR-VER@" to="version" type="package-info"/> </file> </dir> <!-- /PEAR --> <dir name="scripts" baseinstalldir="/"> <file name="pear.bat" role="script"> <tasks:replace from="@bin_dir@" to="bin_dir" type="pear-config" /> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> <tasks:windowseol/> </file> <file name="pecl.bat" role="script"> <tasks:replace from="@bin_dir@" to="bin_dir" type="pear-config" /> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> <tasks:windowseol/> </file> <file name="pear.sh" role="script"> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" /> <tasks:replace from="@pear_version@" to="version" type="package-info" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> <tasks:unixeol/> </file> <file name="pecl.sh" role="script"> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" /> <tasks:replace from="@pear_version@" to="version" type="package-info" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> <tasks:unixeol/> </file> <file name="pearcmd.php" role="php"> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" /> <tasks:replace from="@pear_version@" to="version" type="package-info" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> </file> <file name="peclcmd.php" role="php"> <tasks:replace from="@php_bin@" to="php_bin" type="pear-config" /> <tasks:replace from="@php_dir@" to="php_dir" type="pear-config" /> <tasks:replace from="@pear_version@" to="version" type="package-info" /> <tasks:replace from="@include_path@" to="php_dir" type="pear-config" /> <tasks:footask/> </file> </dir> <!-- /scripts --> <file name="package.dtd" role="data" /> <file name="postinstall.php" role="php"> <tasks:postinstallscript/> </file> <file name="template.spec" role="foo" /> </dir> <!-- / --> </contents> <compatible> <name>FooPackage</name> <channel>pear.php.net</channel> <min>1.3.0</min> <max>1.5.0</max> </compatible> <dependencies> <required> <php> <min>4.2</min> <max>6.0.0</max> </php> <pearinstaller> <min>1.4.0dev13</min> </pearinstaller> <package> <name>Archive_Tar</name> <channel>pear.php.net</channel> <min>1.1</min> <recommended>1.2</recommended> </package> <package> <name>Foo</name> <uri>http://www.example.com/Foo-1.2.0.tgz</uri> </package> <extension> <name>xml</name> </extension> <os> <name>windows</name> <conflicts/> </os> <arch> <pattern>*-i?86-*-*</pattern> </arch> </required> <optional> <package> <name>PEAR_Frontend_Web</name> <channel>pear.php.net</channel> <min>0.5.0</min> </package> <package> <name>PEAR_Frontend_Gtk</name> <channel>pear.php.net</channel> <min>0.4.0</min> </package> </optional> <group name="remoteinstall" hint="adds the ability to install packages to a remote ftp s <package> <name>Net_FTP</name> <channel>pear.php.net</channel> <min>1.3.0RC1</min> <recommended>1.3.0</recommended> </package> </group> <group name="webinstaller" hint="PEAR's web-based installer"> <package> <name>PEAR_Frontend_Web</name> <channel>pear.php.net</channel> <min>0.5.0</min> </package> </group> <group name="gtkinstaller" hint="PEAR's PHP-GTK-based installer"> <package> <name>PEAR_Frontend_Gtk</name> <channel>pear.php.net</channel> <min>0.4.0</min> </package> </group> </dependencies> <usesrole> <role>foo</role> <package>Foo</package> <channel>pear.example.com</channel> </usesrole> <usestask> <task>footask</task> <package>Footask</package> <channel>pear.example.com</channel> </usestask> <phprelease> <installconditions> <os> <name>windows</name> </os> </installconditions> <filelist> <install as="pear.bat" name="scripts/pear.bat" /> <install as="pecl.bat" name="scripts/pecl.bat" /> <install as="pearcmd.php" name="scripts/pearcmd.php" /> <install as="peclcmd.php" name="scripts/peclcmd.php" /> <ignore name="scripts/pear.sh" /> <ignore name="scripts/pecl.sh" /> </filelist> </phprelease> <phprelease> <filelist> <install as="pear" name="scripts/pear.sh" /> <install as="pecl" name="scripts/pecl.sh" /> <install as="pearcmd.php" name="scripts/pearcmd.php" /> <install as="peclcmd.php" name="scripts/peclcmd.php" /> <ignore name="scripts/pear.bat" /> <ignore name="scripts/pecl.bat" /> </filelist> </phprelease> <changelog> <release> <version> <release>1.3.5</release> <api>1.3.0</api> </version> <stability> <release>stable</release> <api>stable</api> </stability> <date>2005-02-26</date> <license uri="http://www.php.net/license/3_0.txt">PHP License</license> <notes> * fix Bug #3505: pecl can't install PDO * enhance pear run-tests dramatically * fix Bug #3506: pear install should export the pear version into the environment </notes> </release> <release> <version> <release>1.4.0a1</release> <api>1.4.0</api> </version> <stability> <release>alpha</release> <api>alpha</api> </stability> <date>2005-02-26</date> <license uri="http://www.php.net/license/3_0.txt">PHP License</license> <notes> This is a major milestone release for PEAR. In addition to several killer features, every single element of PEAR has a regression test, and so stability is much higher than any previous PEAR release, even with the alpha label. New features in a nutshell: * full support for channels * pre-download dependency validation * new package.xml 2.0 format allows tremendous flexibility while maintaining BC * support for optional dependency groups and limited support for sub-packaging * robust dependency support * full dependency validation on uninstall * support for binary PECL packages * remote install for hosts with only ftp access - no more problems with restricted host installation * full support for mirroring * support for bundling several packages into a single tarball * support for static dependencies on a url-based package Specific changes from 1.3.5: * Implement request #1789: SSL support for xml-rpc and download * Everything above here that you just read </notes> </release> </changelog> </package> Special information for PECL developers Inhaltsverzeichnis extsrcrelease and extbinrelease changes for PECL developers -- PECL-specific details of package.xml 2.0 extsrcrelease and extbinrelease changes for PECL developers extsrcrelease and extbinrelease changes for PECL developers -- PECL-specific details of package.xml 2.0 Special extension package tags Most of the tags for PECL-style PHP extension releases are identical to those for PEARstyle PHP script releases. There are a few extsrc/extbin-specific tags that all PECL developers must know about. Tabelle 16-1. PECL extsrc/extbin-specific tags in package.xml 2.0 Tag Description of usage The <providesextension> tag must be right after <dependencies>. This tag tells the installer the name of the extension provided by the package, allowing different package names from the extension. This could be important for binary packages (such as PDO and <providesextension> PDO_windows or something along those lines). <providesextension>PDO</providesextension> <srcpackage> or <srcuri> must follow <providesextension>. Extension binary packages must define either a <srcpackage> tag (for package.xml containing <channel>) or a <srcuri> tag (for package.xml containing <uri>). <srcpackage> or <srcuri> <name>PDO_windowsbin</name> <channel>pecl.php.net</channel> <!-- snip --> <providesextension>PDO</providesextension> <srcpackage>PDO</srcpackage> or, <name>Foo_windowsbin</name> <uri>http://www.example.com/Foo_windowsbin-1.5.0.tgz</uri> <!-- snip --> <providesextension>Foo</providesextension> <srcuri>http://www.example.com/Foo-1.5.0.tgz</srcuri> Detailed Tag Reference for package.xml version 2.0 Inhaltsverzeichnis <channel> -- What is a channel? <uri> -- When should I use <uri>? <lead>, <developer>, <contributor>, and <helper> -- Developer documentation for a release <version> -- versioning in package.xml 2.0 <stability> -- specifying release and API stability <license> -- specifying software license and optional reference to license text <contents> -- specifying the contents of a release <dir> -- documenting a directory in the <contents> tag <file> -- documenting a file in the <contents> tag tasks for <file>s -- specialized file installation and manipulation <compatible> -- Alleviating strict versioning with <compatible> <dependencies> -- Dependency Specification in package.xml 2.0 <usesrole> -- documenting custom file roles used in <contents> <usestask> -- documenting custom tasks used in <contents> <phprelease>, <extbinrelease>, <extsrcrelease>, <bundle> -- specifying the content type of a release Each tag that needs further explanation is documented here (unfinished) <channel> <channel> -- What is a channel? Quick introduction to channels Channels are new in PEAR 1.4.0. Channels are a systemized way of differentiating between different download sources. One such download source is pear.php.net, another is pecl.php.net, and there are several third party channels slowly springing up around the net. The <channel> tag should contain the full channel name, not any alias (don't use "pear", use "pear.php.net". A good rule of thumb to use when determining what channel name to use is "where do I upload my releases to?" If the answer is pear.php.net, that is your package's channel. If the answer is pecl.php.net, then that is your channel. If you aren't running a channel server and wish to serve your packages as well as allow other packages to remotely depend on your package, the new uri-based package distribution method is the best choice, see the <uri> tag documentation link below. See also: <uri> <uri> <uri> -- When should I use <uri>? When to use <uri> instead of <channel> If you do not have a channel server and wish to serve your packages so that others can depend on them, use <uri>. This should contain a static uri that links to a single package version's downloadable .tgz If you do not need to allow external remote dependencies, then simply use the pear.php.net channel as your package's channel. For instance, if you wish to serve package Foo version 1.1.0 from www.example.com, use the uri "http://www.example.com/Foo-1.1.0". Note that the uri must contain the full path MINUS THE EXTENSION. Provide both Foo-1.1.0.tgz and Foo-1.1.0.tar for users without gzip. See also: <channel> <lead>, <developer>, <contributor>, and <helper> <lead>, <developer>, <contributor>, and <helper> -- Developer documentation for a release Documenting who develops a package In package.xml 1.0, a developer was documented using the <maintainer> tag inside of a redundant <maintainers> container tag. This has been simplified in package.xml 2.0 both to slightly speed parsing and to make validation of the xml simpler. Now, the contents of the <role> tag has been extracted as 4 tags to describe the maintainers of a package. In addition, a new internal tag <active> has been added, so that you can honor retired developers' work without having to remove them altogether from package.xml. WARNING: tag order is important. List leads followed by developers followed by contributors and finally helpers. <version> <version> -- versioning in package.xml 2.0 Documenting release version and API version In package.xml 1.0, the version was simply the version. package.xml 2.0 splits the concept of versioning into two components, release and api. The release version is the same familiar versioning concept from package.xml 1.0. This version is validated very carefully by the packager. The API version is informational only - the installer does not use it. It can be used for a package-time replacement by the installer. This can be very useful when implementing a reflective method such as getApiVersion(). In addition, the API version is very loosely validated, and only requires a version_compare()-compatible version number. <stability> <stability> -- specifying release and API stability Documenting release stability and API stability In package.xml 1.0, stability was known as "state" which is not the most accurate description. package.xml 2.0 introduces the term stability and like version splits the concept of stability into two components, release and api. The release stability is the same familiar state from package.xml 1.0. It can be one of: 1. snapshot - a frozen picture of development at a particular moment 2. devel - a very new non-production release. Devel should be used for extremely new, practically untested code. 3. alpha - a new non-production release. Alpha should be used for new code that has an unstable API or untested code. 4. beta - a non-production release. Beta should be used for code that has a stable API and is nearing a fully stable release. Regresion tests and documentation should exist or soon follow to qualify as a beta release. Release candidates should use the beta stability. 5. stable - a production release. Stable releases must have a stable API, and must have regression tests and documentation. The API stability is informational only - the installer does not use it. <license> <license> -- specifying software license and optional reference to license text Documenting release license In package.xml 1.0, the license tag only contained the name of the license. In package.xml 2.0, there are two optional attributes, "uri" and "filesource". "uri" contains a uri that identifies the text of a license, such as "http://www.php.net/license" for the PHP License. "filesource" can be used to specify a LICENSE file within an actual package that contains the text of the license. <contents> <contents> -- specifying the contents of a release Documenting release contents In package.xml 1.0, the contents tag was <filelist>. The purpose of the tag changed dramatically in package.xml 2.0, warranting a name change. Now, <filelist> can be found in the release section of the package.xml. <contents> is used to describe the contents of a tarball. Nothing further. All files in the contents tag will be placed into the tarball regardless of whether they eventually get installed by the PEAR installer. This fact can be used to create a very versatile tarball, one that can be directly unzipped and work out of the box as well as be installed by the PEAR installer and work out of the box. For most release types, contents contains a single <dir> tag that then either contains nested dir tags and/or <file> tags. <dir> <dir> -- documenting a directory in the <contents> tag Documenting directories The <dir> tag is identical to package.xml 1.0. Required attributes are name and optional attributes are baseinstalldir (the relative location where all files and subdirectories will be installed) Note that all files must be contained in a single top-level <dir> tag. For simple packages, simply use <dir name="/"> as the directory name <file> <file> -- documenting a file in the <contents> tag Documenting files The <file> tag is almost identical to package.xml 1.0. Required attributes are name and role. Optional attributes are baseinstalldir and md5sum. Optional attributes platform and install-as have been replaced by the release tags. Specifically, <install> is used to specify install-as, and the <ignore> tag can be used in conjunction with <installconditions> to exclude packages from being installed on particular platforms. For those familiar with the platform attribute, the way to handle this example: <file name="scripts/foo.bat" role="script" install-as="foo.bat" platform="windows"> is to in fact create two release sections. The file tag would then look like: <file name="scripts/foo.bat" role="script"> and the release section would look like this: <phprelease> <installconditions> <os>windows</os> </installconditions> <install name="scripts/foo.bat" as="foo.bat"/> </phprelease> <phprelease> <ignore name="scripts/foo.bat"/> </phprelease> Note that the second <phprelease> tag could just as easily have had an <installconditions> tag containing <os>unix</os>, but this is unnecessary, as the second release will be processed on any system that is not a windows system. tasks for <file>s tasks for <file>s -- specialized file installation and manipulation Using tasks to customize file installation Tasks provide a flexible and customizable way to manipulate file contents or to perform complex installation tasks (hence the name "tasks"). By default, PEAR comes with 4 tasks, but customized tasks can be added simply by adding a file into the PEAR/Tasks directory that follows the conventions of existing tasks. This page does not describe how to create a custom task, only how to use them in package.xml. There are 3 basic tasks and 1 complex task distributed with PEAR. The basic tasks are "tasks:replace", "tasks:windowseol", and "tasks:unixeol". The complex task is "tasks:postinstallscript". "tasks:replace" is nearly identical to the old <replace> tag from package.xml 1.0, and does a text search-and-replace of a file's contents. "tasks:windowseol" and "tasks:unixeol" manipulate the line endings of a file to ensure that the correct line endings are in place for critical files like DOS .bat batch files and unix shell scripts. "tasks:postinstallscript" allows users to choose to run a script to perform further installation functions. <tasks:replace> - customizing file contents The replace task has 3 required attributes: 1. type - This must be either package-info or pear-config. package-info replacements extract information from package.xml itself to use as the replacement text. pearconfig replacements use the value of a configuration variable (as displayed by pear config-show ) as the text for replacement. 2. from - Text to search for in a file. Traditionally, this text is enclosed in "@" to differentiate it from normal text, as in from="@version@" 3. to - Abstract item to use as a replacement for all occurences of "from". packageversion replacements can be one of version, release_date, release_state, release_license, release_notes, apiversion, name, summary, description, notes, time, date, and for some packages extends, srcpackage, srcuri, and providesextension. Note that package-info replacements are performed at packaging time, so files contain package-info replacements inside a .tgz/.tar release. pear-config replacements can only occur on the installation system, and are performed at install-time. <tasks:windowseol> - converting line endings to \r\n This task can be used to enable packaging of windows-specific files (like DOS batch files) on a non-windows system, such as unix systems that convert line endings to \n. Note that this task is performed at package-time, as well as at install-time, so files will contain the correct line endings inside a .tgz/.tar release. <tasks:unixeol> - converting line endings to \n This task can be used to enable packaging of unix-specific files (like sh shell scripts) on a non-unix system, such as windows systems that convert line endings to \r\n. Note that this task is performed at package-time, as well as at install-time, so files will contain the correct line endings inside a .tgz/.tar release. <tasks:postinstallscript> - extreme customization The postinstallscript task informs the installer that the file it references is a postinstallation script. For security reasons, post-install scripts must be manually executed by the users, and as such the installer has special code that is separate from other tasks. The <postinstallscript> tag may define parameters that are used by the installer to retrieve user input. In order to support both the web installer and the command-line installer, all processing of input is performed by PEAR and passed to the post-install script in a strict format. All you need to do is define the parameters using xml inside the <postinstallscript> tag. Here is the xml representing a simple post-install script with parameters: <tasks:postinstallscript> <tasks:paramgroup> <tasks:id>first</tasks:id> <tasks:param> <tasks:name>test</tasks:name> <tasks:prompt>Testing Thingy</tasks:prompt> <tasks:type>string</tasks:type> </tasks:param> </tasks:paramgroup> </tasks:postinstallscript> Note that the only type recognized at this stage is "string" but others will follow. A more complex example follows: <tasks:postinstallscript> <tasks:paramgroup> <tasks:id>first</tasks:id> <tasks:instructions>The first group of questions relates primarily to your favorite color. Answer wisely. </tasks:instructions> <tasks:param> <tasks:name>test</tasks:name> <tasks:prompt>Testing Thingy</tasks:prompt> <tasks:type>string</tasks:type> <tasks:default>hi</tasks:default> </tasks:param> <tasks:param> <tasks:name>test2</tasks:name> <tasks:prompt>Testing Thingy 2</tasks:prompt> <tasks:type>string</tasks:type> </tasks:param> </tasks:paramgroup> <tasks:paramgroup> <tasks:id>second</tasks:id> <tasks:name>first::test</tasks:name> <tasks:conditiontype>preg_match</tasks:conditiontype> <tasks:value>g+</tasks:value> <tasks:param> <tasks:name>test</tasks:name> <tasks:prompt>Testing Thingy a</tasks:prompt> <tasks:type>string</tasks:type> <tasks:default>hi</tasks:default> </tasks:param> <tasks:param> <tasks:name>test2</tasks:name> <tasks:prompt>Testing Thingy b</tasks:prompt> <tasks:type>string</tasks:type> </tasks:param> </tasks:paramgroup> </tasks:postinstallscript> This post-installation script has two parameter groups. The first parameter group has special instructions that are displayed to the user to assist in answering the required prompts. After the first group is processed, the second group is processed (naturally). However, in this case, the second group is a conditional parameter group. A conditional parameter group examines the user input from previous parameter groups and only displays its parameter prompts if a single parameter fits a test. The condition is defined by three tags, <tasks:name>, <tasks:conditiontype>, and <tasks:value>. Note that all three tags are required or xml validation will fail. <tasks:name> is the parameter name from a previous parameter group. The format of name is groupID::parameterName, so as you see above, "first::test" refers to the <tasks:param> first from the <tasks:paramgroup> test. <tasks:conditiontype> determines how the parameter input function will process the value of the parameter specified in <tasks:name>, and can be one of three values, "=" "!=" or "preg_match". • • • =: This (obviously) tests whether the parameters value is equal to the <tasks:value> tag !=: This (obviously) tests whether the parameters value is not equal to the <tasks:value> tag preg_match: This uses the content of the <tasks:value> tag as if it were the stuff between / and / in a preg_match() function call. Do NOT include // brackets in the regular expression. In the <tasks:paramgroup> second, the value "g+" will become: <?php preg_match('/g+/', first::test value) ?> <compatible> <compatible> -- Alleviating strict versioning with <compatible> Working with <recommended> dependency versions and <compatible> The <compatible> tag is designed to be used with a <package> dependency that contains a <recommended> version tag from package pear.example.com/Bar version 1.3.0 like so: <package> <name>Foo</name> <channel>pear.example.com</channel> <min>1.0.0</min> <recommended>1.5.2</recommended> </package> The above dependency can be translated into English as follows: "Use the package pear.example.com/Foo, but only versions 1.0.0 or newer. If pear.example.com/Foo is not installed, install version 1.5.2. If pear.example.com/Foo is installed and is not version 1.5.2, fail unless --force is specified, or pear.example.com/Foo is compatible with me." That last clause "...or pear.example.com/Foo is compatible with me." is controlled by the <compatible> tag. If package Foo version 1.5.3's package.xml has a <compatible> like so: <compatible> <name>Bar</name> <channel>pear.example.com</channel> <min>1.2.0</min> <max>1.3.0</max> <exclude>1.2.9</exclude> </compatible> This will instruct the installer that pear.example.com/Foo version 1.5.3 is compatible with pear.example.com/Bar versions 1.2.0 to 1.3.0 inclusive, but is not compatible with 1.2.9. It is very important to note that only existing versions that have been tested with the package should be mentioned in the <compatible> tag. Future versions of pear.example.com/Bar should simply upgrade the <recommended> tag. <compatible> may contain three versioning tags. The required <min> and <max> are used to define the range of tested and compatible versions, and <exclude> is used to exclude any versions within the range. In the example above, 1.3.0 and 1.2.0 are the highest and lowest versions that may be excluded. There can be an unlimited number of <compatible> tags inside a package.xml. See also: <package> dependencies <dependencies> <dependencies> -- Dependency Specification in package.xml 2.0 Introduction to dependencies in package.xml 2.0 Dependencies are the most difficult aspect of programming. Using code written by other people can be a nightmare without simple ways to control bugs and API changes. Arguably, the handling of dependencies is PEAR's greatest strength, although there are many other nice features. Regardless of your personal opinion of the importance of dependencies, it is crucial to understand how to specify a dependency, and the different ways to ensure that your package is only used on systems that support it. In package.xml 1.0, dependencies were relatively simple, but at the cost of usefulness. Specifying a dependency on a package for applications was actually dangerous. If you wished to limit an installed version of a package to a single version, it would mean preventing upgrade at any cost. package.xml 2.0 provides a simple way to enforce stricter dependency versioning without making upgrades onerous. In package.xml 1.0, dependencies on PHP extensions like PECL extensions was near to a disaster. Extensions had to be present in the php.ini and loaded in memory in order to validate as being installed. This is often impossible, as a different php.ini is used for a production website versus the php.ini used for the pear installer. With package.xml 2.0, dependencies on a PECL-like extension is simple and straightforward, and only requires that the package be installed, and not that the extension be present in memory, although an older style extension dependency is also supported. package.xml 1.0 supports two kinds of dependencies, required and optional. package.xml 2.0 also supports these two dependency types, but introduces a new kind of dependency concept: an optional dependency group. Dependency groups define a feature set. Instead of thinking "This package optionally depends on Net_FTP and optionally depends on Log" think "To remotely install packages, I need the remoteinstall feature, which needs Net_FTP and the Log package". This grouping allows defining sets of packages and extensions that comprise a feature and must be installed all at once for the feature to function properly. package.xml 1.0 only supported php, package, and extension dependencies. package.xml 2.0 supports dependencies on php, package, extension, os, architecture, and PEAR installer. In addition, package.xml 2.0 supports depending on a static package located at a url, and depending on a package that provides an extension to PHP like PECL packages. The PEAR installer dependency is not a dependency on the PEAR package, but a dependency on the currently running PEAR installer, and is more similar to a PHP dependency in that it requires the specified version to be running in memory. This is very useful for circumventing difficult bugs in the PEAR installer that render a package install useless. Structure of <dependencies> The <dependencies> tag re-organizes dependencies into groups and "extracts" attributes into tags. It also un-abbreviates words for clarity and human-readability. The following excerpt of a package.xml version 1.0: <deps> <dep type="pkg" rel="ge" version="1.3.1">Archive_Tar</dep> <dep type="php" rel="ge" version="4.2.0"/> <dep type="pkg" rel="has" optional="yes">PEAR_Frontend_Web</dep> </deps> Approximately translates into this format in package.xml 2.0: <dependencies> <required> <pearinstaller> <min>1.4.0a7</min> </pearinstaller> <php> <min>4.2.0</min> <max>6.0.0</max> </php> <package> <name>Archive_Tar</name> <channel>pear.php.net</channel> <min>1.3.1</min> </package> </required> <optional> <package> <name>PEAR_Frontend_Web</name> <channel>pear.php.net</channel> </package> </optional> </dependencies> These changes were made to simplify xml validation and parsing. Note that unlike package.xml 1.0, the <pearinstaller> and <php> dependencies are required in all package.xml. In addition the <min> tag is required in <pearinstaller>, and both the <min> and <max> tags are required for <php> dependencies. <pearinstaller> dependencies The <pearinstaller> dependency defines the minimum version of PEAR that can properly parse and install the package.xml containing it. As with all dependency tags that support versioning, these 4 tags are supported to define versioning: • • • <min> - minimum version of PEAR required to install this package.xml. This tag is required in all package.xml <pearinstaller> dependencies. <max> - maximum version of PEAR installer supported. Use with caution! This tag will prevent the package from being installed by anyone with a newer version of PEAR! <recommended> - recommended version of PEAR installer. This tag is used for strict version control. The installer will refuse to install a package without the -force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades. • <exclude> - incompatible versions of PEAR installer. Use this to prevent the package from being installed by any PEAR version that cannot properly install the package. Multiple <exclude> tags may be used to exclude more than one version. <php> dependencies As with all dependency tags that support versioning, these 4 tags are supported to define versioning: • • • • <min> - minimum version of PHP required to install this package.xml. This tag is required in all package.xml <php> dependencies. <max> - maximum version of PHP supported. This tag is required in all package.xml <php> dependencies. <recommended> - recommended version of PHP. This tag is used for strict version control. The installer will refuse to install a package without the --force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades. <exclude> - incompatible versions of PHP. Use this to prevent the package from being installed by any PHP version that cannot properly work with the package. Multiple <exclude> tags may be used to exclude more than one version. <subpackage> dependencies Subpackage dependencies share the same xml format as package dependencies. The subpackage dependency should only be used if a package is split into more than one package. In other words, if the child package contains the same files as any earlier version of the parent package, the child package would normally conflict with the parent package because it would be attempting to overwrite the parent package's files with its own files. A simple example should make this clear. Package Foo 1.0.0 contains Foo.php and Foo/Bar.php. Package Foo's developers decide to split Foo into two packages: Foo and Foo_Bar. Foo 1.1.0 contains foo.php, and Foo_Bar 0.1.0 contains Foo/Bar.php. Foo_Bar 0.1.0 conflicts directly with Foo 1.0.0, as both contain the file Foo/Bar.php. If Foo has a subpackage dependency on Foo_Bar, then the installer will ignore the conflict between Foo 1.0.0's Foo/Bar.php and Foo_Bar 0.1.0's Foo/Bar.php just as it ignores the conflict between Foo 1.0.0's Foo.php and Foo 1.1.0's Foo.php. <package> dependencies Understandably, the <package> dependency is PEAR's most complex dependency. PEAR 1.4.0 supports 3 different kinds of package dependencies: 1. Normal, traditional channel server-based package dependencies (same idea as package.xml 1.0). 2. Dependencies on packages that provide PHP extensions (like PECL packages). (These can be both server-based and uri-based dependencies) 3. Static, non-traditional uri-based package dependencies. channel-based <package> depedendencies The most common kind of package dependency is a channel-based dependency. This dependency from package.xml version 1.0: <deps> <dep type="pkg" rel="has">PEAR</dep> </deps> translates to this dependency in package.xml version 2.0: <dependencies> <required> <!-- ... --> <package> <name>PEAR</name> <channel>pear.php.net</channel> </package> </required> </dependencies> Note that <channel> is a required tag for all typical package dependencies. Use pear.php.net for all packages that were packaged using package.xml 1.0, regardless of where they are downloaded from. As with all dependency tags that support versioning, all standard versioning tags are supported (min, max, recommended, exclude). In addition, the <conflicts> tag is supported to create a negative dependency. • <min> - minimum version of a dependency. If the dependency package is installed, and is older than this version, installation will fail. • • <max> - maximum version of a dependency. If the dependency package is installed, and is newer than this version, installation will fail. <recommended> - recommended version of a dependency. This tag is used for strict version control. The installer will refuse to install a package without the --force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades. Note that use of the <compatible> tag in the dependency's package.xml can be used to circumvent the installer's strictness. In essence, the <compatible> tag tells the installer that a dependent package is compatible with the current package, even though it is not the recommended version. • • <exclude> - incompatible versions of a package. Multiple <exclude> tags may be used to exclude more than one version of a dependency. <conflicts> - Negates the dependency. If the package is installed, it cannot satisfy the requirements of the dependency or installation will fail. Here is a rough chart describing how to convert from package.xml 1.0 "rel" attributes to a package.xml 2.0 equivalent. Tabelle 16-1. Converting package.xml 1.0 package dependencies to package.xml 2.0 1.0 2.0 equivalent <dep type="pkg" rel="has">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> </package> <dep type="pkg" rel="ge" version="1.0.0">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> <min>1.0.0</min> </package> 1.0 2.0 equivalent <dep type="pkg" rel="gt" version="1.0.0">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> <min>1.0.0</min> <exclude>1.0.0</exclude> </package> <dep type="pkg" rel="le" version="1.0.0">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> <max>1.0.0</max> </package> <dep type="pkg" rel="ge" version="1.0.0">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> <max>1.0.0</max> <exclude>1.0.0</exclude> </package> <dep type="pkg" rel="ge" version="1.0.0">Foo</dep> <package> <dep type="pkg" rel="le" version="1.9.0">Foo</dep> <name>Foo</name> <channel>pear.php.net</channel> <min>1.0.0</min> <max>1.9.0</max> </package> <dep type="pkg" rel="not">Foo</dep> <package> <name>Foo</name> <channel>pear.php.net</channel> <conflicts/> </package> uri-based <package> dependencies Let's look at uri-based package dependencies. Here is a simple example: <package> <name>Foo<name> <uri>http://www.example.com/Foo-1.3.0</uri> </package> This dependency tells the installer to fetch http://www.example.com/Foo-1.3.0.tgz or http://www.example.com/Foo-1.3.0.tar (both must be available!) if the package Foo is not installed. All uri packages must contain a <uri> tag rather than a <channel> tag and will automatically belong to the pseudo-channel "__uri", but that is not important to the discussion of how to format the xml to create the uri-based package dependency. uri-based package dependencies cannot contain any versioning information, as this is irrelevant: there is only one version possible with a static uri. uri-based dependencies can contain the <conflicts/> tag to specify an absolute conflict with the package, and the <providesextension> tag to specify an extension provided by the static package. PEAR-style <package> dependencies vs. PECL-style <package> dependencies package.xml 2.0 supports differentiating release types, and as such also supports dependencies on PECL-style packages that use the extbinrelease or extsrcrelease type. To specify a dependency on a PHP extension that can be distributed as a PECL package, but could also be bundled with PHP by default, such as the PDO extension, use this dependency style: <package> <name>PDO</name> <channel>pecl.php.net</channel> <min>0.3.1</min> <providesextension>PDO</providesextension> </package> The magic is in the <providesextension> tag. This tag tells the installer to take this process when validating the dependency: 1. Is the extension "PDO" present in memory? If so, is it version 0.3.1 or higher? 2. If not, is the user also installing pecl.php.net/PDO at the same time as this package? If so, is it version 0.3.1 or higher? 3. If not, is pecl.php.net/PDO installed, and is the version 0.3.1 or higher? If any of the three conditions above validate in the order specified, the dependency will be satisfied and installation will continue. This system allows users to use a different php.ini to install PHP extensions and also provides a fail-safe system to depend on extensions. Warnung <providesextension>, like all other extension-related functions in PHP, is case-sensitive. Do not use "pdo" for the "PDO" extension, or your dependency will always fail. <extension> dependencies As with all dependency tags that support versioning, all standard versioning tags are supported (min, max, recommended, exclude). In addition, the <conflicts> tag is supported to create a negative dependency. • <min> - minimum version of PHP extension to install this package.xml. • <max> - maximum version of PHP extension supported. • • • <recommended> - recommended version of PHP extension. This tag is used for strict version control. The installer will refuse to install a package without the -force option unless the version exactly matches recommended. This can be used to provide a level of extra security, as a package can be set to install using a version that is known to work without limiting future upgrades. <exclude> - incompatible versions of PHP extension. Multiple <exclude> tags may be used to exclude more than one version. <conflicts> - Negates the dependency. If the extension is present, it cannot satisfy the requirements of the dependency or installation will fail. <os> dependencies The OS dependency is used to restrict a package to both a particular class of OSes (like unix) and to a specific OS (like darwin, or freebsd). Here is an example: <os> <name>linux</name> </os> To specify that a package can be installed on every OS except the one specified, use the <conflicts/> tag: <os> <name>windows</name> <conflicts/> </os> Possible OS values are: • windows • unix • linux • freebsd • darwin (use for Mac OS X) • sunos • irix • hpux • aix In addition, any esoteric OS that supports the php_uname() function can be used. Note that the "unix" OS is defined as any of linux, freebsd, darwin, sunos, irix, hpux, or aix. <arch> dependencies The arch dependency is used to restrict a package to a specific os and processor architecture. Here is an example: <arch> <pattern>linux-*-i386-*</pattern> </arch> To specify that a package can be installed on every architecture except the one specified, use the <conflicts/> tag: <arch> <pattern>linux-*-i?86-*</pattern> <conflicts/> </arch> The arch pattern is defined by the OS_Guess->matchSignature() method, and is as follows: sysname[-release[-cpu[-extra]]]. All segments within [] are optional, and the wildcard "*" can be used in all segments instead of a value. In addition, the "?" wildcard can be used to specify a single character that can match any value. i?86 will match i386, i686, i586 and so on. sysname is the same as the os dependency, except unix is not supported. release is the version of the operating system. cpu is the specific cpu, and is typically i?86, sparc, powerpc. extra is any other stuff on the end of php_uname(), including the glibc version <usesrole> <usesrole> -- documenting custom file roles used in <contents> Documenting custom file roles Standard file roles provided by default with PEAR are: • php • data • doc • test • script • src • ext If your package chooses to use a role provided by a third party that implements some more advanced file installation handling, all you need to do is specify the role in the xml for the <file> tag that contains it like so: <file role="foo"/> However, if a user does not have the package installed that provides the custom role "foo", then the error message on installation will simply say "unknown role 'foo'", which is not very helpful. The <usesrole> tag instead prompts the installer to tell the user "this package uses the custom role 'foo', install package pear.example.com/Foo to use" <usesrole> <role>foo</role> <package>Foo</package> <channel>pear.example.com</channel> </usesrole> Note that static URI packages (channel-less packages) are also supported: <usesrole> <role>foo</role> <uri>http://pear.example.com/Foo-1.2.0</uri> </usesrole> <usestask> <usestask> -- documenting custom tasks used in <contents> Documenting custom file tasks Standard file tasks provided by default with PEAR are documented in this location. If your package chooses to use a task provided by a third party, all you need to do is specify the task as part of the xml for the <file> tag that contains it like so: <file role="php"> <tasks:foo/> </file> However, if a user does not have the package installed that provides the custom task "foo", then the error message on installation will simply say "unknown task 'foo'", which is not very helpful. The <usestask> tag instead prompts the installer to tell the user "this package uses the custom task 'foo', install package pear.example.com/Foo to use" <usestask> <task>foo</task> <package>Foo</package> <channel>pear.example.com</channel> </usestask> Note that static URI packages (channel-less packages) are also supported: <usestask> <task>foo</task> <uri>http://pear.example.com/Foo-1.2.0</uri> </usesrole> <phprelease>, <extbinrelease>, <extsrcrelease>, <bundle> <phprelease>, <extbinrelease>, <extsrcrelease>, <bundle> -- specifying the content type of a release Documenting release type In package.xml 1.0, there was one release type. package.xml 2.0 provides much finer control over the kind of release in order to provide three new release types: extension binary release, extension source release, and package bundle release. All of the normal release tags (phprelease, extsrcrelease, extbinrelease) may contain two optional sections, <installconditions> and <filelist>. The purpose of these sections is to allow specification of different file install groups based on the target OS for installation, or other common install conditions. To be clear: in package.xml, there was 1 <release> tag. package.xml 2.0 allows several adjacent release tags, each specifying a different install set. This actually simplifies complex installation filesets by separating the contents listing of the tarball from how the installer should manipulate this listing. Debugging installation file sets should be much simpler with this change. The <filelist> tag can contain only two possible tags, <install> and <ignore>. install has two required attributes, "name" and "as". The install tag is used in the same manner as package.xml's install-as attribute for the <file>, to specify a new installation location for a file in the contents list. The ignore tag is used to completely ignore a file. The <installconditions> tag can contain 4 tags whose format can be found in the <dependencies> section: <php>, <extension>, <os>, and <arch>. Each tag can appear exactly once except for the extension tag, which can appear limitless times. The php tag is used to specify a php version or range of versions that an install set should be valid with. The extension tag is used to specify extensions that must be present for an install set to be valid. The os tag is used to specify an OS that must be present for an install set to be valid. Note that unix can be used to match all flavors, and linux can be used to match all linuxbased OSes. Darwin should be used for Mac OS X, and * can be used to match all operating systems. The arch tag is used to specify a uname string or portion of a uname string that must match in order for the install set to be valid. <phprelease> The phprelease release type is designed for PEAR-style PHP script package releases. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="php", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in php releases. <extsrcrelease> The extsrcrelease release type is for PECL-style PHP extension releases that must be compiled in order to be useable. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="src", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in extension source releases. In addition, the <providesextension> tag must be present in order to document the name of the extension this package provides must be in the package.xml as well. <extbinrelease> The extbinrelease release type is for PECL-style PHP Extension binary releases that are pre-compiled. It causes a few specific validation changes. First of all, the <contents> tag must contain <file> and <dir> tags. The only valid roles for files are role="ext", role="data", role="doc", and role="test" plus any custom roles that the user has installed for use in extension binary releases. In addition, the <srcpackage> or <srcuri> and the <providesextension> tags must be present in order to document the package that provides extension source for this binary release, and the name of the extension this package provides must be in the package.xml as well. <bundle> The bundle release type is designed to allow packaging several other package releases into a single bundle of packages that will all be installed at the same time. This can be used to distribute a complete application as one tarball, or to distribute a library of packages in a single tarball. Unlike the other release types, a bundle release's <contents> tag must contain only the <bundledpackage> tag. The contents of the bundledpackage should be release names like "Foo-1.2.3.tgz" In addition, the <bundle/> tag must be empty. Kapitel 17. Releasing A Package The steps required from package maintainers to release a package. Prerequisites Rolling a new release requires that the package to which the release belongs has been approved by the PEAR developers and that you have a valid PEAR website account. Information about meeting this two requirements can be found in the chapter Contributing your own code. Validating The Package Definition File Next, you should check the package definition file (package.xml) for validity. This is done by running the command: pear package-validate package.xml. Fix the errors and warnings, if any, and proceed to the next step. Anmerkung: For help with writing the package definition file see the package definition file description. Packaging The Release Tarball Now that your package has a valid package definition file, you can package the release tarball. Cd to the top-level directory of the package and run: pear package This will create the release tarball that will be used later to upload the new release. Anmerkung: Please note that the zlib extension needs to be enabled in your PHP build in order to create the release tarball. Next, you should install the package locally by running: pear install <file> (file is the tarball you just created). This is done to ensure that the package definition file is not only valid but also contains valid information. You should manually check that every file is installed in the right place. If your package contains test scripts, which is highly recommended, you should run them. If anything fails at this stage, correct it and re-package and re-test. When everything seems OK, proceed. Releasing The Package Through The Web Interface First, you should login to the PEAR website using the account you've been given (see the first step). Now, finally, you can release your package. This is done again using the convenient web interface. Use the form at http://pear.php.net/release-upload.php. That's it! Your package has been released, an announcement has been sent to the mailing lists. Kapitel 18. Supporting PEAR development How to support the PEAR community There are numerous ways to support the PEAR project, that are described in this part of the guide. Reporting and fixing bugs There is a chapter devoted to reporting and fixing bugs in the "Reporting Bugs" section of the manual, found here. Contributing new features to packages If you have a feature you would like to see included in a package, don't hesitate to contact the maintainer of the package. You can find out who the maintainer of a package is by browsing the package list on the PEAR website and selecting the desired package. The maintainer(s) is/are listed on the package information page. Becoming the new maintainer for an unmaintained package If a developer has given up the maintainership of his package, you can take over this job. If you feel brave enough to answer support questions, fix bugs and manage release cycles, you can contact the previous maintainer or the PEAR developers mailing list and announce your will to maintain the package. Buying things from wishlists For all the PEAR developers, PEAR is a project they are working on in their free-time, which means that they don't earn any money with it. If you or the company you are working for is using a PEAR package in one of your/their (commercial) products, you/they can do this for free, of course. But if you think that the author of the package you are using desires some credits, it would be nice to buy something from his wishlist at Amazon or another internet store. To see if a PEAR developer has registered his wishlist, surf to the Account information page and select the developer from the list there. If he has a wishlist, it's noted somewhere on the detail page. Kapitel 19. Recommendations Why recommendations? The following recommendations describe topics which were discussed and agreed upon by the PEAR developers on the developers mailinglist. They aren't strict rules, which you need to follow (like Coding Stardards), but are intended as guidelines for a common API scheme and easier package interoperability. Please consider following them in your packages where possible. Color Representation inside PEAR Packages In case a package has to deal with colors, it is recommended that developers store and use an array representation of the color values in their PEAR packages. All values are in the range of 0..255. RGB represesentation The following snippet defines an array that holds the RGB definition of the green coloring that is used in the official PEAR logo. $color = array(0x33, 0x99, 0x00); or $color = array(51, 153, 0); Please note that the internal, numerical representation of both forms of the example are equal. The values represent the RGB (red, green, blue) values. It was decided not to use "r", "g" and "b" as indices for the array, because numerical indices allow easier creation of color arrays in the sourcecode, make handling less complicated and are an already commonly used array representation for colors. RGB representation with alpha-values Since this an extension of the RGB representation above, it is recommended to use a forth value for alpha-channel-prepresentation. An example of the „PEAR-green“ with aprox. 80% intensity would be: $color = array(0x33, 0x99, 0x00, 0xCC); For consistency the alpha-value is also from the range 0..255. A value of 255 means fully opaque (full color-intensity, same as in RGB- notation), 0 means fully transparent. Please note this is in contrast to the alpha-value used by imagecolorallocate(). The alpharepresentation used in PEAR was choosen for consistency with the other RGB values and because it is commonly accepted practise in many other applications (image-processing tools, etc.). Other color representations than RGB(A) Since RGB/RGBA will used for graphic generation on a computer we decided to leave out an optional type-identifier classifying colors as RGB/RGBA. However for different colorrepresentations an identifier is needed. The optional identifier "type" can be added to the color array. $color = array(0x33, 0x99, 0x00, 0xCC, "type" => "RGB"); Currently the following types are definied, with array-indices from 0..n follwing the colornames listed behind them: • RGB - red, green, blue • CYMK - cyan, yellow, magenta, black (key) Please note that also the RGBA representation has the type "RGB" since it's closely related. Conversion to/between the color-representations The PEAR-package Image_Color will (hopefully soon) contain all needed functions to convert arbitrary color formats to the internal RGBA representation and convert different color representations. Status: Currently Image_Color already offers functions to convert color-names (e.g. "green") and hex-representations-strings (e.g. "#339900") to the PEAR-RGBA-format. We are working to get alpha- channel support added hopefully soon and will later add funtions for CYMK-conversion as well. Kapitel 20. Writing documentation This chapter provides a detailed description how to write documentation using one of the supported formats. It is aimed at both PEAR developers that are already maintaining packages in PEAR and at people who are planning to contribute a new package. The DocBook XML format DocBook is an XML dialect that is used by a wide range of projects to maintain their documentation. Examples for DocBook usage in OpenSource projects are the documentations of KDE and PHP. PEAR has opted for using DocBook, because we believe that it provides a solid foundation for the technical documentation for PEAR packages. The trade-off for using DocBook is that it is relatively hard to use. Testing documentation requires a number of tools to be installed and one needs to learn a (not very complicated) XML dialect. Once one is familiar with how DocBook works, they will enjoy writing documentation with it though. The book [DocBook: The Definitive Guide], written by Norman Walsh and Leonard Muellner and published by O'Reilly & Associates, Inc., is available online and it makes up a great resource for people interested in learning DocBook. Definitely check out the book's „DocBook Element Reference“ section. This portion provides detailed information about each element, including which elements can (and must) be used as parents and children. Required software Even if DocBook XML can (like any other XML file) be written using a normal text editor, it is optimal for users to install some software on their machine in order to test the validity of the documenting efforts. A list of the required software and a installation instruction can be found in the PHP Documentation HOWTO. Apart from providing information about the software, this HOWTO also provides a ton of other useful information that goes far beyond this chapter. One is encouraged to completely read it. (Chapter II can be skipped, because it only contains information that is very PHP specific.) Unfortunately, installing that software can be difficult under some circumstances. If you are unable to get it working, don't use that as an excuse for not writing documentation. There are two test servers that every two hours automatically download peardoc from CVS and build the manual. Any parsing errors your changes cause will show up in the logs the next time the build happens: http://www.appelsiini.net/~tuupola/php/peardoc2/peardoc.txt (time zone: EET = UTC+2, EEST = UTC+3) http://pear.php-tools.net/peardoc.log (time zone: CET = UTC+1, CEST = UTC+2) http://pear.php-tools.net/peardoc-error.log These automatic builds also give you an idea of what your changes will look like in the actual manual. This is helpful because the manual on the PEAR website is only built once per week (Sundays ~12:00 UTC). http://www.appelsiini.net/~tuupola/php/peardoc2/ http://pear.php-tools.net/peardoc/ Warnung The manual on the PEAR website is built only once per week. Any XML validation errors will cause the build to fail. If the main build fails, the old version remains in place, meaning the manual will be out of date. Therefore, always check the test build logs to ensure your changes are valid. More importantly, do not commit updates shortly before the main build happens (Sundays ~12:00 UTC). Once the necessary software is in place, one has to get the latest version of the XML sources from PEAR's CVS repository: $ cvs -d :pserver:<user>@cvs.php.net:/repository login [password] $ cvs co peardoc If you do not own an account for cvs.php.net, please choose cvsread as the username. When asked for the password, type phpfi. After that the directory ./peardoc will contain a local copy („sandbox“) of the latest sources. If you are not yet familiar with CVS, then the online book „Open Source Development with CVS“ will provide you with all the necessary information. Directory structure This chapter will not describe all the details about the directory structure, because one can find out the essentials about it by browsing the previously created directory peardoc. As a starting point for package documentors peardoc/en/package/ fits well. If one has further questions concerning the directory structure, they can ask on the documentation mailinglist. Writing documentation Instead of a long and boring description for writing documentation using DocBook, we would like to point you to a bunch of „reference documents“, from which you should be able to learn quickly: • peardoc/authoring The CVS tree has a complete set of DocBook XML templates. These files provide the standard of how PEAR documentation should look. The simplest way to utilize them is to copy them to your working directory, rename them accordingly, edit the contents to match the reality of your program and then upload them to your package's directory in the repository. • HTTP Request The documentation for HTTP_Request, which is a relatively small package, only consists of a bunch of end-user documentation, which describes all of the basic features of the package. Each feature description includes at least one example. For small packages with only a handful of methods this documentation type is absolutely enough. • XML Beautifier XML_Beautifier is a package that is also relatively compact, but which supports different configuration options. These options are described in the documentation Additionally the documentation gives usage examples and (unlike HTTP_Request) also includes API documentation for its methods. • DB DB is a large PEAR package and has excellent documentation, including usage examples. The DB docs carefully adhere to the formatting specified in peardoc/authoring. The link above goes to the DocBook source code in the CVS repository. It might be helpful to examine the HTML generated therefrom. In addition to the examples above, you will find much more documentation examples by browsing the peardoc directory, which contains your local version of the CVS tree. Especially the directory peardoc/en/packages/ should be of interest for you. You can also browse the CVS module using the web interface, including the raw XML for the file you are presently reading. Allowed characters The letters allowed inside elements are A-Z and a-z. Other characters, such as é must use entities (in this case: é). A list of the most common entities can be found at: http://www.evolt.org/article/A_Simple_Character_Entity_Chart/17/21234/ If the characters you need aren't in that list, go to http://www.oasisopen.org/docbook/xmlcharent/0.1/index.shtml and look at the other entity lists. Testing documentation Using GNU make Generating human-readable versions of the DocBook sources requires the existance of the above-mentioned software. The PEAR documentation system uses Unix style makefiles: peardoc$ autoconf peardoc$ ./configure --with-lang=en peardoc$ make html If you want to build a language other than English, change en, above, to the appropriate language code. This will generate a "raw" HTML version of the whole manual. The result will be placed in the subdirectory html/. The command make test does not generate any human-readable result, but it can be used to make sure that the XML is syntactically correct and that the build runs fine. And it is much faster than make html. Using xmllint Alternatively one can use the xmllint program that is part of the libxml2 toolkit. This is especially useful for systems where the DSSSL/make setup does not work properly. In addition to testing the well-formedness of the DocBook sources, xmllint can also check the semantical correctness with the help of RELAX NG schemas. The schema files for DocBook are available as a ZIP package from docbook.org. After unzipping the package into the directory relaxng/ inside the peardoc source folder, one can run xmllint from the root folder of the PEAR documentation as follows: xmllint --valid --noout --relaxng relaxng/ manual.xml Partial builds The build process (not the test builds, which are reasonably quick) actually takes a very long time which makes debugging and testing a very hard task. In order to increase build performance, the script make-partial.php in the root directory of the documentation module may be used. This is an interactive command line script that will enable to you to selectively include the different parts of the manual. In the following example a version of the manual is generated which only contains a certain part of the Developer's Guide and the documentation for the HTTP packages. Using these partial builds reduces the build time dramatically. peardoc$ ./make-partial.php Include about-pear? [NO] Include guide-newmaint? [NO] Include guide-developers? [NO] y Include guide.developers.intro? [NO] Include guide.developers.meaning? [NO] Include guide.developers.contributing? [NO] Include guide.developers.packagedef? [NO] Include guide.developers.release? [NO] Include guide.developers.supporting? [NO] Include guide.developers.recommendations? [NO] Include guide.developers.documentation? [NO] y Include core? [NO] Include packages? [NO] y Include package.authentication? [NO] Include package.benchmarking? [NO] Include package.caching? [NO] Include package.configuration? [NO] Include package.console? [NO] Include package.database? [NO] Include package.datetime? [NO] Include package.encryption? [NO] Include package.fileformats? [NO] Include package.filesystem? [NO] Include package.gtk? [NO] Include package.html? [NO] Include package.http? [NO] y Include package.images? [NO] Include package.internationalization? [NO] Include package.logging? [NO] Include package.mail? [NO] Include package.math? [NO] Include package.networking? [NO] Include package.numbers? [NO] Include package.payment? [NO] Include package.pear? [NO] Include package.php? [NO] Include package.science? [NO] Include package.streams? [NO] Include package.structures? [NO] Include package.system? [NO] Include package.text? [NO] Include package.tools? [NO] Include package.xml? [NO] Include package.webservices? [NO] Include pecl? [NO] CONFIG_FILES=manual.xml CONFIG_HEADERS= ./config.status creating manual.xml /usr/bin/jade -wno-idref -d html.dsl -V use-output-dir -t sgml ./phpdocxml.dcl manual.xml Translating documentation Translating documentation is another important task. Not only does new documentation need to be translated into the existing languages, additional languages are welcome. Also, existing translations need to be brought up to date because the English versions have been changed. Help on how to perform the translation process is in the Revision Tracking section of the manual. When writing the translations, please remember that letters other than A-Z and a-z need to be converted to entities. Questions? We are well aware that we cannot cover all questions about writing DocBook documentation in this chapter. If you have more questions or problems, do not hesitate to get in touch with the documentation team at [email protected]. To join the pear-doc list send an email to [email protected]. Tips for good documentation This section of the chapter does not deal with the specifics of organizing documentation in the peardoc standard, but instead with how to organize documentation logically. 1. First, every package solves a problem. What is this problem? Try to figure out what assumptions your end-users might not have about the problem (they may not realize that this is a problem that needs solving). For instance, a template package solves the problem of both separating design from code, and separating business logic from display logic. If possible, explain the problem in terms that even a novice programmer can understand. 2. Next, how does the package uniquely solve the problem? This is something that most documentation lacks. For example, there are many template engines. All of them solve the same problem, but none of them do it in the same way. A block-based template engine does not have any logic at all, whereas a template like Smarty defines a whole new template language. Some template engines compile their templates, others don't. What is unique about your package? Can someone who has never seen the code get a good idea of how it solves the problem? 3. Provide examples! Start right away with simple examples that shows the basic feature set -- they will show users how to quickly start using the package. More complex examples will help the users in understanding advanced ways of using the package. 4. If your package exposes complex interfaces or multiple constants that can't be fully explained in one or two examples (which is very likely), do not miss to explain them thoroughly in the documentation. Document any interfaces that users must use, such as a database DSN, command-line arguments for applications, configuration file contents, or any other non-code element. 5. Last, proofread your documentation. If possible, have someone else who is not as familiar with your project take a look at the documentation. They will catch assumptions that you have missed. IV. Neue Funktionen in PEAR 1.4 Inhaltsverzeichnis 21. Introduction 22. Channels 23. Custom File Roles 24. Custom File Tasks 25. Post-installation Scripts Kapitel 21. Introduction The debut of PEAR 1.4.0 is very exciting. This chapter documents all of the differences between PEAR 1.3.x and the new features introduced in PEAR 1.4. The most significant change in PEAR 1.4 is the addition of channels, a simple and effective method of distributing application development. This change has driven most of the other changes to PEAR, and in fact full application support is a major goal of this release. In addition to channels, support for customization of the install process has been seriously enhanced with the addition of three essential features for application development: • Custom file installation roles in package.xml • Custom file tasks in package.xml • Post-installation scripts Kapitel 22. Channels PEAR Channels provide a robust and effective way of distributing development. The addition of channel support to the PEAR installer as of version 1.4.0 means that it is now simpler to distribute any PHP code project using the PEAR installer than it ever was. PEAR Channels allow developers of applications to effectively depend upon packages from pear.php.net and any other source that provides a channel server. For users of these applications, this eliminates the complexity of installation and configuration. Now, all the user will need to do is to type a single pear install channel/Packagename command and go! Before PEAR 1.4.0, the only solution to depending on code from several sources is to bundle the code. This has several bad side effects, the most obvious of which is that code size increases dramatically, and makes upgrading for a minor bug fix a complicated download for the user. Channels allow an application developer to depend on packages from pear.php.net, a package from pear.example.com, and others. The user will only need to install/upgrade from a single source using the pear installer. With the current state of affairs, the pear installer is only really useful for installing, well, PEAR packages. Because of this difficulty (among others), traditionally very few packages are available as PEAR packages that can be installed with the PEAR installer. PEAR 1.4.0+ aims to eliminate this and other barriers to application development. Incomplete documentation Documentation is not yet complete channel.xml channel.xml -- The channel definition file How to describe a channel Discovery of a channel's capabilities is extremely flexible. The XSD schema defining channel.xml can be found at http://pear.php.net/dtd/channel-1.0.xsd. Channel.xml defines: 1. the channel name 2. an optional suggested user alias for the channel 3. a brief summary of the channel's purpose 4. an optional package to perform custom validation of packages on both download and packaging 5. a list of protocols supported by a channel (XML-RPC, SOAP, and REST are supported) 6. a list of mirrors and the protocols they support. Here is a sample channel.xml with all elements: <channel version="1.0" xsi:schemaLocation="http://pear.php.net/channel-1.0 http://pear.php.net/dtd/channel-1.0.xsd"> <name>pear.example.com</name> <suggestedalias>foo</suggestedalias> <summary>Example channel.xml</summary> <validatepackage version="1.3.4">Foo_Validate</validatepackage> <servers> <primary port="8080" ssl="yes"> <xmlrpc> <!-- default path is xmlrpc.php --> <function version="1.0">logintest</function> <function version="1.0">package.listLatestReleases</function> <function version="1.0">package.listAll</function> <function version="1.0">package.info</function> <function version="1.0">package.getDownloadURL</function> <function version="1.1">package.getDownloadURL</function> <function version="1.0">package.getDepDownloadURL</function> <function version="1.1">package.getDepDownloadURL</function> <function version="1.0">package.search</function> <function version="1.0">channel.listAll</function> </xmlrpc> <rest> <!-- no default path, all must be defined in baseurl --> <baseurl type="package">http://pear.example.com/rest/1.0/package</baseurl> <baseurl type="category">http://pear.example.com/rest/1.0/category</baseurl> </rest> <soap path="soapy.php"> <!-- default path is soap.php --> <function version="1.0">package.listAll</function> </soap> </primary> <mirror server="foo2.example.com/pearmirror"> <xmlrpc path="mirrorxmlrpc.php"> <!-- default path is xmlrpc.php --> <function version="1.0">package.listLatestReleases</function> <function version="1.0">package.listAll</function> <function version="1.0">package.info</function> <function version="1.0">package.getDownloadURL</function> <function version="1.1">package.getDownloadURL</function> <function version="1.0">package.getDepDownloadURL</function> <function version="1.1">package.getDepDownloadURL</function> <function version="1.0">package.search</function> </xmlrpc> <rest> <!-- no default path, all must be defined in baseurl --> <baseurl type="package">http://foo2.example.com/rest/1.0/package</baseurl> </rest> </mirror> </servers> </channel> <name> A channel's name should be the name of the server that users would browse to in order to learn more about the packages being offered. For instance, PEAR packages are located in the pear.php.net channel. PECL packages are located in the pecl.php.net channel. Note that for backwards compatibility, all existing packages based on package.xml version 1.0 are in the pear.php.net channel. The benefit that comes from using the server name as the channel name is that autodiscovery becomes a real possibility, as well as ease of locating packages increases dramatically. A channel need not be located in the document root, a channel can contain a path. This is a perfectly valid channel name: foo.example.com/path/to/pear. Note that users would have to type: $ pear install foo.example.com/path/to/pear/Packagename Unless you provide a <suggestedalias>. The channel's definition file "channel.xml" must be placed in the root channel directory. If a channel is "pear.example.com", the channel.xml must be located in "http://pear.example.com/channel.xml". If the channel is "pear.example.com/path/to/pear", then the channel.xml must be located in "http://pear.example.com/path/to/pear/channel.xml" <suggestedalias> <suggestedalias> defines a shorter, more friendly name to use when installing packages from a channel. For instance, the pear.php.net channel's suggested alias is "pear". The best aliases for a channel will be no more than 6 characters long - remember, a user must type them often when installing or upgrading, and this can be tedious for longer aliases. Rather than call this tag <alias>, as it was originally named, the tag is named <suggestedalias> in order to provide the user some latitude. If the user does not like the alias suggested by the channel owners, he or she can easily re-alias a channel through the channel-alias command. <summary> This tag provides a short description of what packages the user should expect to find on this channel. The summary is what users will see when the use the list-channels command. <validatepackage> Most channels will be satisfied with the restrictions placed upon package naming, versioning, and so on that PEAR provides by default. However, for some channels, the validation will be too strict, and others, too relaxed. The <validatepackage> tag provides the next level of customization. If omitted, the installer assumed that the PEAR_Validate class should be used. Note that a looser version validation is provided by the PEAR_Validate_PECL class, for channels like pecl.php.net that do not wish to deal with PEAR's warnings on version transgressions. <validatepackage> requires a version attribute and text content. The text content must be the name of a package that can be installed via: $ pear install channelname.example.com/Packagename-version as in: $ pear install pear.example.com/Foo_Validate-1.3.4 for the sample channel.xml at the beginning of this section. In addition, the package must provide a single class named after the package in a file using the PEAR naming conventions (all underscores "_" converted into path separators "/" so that Foo_Validate is located in Foo/Validate.php), and this class should extend PEAR_Validate. Methods beginning with "validate" like validateVersion() are intended to be overridden by validation classes for use in extending existing validation functionality. <servers>: <primary> and <mirror> Mirroring is explicitly supported in channel.xml and in the PEAR installer. Users can choose their favorite mirror via the default_channel configuration option, and channel.xml can list all the possible mirrors using the (surprise) <mirror> tag. The <primary> tag is used to define the location of protocols, and to list the protocols that are supported by the main channel server. Optional attributes can be used to modify how the PEAR installer will attempt to connect to the server. The "port" attribute can be used to define how the installer will connect to XML-RPC and SOAP services. REST services are always controlled by the individual <baseurl> tags. <xmlrpc>, <soap>, <rest> channel.xml knows about the XML-RPC, SOAP, and REST protocols for web services. However, the PEAR installer only supports XML-RPC currently, and may support REST shortly. No support for SOAP is planned for the near future. However, should it ever be implemented, channel.xml is ready. The <xmlrpc> and <soap> tags have identical formats. Both tags can contain an optional attribute "path" that tells the PEAR installer which URL to query. By default, the path is protocol.php, as in xmlrpc.php or soap.php. In other words, to access XML-RPC functions for the pear.example.com channel defined in the sample channel.xml, the installer would query https://pear.example.com:8080/xmlrpc.php for XML-RPC functions, but would query https://pear.example.com:8080/soapy.php for SOAP functions. The <rest> tag reflects the design concept behind REST: each resource is defined by a base URL in tag <baseurl> that is then used by the installer along with hyperlinks to glean the same information that XML-RPC or SOAP would provide. Required attribute "type" tells the installer what kind of information is provided by the base URL, and how to parse that information. <function> The <function> tag is quite simple. A required version attribute informs the installer what the API is, and the text content informs the installer what the name of the function is. Note that multiple functions with different versions can co-exist peacefully, as in: <function version="1.0">package.getDownloadURL</function> <function version="1.1">package.getDownloadURL</function> If a newer API is backwards-compatible, always define every possible API version in order to prevent older installer versions from giving up. Why not use a standard such as wsdl? Some of you may be asking "why create another standard for web services discovery?" The answer is simple: channel.xml does not supplant the role that WSDL has for java, or XML-RPC introspection occupies. channnel.xml is a layer on top of these technologies. The point is to quickly list the remote protocols that are supported, not to describe what they do. The PEAR installer is specialized enough that a generic listing of parameters and return values is entirely unnecessary: the installer knows exactly what xml-rpc function package.info version 1.0 requires and what it returns. Any other information simply adds wasted bandwidth and disk space. XML-RPC functions XML-RPC functions -- XML-RPC function API documentation What XML-RPC functions are available in a standard channel? A standard PEAR channel should support this list of XML-RPC functions: • logintest - a stub function • package.getDownloadURL - retrieve a URL to download a package • package.getDepDownloadURL - retrieve a URL to download a package dependency • package.info - retrieve information on a package • package.listAll - list all packages and verbose information on each package • package.listLatestReleases - list all packages and their latest release versions • package.search - search all packages for a match Channels can also implement channel.listAll, but we recommend that this only be implemented by pear.php.net and pecl.php.net channels, as the command is utilized by the update-channels command to retrieve an official list of channels. logintest The logintest xml-rpc function is called by the login command, and should return a boolean TRUE package.getDownloadURL false|struct package.getDownloadURL (struct packageinfo [, string preferred_state = stable [, (v1.1) string installed_version = false]]) false|struct packageinfo an array of format: array( ) 'channel' => channel name, 'package' => package name, ['version' => specific version to retrieve,] ['state' => specific state to retrieve,] if both version and state are set, the version index should be ignored. string preferred_state = stable The client-side preferred_state. This should be used to exclude releases that are too unstable. string installed_version = false The current installed version of the package on the client-side. This will either be a version string, or false if the package is not installed. Use this to ensure that older versions are never returned (as defined by version_compare(possible_version, installed_version, "<")). The package.getDownloadURL function should return an array with either two or three indices. • "version" => version of the release returned • "info" => the complete package.xml contents from the release "url" => a URL from which to download this release. If no releases exist that fit the constraints defined by preferred_state, installed_version, and the version/state indices of packageinfo, then do not return this index, and instead return the version and package.xml of the latest release. • The url entry should NOT append .tgz or .tar, but should be something like "http://pear.php.net/get/PEAR-1.4.0" instead of "http://pear.php.net/get/PEAR1.4.0.tgz" Note that version 1.0 of package.getDownloadURL did not have the installed_version parameter. Version 1.1 of package.getDownloadURL does - that is the only difference between the two versions. package.getDepDownloadURL false|struct package.getDepDownloadURL (string xsdversion, struct dependency, struct parentpackage [, string preferred_state = stable [, (v1.1) string installed_version = false]]) string xsdversion This should be either '1.0' or '2.0', and should match the version attribute from the top-level <package version="X.0"> tag. This should be used to determine how to process the second parameter. struct dependency if the first parameter xsdversion is '1.0', this should be an array of format: array( ) 'name' => package name 'type' => 'pkg' - anything else is an error 'rel' => 'has', 'ge', 'le', 'lt', 'le', 'not', 'ne' ['version' => specific version to retrieve,] if xsdversion is '2.0', this should be an array of format: array( ) 'name' => package name 'channel' => package channel - see notes below ['min' => minimum version (inclusive),] ['max' => maximum version (inclusive),] ['exclude' => single version to exclude (string), or array of versions to exclude,] Note that you must always verify that the channel matches your channel. If your channel server is not at pear.php.net or pecl.php.net, you must reject all xsdversion='1.0' requests, and all xsdversion='2.0' requests where the channel is not your channel. struct parentpackage This is information on the parent package, and is an array of format: array( ) 'channel' => channel name, 'package' => package name, 'version' => specific version to retrieve, string preferred_state = stable The client-side preferred_state. This should be used to exclude releases that are too unstable. string installed_version = false The current installed version of the dependency on the client-side. This will either be a version string, or false if the package is not installed. Use this to ensure that older versions are never returned (as defined by version_compare(possible_version, installed_version, "<")). Like package.getDownloadURL, package.getDepDownloadURL should return an array with either two or three indices. • "version" => version of the release returned • "info" => the complete package.xml contents from the release • "url" => a URL from which to download this release. If no releases exist that fit the constraints defined by preferred_state, installed_version, and the version/state indices of packageinfo, then do not return this index, and instead return the version and package.xml of the latest release. The url entry should NOT append .tgz or .tar, but should be something like "http://pear.php.net/get/PEAR-1.4.0" instead of "http://pear.php.net/get/PEAR1.4.0.tgz" Note that version 1.0 of package.getDepDownloadURL did not have the installed_version parameter. Version 1.1 of package.getDepDownloadURL does - that is the only difference between the two versions. package.info false|struct package.info (string package [, string field = null]) string package Package name to retrieve information about string field = null specific field to retrieve information about. If null, this should return an array with this indices, although others could be set as well: <?php array( 'name' => 'package name', 'category' => 'category name', 'license' => 'package license', 'summary' => 'package summary', 'description' => 'package description', 'releases' => array( // all releases indexed by version '0.1' => array( 'license' => 'release license', 'summary' => 'release summary', 'description' => 'release description', 'releasedate' => 'date of release', 'releasenotes' => 'release notes', 'state' => 'release stability', // the next index is optional 'deps' => array( array( // release dependencies of latest release 'type' => 'dep type from package.xml <dep>', 'relation' => 'rel from package.xml <dep>', 'version' => 'version from package.xml <dep>, or empty string', 'name' => 'name from package.xml <dep>', 'optional' => 'yes or no', ), // and so on with all deps ), ), // and so on with all releases // releases should be ordered by releasedate DESC ), ); ?> The second parameter, if set, must be one of these choices: • authors - a current list of package maintainers in format: <?php array( 'handle1' => array( 'name' => 'Maintainer Name', 'email' => '[email protected]', 'role' => 'role from package.xml (lead, developer, contributor, helper)', ), 'handle2' => array( 'name' => 'Maintainer Name 2', 'email' => '[email protected]', 'role' => 'role from package.xml (lead, developer, contributor, helper)', ), // etc. ); ?> • category - the category this package is in • description - the description of the latest release • license - package license of latest release • notes - release notes of the latest release • • releases - an array of the format documented above, containing information on all releases summary - summary from latest release package.listAll struct package.listAll ([bool released_only = true [, bool stable_only = true]]) bool released_only = TRUE If TRUE, then packages that have no releases should not be returned in the listing of available packages bool stable_only = TRUE If TRUE, then packages that have no stable releases should not be returned in the listing of available packages This function should return an array of this format for all packages that match the constraints defined above: array( array( 'name' => 'packagename', 'category' => 'category name', 'license' => 'release license', 'summary' => 'package summary', 'description' => 'package description', 'stable' => 'latest release version that matches constraints', 'unstable' => 'latest unstable release version or false if stable_only', 'state' => 'release state of latest release that matches constraints', 'deps' => array( // same format as for package.info ) ), // etc. ); package.listLatestReleases struct package.listLatestReleases ([string state = '']) string state = '' If '', then the newest release will be returned for all packages. Otherwise, it must be one of 'snapshot', 'devel', 'alpha', 'beta', or 'stable', and the function should return the newest release that is more stable than state. If state is 'beta', then the function should return the latest release that is beta or stable. If state is 'devel', the function should return the latest release that is devel, alpha, beta, or stable, and so on. This function should return an array of this format for all packages that have a release within the constraint defined by the "state" parameter: array( array( 'package' => 'packagename', 'version' => 'release version', 'state' => 'release stability', 'filesize' => 'size of the .tgz file to download', ), // etc. ); package.search struct package.listAll (string fragment [, string|bool summary = false [, bool released_only = true [, bool stable_only = true]]]) string fragment A text fragment to use when searching for packages by name string|bool summary = FALSE If set to false, this should be ignored. Otherwise, this should be used to search through the summaries of packages that match the first parameter to limit the list of returned packages. bool released_only = TRUE If TRUE, then packages that have no releases should not be returned in the listing of available packages bool stable_only = TRUE If TRUE, then packages that have no stable releases should not be returned in the listing of available packages This function should return an array of this format for all packages that match the constraints defined above: array( array( 'name' => 'packagename', 'category' => 'category name', 'license' => 'release license', 'summary' => 'package summary', 'description' => 'package description', 'stable' => 'latest release version that matches constraints', 'unstable' => 'latest unstable release version or false if stable_only', 'state' => 'release state of latest release that matches constraints', 'deps' => array( // same format as for package.info ) ), // etc. ); Kapitel 23. Custom File Roles Warnung As of PEAR version 1.4.3, the required format for custom file roles has been changed due to a minor security vulnerability. All custom file roles must now define a Role.xml file in order to properly declare a custom file role. See the example below for more information. One of the programming features that the PEAR installer enforces is the separation of files into separate categories, and the important idea that files of a similar category are always installed into the same location, or at least handled the same way, as in the case of role="src" for PECL packages. This has been quite successful for smaller library-style packages, but complete applications cannot function without customized installation locations. For instance, some files may be intended for use in a public web frontend, others for library location. PEAR 1.4 introduces the possibility of defining custom installation roles to fill this void. Using a customized role in a package.xml To use a custom installation role that another programmer has written, there are three steps that are necessary. First, the <usesrole> tag should be used to define each custom role that is used in the package.xml. Next, the role should simply be used for the files it pertains to. Finally, a dependency on the package that provides the custom role should be added to the package.xml, just for completeness. Pretty simple! Defining a customized role for use in a package.xml To define a custom role, you need to create a package containing a single file. Here is a sample package.xml that could be a custom role: <?xml version="1.0"?> <package version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>Chiarafoo</name> <channel>pear.chiaraquartet.net</channel> <summary>Chiarafoo role</summary> <description> The chiarafoo role installs files into your customized Foo directory </description> <lead> <name>Greg Beaver</name> <user>cellog</user> <email>[email protected]</email> <active>yes</active> </lead> <date>2005-03-21</date> <version> <release>1.0.0</release> <api>1.0.0</api> </version> <stability> <release>stable</release> <api>stable</api> </stability> <license uri="http://www.php.net/license">PHP License</license> <notes> Provides the chiarafoo file role </notes> <contents> <dir name="/" baseinstalldir="PEAR/Installer/Role"> <file name="Chiarafoo.xml" role="php"/> <file name="Chiarafoo.php" role="php"> <tasks:replace from="@package_version@" to="version" type="package-info"/> </file> </dir> <!-- / --> </contents> <dependencies> <required> <php> <min>4.2.0</min> </php> <pearinstaller> <min>1.4.3</min> </pearinstaller> </required> </dependencies> <phprelease/> </package> The XML file Chiarafoo.xml should be similar to this file: <role version="1.0"> <releasetypes>php</releasetypes> <installable>1</installable> <locationconfig>foo_dir</locationconfig> <honorsbaseinstall>1</honorsbaseinstall> <unusualbaseinstall /> <phpfile>1</phpfile> <executable /> <phpextension /> <config_vars> <foo_dir> <type>directory</type> <default><php_dir/><constant>DIRECTORY_SEPARATOR</constant><text>Foo</text></default> <doc>directory where foo files are installed</doc> <prompt>PHP foo directory</prompt> <group>File Locations</group> </foo_dir> </config_vars> </role> The script in Chiarafoo.php is incredibly simple: <?php /** * PEAR_Installer_Role_Chiarafoo * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to [email protected] so we can mail you a copy immediately. * * @category pear * @package Chiarafoo * @author Greg Beaver <[email protected]> * @copyright 2005 Greg Beaver * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: customroles.xml,v 1.4 2005/11/03 05:06:52 cellog Exp $ * @link http://pear.chiaraquartet.net/index.php?package=Chiarafoo * @since File available since Release 0.1.0 */ /** * @category pear * @package Chiarafoo * @author Greg Beaver <[email protected]> * @copyright 2005 Greg Beaver * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.chiaraquartet.net/index.php?package=Chiarafoo * @since Class available since Release 0.1.0 */ class PEAR_Installer_Role_Chiarafoo extends PEAR_Installer_Role_Common { /** * @param PEAR_Installer * @param PEAR_PackageFile_v2 * @param array file attributes * @param string relative path to file in package.xml */ function setup(&$installer, $pkg, $atts, $file) { // do something special with the installer } } ?> Since PEAR 1.4.3, nothing else is necessary for a successful implementation of a file role. The contents of the role's XML file must contain these tags: • <releasetypes> • <installable> • <locationconfig> • <honorsbaseinstall> • <unusualbaseinstall> • <phpfile> • <executable> • <phpextension> • (optional) <config_vars> The <releasetypes> tag This tag can only contain one of the following values: • php • extsrc • extbin In order to specify compatibility with multiple release types, use multiple <releasetypes> tags as in: <releasetypes>php</releasetypes> <releasetypes>extsrc</releasetypes> <releasetypes>extbin</releasetypes> releasetypes defines the kind of releases that this role can be used in. For instance, the "src" role is reserved for extsrc packages, and cannot be used in regular PEAR-style php releases. The "data" role can be used in any release, and would define <releasetypes> as: <releasetypes>php</releasetypes> <releasetypes>extsrc</releasetypes> <releasetypes>extbin</releasetypes> The <installable> tag This tag must be either <installable>1</installable> or empty (<installable/>) and determines whether files utilizing this custom role can be installed. Any file that should be installed must set this to 1. Only roles such as the "src" role that is processed and used to create the files that are eventually installed should set this to an empty tag. The <locationconfig> tag This tag is used for all installable files to determine which configuration variable contains the directory in which the file should be installed. For instance, the php role uses the "php_dir" locationconfig, the data role uses "data_dir". Our example role, chiarafoo, uses the "foo_dir" configuration variable, and then through the definition of <config_vars> tells the installer what foo_dir means. Note that once a custom role is installed, the user can config-set/ config-get/config-show the variable just like any other configuration variable! <config_vars> can define more than one configuration variable, but note that more than 3 variables will trigger an error, disallowing any of them, as a security precaution. The <honorsbaseinstall> tag This tag controls whether a role reacts to the "baseinstalldir" attribute of a <file> or <dir> tag. Any role that honors baseinstalldir can potentially allow conflicting files from different packages, and so a check has to be made. A file role that does not honor baseinstalldir is always installed into: Packagename/full/path/from/contents/file.ext To specify this value, use <honorsbaseinstall>1</honorsbaseinstall> For all other cases, it should be an empty tag (<honorsbaseinstall/>) The <unusualbaseinstall> tag This tag controls whether a role that would normally ignore the "baseinstalldir" attribute of a <file> or <dir> tag would honor it, but still use the Packagename/baseinstalldir/full/path/from/contents/file.ext instead of baseinstalldir/full/path/from/contents/file.ext. Any role that supports the unusual baseinstalldir type cannot conflict with other files because the package name is always the parent directory. To specify this value, use <unusualbaseinstall>1</unusualbaseinstall> For all other cases, it should be an empty tag (<unusualbaseinstall/>) The <phpfile> tag This tag should be set to 1 (<phpfile>1</phpfile>) for any roles that contain php script files. These files are analyzed at package time, possibly catching errors before release. For all other cases, it should be an empty tag (<phpfile/>) The <executable> tag This tag should be set to 1 (<executable>1</executable>) for roles like the "script" role that should have their executable attribute set via chmod() on install. For all other cases, it should be an empty tag (<executable/>) The <phpextension> tag This tag should be used for roles like the "ext" role that provide a binary PHP extension. To specify this value, use <phpextension>1</phpextension> For all other cases, it should be an empty tag (<phpextension/>) The optional <config_vars> tag This tag is used to define configuration variables that should be added to the installer by this custom file role. Note that the installer will not allow a custom file role to create more than 3 configuration variables. To define configuration variables, create tags with the name of the configuration variable, and then sub-tags defining information about the configuration variable. These tags are transformed into the PHP array format expected by the PEAR_Config class using an adapted version of Stephan Schmidt's excellent XML_Unserializer class (from the XML_Serializer package). As such, it is easiest to understand the XML format by examining existing configuration variables. array( 0: 1: 2: 3: 'password' => array( 'type' => 'password', 'default' => '', 'doc' => '(maintainers) your PEAR account password', 'prompt' => 'PEAR password (for maintainers)', 'group' => 'Maintainers', ), // Advanced 'verbose' => array( 'type' => 'integer', 'default' => PEAR_CONFIG_DEFAULT_VERBOSE, 'doc' => 'verbosity level really quiet somewhat quiet verbose debug', 'prompt' => 'Debug Log Level', 'group' => 'Advanced', ), 'preferred_state' => array( 'type' => 'set', 'default' => PEAR_CONFIG_DEFAULT_PREFERRED_STATE, ); 'doc' => 'the installer will prefer releases with this state when installing p 'valid_set' => array( 'stable', 'beta', 'alpha', 'devel', 'snapshot'), 'prompt' => 'Preferred Package State', 'group' => 'Advanced', ), These sample configuration values from the actual PEAR_Config class would translate into this XML: <config_vars> <password> <type>password</type> <default /> <doc>(maintainers) your PEAR account password'</doc> <prompt>PEAR password (for maintainers)</prompt> <group>Maintainers</group> </password> <verbose> <type>integer</type> <default><constant>PEAR_CONFIG_DEFAULT_VERBOSE</constant></default> <doc>verbosity level 0: really quiet 1: somewhat quiet 2: verbose 3: debug</doc> <prompt>Debug Log Level</prompt> <group>Advanced</group> </verbose> <preferred_state> <type>set</type> <default><constant>PEAR_CONFIG_DEFAULT_PREFERRED_STATE</constant></default> <doc>the installer will prefer releases with this state when installing packages without <valid_set>stable</valid_set> <valid_set>beta</valid_set> <valid_set>alpha</valid_set> <valid_set>devel</valid_set> <valid_set>snapshot</valid_set> <prompt>Preferred Package State</prompt> <group>Advanced</group> </preferred_state> </config_vars> Note that the simple array defining the set converts each value into a separate <valid_set> tag for the preferred_state configuration variable. The <default> tag's value can accept either a simple string, or three different kinds of tags: • • • <text> - this will be converted into a PHP string <constant> - the contents of this sub-tag will be used to retrieve the value of a pre-defined PHP constant, or a pre-defined PEAR constant (as defined in PEAR_Config or PEAR_Common) and substitute the value for the <constant> tag. any default configuration variable. These include default_channel, preferred_mirror, remote_config, auto_discover, master_server, http_proxy, php_dir, ext_dir, doc_dir, bin_dir, data_dir, test_dir, cache_dir, php_bin, username, password, verbose, preferred_state, umask, cache_ttl, sig_type, sig_bin, sig_keyid, and sig_keydir. when used, the configuration variable should simply be an empty tag like <php_dir/>. The tag will be replaced with the default value of the configuration variable, not the currently assigned value. For instance, this example default value: <default><text0>hi there </text0><constant>PHP_OS</constant><text1> user, your default php might convert into something like "hi there Linux user, your default php_dir is /usr/local/lib/php/pear". Our example Chiarafoo role's foo_dir default value: <default><php_dir/><constant>DIRECTORY_SEPARATOR</constant><text>Foo</text></default> might convert into something like "/usr/local/lib/php/Foo" or "C:\php5\pear\Foo". Note that in order to use multiple <constant> or <text> tags, you must append a numbered suffix as in the <text0> <text1> example above. Only one PEAR configuration variable may be used per default value. Note that if you use <type>integer</type>, no matter what default value is specified, it will be casted into an integer by PEAR_Config. Kapitel 24. Custom File Tasks For many small library packages, very little customization is needed. Just install and go. package.xml 1.0 is very good at this task. As packages grow in size and complexity, it is often necessary to make slight changes to the contents of files, and occasionally to external components such as databases. package.xml 1.0 provides a single undocumented system of customizing file contents through the <replace> tag, like so: <file name="blah.php" role="php"> <replace from="@token@" to="version" type="package-info"/> <replace from="@anothertoken@" to="php_dir" type="pear-config"/> </file> This example above would scan the blah.php file at installation, and then use str_replace() to replace all occurences of the string @token@ with the package's version number. Then, it would replace all occurences of the string @anothertoken@ with the value of the user's php_dir configuration variable. Although powerful, the replace tag is the only customization tag available in package.xml version 1.0. When developing package.xml version 2.0, the replace tag and innovative work of other projects such as Phing became the inspiration for an expanded kind customization called a "task". Tasks are defined by xml children of a <file> tag. Tasks are implemented by extending the PEAR_Task_Common task. Using a customized task in a package.xml Tasks are defined in package.xml through the tasks namespace, which is currently http://pear.php.net/dtd/tasks-1.0. The current tasks namespace is defined by http://pear.php.net/dtd/tasks-1.0.xsd. Custom tasks bundled with PEAR include: • <tasks:replace> • <tasks:unixeol> • <tasks:windowseol> • <tasks:postinstallscript> The xml for each of these tasks is documented here. Creating customized tasks in PHP Creating a custom task involves creating a class that validates xml, and performs the task when called upon. Tasks can be invoked in two situations: at package-time and at installtime. Each task can control whether it should be called at package-time, install-time, or at both times. There are two kinds of tasks: simple and multiple. Most tasks are simple tasks. Simple tasks are self-contained: all customization is limited to that file. Multiple tasks are collected during installation and processed fully as a unit after files have been committed to disk, allowing more complex processing. All simple tasks must define 3 methods, all multiple task must define 4 methods. These are: • validateXml() • init() • startSession() • run() (multiple tasks only) validateXml() true|array validateXml (PEAR_PackageFile_v2 $pkg, string|array $xml, PEAR_Config &$config, array $fileAttributes) This method is called upon package.xml validation and should be used to validate the task's xml content. Upon error, a simple array of format array(CODE, message) must be returned. The code must be one of the following constants, as defined in PEAR/Task/Common.php: • • • • PEAR_TASK_ERROR_NOATTRIBS - Attributes were expected, but none were present. PEAR_TASK_ERROR_MISSING_ATTRIB - A specific attribute is not present. PEAR_TASK_ERROR_WRONG_ATTRIB_VALUE - The value of an attribute is incorrect. PEAR_TASK_ERROR_INVALID - Any other error in validation. The error message should include the file name as defined by $fileAttributes['name'], and include as much useful information about the location of the validation error as possible. PEAR_PackageFile_v2 $pkg This is the package.xml object that contains the task. string|array $xml The raw parsed content of the task's xml as parsed from package.xml. Tags like <tasks:windowseol> that have no attributes or child elements will be passed an empty string ''. Otherwise, simple text content will be a string, and nested tags/attributes will be passed in as an array. Here is a list of sample xml and their parsed values: • <tasks:blah/> string(""); • <tasks:blah>hello </tasks:blah> string("hello"); • <tasks:blah>hello <tasks:boo/> </tasks:blah> array('_content' => 'hello', 'tasks:boo' => string('')) • <tasks:blah foo="one"> <tasks:boo/> </tasks:blah> array('attribs' => array('foo' => 'one'), 'tasks:boo' => string('')) PEAR_Config $config This is the current configuration object array $fileAttributes The parsed attributes of the <file> tag that encloses this tag. This is guaranteed to contain indices name, specifying the file name, and role, specifying the file role. Other attributes like baseinstalldir may be present but are not required, and so will not be guaranteed to be present for every file. init() void init (string|array $xml, array $fileAttributes, string|null $lastVersion) The init() function is called immediately prior to the startSession() method, and should be used for initialization that is not directly related to file modification. This method may move to another location in the installation process at any time. The logical separation of initialization from task action is important and the order of execution can be depended upon. string|array $xml The raw parsed content of the task's xml as parsed from package.xml. Tags like <tasks:windowseol> that have no attributes or child elements will be passed an empty string ''. Otherwise, simple text content will be a string, and nested tags/attributes will be passed in as an array. Here is a list of sample xml and their parsed values: • <tasks:blah/> string(""); • <tasks:blah>hello </tasks:blah> string("hello"); • <tasks:blah>hello <tasks:boo/> </tasks:blah> array('_content' => 'hello', 'tasks:boo' => string('')) • <tasks:blah foo="one"> <tasks:boo/> </tasks:blah> array('attribs' => array('foo' => 'one'), 'tasks:boo' => string('')) array $fileAttributes The parsed attributes of the <file> tag that encloses this tag. This is guaranteed to contain indices name, specifying the file name, and role, specifying the file role. Other attributes like baseinstalldir may be present but are not required, and so will not be guaranteed to be present for every file. string|null $lastVersion This will be set to the string representing the version of the last installed version of this package. This is useful for determining whether the package is being upgraded or is a fresh installation. If the package is being installed for the first time, NULL will be passed in. startSession() string|false|PEAR_Error startSession (string $contents, string $dest) For non-script tasks, startSession() is called to actually execute a task. The task should perform all needed operations on the file contents, and on success return the file contents regardless of any modification. These contents will be written to disk, so it is imperative that they be the full, original file contents if no modification is made to them. For script tasks, startSession() is called to determine whether the script can be safely executed. For both task types, script and non-script, a return value of FALSE will cause the task to be silently skipped. A return value of a PEAR_Error will cause processing of all operations to stop, and an error message to be displayed by the installer prior to exiting. Any other return value will cause the script to be processed normally by the frontend as a post-installation script. string $contents The original contents of the file whose <file> tag in package.xml contains the task tag. string $dest The full path to the final installed file location. This is strictly informational, as the file does not yet exist, and should only be used for error messages or other processing that does not attempt to modify the file. run() false|string run (array $tasks) The run() method should return FALSE on success, and an error message if there is a problem. This method is called only for tasks that define $this->type as multiple. For each task within package.xml that has this task, the run() method will be called with an array containing all of the task objects from the package.xml. array $tasks An array of task objects. Kapitel 25. Post-installation Scripts Incomplete documentation Documentation is not yet complete The XML format for defining a post-install script in package.xml is documented here. This document describes the required elements for the PHP post-install script itself. Naming requirements for a post-install script PHP file Post-install script files can be named anything one desires, but the class within the file must be the same name as the file with all path separators replaced by underscores. In other words, this postinstall script: Path/To/Script.php Must contain a class named Path_To_Script. Due to casing differences between operating systems, it is recommended to always use lowercased file names. Structure of a post-install script The post-install script class must contain two methods, one named init(), and the other named run(). The init() method is called at the same time as all other post-install scripts. The run() method is called at the conclusion of each parameter group in order to process the user's responses to queries. The init() method void init (PEAR_Config $config, PEAR_PackageFile_v2 $self, string|null $lastInstalledVersion) PEAR_Config $xml The current configuration used for installation. PEAR_PackageFile_v2 $self The package.xml contents as abstracted by this object. string|NULL $lastInstalledVersion The last version of this package that was installed. This is a very important parameter, as it is the only way to determine whether a package is being installed from scratch, or upgraded from a previous version. Using this parameter, it is possible to determine what incremental changes, if any, need to be performed. The run() method bool run (array $infoArray, string $paramGroupId) array $infoArray if $paramGroupId is _undoOnError, then $infoArray will contain a list of successfully completed parameter group sections. This can be used to restore any system changes made by the installation script. Otherwise, $infoArray contains the results of the user input from the most recent <paramgroup> section. string $paramGroupId This variable either contains _undoOnError or the contents of the most recent <paramgroup>'s <id> tag. Note that paramgroup id cannot begin with an underscore (_), and so _undoOnError can only be triggered by the PEAR installer. V. Core-Bestandteile Inhaltsverzeichnis 26. PEAR base classes 27. PEAR Installer classes Kapitel 26. PEAR base classes The Core section provides information about the base classes in PEAR PEAR Inhaltsverzeichnis Introduction -- How to handle the PEAR base class (destructors, error handling) Constants -- Predefined Constants PEAR::PEAR() -- constructor (bezogen auf Package-Entwickler) PEAR::_PEAR() -- Deconstructor (bezogen auf Package-Entwickler) PEAR::getStaticProperty() -- handle static properties (bezogen auf Package-Entwickler) PEAR::registerShutdownFunc() -- set a shutdown function for static classes (bezogen auf Package-Entwickler) PEAR::isError() -- checks for a PEAR_Error object PEAR::raiseError() -- Create a new PEAR_Error object and optionally specify errorhandling instructions PEAR::setErrorHandling() -- sets handling of errors generated through PEAR packages PEAR::expectError() -- add an error code for non-disabling temporary error handling PEAR::popExpect() -- removes the last error code for non-disabling temporary error handling PEAR::loadExtension() -- OS independant PHP extension load PEAR provides functions for handling errors and sets the behavoir in case of error. And, it gives package developers a set of functions to make their lives easier. Introduction Introduction -- How to handle the PEAR base class (destructors, error handling) Synopsis require_once "PEAR.php"; class classname extends PEAR { ... } Description The PEAR base class provides standard functionality that is used by most PEAR classes. Normally you never make an instance of the PEAR class directly, you use it by subclassing it. Its key features are: • request-shutdown object "destructors" • error handling PEAR "destructors" If you inherit PEAR in a class called ClassName, you can define a method in it called _ClassName (the class name with an underscore prepended) that will be invoked when the request is over. This is not a destructor in the sense that you can "delete" an object and have the destructor called, but in the sense that PHP gives you a callback in the object when PHP is done executing. See the example below. Important! In order for destructors to work properly, you must instantiate your class with the "=& new" operator like this: $obj =& new MyClass(); If you only use "= new", the object registered in PEAR's shutdown list will be a copy of the object at the time the constructor is called, and it will be this copy's "destructor" that will be called upon request shutdown. PEAR Error Handling PEAR's base class also provides a way of passing around more complex errors than a true/false value or a numeric code. A PEAR error is an object that is either an instance of the class PEAR_Error, or some class inheriting PEAR_Error. One of the design criteria of PEAR's errors is that it should not force a particular type of output on the user, it should be possible to handle errors without any output at all if that is desirable. This makes it possible to handle errors gracefully, also when your output format is different from HTML (for example WML or some other XML format). The error object can be configured to do a number of things when it is created, such as printing an error message, printing the message and exiting, raising an error with PHP's trigger_error() function, invoke a callback, or none of the above. This is typically specified in PEAR_Error's constructor, but all of the parameters are optional, and you can set up defaults for errors generated from each object based on the PEAR class. See the PEAR error examples for how to use it and the PEAR_Error reference for the full details. Examples The example below shows how to use the PEAR's "poor man's kinda emulated destructors" to implement a simple class that holds the contents of a file, lets you append data to the object and flushes the data back to the file at the end of the request: Beispiel 26-1. PEAR: emulated destructors require_once "PEAR.php"; class FileContainer extends PEAR { var $file = ''; var $contents = ''; var $modified = 0; function FileContainer($file) { $this->PEAR(); // this calls the parent class constructor $fp = fopen($file, "r"); if (!is_resource($fp)) { return; } $this->file = $file; while ($data = fread($fp, 2048)) { $this->contents .= $data; } fclose($fp); } function append($str) { $this->contents .= $str; $this->modified++; } // The "destructor" is named like the constructor // but with an underscore in front. function _FileContainer() { if ($this->modified) { $fp = fopen($this->file, "w"); if (!is_resource($fp)) { return; } fwrite($fp, $this->contents); fclose($fp); } } } $fileobj =& new FileContainer("testfile"); $fileobj->append("this ends up at the end of the file\n"); // When the request is done and PHP shuts down, $fileobj's // "destructor" is called and updates the file on disk. Anmerkung: PEAR "destructors" use PHP's shutdown callbacks (register_shutdown_function()), and in PHP < 4.1, you can't output anything from these when PHP is running in a web server. So anything printed in a "destructor" gets lost except when PHP is used in command-line mode. In PHP 4.1 and higher, output can be also generated in the destructor. Also, see the warning about how to instantiate objects if you want to use the destructor. The next examples illustrate different ways of using PEAR's error handling mechanism. Beispiel 26-2. PEAR error example (1) function mysockopen($host = "localhost", $port = 8090) { $fp = fsockopen($host, $port, $errno, $errstr); if (!is_resource($fp)) { return new PEAR_Error($errstr, $errno); } return $fp; } $sock = mysockopen(); if (PEAR::isError($sock)) { print "mysockopen error: ".$sock->getMessage()."\n"; } This example shows a wrapper to fsockopen() that delivers the error code and message (if any) returned by fsockopen in a PEAR error object. Notice that PEAR::isError() is used to detect whether a value is a PEAR error. PEAR_Error's mode of operation in this example is simply returning the error object and leaving the rest to the user (programmer). This is the default error mode. In the next example we're showing how to use default error modes: Beispiel 26-3. PEAR error example (2) class TCP_Socket extends PEAR { var $sock; function TCP_Socket() { $this->PEAR(); } function connect($host, $port) { $sock = fsockopen($host, $port, $errno, $errstr); if (!is_resource($sock)) { return $this->raiseError($errstr, $errno); } } } $sock = new TCP_Socket; $sock->setErrorHandling(PEAR_ERROR_DIE); $sock->connect('localhost', 8090); print "still alive\n"; Here, we set the default error mode to PEAR_ERROR_DIE, and since we don't specify any error mode in the raiseError call (that'd be the third parameter), raiseError uses the default error mode and exits if fsockopen fails. Global Variables Used The PEAR class uses some global variables to register global defaults, and an object list used by the "destructors". All of the global variables associated with the PEAR class have a _PEAR_ name prefix. $_PEAR_default_error_mode If no default error mode is set in an object, this mode will be used. Must be one of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE or PEAR_ERROR_CALLBACK. Don't set this variable directly, call PEAR::setErrorHandling() as a static method like this: PEAR::setErrorHandling(PEAR_ERROR_DIE); $_PEAR_default_error_options If the error mode is PEAR_ERROR_TRIGGER, this is the error level (one of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). Don't set this variable directly, call PEAR::setErrorHandling() as a static method like this: PEAR::setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_ERROR); $_PEAR_default_error_callback If no options parameter is used when an error is raised and the error mode is PEAR_ERROR_CALLBACK, the value of this variable is used as the callback. This means that you can switch the error mode temporarily and return to callback mode without specifying the callback function again. A string value represents a function, a twoelement array with an object at index 0 and a string at index 1 represents a method. Again, don't set this variable directly, call PEAR::setErrorHandling() as a static method like this: PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "my_error_handler"); Here is an example of how you can switch back and forth without specifying the callback function again: PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "my_function_handler"); do_some_stuff(); PEAR::setErrorHandling(PEAR_ERROR_DIE); do_some_critical_stuff(); PEAR::setErrorHandling(PEAR_ERROR_CALLBACK); // now we're back to using my_function_handler again Constants Constants -- Predefined Constants PEAR_ERROR_CALLBACK PEAR error handling related. See PEAR_Error, setErrorHandling() PEAR_ERROR_DIE PEAR error handling related. See PEAR_Error, setErrorHandling() PEAR_ERROR_PRINT PEAR error handling related. See PEAR_Error, setErrorHandling() PEAR_ERROR_RETURN PEAR error handling related. See PEAR_Error, setErrorHandling() PEAR_ERROR_TRIGGER PEAR error handling related. See PEAR_Error, setErrorHandling() PEAR::PEAR() PEAR::PEAR() -- constructor (bezogen auf Package-Entwickler) Synopsis require_once 'PEAR.php'; void PEAR::PEAR (string [$errorClass = PEAR_Error]) Beschreibung If you want to use the deconstructor functionality provide by PEAR, you have to call $this->PEAR() in the constructor of your class. Parameter • string $errorClass - the name of the error class to use. Hinweise Diese Methode kann statisch aufgerufen werden. PEAR::_PEAR() PEAR::_PEAR() -- Deconstructor (bezogen auf Package-Entwickler) Synopsis require_once 'PEAR.php'; void PEAR::_PEAR () Beschreibung Does nothing right now, but is included for forward compatibility, so subclass destructors should always call it. PEAR::getStaticProperty() PEAR::getStaticProperty() -- handle static properties (bezogen auf Package-Entwickler) Synopsis require_once 'PEAR.php'; mixed &PEAR::getStaticProperty (string $class, string $var) Beschreibung If you have a class that's mostly/entirely static, and you need static properties, you can use this method to simulate them. Eg. in your method(s) do this: $myVar = &PEAR::getStaticProperty('myVar'); You must use a reference, or they will not persist! Parameter • string $class - the name of your class, where you call getStaticProperty() • string $var the variable to retrieve. Rückgabewert mixed - A reference to the variable. If not set, it will be auto initialised to NULL. Beispiel Beispiel 26-1. Using getStaticProperty() <?php require_once 'PEAR.php'; class myClass { function setValue( $set) { $foo = &PEAR::getStaticProperty('myClass', "foo"); $foo = $set; } function view() { print PEAR::getStaticProperty('myClass', "foo"); } } myClass::setValue('value = foo'); myClass::view(); ?> This would print value = foo PEAR::registerShutdownFunc() PEAR::registerShutdownFunc() -- set a shutdown function for static classes (bezogen auf Package-Entwickler) Synopsis require_once 'PEAR.php'; void PEAR::registerShutdownFunc (array $func [, array $var = array()]) Beschreibung The indicated function is called, before the PHP interpreter will be finished. Parameter • • array $func - the name of the class and of the function to ccore. array $var - possible required function parameters. The parameters are handed over to the function in accordance with their succession of the array. Beispiel Beispiel 26-1. Using registerShutdownFunc() <?php require_once 'PEAR.php'; class myClass { function myClass() { PEAR::registerShutdownFunc(array('myClass', 'shutdown'), array('param1', 'param2')); } function shutdown( $param1, $param2) { // do something before we will die } } ?> PEAR::isError() PEAR::isError() -- checks for a PEAR_Error object Synopsis require_once 'PEAR.php'; boolean PEAR::isError (mixed $data [, mixed $msgcode]) Beschreibung isError() examines whether a variable is a PEAR_Error object and - optional - contains a specific error message or code. Parameter mixed $data variable to check mixed $msgcode additional error message or error code to check Rückgabewert mixed - returns TRUE, if the variable was a PEAR_Error and, if given, contains $msgcode PEAR::raiseError() PEAR::raiseError() -- Create a new PEAR_Error object and optionally specify errorhandling instructions Synopsis require_once 'PEAR.php'; PEAR_Error PEAR::raiseError (mixed $message [, int $code [, int $mode [, int|array $options [, mixed $userinfo [, string $error_class [, boolean $skipmsg]]]]]]) Beschreibung raiseError() Parameter string $message Error message string or PEAR_Error object. The default message is unknown error if left blank. integer $code Error code. It is recommended to use an error code for even the simplest errors, in order to simplify error handling and processing. integer $mode Error mode. This is one of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, PEAR_ERROR_CALLBACK, or PEAR_ERROR_EXCEPTION. See setErrorHandling() for detailed information and examples of the meaning of these constants. mixed $options Error options. This depends on the value of $mode, and is documented in setErrorHandling(). mixed $userinfo Optional user information. This can be used to store any error-specific information, and has an unspecified format. string $error_class Error class name to use as the error object. The default error class is PEAR_Error. Use this parameter to specify another class to use, such as a custom class extending PEAR_Error boolean $skipmsg Use this parameter if you are using a custom class that does not accept an error message in its constructor. Never use this parameter without the $error_class parameter - it will not work. Rückgabewert A PEAR_Error object is returned, unless PEAR_ERROR_DIE terminates execution or a PEAR_ERROR_EXCEPTION is never handled. PEAR::setErrorHandling() PEAR::setErrorHandling() -- sets handling of errors generated through PEAR packages Synopsis require_once 'PEAR.php'; void PEAR::setErrorHandling ([integer $mode = NULL [, mixed $options = NULL]]) Beschreibung setErrorHandling() can be invoked as both a standard object method ($obj>setErrorHandling) and as a static method (PEAR::setErrorHandling). If called statically, PEAR::setErrorHandling() sets the default error handling behaviour for all PEAR objects (global error handling behaviour). If called as an object method, $obj->setErrorHandling() sets the default error handling for only that object (local error handling behaviour). Parameter • integer $mode - one of the following constants • • • PEAR_ERROR_RETURN If an error occurs, a PEAR_Error is returned from the error-generation method (normally raiseError().) PEAR_ERROR_PRINT Like PEAR_ERROR_RETURN, but an error message will be printed additionally. PEAR_ERROR_TRIGGER Like PEAR_ERROR_RETURN, but the PHP builtinfunction trigger_error() will be called in PEAR_Error's constructor with the error message. • • • • PEAR_ERROR_DIE The script will terminate and an error message will be printed on instantiation of a PEAR_Error. PEAR_ERROR_CALLBACK If a error occurs, the callback passed to $options is called. PEAR_ERROR_EXCEPTION If Zend Engine 2 is present, then an exception will be thrown using the PEAR_Error object. mixed $options - the value for $options depends on $mode • • • PEAR_ERROR_PRINT and PEAR_ERROR_DIE support an optional printf() format string used when printing the error message. This format string should contain a single %s, which will be used to insert the error message into the string. Use the string to enclose the error message with other useful information not included in the error message prefix or error message. PEAR_ERROR_TRIGGER requires an user error level constant used by trigger_error() (possible constants: E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). Note that if the error constant is not one of these valid error constants, a PHP warning will be triggered. PEAR_ERROR_CALLBACK The callback must be a function name in the format described in the Pseudo-Type section of the PHP manual (either a string, or an array). The callback must accept a single parameter, the PEAR_Error object generated by an error condition. Note that if the callback is not a valid callback, a PHP warning will be triggered. Here's an example of a few ways to use setErrorHandling: <?php require_once 'PEAR.php'; // dummy error constant for this example define('MYCLASS_ERROR_CODE', 1); // demonstration of default global error handling // in this case, all PEAR Errors will trigger a PHP warning PEAR::setErrorHandling(PEAR_ERROR_TRIGGER, E_USER_WARNING); // Note that the file and line number will be in the constructor of PEAR_Error // in PEAR.php PEAR::raiseError('test warning', MYCLASS_ERROR_CODE); // this error specifies a mode, and overrides the default global error handling $e = PEAR::raiseError('return only', MYCLASS_ERROR_CODE, PEAR_ERROR_RETURN); PEAR::setErrorHandling(PEAR_ERROR_PRINT, "Gronk error: %s<br />\n"); // prints "Gronk error: test warning<br />\n" PEAR::raiseError('test warning', MYCLASS_ERROR_CODE); /** * Fake class to demonstrate error handling * @package myClass */ class myClass extends PEAR { /** * Demonstration of default local error handling */ function myClass() { // object method callback $this->setErrorHandling(PEAR_ERROR_CALLBACK, array(&$this, 'handleErr')); // prints "custom handler...is working" PEAR::raiseError('custom handler', MYCLASS_ERROR_CODE); // static class method callback $this->setErrorHandling(PEAR_ERROR_CALLBACK, array('myClass', 'handleErrStatic')); PEAR::raiseError('custom handler', MYCLASS_ERROR_CODE); // function callback $this->setErrorHandling(PEAR_ERROR_CALLBACK, 'standardCallback'); PEAR::raiseError('custom handler', MYCLASS_ERROR_CODE); } /** * Callback set by the constructor * @param PEAR_Error The error object */ function handleErr($error) { $this->lastError = $error->getMessage(); print $error->getMessage() . "...is working\n"; } /** * Static callback set by the constructor * * Note that in PHP 5, $this is not set if the method is declared with * the "static" access modifier. In PHP 4, $this is set, but is not * set to the myClass object, so don't use it! * @param PEAR_Error The error object * @static */ function handleErrStatic($error) { print 'static ' . $error->getMessage() . "...is working\n"; } } /** * @param PEAR_Error The error object */ function standardCallback($error) { print 'normal function callback: ' . $error->getMessage(); } // This causes the printing of three messages through error callbacks: // "custom handler...is working" // "static custom handler... is working" // "normal function callback: custom handler" $mine = new myClass; PEAR::setErrorHandling(PEAR_ERROR_DIE); // terminates the script with the error message "oops" PEAR::raiseError('oops', MYCLASS_ERROR_CODE); ?> PEAR::expectError() PEAR::expectError() -- add an error code for non-disabling temporary error handling Synopsis require_once 'PEAR.php'; integer PEAR::expectError ([mixed $errorCode = '*']) Beschreibung This method is used to tell which errors you expect to get. Expected errors are always returned with error mode PEAR_ERROR_RETURN. Expected error codes are stored in a stack, and this method pushes a new element onto it. The list of expected errors are in effect until they are popped off the stack with the popExpect() method. Parameter • mixed $errorCode - the expected PEAR_Error error code or an array of error codes. If set to '*' every error is expected. Rückgabewert integer - the size of the error code stack. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Siehe auch popExpect() PEAR::popExpect() PEAR::popExpect() -- removes the last error code for non-disabling temporary error handling Synopsis require_once 'PEAR.php'; mixed PEAR::popExpect () Beschreibung This method pops one element off the expected error codes stack. Rückgabewert mixed - the removed error code or array of error codes Hinweise Diese Methode kann nicht statisch aufgerufen werden. Siehe auch expectError() PEAR::loadExtension() PEAR::loadExtension() -- OS independant PHP extension load Synopsis require_once 'PEAR.php'; boolean PEAR::loadExtension (string $ext) Beschreibung Loads an extension by name Parameter string $ext The case-sensitive name of the PHP extension without filename suffix or php_ prefix. Rückgabewert boolean - returns TRUE, if extension could be loaded Hinweise Diese Methode kann statisch aufgerufen werden. Beispiel Beispiel 26-1. Loading the domxml-extension if(!PEAR::loadExtension("domxml")) { echo 'Could not load DomXML-Extension!'; exit(); } PEAR_Error Inhaltsverzeichnis PEAR_Error::addUserInfo() -- add user information PEAR_Error::getCallback() -- get callback function name PEAR_Error::getCode() -- get error code PEAR_Error::getMessage() -- get error message PEAR_Error::getMode() -- get error mode PEAR_Error::getDebugInfo() -- get debug information PEAR_Error::getType() -- get error type PEAR_Error::getUserInfo() -- get additional user-supplied information PEAR_Error::PEAR_Error() -- constructor PEAR_Error::toString() -- make string representation PEAR_Error is an object created by every function in PEAR in case of a failure. It provides information on why a function fails. How you get the object depends on PEAR::SetErrorHandling() PEAR_Error::addUserInfo() PEAR_Error::addUserInfo() -- add user information Synopsis require_once 'PEAR.php'; void PEAR_Error::addUserInfo (string $info) Beschreibung Adds an user information to the error object. Parameter • string - user info Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getCallback() PEAR_Error::getCallback() -- get callback function name Synopsis require_once 'PEAR.php'; string PEAR_Error::getCallback () Beschreibung Returns the name of the function called in case of throwing a PEAR_Error object. Rückgabewert string - function name Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getCode() PEAR_Error::getCode() -- get error code Synopsis require_once 'PEAR.php'; integer PEAR_Error::getCode () Beschreibung Returns the error code coming with the error object. Rückgabewert integer - error number Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getMessage() PEAR_Error::getMessage() -- get error message Synopsis require_once 'PEAR.php'; string PEAR_Error::getMessage () Beschreibung Returns the error message coming with the error object. Rückgabewert string - error message Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getMode() PEAR_Error::getMode() -- get error mode Synopsis require_once 'PEAR.php'; integer PEAR_Error::getMode () Beschreibung Returns the error mode used for throwing the error object. Rückgabewert integer - error mode Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getDebugInfo() PEAR_Error::getDebugInfo() -- get debug information Synopsis require_once 'PEAR.php'; string PEAR_Error::getDebugInfo () Beschreibung Returns debug information about an error Rückgabewert string - error debug information Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getType() PEAR_Error::getType() -- get error type Synopsis require_once 'PEAR.php'; integer PEAR_Error::getType () Beschreibung Returns the name of the error class of the object. Rückgabewert string - error class name Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::getUserInfo() PEAR_Error::getUserInfo() -- get additional user-supplied information Synopsis require_once 'PEAR.php'; string PEAR_Error::getUserInfo () Beschreibung Returns additional information about an error Rückgabewert string - error information Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Error::PEAR_Error() PEAR_Error::PEAR_Error() -- constructor Synopsis require_once 'PEAR.php'; void PEAR_Error::PEAR_Error (string [$message = 'unknown error'], integer [$code = NULL], integer [$mode = NULL], mixed [$options = NULL], string [$userinfo = NULL]) Beschreibung Constructor Parameter • string $message - the error message. A brief description of the occured failure or problem. • string $code - the error code. An error specific number. • integer $mode - the error mode • mixed $options - error mode specific options • string $userinfo - a string for additional user or debug info Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Error::toString() PEAR_Error::toString() -- make string representation Synopsis require_once 'PEAR.php'; string PEAR_Error::toString () Beschreibung Makes a string representation of the error object. Rückgabewert string - object representation Hinweise Diese Methode kann nicht statisch aufgerufen werden. Intelligent Error Handling with PEAR_ErrorStack Inhaltsverzeichnis Introduction to using PEAR_ErrorStack for advanced error handling -- Using PEAR_ErrorStack to do both simple and advanced error handling constructor PEAR_ErrorStack::PEAR_ErrorStack() -- Set up a new error stack instance PEAR_ErrorStack::getErrorMessage() -- Standard error message generation callback PEAR_ErrorStack::getErrorMessageTemplate() -- Standard Error Message Template generator from error code PEAR_ErrorStack::getErrors() -- Retrieve all errors since last purge PEAR_ErrorStack::getFileLine() -- Standard file/line number/function/class context callback PEAR_ErrorStack::getMessageCallback() -- Get an error code => error message mapping callback PEAR_ErrorStack::hasErrors() -- Determine whether there are any errors on the stack PEAR_ErrorStack::pop() -- Pop an error off of the error stack PEAR_ErrorStack::popCallback() -- Remove a callback from the error callback stack PEAR_ErrorStack::push() -- Add an error to the stack PEAR_ErrorStack::pushCallback() -- Set an error Callback If set to a valid callback, this will be called every time an error is pushed onto the stack. The return value will be used to determine whether to allow an error to be pushed or logged. PEAR_ErrorStack::raiseError() -- emulate PEAR::raiseError() PEAR_ErrorStack::setContextCallback() -- Set a callback that generates context information (location of error) for an error stack PEAR_ErrorStack::setDefaultCallback() -- Sets a default callback to be used by all error stacks PEAR_ErrorStack::setDefaultLogger() -- Set up a PEAR::Log object for all error stacks that don't have one PEAR_ErrorStack::setErrorMessageTemplate() -- Set the Error Message Template array PEAR_ErrorStack::setLogger() -- Set up a PEAR::Log object for this error stack PEAR_ErrorStack::setMessageCallback() -- Set an error code => error message mapping callback PEAR_ErrorStack::singleton() -- Return a single error stack for this package. PEAR_ErrorStack::staticGetErrors() -- Get a list of all errors since last purge, organized by package PEAR_ErrorStack::staticHasErrors() -- Determine whether there are any errors on any error stack PEAR_ErrorStack::staticPopCallback() -- Remove a callback from every error callback stack PEAR_ErrorStack::staticPush() -- Static version of push() PEAR_ErrorStack::staticPushCallback() -- Set an error Callback for every package's error stack PEAR_ErrorStack::_log() -- Log an error using PEAR::Log Package PEAR_ErrorStack Constants -- Constants defined in and used by PEAR_ErrorStack PEAR_ErrorStack is an experimental error raising and handling implementation for PEAR that is designed to replace PEAR_Error when it has stabilized. PEAR_ErrorStack is both backwards compatible with PEAR_Error and forward compatible with PHP 5's Exception class. There are many other features, all described in the Introduction. Usage: 1 2 3 4 // global error stack $global_stack = &PEAR_ErrorStack::singleton('MyPackage'); // local error stack $local_stack = new PEAR_ErrorStack('MyPackage'); Introduction to using PEAR_ErrorStack for advanced error handling Introduction to using PEAR_ErrorStack for advanced error handling -- Using PEAR_ErrorStack to do both simple and advanced error handling Synopsis Introduction to the usage of PEAR_ErrorStack Introduction This class is available as part of the PEAR package. Features include: • Fully unit-tested and documented • blazingly fast - blows PEAR_Error out of the water • Package-specific errors • Error levels (notice/warning/error/exception) • Error context data is saved separate from error message • Error cascading - parent errors can be specified • • Dynamic error message generation allows generation of multiple and distinct error messages from the same error object Sophisticated callbacks are available for error message generation, error context generation, and error handling functionality, see Error Context Display, Custom Error Message Generation, and controlling error generation PEAR_ErrorStack implements error raising and handling using a stack pattern. This has tremendous advantages over the PEAR_Error Implementation. PEAR_Error centralizes all error creation and handling in the constructor of the PEAR_Error object. Once an object has been created, all handling must have been completed, either through checking the return value of a method, or through a single global callback. In addition, it is nearly impossible to determine the source of an error, and the baggage of all of the PEAR base class's bulky, slow methods accompanies every error creation. <?php // traditional PEAR_Error usage require_once 'PEAR.php'; class myobj { // there is no way to know where $err comes from function errorCallback($err) { $this->display($err->getMessage()); $this->log($err->getMessage()); } function log($msg) { error_log($msg, 3, 'somefile.log') } } function display($msg) { echo $msg . '<br />'; } $myobj = new myobj; // using a callback PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array(&$myobj, 'errorCallback')); $ret = SomePackage::doSomething(); if (PEAR::isError($ret)) { // do some handling - this error is also displayed and logged } PEAR::pushErrorHandling(PEAR_ERROR_RETURN); $ret = SomePackage::doSomething(); if (PEAR::isError($ret)) { // do some handling - this error is not displayed or logged } PEAR::popErrorHandling(); ?> The PEAR_ErrorStack class has built in knowledge of the Log package, can easily differentiate and even automatically re-package errors with little to no difficulty. <?php // PEAR_ErrorStack error handling require_once 'PEAR/ErrorStack.php'; require_once 'Log.php'; define('MYPACKAGE_ERROR_DBERROR', 1); class myobj { var $_stack; function myobj() { $this->_stack = &PEAR_ErrorStack::singleton('MyPackage'); } function errorCallback($err) { switch($err['package']){ case 'MyPackage': // tell the error stack to log the error only // it will not be pushed onto the stack return PEAR_ERRORSTACK_LOG; break; case 'InternalDbPackage': // re-package these errors as a mypackage error fit // for enduser consumption $this->_stack->push(MYPACKAGE_ERROR_DBERROR, 'error', array('dbmessage' => $err['message'], 'dbcode' => $err['code'], 'We are having Connection problems, please' . 'try again in a few moments'), '', $err); // include the error as re-packaged // tell the internal DB error stack to ignore this error, // as if it never happened return PEAR_ERRORSTACK_IGNORE; break; } // switch } } $myobj = &new myobj; // separate error stacks for my package, and the internal DB package $dbstack = &PEAR_ErrorStack::singleton('InternalDbPackage'); $mystack = &PEAR_ErrorStack::singleton('MyPackage'); // set up a file log using PEAR::Log $log = &Log::Factory('file', 'somefile.log', 'MyPackage error log'); $mystack->setLogger($log); // set up a default log to use for all error stacks PEAR_ErrorStack::setDefaultLogger($log); // any errors returned by MyPackage are logged $ret = SomePackage::doSomething(); // Note that $ret need not be checked for any error condition - errors are // totally separate from code if ($dbstack->hasErrors()) { var_dump($dbstack->getErrors(); } // sets a default callback for all errors PEAR_ErrorStack::setDefaultCallback(array(&$myobj, 'errorCallback')); // any db errors are transparently repackaged as // user-friendly MyPackage errors now $ret = SomePackage::doSomething(); ?> Why write a new error-handling routine when PEAR_Error already exists? There are several problems with PEAR_Error. Although an error message is present in an error class, processing this error message automatically is excessively difficult for computers. In addition, the error message cannot easily be translated once it has been placed into the PEAR_Error. There is also no standard facility for storing error-related data in the error class. On top of error message-related issues, there is no way to automatically determine which package a PEAR_Error object comes from, or the severity of an error. Fatal errors look exactly the same as non-fatal errors. The largest flaw with PEAR_Error object is the single-error type design. Every PEAR_Error object is just a PEAR_Error object. There is no differentiating between the severity of an error, or its origin. The only way to determine the severity is to use PEAR_ERROR_TRIGGER and E_USER_NOTICE/E_USER_WARNING/E_USER_ERROR constants from php's trigger_error. But using this functionality does not justify 900 lines of code, simply because trigger_error() is built into PHP itself! Now, to start using your newly created error objects, change all of your PEAR::raiseError() or PEAR::throwError() calls from this... <?php require_once 'PEAR.php'; // old way: $error_specific_info = 'bad'; $e = PEAR::raiseError("error message - very " . $error_specific_info . " way to do things", MYPACKAGE_ERROR_FOO); // another old way: $e = PEAR::throwError("error message - very " . $error_specific_info . " way to do things", MYPACKAGE_ERROR_FOO); ?> ...to something like this: <?php require_once 'PEAR/ErrorStack.php'; // new way // version 1: stack instance access $stack = &PEAR_ErrorStack::singleton('MyPackage'); $stack->push(MYPACKAGE_ERROR_DBERROR, 'error', array('query' => $query, 'dsn' => $dsn), 'Critical Database Error: Contact Administrator immediately'); // version 2: static singleton access (slightly slower) PEAR_ErrorStack::staticPush('MyPackage', MYPACKAGE_ERROR_DBERROR, 'error', array('query' => $query, 'dsn' => $dsn), 'Critical Database Error: Contact Administrator immediately'); ?> For basic use, this is all that is needed to use the PEAR_ErrorStack package in place of PEAR_Error. Advanced Features Error Context Display In some cases, you may want to customize error generation. For instance, for many exceptions, it is useful to include file, line number, and class/function context information in order to trace an error. A default option is available which will be sufficient for most cases, and that is PEAR_ErrorStack::getFileLine(). Not all package errors occur in the PHP source file. For instance, compiling template engines errors can occur in the template source files. Database errors can occur in the text of a query, or internal to the database server. Internet package errors can occur on another server. All of this information can be included in an error message using a context grabbing callback. <?php require_once 'PEAR/ErrorStack.php'; class DatabaseClass { var $_dbError; var $_dbErrorMsg; var $_dbQuery; var $_dbPos; /** * Context grabber for the Database package * @param integer Error Code * @param array Error parameters passed into {@link PEAR_ErrorStack::push()} * @param array Output of debug_backtrace() (not used in this callback) */ function getErrorContext($code, $params, $backtrace) { $context = array( 'errorcode' => $this->_dbError, 'errormsg' => $this->_dbErrorMsg, 'query' => $this->_dbQuery, 'pos' => $this->_dbPos, ); return $context; } } $db = new DatabaseClass; PEAR_ErrorStack::staticSetContextCallback('Database', array(&$db, 'getErrorContext')); ?> The context information is formatted to be easily processed by an external application. If you wish context information to be in the error message, the error message callback should be used to add the information in a human-readable format to the error message, as described in the next section. Custom Error Message Generation There are three methods of PEAR_ErrorStack designed for use with generating error messages efficiently. To use them, you must do one of three things: • Call PEAR_ErrorStack::setErrorMessageTemplate(), and set an array mapping error codes to error message templates, like so: <?php define('ERROR_ONE', 1); define('ERROR_TWO', 2); define('ERROR_THREE', 3); define('ERROR_FOUR', 4); require_once 'PEAR/ErrorStack.php'; $stack = &PEAR_ErrorStack::singleton('mypackage'); $messages = array( ERROR_ONE => 'The gronk number %num% dropped a %thing%', ERROR_TWO => 'The %list% items were missing', ERROR_THREE => 'I like chocolate, how about %you%?', ERROR_FOUR => 'and a %partridge% in a pear %tree%', ); $stack->setErrorMessageTemplate($messages); ?> Substitution is done using str_replace, and is very simple. Basically, if a variable name is enclosed in percent signs (%), it will be replaced with the value passed in the associative array. If an array array('varname' => 'value'); is passed to either method, all occurrences of %varname% will be replaced by value. In addition, if values are objects, the methods will search for a method named "__toString()" and if found, will use that to convert the object to a string. If an array of strings is passed in, they will be joined by commas. <?php array('varname' => array('first', 'second', 'third')); // this will become 'first, second, third' ?> • Call PEAR_ErrorStack::setMessageCallback(), and set a custom error message generating function or method. This is probably the best option for the majority of complex situations, as it allows users to override or even extend the existing error message callback using PEAR_ErrorStack::getMessageCallback(). For example: <?php require_once 'PEAR/ErrorStack.php'; class foo { var $_oldcallback; function callback(&$stack, $err) { $message = call_user_func_array($this->_oldcallback, array(&$stack, $err)); $message .= "File " . $err['context']['file']; return $message; } } $a = new foo; $stack = &PEAR_ErrorStack::singleton('otherpackage'); $a->_oldcallback = $stack->getMessageCallback('otherpackage'); $stack->setMessageCallback(array(&$a, 'callback')); ?> • Extend PEAR_ErrorStack with your own class, and override PEAR_ErrorStack::getErrorMessageTemplate() or PEAR_ErrorStack::getErrorMessage(). To guarantee that this class will be used by other packages/applications, use this code right after the class declaration: <?php PEAR_ErrorStack::singleton('mypackage', false, null, 'MyPEAR_ErrorStack'); ?> Controlling error generation There are many scenarios in which fine-grained control over error raising is absolutely necessary. A generic error handling callback means that every single error raised will be handled in the same error callback. Although PEAR_ErrorStack is designed to operate with independent callbacks for each package, generic error handling is possible through the PEAR_ErrorStack::staticPushCallback() method. This is no different from PEAR_Error's PEAR_ERROR_CALLBACK error handling mode. PEAR_ErrorStack's real strength comes from the callback itself. PEAR_Error's callback has no actual effect on the error message - all error handling must happen in the callback method or function itself. PEAR_ErrorStack's callback can influence the error through the use of three constants: • PEAR_ERRORSTACK_IGNORE • PEAR_ERRORSTACK_PUSH • PEAR_ERRORSTACK_LOG PEAR_ERRORSTACK_IGNORE informs the stack to ignore the error, as if it never occurred. The error will be neither logged, nor pushed on the stack. It will, however, be returned from PEAR_ErrorStack::push() PEAR_ERRORSTACK_PUSH informs the stack to push the error onto the error stack, but not to log the error. PEAR_ERRORSTACK_LOG informs the stack not to push the error onto the error stack, but only to log the error. <?php define('ERROR_CODE_ONE',1); define('ERROR_CODE_TWO',2); define('ERROR_CODE_THREE',3); require_once 'PEAR/ErrorStack.php'; require_once 'Log.php'; function somecallback($err) { switch($err['code']){ case ERROR_CODE_ONE: return PEAR_ERRORSTACK_IGNORE; break; case ERROR_CODE_TWO: return PEAR_ERRORSTACK_PUSH; break; case ERROR_CODE_THREE: return PEAR_ERRORSTACK_LOG; break; } // switch } $log = &Log::factory('display'); $stack = &PEAR_ErrorStack::singleton('mypackage'); $stack->setLogger($log); $stack->pushCallback('somecallback'); $stack->push(ERROR_CODE_ONE); $stack->push(ERROR_CODE_TWO); $stack->push(ERROR_CODE_THREE); var_dump(PEAR_ErrorStack::staticGetErrors()); // simulate PEAR_ERROR_CALLBACK, with specific callback for mypackage // every other package will only log errors, only mypackage's errors // are pushed on the stack, conditionally class myclass { function acallback($err) { return PEAR_ERRORSTACK_LOG; } } $stack2 = PEAR_ErrorStack::singleton('anotherpackage'); $stack3 = &PEAR_ErrorStack::singleton('thirdpackage'); PEAR_ErrorStack::setDefaultCallback(array('myclass', 'acallback')); ?> Repackaging errors from one package to another The most obvious usage for an error callback involves a common scenario in many userlevel applications that use system-level packages. If you write a Content Management System (CMS) with the PEAR DB package, it is usually a bad idea to display database-level errors when a user clicks on a link to add a message to a forum. PEAR_ErrorStack can be used to repackage this error as a MyPackage error. <?php define('MYPACKAGE_ERROR_DBDOWN',1); require_once 'PEAR/ErrorStack.php'; function repackage($err) { if ($err['package'] == 'DB') { $mystack = &PEAR_ErrorStack::singleton('mypackage'); $mystack->push(MYPACKAGE_ERROR_DBDOWN, 'error', array('olderror' => $err)); // ignore the DB error, but save it in the mypackage error, for logging return PEAR_ERRORSTACK_IGNORE; } } ?> Emulating the @ operator One of the difficult-to-use strengths of PEAR_Error involves the PEAR::expectError() method. With regular PHP errors, it is possible to silence them using the @ operator like so: <?php @file_get_contents(); ?> Emulating this behavior with PEAR_ErrorStack is simple. <?php define('ERROR_CODE_SOMETHING', 1); require_once 'PEAR/ErrorStack.php'; function silence($err) { // ignore all errors return PEAR_ERRORSTACK_IGNORE; } $stack = &PEAR_ErrorStack::singleton('mypackage'); $stack->pushCallback('silence'); $stack->push(ERROR_CODE_SOMETHING); ?> PEAR_ErrorStack can take this one step further, and only log errors or only put errors on the error stack, using the other two constants. Finally, particular errors can be singled out, and all others ignored. <?php define('SOMEPACKAGE_ERROR_THING', 1); require_once 'PEAR/ErrorStack.php'; function silenceSome($err) { if ($err['package'] != 'somepackage') { // ignore all errors from other packages return PEAR_ERROR_IGNORE; } if ($err['code'] != SOMEPACKAGE_ERROR_THING) { // ignore all other error codes return PEAR_ERRORSTACK_IGNORE; } } $stack = &PEAR_ErrorStack::singleton('mypackage'); $stack->pushCallback('silenceSome'); $stack->push(ERROR_CODE_SOMETHING); ?> Backwards compatibility with PEAR_Error, Forward compatibility with PHP 5 Exception PEAR_ErrorStack can also be programmed to automatically raise a PEAR_Error using PEAR::raiseError(), simply pass in true to the PEAR_Error compatibility like so: <?php require_once 'PEAR/ErrorStack.php'; $stack = &PEAR_ErrorStack::singleton('mypackage', false, false, true); ?> Backward Compatibility break As of PEAR 1.3.2, PEAR_ErrorStack->push() no longer returns an exception class. Code that relies on this behavior will not work PEAR_ErrorStack will return an exception automatically in PHP 5. You can set the exception class name that will be returned using the following code: <?php require_once 'PEAR/ErrorStack.php'; $stack = &PEAR_ErrorStack::singleton('mypackage', false, null, 'PEAR_ErrorStack', false, ' ?> constructor PEAR_ErrorStack::PEAR_ErrorStack() constructor PEAR_ErrorStack::PEAR_ErrorStack() -- Set up a new error stack instance Synopsis require_once 'PEAR/ErrorStack.php'; void constructor PEAR_ErrorStack::PEAR_ErrorStack (string $package [, callback $msgCallback = FALSE [, callback $contextCallback = FALSE [, boolean $throwPEAR_Error = FALSE]]]) Backwards Compatibility Warning Warnung As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5, and the last parameter has been removed. Code that relies upon this behavior will break. Beschreibung Creates a new private PEAR_ErrorStack. To access a universal stack, use PEAR_ErrorStack::singleton() Parameter string $package name of the package this error stack represents callback $msgCallback callback used for error message generation callback $contextCallback callback used for context generation, defaults to getFileLine() boolean $throwPEAR_Error string $exceptionClass exception class to instantiate if in PHP 5 Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::getErrorMessage() PEAR_ErrorStack::getErrorMessage() -- Standard error message generation callback Synopsis require_once 'PEAR/ErrorStack.php'; string PEAR_ErrorStack::getErrorMessage (PEAR_ErrorStack &$stack, array $err [, string|false$template = FALSE]) Beschreibung This method may also be called by a custom error message generator to fill in template values from the params array, simply set the third parameter to the error message template string to use The special variable %__msg% is reserved: use it only to specify where a message passed in by the user should be placed in the template, like so: Error message: %msg% - internal error If the message passed like so: <?php $stack->push(ERROR_CODE, 'error', array(), 'server error 500'); ?> The returned error message will be "Error message: server error 500 - internal error" Parameter PEAR_ErrorStack &$stack array $err string|false $template Pre-generated error message template Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::getErrorMessageTemplate() PEAR_ErrorStack::getErrorMessageTemplate() -- Standard Error Message Template generator from error code Synopsis require_once 'PEAR/ErrorStack.php'; string PEAR_ErrorStack::getErrorMessageTemplate (mixed $code) Beschreibung Standard Error Message Template generator from error code Parameter mixed $code Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::getErrors() PEAR_ErrorStack::getErrors() -- Retrieve all errors since last purge Synopsis require_once 'PEAR/ErrorStack.php'; array PEAR_ErrorStack::getErrors ([boolean $purge = FALSE [, string| false $level = FALSE]]) Beschreibung Retrieve all errors since last purge, or filter all errors and only return errors of a particular error level, leaving the rest on the stack. Parameter boolean $purge set in order to empty the error stack string $level Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::getFileLine() PEAR_ErrorStack::getFileLine() -- Standard file/line number/function/class context callback Synopsis require_once 'PEAR/ErrorStack.php'; array|false PEAR_ErrorStack::getFileLine (array $code, unused $params [, integer $backtrace = NULL]) Beschreibung This function uses a backtrace generated from debug_backtrace and so will not work at all in PHP < 4.3.0. The frame should reference the frame that contains the source of the error. Parameter array $code Results of debug_backtrace() unused $params integer $backtrace backtrace frame. Rückgabewert returns either array('file' => file, 'line' => line, 'function' => function name, 'class' => class name) or if this doesn't work, then false Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::getMessageCallback() PEAR_ErrorStack::getMessageCallback() -- Get an error code => error message mapping callback Synopsis require_once 'PEAR/ErrorStack.php'; array|string|false PEAR_ErrorStack::getMessageCallback () Beschreibung This method returns the current callback that can be used to generate error messages Rückgabewert returns Callback function/method or false if none Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::hasErrors() PEAR_ErrorStack::hasErrors() -- Determine whether there are any errors on the stack Synopsis require_once 'PEAR/ErrorStack.php'; boolean PEAR_ErrorStack::hasErrors ([string $level = false]) Beschreibung Determine whether there are any errors on the stack Parameter string $level Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::pop() PEAR_ErrorStack::pop() -- Pop an error off of the error stack Synopsis require_once 'PEAR/ErrorStack.php'; false|array PEAR_ErrorStack::pop () Beschreibung Pop an error off of the error stack Fehler-Meldungen throws no exceptions thrown Hinweise since 0.4alpha it is no longer possible to specify a specific error level to return - the last error pushed will be returned instead. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::popCallback() PEAR_ErrorStack::popCallback() -- Remove a callback from the error callback stack Synopsis require_once 'PEAR/ErrorStack.php'; array|string|false PEAR_ErrorStack::popCallback () Beschreibung Remove a callback from the error callback stack Fehler-Meldungen throws no exceptions thrown Siehe auch see PEAR_ErrorStack::pushCallback() Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::push() PEAR_ErrorStack::push() -- Add an error to the stack Synopsis require_once 'PEAR/ErrorStack.php'; PEAR_Error|array PEAR_ErrorStack::push (integer $code [, string $level = 'error' [, array $params = array() [, string $msg = FALSE [, array $repackage = FALSE [, array $backtrace = FALSE]]]]]) Backwards Compatibility Warning Warnung As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5. Code that relies upon this behavior will break. Beschreibung If the message generator exists, it is called with 2 parameters. the current Error Stack object • an array that is in the same format as an error. Available indices are 'code', 'package', 'time', 'params', 'level', and 'context' • Next, if the error should contain context information, this is handled by the context grabbing method. Finally, the error is pushed onto the proper error stack Parameter integer $code Package-specific error code string $level Error level. This is NOT spell-checked array $params associative array of error parameters string $msg Error message, or a portion of it if the message is to be generated array $repackage If this error re-packages an error pushed by another package, place the array returned from pop() in this parameter array $backtrace Protected parameter: use this to pass in the http://www.php.net/manuallookup.php?pattern=debug_backtrace that should be used to find error context. Rückgabewert returns if compatibility mode is on, a PEAR_Error is also thrown. If the class Exception exists, then one is returned to allow code like: <?php 1 throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); ?> The errorData property of the exception class will be set to the array that would normally be returned. If a PEAR_Error is returned, the userinfo property is set to the array Otherwise, an array is returned in this format: <?php 1 2 3 4 5 6 7 8 9 10 ?> array( 'code' => $code, 'params' => $params, 'package' => $this->_package, 'level' => $level, 'time' => time(), 'context' => $context, 'message' => $msg, //['repackage' => $err] repackaged error array ); Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::pushCallback() PEAR_ErrorStack::pushCallback() -- Set an error Callback If set to a valid callback, this will be called every time an error is pushed onto the stack. The return value will be used to determine whether to allow an error to be pushed or logged. Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::pushCallback (string|array $cb) Beschreibung The return value must be one of the PEAR_ERRORSTACK_* constants. This functionality can be used to emulate PEAR's pushErrorHandling, and the PEAR_ERROR_CALLBACK mode, without affecting the integrity of the error stack or logging Parameter string|array $cb Fehler-Meldungen throws no exceptions thrown Siehe auch see PEAR_ErrorStack::popCallback() see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::raiseError() PEAR_ErrorStack::raiseError() -- emulate PEAR::raiseError() Synopsis require_once 'PEAR/ErrorStack.php'; PEAR_Error PEAR_ErrorStack::raiseError () Beschreibung See PEAR::raiseError() Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_ErrorStack::setContextCallback() PEAR_ErrorStack::setContextCallback() -- Set a callback that generates context information (location of error) for an error stack Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::setContextCallback (array|string|null $contextCallback) Beschreibung This method sets the callback that can be used to generate context information for an error. Passing in NULL will disable context generation and remove the expensive call to debug_backtrace() Parameter mixed $contextCallback A valid callback as defined by is_callable() Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::setDefaultCallback() PEAR_ErrorStack::setDefaultCallback() -- Sets a default callback to be used by all error stacks Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::setDefaultCallback ([array|string $callback = FALSE]) Beschreibung This method sets the callback that can be used to generate error messages for a singleton Parameter array|string $callback Callback function/method Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::setDefaultLogger() PEAR_ErrorStack::setDefaultLogger() -- Set up a PEAR::Log object for all error stacks that don't have one Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::setDefaultLogger (Log &$log) Beschreibung Set up a PEAR::Log object for all error stacks that don't have one Parameter Log &$log Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::setErrorMessageTemplate() PEAR_ErrorStack::setErrorMessageTemplate() -- Set the Error Message Template array Synopsis require_once 'PEAR/ErrorStack.php'; string PEAR_ErrorStack::setErrorMessageTemplate (mixed $template) Beschreibung The array format must be: array(error code => 'message template',...) Error message parameters passed into push() will be used as input for the error message. If the template is 'message %foo% was %bar%', and the parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will be 'message one was six' Parameter mixed $template Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::setLogger() PEAR_ErrorStack::setLogger() -- Set up a PEAR::Log object for this error stack Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::setLogger (Log &$log) Beschreibung Set a PEAR::Log object to use for a specific error stack instance Parameter Log &$log Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::setMessageCallback() PEAR_ErrorStack::setMessageCallback() -- Set an error code => error message mapping callback Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::setMessageCallback (mixed $msgCallback) Beschreibung This method sets the callback that can be used to generate error messages for any PEAR_ErrorStack instance Parameter mixed $msgCallback Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ErrorStack::singleton() PEAR_ErrorStack::singleton() -- Return a single error stack for this package. Synopsis require_once 'PEAR/ErrorStack.php'; PEAR_ErrorStack & PEAR_ErrorStack::singleton (string $package [, callback $msgCallback = FALSE [, callback $contextCallback = FALSE [, boolean $throwPEAR_Error = FALSE, string [$stackClass = 'PEAR_ErrorStack']]]]) Backwards Compatibility Warning Warnung As of PEAR 1.3.2, PEAR_ErrorStack no longer instantiates and returns an Exception object in PHP5, and the second-to-last parameter has been removed. Code that relies upon this behavior will break. Beschreibung Note that all parameters are ignored if the stack for package $package has already been instantiated Parameter string $package name of the package this error stack represents callback $msgCallback callback used for error message generation callback $contextCallback callback used for context generation, defaults to getFileLine() boolean $throwPEAR_Error If TRUE, then PEAR::raiseError() will be called and a PEAR_Error object will be returned from calls to PEAR_ErrorStack::push() string $stackClass class to instantiate Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::staticGetErrors() PEAR_ErrorStack::staticGetErrors() -- Get a list of all errors since last purge, organized by package Synopsis require_once 'PEAR/ErrorStack.php'; array PEAR_ErrorStack::staticGetErrors ([boolean $purge = FALSE [, string|false $level = FALSE [, boolean $merge = FALSE, array [$sortfunc = array('PEAR_ErrorStack', '_sortErrors')]]]]) Backwards Compatibility Warning Warnung As of PEAR 1.3.2, the second parameter is a new parameter $level. Any code that relies on $merge being the second parameter will break. Beschreibung Static version of PEAR_ErrorStack::getErrors() , returns all errors from all singleton stacks. Parameter boolean $purge Set to purge the error stack of existing errors string $level Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored) boolean $merge Set to return a flat array, not organized by package array $sortfunc Function used to sort a merged array - default sorts by time, and should be good for most cases Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::staticHasErrors() PEAR_ErrorStack::staticHasErrors() -- Determine whether there are any errors on any error stack Synopsis require_once 'PEAR/ErrorStack.php'; boolean PEAR_ErrorStack::staticHasErrors ([string|false $package = false [, string $level = false]]) Beschreibung Static version of PEAR_ErrorStack::hasErrors(). Returns TRUE if any singleton stack has any errors pending. Since PEAR 1.3.2, If $package is specified, it will call PEAR_ErrorStack::hasErrors for the singleton error stack of that package. If level is specified, hasErrors will ignore any errors not conforming to the error level specified. Use this to simulate error_reporting(E_NOTICE), for example Parameter string|FALSE $package Package name to retrieve error information from, or false to retrieve error information from all singleton stacks string $level Level name to check for a particular severity. Use this to determine whether only a particular class of errors has occurred, such as whether any warnings have occurred (errors will be ignored) Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::staticPopCallback() PEAR_ErrorStack::staticPopCallback() -- Remove a callback from every error callback stack Synopsis require_once 'PEAR/ErrorStack.php'; array|string|false PEAR_ErrorStack::staticPopCallback () Beschreibung Pop a callback from every Error Stack. No check is made to determine whether this is a good idea, so use with discretion. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Siehe auch see PEAR_ErrorStack::staticPushCallback() Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::staticPush() PEAR_ErrorStack::staticPush() -- Static version of push() Synopsis require_once 'PEAR/ErrorStack.php'; PEAR_Error|null|Exception PEAR_ErrorStack::staticPush (string $package, integer $code [, string $level = 'error' [, array $params = array() [, string $msg = FALSE [, array $repackage = FALSE [, array $backtrace = FALSE]]]]]) Beschreibung Parameter string $package Package name this error belongs to integer $code Package-specific error code string $level Error level. This is NOT spell-checked array $params associative array of error parameters string $msg Error message, or a portion of it if the message is to be generated array $repackage If this error re-packages an error pushed by another package, place the array returned from pop() in this parameter array $backtrace Protected parameter: use this to pass in the debug_backtrace that should be used to find error context Rückgabewert returns if compatibility mode is on, a PEAR_Error is also thrown. If the class Exception exists, then one is returned to allow code like: <?php 1 ?> throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob'))); Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::staticPushCallback() PEAR_ErrorStack::staticPushCallback() -- Set an error Callback for every package's error stack Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::staticPushCallback (string|array $cb) Beschreibung Set an error callback for every package's singleton error stack. Parameter string|array $cb Fehler-Meldungen Es werden keine Exceptions ausgelöst. Siehe auch see PEAR_ErrorStack::staticPopCallback() , PEAR_ErrorStack::pushCallback() see PEAR_ERRORSTACK_PUSHANDLOG , PEAR_ERRORSTACK_PUSH , PEAR_ERRORSTACK_LOG Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ErrorStack::_log() PEAR_ErrorStack::_log() -- Log an error using PEAR::Log Synopsis require_once 'PEAR/ErrorStack.php'; void PEAR_ErrorStack::_log (array $err [, array $levels = array( 'exception' => PEAR_LOG_CRIT, 'alert' => PEAR_LOG_ALERT, 'critical' => PEAR_LOG_CRIT, 'error' => PEAR_LOG_ERR, 'warning' => PEAR_LOG_WARNING, 'notice' => PEAR_LOG_NOTICE, 'info' => PEAR_LOG_INFO, 'debug' => PEAR_LOG_DEBUG)]) Beschreibung This is a protected function, and should only be called by child classes that extend PEAR_ErrorStack Parameter array $err Error array array $levels Error level => Log constant map Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. Package PEAR_ErrorStack Constants Package PEAR_ErrorStack Constants -- Constants defined in and used by PEAR_ErrorStack All Constants Constants defined in ErrorStack.php Tabelle 26-1. Constants defined in ErrorStack.php Name Value Line Number PEAR_ERRORSTACK_ERR_NONCLASS 1 110 PEAR_ERRORSTACK_ERR_OBJTOSTRING 2 116 PEAR_ERRORSTACK_IGNORE 4 103 PEAR_ERRORSTACK_LOG 3 99 PEAR_ERRORSTACK_PUSH 2 94 PEAR_ERRORSTACK_PUSHANDLOG 1 89 System Inhaltsverzeichnis Introduction -- General usage informations System::rm -- remove files System::mkDir -- create directories System::&cat -- concatenate files System::mktemp -- Create temporary files or directories System::tmpdir -- Get path of temporal directory System::which -- show full path of a command Commandline functions System provides an API for cross platform compatible commandline programs. Introduction Introduction -- General usage informations Command line style The System functions are called like there commandline pendants if (!System::rm('-r file1 dir1')) { print "Could not delete all the files"; } The arguments of the functions can be introduced as string or array: System::rm(array('-r', 'file1', 'dir1')); System works like any other PHP function and will return FALSE, when the operation could no be completed enterely or partially. System won't stop when a error is found, it will try to continue. For example, if you are trying to delete three files and the first one can't be deleted, the next two files will be deleted but the function will return FALSE. Errors will be printed out using the PHP function trigger_error()() so all the System methods can be silenced prefix a '@' sign before the function call (for example: @System::mkdir('-p dir1/dir2/dir3');). Compatibility System provides file system functions. They are named like the file system commands on Unix systems and supports the same options independent of your operation system. At the moment the functions are tested under Linux and Windows. Further reports about compatibility on other systems are welcome. Warnung In earlier versions of PHP 4, unlink() may fail on Windows. This bug is already fixed in up-to-date versions. Man Pages This manual describes the parameters of the System functions, most only a string. The arguments and options of the specific command are not documented in the manual. Please take a look on the man-pages on unix-like systems man commandname or when man-pages not avaible on your system, visit the On-line UNIX manual pages System::rm System::rm -- remove files Synopsis require_once "System.php"; mixed System::rm (string $args) Beschreibung The rm command for removing files. Supports multiple files and dirs and also recursive deletes. Parameter • string $args - the arguments for rm Rückgabewert mixed - TRUE for success Hinweise Diese Methode kann statisch aufgerufen werden. Siehe auch rm man page System::mkDir System::mkDir -- create directories Synopsis require_once "System.php"; bool System::mkDir (string $args) Beschreibung Creates directories. Parameter • string $args - the name of the directory/-ies to create Rückgabewert bool - TRUE for success Hinweise Diese Methode kann statisch aufgerufen werden. Siehe auch mkdir man page System::&cat System::&cat -- concatenate files Synopsis require_once "System.php"; boolean System::&cat (string $args) Beschreibung Concatenate files. The method uses fopen(), URLs should work too. Parameter • string $args - the arguments Rückgabewert boolean - TRUE on success Hinweise Diese Methode kann statisch aufgerufen werden. Siehe auch cat man page Beispiel Beispiel 26-1. Using &cat() $var = System::cat('sample.txt test.txt'); System::cat('sample.txt test.txt > final.txt'); System::cat('sample.txt test.txt >> final.txt'); System::mktemp System::mktemp -- Create temporary files or directories Synopsis require_once "System.php"; mixed System::mktemp ([string $args = NULL]) Beschreibung Creates temporary files or directories. This function will remove the created files when the scripts finish its execution. Parameter • string $args - The arguments • • • prefix - The string that will be prepended to the temp name (defaults to tmp) -d - A temporary dir will be created instead of a file. -t - The target dir where the temporary file or directory will be created. If this parameter is missing, by default the enviroment vars TMP on Windows or TMPDIR on Unix will be used. If these vars are also missing c:\windows\temp or /tmp will be used. Rückgabewert mixed - the full path of the created file or dir, or FALSE Hinweise Diese Methode kann statisch aufgerufen werden. Siehe auch mktemp man page Beispiel Beispiel 26-1. Using mktemp() $tempfile = System::mktemp("prefix"); $tempdir = System::mktemp("-d prefix"); $tempfile = System::mktemp(); $tempfile = System::mktemp("-t /var/tmp prefix"); System::tmpdir System::tmpdir -- Get path of temporal directory Synopsis require_once "System.php"; string System::tmpdir () Beschreibung Get the path of the temporal directory set in the system by looking in its environments variables. Rückgabewert string - The temporal directory on the system Hinweise Diese Methode kann statisch aufgerufen werden. php.ini-recommended removes the E from the variables_order setting, making unavaible the $_ENV array Siehe auch tmpdir man page System::which System::which -- show full path of a command Synopsis require_once "System.php"; mixed System::which (string $program [, boolean $fallback = FALSE]) Beschreibung The command shows the full path of a command. Parameter • string $program - the command to search for • boolean $fallback - value to return in case of program not found Rückgabewert mixed - A string with the full path or FALSE if not found Hinweise Diese Methode kann statisch aufgerufen werden. Siehe auch which man page Kapitel 27. PEAR Installer classes The PEAR Installer classes provides an API for the administration and management of PEAR Packages. Warnung Documentation is not fully up-to-date with PEAR version 1.4.0. PEAR_Autoload Inhaltsverzeichnis PEAR_Autoloader::addAggregateObject() -- Add an aggregate object to object. PEAR_Autoloader::addAutoload() -- Add one or more autoload entries PEAR_Autoloader::removeAggregateObject() -- Remove an aggregate object PEAR_Autoloader::removeAutoload() -- Remove an autoload entry PEAR_Autoloader::__call() -- Overloaded object call handler This class is for objects where you want to separate the code for some methods into separate classes. This is useful if you have a class with not-frequently-used methods that contain lots of code that you would like to avoid always parsing. Class Trees for PEAR_Autoloader • PEAR • PEAR_Autoloader PEAR_Autoloader::addAggregateObject() PEAR_Autoloader::addAggregateObject() -- Add an aggregate object to object. Synopsis require_once 'PEAR/autoloader.php'; void PEAR_Autoloader::addAggregateObject (string $classname) Beschreibung Add an aggregate object to this object. If the specified class is not defined, loading it will be attempted following PEAR's file naming scheme. All the methods in the class will be aggregated, except private ones (name starting with an underscore) and constructors. Parameter string $classname what class to instantiate for the object. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Autoloader::addAutoload() PEAR_Autoloader::addAutoload() -- Add one or more autoload entries Synopsis require_once 'PEAR/autoloader.php'; void PEAR_Autoloader::addAutoload (string $method, string ''[$classname = NULL]) Beschreibung Add one or more autoload entries. Parameter string $method which method to autoload string $classname which class to find the method in. If the $method parameter is an array, this parameter may be omitted (and will be ignored if not), and the $method parameter will be treated as an associative array with method names as keys and class names as values. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Autoloader::removeAggregateObject() PEAR_Autoloader::removeAggregateObject() -- Remove an aggregate object Synopsis require_once 'PEAR/autoloader.php'; bool PEAR_Autoloader::removeAggregateObject (string $classname) Beschreibung Remove an aggregate object. Parameter string $classname the class of the object to remove Rückgabewert bool Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Autoloader::removeAutoload() PEAR_Autoloader::removeAutoload() -- Remove an autoload entry Synopsis require_once 'autoloader.php'; bool PEAR_Autoloader::removeAutoload (string $method) Beschreibung Remove an autoload entry. Parameter string $method which method to remove the autoload entry for Rückgabewert bool Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Autoloader::__call() PEAR_Autoloader::__call() -- Overloaded object call handler Synopsis require_once 'PEAR/autoloader.php'; mixed PEAR_Autoloader::__call (string $method, string $args, mixed &$retval) Beschreibung Overloaded object call handler, called each time an undefined/aggregated method is invoked. This method repeats the call in the right aggregate object and passes on the return value. Parameter string $method which method that was called string $args An array of the parameters passed in the original call mixed &$retval Rückgabewert mixed - The return value from the aggregated method, or a PEAR_Error if the called method was unknown. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Builder Inhaltsverzeichnis PEAR_Builder::PEAR_Builder() -- constructor PEAR_Builder::build() -- Build an extension from source PEAR_Builder::log() -PEAR_Builder::phpizeCallback() -- Message callback function when running phpize Class to handle building (compiling) extensions. Class Trees for PEAR_Builder • PEAR_Common • PEAR_Builder PEAR_Builder::PEAR_Builder() PEAR_Builder::PEAR_Builder() -- constructor Synopsis require_once 'PEAR/builder.php'; void PEAR_Builder::PEAR_Builder (object &$ui) Beschreibung PEAR_Builder constructor Parameter object &$ui user interface object (instance of PEAR_Frontend_*) Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Builder::build() PEAR_Builder::build() -- Build an extension from source Synopsis require_once 'PEAR/builder.php'; array PEAR_Builder::build (string $descfile [, mixed $callback = NULL]) Beschreibung Build an extension from source. Runs phpize in the source directory, but compiles in a temporary directory (/var/tmp/pear-build-USER/PACKAGE-VERSION). Parameter string $descfile path to XML package description file mixed $callback callback function used to report output Rückgabewert array - an array of associative arrays with built files, format: array( array( 'file' => '/path/to/ext.so', 'php_api' => YYYYMMDD, 'zend_mod_api' => YYYYMMDD, 'zend_ext_api' =>; YYYYMMDD ), ... ) Siehe auch PEAR_Common::infoFromDescriptionFile Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Builder::log() PEAR_Builder::log() -- Synopsis require_once 'PEAR/builder.php'; void PEAR_Builder::log (mixed $level, mixed $msg) Beschreibung Dieses Package ist noch nicht dokumentiert. Parameter mixed $level mixed $msg Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Builder::phpizeCallback() PEAR_Builder::phpizeCallback() -- Message callback function when running phpize Synopsis require_once 'PEAR/builder.php'; void PEAR_Builder::phpizeCallback (string $what, mixed $data) Beschreibung Message callback function used when running the phpize program. Extracts the API numbers used. Ignores other message types than „cmdoutput“. Parameter string $what the type of message mixed $data the message Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile Inhaltsverzeichnis Class Summary PEAR_ChannelFile -- The Channel handling class constructor PEAR_ChannelFile::PEAR_ChannelFile() -- PEAR_ChannelFile PEAR_ChannelFile::addFunction() -- Add a protocol to the provides section PEAR_ChannelFile::addMirror() -- addMirror PEAR_ChannelFile::addMirrorFunction() -- Add a protocol to a mirror's provides section PEAR_ChannelFile::fromAny() -- Returns channel information from different sources PEAR_ChannelFile::fromArray() -- fromArray PEAR_ChannelFile::fromXmlFile() -- Parse a channel.xml file. Expects the name of a channel xml file as input. PEAR_ChannelFile::fromXmlString() -- fromXmlString PEAR_ChannelFile::getAlias() -- Return the suggested alias users can use to refer to this channel on the command-line. PEAR_ChannelFile::getBaseURL() -- Get the URL to access a base resource. PEAR_ChannelFile::getErrors() -- Wrapper to PEAR_ErrorStack::getErrors() PEAR_ChannelFile::getFunction() -- getFunction PEAR_ChannelFile::getFunctions() -- Retrieve a list of all xmlrpc/soap functions PEAR_ChannelFile::getMirror() -- Get the unserialized XML representing a mirror PEAR_ChannelFile::getMirrors() -- Retrieve a list of all mirrors and their contents PEAR_ChannelFile::getName() -- retrieve the channel name PEAR_ChannelFile::getPath() -- getPath PEAR_ChannelFile::getPort() -- retrieve the socket port used to connect to the server PEAR_ChannelFile::getServer() -- Retrieve the channel server PEAR_ChannelFile::getSSL() -- get SSL support for a channel or mirror PEAR_ChannelFile::getSummary() -- Get channel summary PEAR_ChannelFile::getValidationObject() -- Retrieve the object that can be used for custom validation PEAR_ChannelFile::getValidationPackage() -- Retrieve the name of the validation package for this channel PEAR_ChannelFile::isIncludeable() -- Determine whether a file exists in the include_path and is readable PEAR_ChannelFile::lastModified() -- This function is used by the channel updater and retrieves a value set by the registry, or the current time if it has not been set PEAR_ChannelFile::resetFunctions() -- Empty all protocol definitions PEAR_ChannelFile::resetREST() -- Since REST does not implement RPC, provide this as a logical wrapper around resetFunctions for REST PEAR_ChannelFile::setAlias() -- Set the channel alias PEAR_ChannelFile::setBaseURL() -- set the base URL for a REST resource, or set of REST resources PEAR_ChannelFile::setDefaultPEARProtocols() -- Set a channel's protocols to the protocols supported by pearweb PEAR_ChannelFile::setName() -- setName PEAR_ChannelFile::setPath() -- Set the file path for xmlrpc or soap PEAR_ChannelFile::setPort() -- Set the socket number (port) that is used to connect to this channel PEAR_ChannelFile::setServer() -- set the Channel server PEAR_ChannelFile::setSSL() -- Sets whether SSL is used to connect to this channel PEAR_ChannelFile::setSummary() -- set the summary of a channel's purpose PEAR_ChannelFile::setValidationPackage() -- Set the package validation object if it differs from PEAR's default. PEAR_ChannelFile::supports() -- determines whether a webservices function is supported by a channel PEAR_ChannelFile::supportsREST() -- Determines whether a channel supports any Representational State Transfer (REST) resources PEAR_ChannelFile::toArray() -- return the channel representation in array format PEAR_ChannelFile::toXml() -- Return an XML document based on the internal representation of this channel PEAR_ChannelFile::validate() -- Validate channel information. PEAR_ChannelFile::validChannelServer() -- Test whether a string contains a valid channel server. Package PEAR Constants -- Constants defined in and used by PEAR Class Summary PEAR_ChannelFile Class Summary PEAR_ChannelFile -- The Channel handling class The Channel handling class Represents channel.xml Class Trees for PEAR_ChannelFile • PEAR_ChannelFile constructor PEAR_ChannelFile::PEAR_ChannelFile() constructor PEAR_ChannelFile::PEAR_ChannelFile() -- PEAR_ChannelFile Synopsis require_once '/ChannelFile.php'; void constructor PEAR_ChannelFile::PEAR_ChannelFile () Beschreibung Simply creates the local error stack for the PEAR_ChannelFile object. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::addFunction() PEAR_ChannelFile::addFunction() -- Add a protocol to the provides section Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::addFunction (string $type, string $version, string [$name = ''], string [$mirror = false]) Beschreibung Adds a supported xml-rpc or SOAP function to a channel definition file. The type should be xmlrpc or soap in lower-cased letters. No validation is performed on insert. For example: <?php require_once 'PEAR/ChannelFile.php'; $chan = new PEAR_ChannelFile; $chan->setName('foo.example.com'); $chan->setSummary('demonstrate addFunction'); $chan->addFunction('xmlrpc', '1.0', 'people.list'); $chan->addFunction('oops', '1.0', 'bad.type'); ?> The oops protocol will be successfully created, but will fail upon validation. Adding a function to a mirror simply validated to ensure that the mirror already exists. <?php require_once 'PEAR/ChannelFile.php'; $chan = new PEAR_ChannelFile; $chan->setName('foo.example.com'); $chan->setSummary('demonstrate addFunction'); // fails: mirror not found $chan->addFunction('soap', '1.0', 'people.list', 'mirror.example.com'); $chan->addMirror('mirror.example.com'); // succeeds $chan->addFunction('soap', '1.0', 'people.list', 'mirror.example.com'); ?> Parameter string $type protocol type string $version protocol version string $name protocol name, if any string $mirror mirror name, if this is a mirror's protocol Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::addMirror() PEAR_ChannelFile::addMirror() -- addMirror Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::addMirror (string $server, int [$port = null]) Beschreibung Add a mirror server. Note that mirrors must be added to a channel.xml in order for users to use them. Unofficial mirrors are not allowed without user intervention. Parameter string $server mirror server integer $port mirror http port Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::addMirrorFunction() PEAR_ChannelFile::addMirrorFunction() -- Add a protocol to a mirror's provides section Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::addMirrorFunction (string $mirror, string $type, string $version, string [$name = '']) Beschreibung This is a direct way to add a xmlrpc or soap function to a mirror. See docs for addFunction(). Parameter string $mirror mirror name (server) string $type protocol type string $version protocol version string $name protocol name, if any Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::fromAny() PEAR_ChannelFile::fromAny() -- Returns channel information from different sources Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::fromAny (string $info) Beschreibung Parse data from either a string or a channel.xml file. Parameter string $info Filename of the source, or the source itself Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::fromArray() PEAR_ChannelFile::fromArray() -- fromArray Synopsis require_once '/ChannelFile.php'; PEAR_ChannelFile |false PEAR_ChannelFile::fromArray (array $data, mixed [$compatibility = FALSE], mixed [$stackClass = 'PEAR_ErrorStack']) Beschreibung Use this method with caution. This is intended to allow easy import of a pre-parsed channel.xml from another PEAR_ChannelFile class. It also makes possible the registry storage of channel.xml. Parameter array $data The pre-parsed channel data mixed $compatibility mixed $stackClass Rückgabewert returns false if invalid Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_ChannelFile::fromXmlFile() PEAR_ChannelFile::fromXmlFile() -- Parse a channel.xml file. Expects the name of a channel xml file as input. Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::fromXmlFile (string $descfile) Beschreibung Parse the contents of a channel.xml and store in the current PEAR_ChannelFile object. Parameter string $descfile name of channel xml file Rückgabewert returns success of parsing Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::fromXmlString() PEAR_ChannelFile::fromXmlString() -- fromXmlString Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::fromXmlString (string $data) Beschreibung Parse the contents of a channel.xml and store in the current PEAR_ChannelFile object. Parameter string $data contents of package.xml file Rückgabewert returns success of parsing Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getAlias() PEAR_ChannelFile::getAlias() -- Return the suggested alias users can use to refer to this channel on the command-line. Synopsis require_once '/ChannelFile.php'; string PEAR_ChannelFile::getAlias () Beschreibung This returns the channel alias. For instance, channel pear.php.net's alias is pear, channel pecl.php.net's alias is pecl. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getBaseURL() PEAR_ChannelFile::getBaseURL() -- Get the URL to access a base resource. Synopsis require_once '/ChannelFile.php'; string PEAR_ChannelFile::getBaseURL (string $resourceType, string| false [$mirror = FALSE]) Beschreibung Hyperlinks in the returned xml will be used to retrieve the proper information needed. This allows extreme extensibility and flexibility in implementation Parameter string $resourceType Resource Type to retrieve mixed $mirror Mirror name, or false for primary server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getErrors() PEAR_ChannelFile::getErrors() -- Wrapper to PEAR_ErrorStack::getErrors() Synopsis require_once '/ChannelFile.php'; array PEAR_ChannelFile::getErrors (boolean [$purge = FALSE]) Beschreibung Retrieve any errors from the last validation attempt. Parameter boolean $purge determines whether to purge the error stack after retrieving Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getFunction() PEAR_ChannelFile::getFunction() -- getFunction Synopsis require_once '/ChannelFile.php'; array PEAR_ChannelFile::getFunction (string $type, string [$name = NULL], string [$mirror = FALSE]) Beschreibung Retrieve the xml representation of a function. If found, the array is of format: <?php array( '_content' => 'functionname', 'attribs' => array('version' => 'version.number') ); ?> Parameter string $type Protocol type string $name Function name (NULL to return the first protocol of the type requested) string $mirror Mirror name, if any Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getFunctions() PEAR_ChannelFile::getFunctions() -- Retrieve a list of all xmlrpc/soap functions Synopsis require_once '/ChannelFile.php'; array|false PEAR_ChannelFile::getFunctions (string $protocol, string [$mirror = FALSE]) Beschreibung This retrieves an array of all defined xmlrpc and soap functions. Use getBaseURL() to access rest base URLs. The format of each function is the same as is returned by getFunction() Parameter string $protocol protocol type (xmlrpc, soap) string $mirror Mirror name Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getMirror() PEAR_ChannelFile::getMirror() -- Get the unserialized XML representing a mirror Synopsis require_once '/ChannelFile.php'; array|false PEAR_ChannelFile::getMirror (mixed $server) Beschreibung This returns the entire contents of the <mirror> tag as unserialized by the parser. Parameter mixed $server Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getMirrors() PEAR_ChannelFile::getMirrors() -- Retrieve a list of all mirrors and their contents Synopsis require_once '/ChannelFile.php'; array PEAR_ChannelFile::getMirrors () Beschreibung This returns an array of mirror information in the format defined by getMirror() Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getName() PEAR_ChannelFile::getName() -- retrieve the channel name Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::getName () Beschreibung Note that the channel name is the channel server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getPath() PEAR_ChannelFile::getPath() -- getPath Synopsis require_once '/ChannelFile.php'; string PEAR_ChannelFile::getPath (string $protocol, string|false [$mirror = FALSE]) Beschreibung Retrieve the relative path to access the protocol desired. If the channel is named foo.example.com and xmlrpc is accessed at foo.example.com/xml/rpc then path will be xml/rpc. Parameter string $protocol xmlrpc or soap string|FALSE $mirror mirror name or FALSE for primary server Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getPort() PEAR_ChannelFile::getPort() -- retrieve the socket port used to connect to the server Synopsis require_once '/ChannelFile.php'; int|80 PEAR_ChannelFile::getPort (mixed [$mirror = FALSE]) Beschreibung web services are served through http servers, and so most servers use port 80. This function can be used to determine if a non-standard port is in use at a channel. Parameter mixed $mirror Mirror name or FALSE for primary server Rückgabewert returns port number to connect to Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getServer() PEAR_ChannelFile::getServer() -- Retrieve the channel server Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::getServer () Beschreibung This is an alias for getName(). Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getSSL() PEAR_ChannelFile::getSSL() -- get SSL support for a channel or mirror Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::getSSL (mixed [$mirror = FALSE]) Beschreibung This function can be used to determine whether a channel or mirror requires a secure connection through SSL in order to access the packages. Parameter string|FALSE $mirror Mirror name or false for primary server Rückgabewert returns Determines whether secure sockets layer (SSL) is used to connect to this channel Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getSummary() PEAR_ChannelFile::getSummary() -- Get channel summary Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::getSummary () Beschreibung Return the brief description of a channel's purpose. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getValidationObject() PEAR_ChannelFile::getValidationObject() -- Retrieve the object that can be used for custom validation Synopsis require_once '/ChannelFile.php'; PEAR_Validate|false & PEAR_ChannelFile::getValidationObject (string| false [$package = FALSE]) Beschreibung Retrieve the channel validation object. The package parameter is intended to notify getValidationObject() of the package to be validated. If the package is in fact the channel validation package, then PEAR_Validate will be used for validation. This prevents an endless loop that would otherwise occur. Parameter string|FALSE $package The name of the package to validate. If the package is the channel validation package, PEAR_Validate is returned. Rückgabewert returns false is returned if the validation package cannot be located Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::getValidationPackage() PEAR_ChannelFile::getValidationPackage() -- Retrieve the name of the validation package for this channel Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::getValidationPackage () Beschreibung Retrieve the name of the channel's validation package as defined in channel.xml Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::isIncludeable() PEAR_ChannelFile::isIncludeable() -- Determine whether a file exists in the include_path and is readable Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::isIncludeable (string $path) Beschreibung Determine whether a file exists in the include_path and is readable Parameter string $path Relative path to file. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::lastModified() PEAR_ChannelFile::lastModified() -- This function is used by the channel updater and retrieves a value set by the registry, or the current time if it has not been set Synopsis require_once '/ChannelFile.php'; string PEAR_ChannelFile::lastModified () Beschreibung \ This method is used by the channel-update command in order to determine whether the local copy of channel.xml is up-to-date. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::resetFunctions() PEAR_ChannelFile::resetFunctions() -- Empty all protocol definitions Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::resetFunctions (string $type, string|false [$mirror = FALSE]) Beschreibung Clear all functions defined in the channel.xml, in order to start adding a new list. Parameter string $type protocol type (xmlrpc, soap) string|FALSE $mirror mirror name, if any Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::resetREST() PEAR_ChannelFile::resetREST() -- Since REST does not implement RPC, provide this as a logical wrapper around resetFunctions for REST Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::resetREST (string|false [$mirror = FALSE]) Beschreibung Similar to resetFunctions(), resetREST() removes all REST base URLs in order to start adding new REST functions to a channel. Parameter string|FALSE $mirror mirror name, if any Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setAlias() PEAR_ChannelFile::setAlias() -- Set the channel alias Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::setAlias (string $alias, boolean [$local = FALSE]) Beschreibung Set the suggested alias that users can use on the command-line as a shortcut access to this channel. For instance, channel pear.php.net's alias is pear. Parameter string $alias The alias boolean $local determines whether the alias is in channel.xml or local. If local, then this is the result of a pear channel-alias command. Rückgabewert returns success Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setBaseURL() PEAR_ChannelFile::setBaseURL() -- set the base URL for a REST resource, or set of REST resources Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::setBaseURL (string $resourceType, string $url, string|false [$mirror = FALSE]) Beschreibung Set the base URL that users should use to access a REST resource or set of REST resources. Parameter string $resourceType Resource Type this url links to string $url URL string|FALSE $mirror mirror name, if this is not a primary server REST base URL Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setDefaultPEARProtocols() PEAR_ChannelFile::setDefaultPEARProtocols() -- Set a channel's protocols to the protocols supported by pearweb Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::setDefaultPEARProtocols (string [$version = '1.0'], string|false [$mirror = FALSE]) Beschreibung This method sets up a channel's xmlrpc protocols to match that of pearweb (pear.php.net). Note that it does not configure REST resources, that must be done manually through setBaseURL(). Parameter string $version version of pearweb protocols to use. string|FALSE $mirror Mirror name or false for primary server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setName() PEAR_ChannelFile::setName() -- setName Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::setName (string $name) Beschreibung Set the primary server (and name) of the channel. Parameter string $name Channel name. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setPath() PEAR_ChannelFile::setPath() -- Set the file path for xmlrpc or soap Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::setPath (string $protocol, string|false $path, string|false [$mirror = FALSE]) Beschreibung Set the relative location to the channel that should be used to connect to the selected protocol. Defaults are xmlrpc.php for xml-rpc and soap.php for SOAP. Parameter string $protocol xmlrpc or soap string|FALSE $path name of the mirror server, or FALSE for the primary string|FALSE $mirror Mirror name or false for primary server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setPort() PEAR_ChannelFile::setPort() -- Set the socket number (port) that is used to connect to this channel Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::setPort (integer $port, string|false [$mirror = FALSE]) Beschreibung As web services connect to channels through web servers, this can be used to set the port that should be used to connect. Default is 80 for regular webservers, and 443 for SSL secure servers. Parameter integer $port port number string|FALSE $mirror name of the mirror server, or FALSE for the primary server Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setServer() PEAR_ChannelFile::setServer() -- set the Channel server Synopsis require_once '/ChannelFile.php'; string|false PEAR_ChannelFile::setServer (string $server, string| false [$mirror = FALSE]) Beschreibung This is an alias to setName(). Parameter string $server Server name string|FALSE $mirror Mirror server name or FALSE for primary server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setSSL() PEAR_ChannelFile::setSSL() -- Sets whether SSL is used to connect to this channel Synopsis require_once '/ChannelFile.php'; void PEAR_ChannelFile::setSSL (bool [$ssl = TRUE], string|false [$mirror = FALSE]) Beschreibung This function is used to inform the PEAR installer to use SSL when connecting to this channel server. Parameter boolean $ssl Determines whether to turn on SSL support or turn it off string|FALSE $mirror name of the mirror server, or FALSE for the primary server Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setSummary() PEAR_ChannelFile::setSummary() -- set the summary of a channel's purpose Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::setSummary (string $summary) Beschreibung This sets a human-readable description of a channel's purpose. Parameter string $summary The channel summary Rückgabewert returns success Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::setValidationPackage() PEAR_ChannelFile::setValidationPackage() -- Set the package validation object if it differs from PEAR's default. Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::setValidationPackage (string|false $validateclass, string $version) Beschreibung The class must be either in memory (PEAR_Validate or PEAR_Validate_PECL) or be available for include_once() via a simple formula: Transform the underscores (_) into directory separators (/), append .php and include. A validation class named Foo_Bar_Baz should be available for inclusion via this code: <?php include_once 'Foo/Bar/Baz.php'; ?> In addition, the validation package must be available for installation from the channel with the version number to install specified by the $version parameter. Parameter string|FALSE $validateclass pass in FALSE to reset to the default packagename regex string $version The package version that must be installed for this channel to validate properly. Rückgabewert returns success Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::supports() PEAR_ChannelFile::supports() -- determines whether a webservices function is supported by a channel Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::supports (string $type, string [$name = NULL], string|false [$mirror = FALSE], string [$version = '1.0']) Beschreibung This is used in the installer to determine whether a protocol is supported before attempting to connect to a remote server and invoke the function needed. Parameter string $type protocol type (xmlrpc or soap) string $name function name (like package.info) string|FALSE $mirror Mirror server name or FALSE for primary server string $version function version Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::supportsREST() PEAR_ChannelFile::supportsREST() -- Determines whether a channel supports any Representational State Transfer (REST) resources Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::supportsREST (string [$mirror = FALSE]) Beschreibung This does not check to see which REST resources are supported, use getBaseURL() to check specific REST resource or resource group support. Parameter string|FALSE $mirror Mirror server name or FALSE for the primary server. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::toArray() PEAR_ChannelFile::toArray() -- return the channel representation in array format Synopsis require_once '/ChannelFile.php'; array PEAR_ChannelFile::toArray () Beschreibung This function should not be used to directly manipulate data, but instead as a means to serialize and transport the data in a more efficient manner than as the original xml. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::toXml() PEAR_ChannelFile::toXml() -- Return an XML document based on the internal representation of this channel Synopsis require_once '/ChannelFile.php'; string PEAR_ChannelFile::toXml () Beschreibung This should be used to generate a channel.xml based on the data stored in the PEAR_ChannelFile class. Rückgabewert returns XML data Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::validate() PEAR_ChannelFile::validate() -- Validate channel information. Synopsis require_once '/ChannelFile.php'; boolean PEAR_ChannelFile::validate () Beschreibung Specific errors can be retrieved post-validation with the getErrors() method. Errors are stored by the PEAR_ErrorStack class, more information on the format of the array can be found in the documentation for PEAR_ErrorStack. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_ChannelFile::validChannelServer() PEAR_ChannelFile::validChannelServer() -- Test whether a string contains a valid channel server. Synopsis require_once '/ChannelFile.php'; bool PEAR_ChannelFile::validChannelServer (string $server) Beschreibung determines whether a channel server is a valid servername. Parameter string $server Server name. May contain subpaths as in foo.example.com/path/to/channel Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann statisch aufgerufen werden. Package PEAR Constants Package PEAR Constants -- Constants defined in and used by PEAR All Constants Constants defined in ChannelFile.php Tabelle 27-1. Error Constants defined in ChannelFile.php Name Value Line Number PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER 4 48 PEAR_CHANNELFILE_ERROR_EMPTY_REGEX 24 97 PEAR_CHANNELFILE_ERROR_INVALID 23 93 PEAR_CHANNELFILE_ERROR_INVALID_HOST 11 81 PEAR_CHANNELFILE_ERROR_INVALID_MIRROR 21 85 PEAR_CHANNELFILE_ERROR_INVALID_MIRRORTYPE 22 89 PEAR_CHANNELFILE_ERROR_INVALID_NAME 7 65 PEAR_CHANNELFILE_ERROR_INVALID_PORT 33 122 PEAR_CHANNELFILE_ERROR_INVALID_SSL 37 138 PEAR_CHANNELFILE_ERROR_INVALID_VERSION 2 38 PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND 32 118 PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY 9 73 PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE 35 130 PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME 27 109 PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION 28 113 PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME 26 105 PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION 25 101 Name Value Line Number PEAR_CHANNELFILE_ERROR_NO_HOST 10 77 PEAR_CHANNELFILE_ERROR_NO_NAME 6 61 PEAR_CHANNELFILE_ERROR_NO_STATICVERSION 34 126 PEAR_CHANNELFILE_ERROR_NO_SUMMARY 8 69 PEAR_CHANNELFILE_ERROR_NO_VERSION 1 33 PEAR_CHANNELFILE_ERROR_NO_XML_EXT 3 43 PEAR_CHANNELFILE_ERROR_PARSER_ERROR 5 53 PEAR_CHANNELFILE_URI_CANT_MIRROR 36 134 PEAR_Command Inhaltsverzeichnis PEAR_Command::factory() -- get object for executing a command. PEAR_Command::getCommands() -- get list of currently supported commands PEAR_Command::getDescription() -- get description for a command PEAR_Command::getGetoptArgs() -- compiles arguments for getopt PEAR_Command::getHelp() -- get help for command PEAR_Command::getShortcuts() -- get list of command shortcuts. PEAR_Command::registerCommands() -- scan the command directory PEAR command class, a simple factory class for administrative commands. PEAR_Command::factory() PEAR_Command::factory() -- get object for executing a command. Synopsis require_once 'PEAR/command.php'; object PEAR_Command::factory (string $command, object &$config) Beschreibung Get the right object for executing a command. Parameter string $command The name of the command object &$config Instance of PEAR_Config object Rückgabewert object the command object Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::getCommands() PEAR_Command::getCommands() -- get list of currently supported commands Synopsis require_once 'PEAR/command.php'; array PEAR_Command::getCommands (void) Beschreibung Get the list of currently supported commands, and what classes implement them. Rückgabewert array command => implementing class Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::getDescription() PEAR_Command::getDescription() -- get description for a command Synopsis require_once 'PEAR/command.php'; string PEAR_Command::getDescription (string $command) Beschreibung Get description for a command. Parameter string $command Name of the command Rückgabewert string command description Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::getGetoptArgs() PEAR_Command::getGetoptArgs() -- compiles arguments for getopt Synopsis require_once 'PEAR/command.php'; void PEAR_Command::getGetoptArgs (string $command, string &$short_args, array &$long_args) Beschreibung Compiles arguments for getopt. Parameter string $command command to get optstring for string &$short_args (reference) short getopt format array &$long_args (reference) long getopt format Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Error code Error value Meaning Solution Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::getHelp() PEAR_Command::getHelp() -- get help for command Synopsis require_once 'PEAR/command.php'; string PEAR_Command::getHelp (string $command) Beschreibung Get help for command. Parameter string $command Name of the command to return help for Rückgabewert string help text Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::getShortcuts() PEAR_Command::getShortcuts() -- get list of command shortcuts. Synopsis require_once 'PEAR/command.php'; array PEAR_Command::getShortcuts (void) Beschreibung Get the list of command shortcuts. Rückgabewert array shortcut => command Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Command::registerCommands() PEAR_Command::registerCommands() -- scan the command directory Synopsis require_once 'PEAR/command.php'; bool PEAR_Command::registerCommands ([bool $merge = FALSE [, string $dir = NULL]]) Beschreibung Scan through the Command directory looking for classes and see what commands they implement. Parameter boolean $merge if FALSE (default), the new list of commands should replace the current one. If TRUE, new entries will be merged with old. string $dir where (what directory) to look for classes, defaults to the Command subdirectory of the directory from where this file (__FILE__) is included. Rückgabewert bool TRUE on success Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Common Inhaltsverzeichnis PEAR_Common::PEAR_Common() -- PEAR_Common constructor PEAR_Common::addTempFile() -- register a temporary file or directory PEAR_Common::analyzeSourceCode() -- analyze the source code of the given PHP file PEAR_Common::buildProvidesArray() -- Build a array PEAR_Common::downloadHttp() -- Download a file through HTTP PEAR_Common::infoFromAny() -- Returns package information from different sources PEAR_Common::infoFromDescriptionFile() -- Returns information about a package file PEAR_Common::infoFromString() -- Returns information about a package file PEAR_Common::infoFromTgzFile() -- Returns information about a package file PEAR_Common::log() -- Logging method PEAR_Common::mkDirHier() -- Create a directory and necessary parent directories PEAR_Common::mkTempDir() -- Create and register a temporary directory. PEAR_Common::setFrontendObject() -- Set object representing frontend to use. PEAR_Common::validatePackageInfo() -- Validate XML package definition file PEAR_Common::validPackageName() -- Test whether a string is a valid package name PEAR_Common::xmlFromInfo() -- Return an XML document based on the package info Class providing common functionality for PEAR administration classes. Class Trees for PEAR_Common() • PEAR • PEAR_Common PEAR_Common::PEAR_Common() PEAR_Common::PEAR_Common() -- PEAR_Common constructor Synopsis require_once 'PEAR/common.php'; void PEAR_Common::PEAR_Common (void) Beschreibung PEAR_Common constructor Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Common::addTempFile() PEAR_Common::addTempFile() -- register a temporary file or directory Synopsis require_once 'PEAR/common.php'; void PEAR_Common::addTempFile (string $file) Beschreibung Register a temporary file or directory. When the destructor is executed, all registered temporary files and directories are removed. Parameter string $file name of file or directory Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Common::analyzeSourceCode() PEAR_Common::analyzeSourceCode() -- analyze the source code of the given PHP file Synopsis require_once 'PEAR/common.php'; array PEAR_Common::analyzeSourceCode (string $file) Beschreibung Analyze the source code of the given PHP file Parameter string $file Filename of the PHP file Rückgabewert array - hash list of declared_classes, declared_methods, declared_functions and used_classes Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Common::buildProvidesArray() PEAR_Common::buildProvidesArray() -- Build a array Synopsis require_once 'PEAR/common.php'; void PEAR_Common::buildProvidesArray (array $srcinfo) Beschreibung Build a "provides" array from data returned by analyzeSourceCode(). The format of the built array is like this: array( 'class;MyClass' => array( 'type' => 'class', 'name' => 'MyClass' ), ... ) Parameter array $srcinfo array with information about a source file as returned by the analyzeSourceCode() method. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::downloadHttp() PEAR_Common::downloadHttp() -- Download a file through HTTP Synopsis require_once 'PEAR/common.php'; string PEAR_Common::downloadHttp (string $url, object &$ui [, string $save_dir = '.' [, mixed $callback = NULL]]) Beschreibung Download a file through HTTP. Considers suggested file name in Content-disposition: header and can run a callback function for different events. The callback will be called with two parameters: the callback type, and parameters. The implemented callback types are: • • • • 'setup' - called at the very beginning, parameter is a UI object that should be used for all output 'message' - the parameter is a string with an informational message 'saveas' - may be used to save with a different file name, the parameter is the filename that is about to be used. If a 'saveas' callback returns a non-empty string, that file name will be used as the filename instead. Note that $save_dir will not be affected by this, only the basename of the file. 'start' - download is starting, parameter is number of bytes that are expected, or -1 if unknown • 'bytesread' - parameter is the number of bytes read so far • 'done' - download is complete, parameter is the total number of bytes read • 'connfailed' - if the TCP connection fails, this callback is called with array(host,port,errno,errmsg) • 'writefailed' - if writing to disk fails, this callback is called with array(destfile,errmsg) If an HTTP proxy has been configured (http_proxy PEAR_Config setting), the proxy will be used. Parameter string $url the URL to download object &$ui PEAR_Frontend_* instance string $save_dir directory to save file in mixed $callback function/method to call for status updates object $config PEAR_Config instance Rückgabewert string - Returns the full path of the downloaded file or a PEAR error on failure. If the error is caused by socket-related errors, the error object will have the fsockopen error code available through getCode(). Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::infoFromAny() PEAR_Common::infoFromAny() -- Returns package information from different sources Synopsis require_once 'PEAR/common.php'; string PEAR_Common::infoFromAny (string $info) Beschreibung Returns package information from different sources. This method is able to extract information about a package from a .tgz archive or from a XML package definition file. Parameter string $info Filename of the source ('package.xml', '<package>.tgz') Rückgabewert string - Package information Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::infoFromDescriptionFile() PEAR_Common::infoFromDescriptionFile() -- Returns information about a package file Synopsis require_once 'PEAR/common.php'; array PEAR_Common::infoFromDescriptionFile (string $descfile) Beschreibung Returns information about a package file. Expects the name of a package xml file as input. Parameter string $descfile name of package xml file Rückgabewert array - array with package information Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::infoFromString() PEAR_Common::infoFromString() -- Returns information about a package file Synopsis require_once 'PEAR/common.php'; array PEAR_Common::infoFromString (string $data) Beschreibung Returns information about a package file. Expects the contents of a package xml file as input. Parameter string $data content of package xml file Rückgabewert array - array with package information Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::infoFromTgzFile() PEAR_Common::infoFromTgzFile() -- Returns information about a package file Synopsis require_once 'PEAR/common.php'; array PEAR_Common::infoFromTgzFile (string $file) Beschreibung Returns information about a package file. Expects the name of a gzipped tar file as input. Parameter string $file name of .tgz file Rückgabewert array - array with package information Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::log() PEAR_Common::log() -- Logging method Synopsis require_once 'PEAR/common.php'; void PEAR_Common::log (int $level, string $msg) Beschreibung Logging method. Parameter integer $level log level (0 is quiet, higher is noisier) string $msg message to write to the log Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::mkDirHier() PEAR_Common::mkDirHier() -- Create a directory and necessary parent directories Synopsis require_once 'common.php'; bool PEAR_Common::mkDirHier (string $dir) Beschreibung Wrapper to System::mkDir(), creates a directory as well as any necessary parent directories. Parameter string $dir directory name Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::mkTempDir() PEAR_Common::mkTempDir() -- Create and register a temporary directory. Synopsis require_once 'PEAR/common.php'; string PEAR_Common::mkTempDir (string [$tmpdir = '']) Beschreibung Create and register a temporary directory. Parameter string $tmpdir Directory to use as tmpdir. Will use system defaults (for example /tmp or c:\windows\temp) if not specified. Rückgabewert string name of created directory Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::setFrontendObject() PEAR_Common::setFrontendObject() -- Set object representing frontend to use. Synopsis require_once 'common.php'; void PEAR_Common::setFrontendObject (object &$ui) Beschreibung Set object that represents the frontend to be used. Parameter object $ui Reference of the frontend object Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::validatePackageInfo() PEAR_Common::validatePackageInfo() -- Validate XML package definition file Synopsis require_once 'common.php'; boolean PEAR_Common::validatePackageInfo (string $info, array &$errors, array &$warnings [, string $dir_prefix = '']) Beschreibung Validate XML package definition file. Parameter string $info Filename of the package archive or of the package definition file array $errors Array that will contain the errors array $warnings Array that will contain the warnings string $dir_prefix directory where source files may be found, or empty if they are not available Rückgabewert bool - TRUE if valid Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::validPackageName() PEAR_Common::validPackageName() -- Test whether a string is a valid package name Synopsis require_once 'PEAR/common.php'; bool PEAR_Common::validPackageName (string $name) Beschreibung Test whether a string contains a valid package name. Parameter string $name the package name to test Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Common::xmlFromInfo() PEAR_Common::xmlFromInfo() -- Return an XML document based on the package info Synopsis require_once 'PEAR/common.php'; string PEAR_Common::xmlFromInfo (array $pkginfo) Beschreibung Return an XML document based on the package info (as returned by the PEAR_Common::infoFrom*() methods). Parameter array $pkginfo package info Rückgabewert string - XML data Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config Inhaltsverzeichnis PEAR_Config::PEAR_Config() -- Constructor PEAR_Config::apiVersion() -- return API version (1.1 as of PEAR 1.4.0 PEAR_Config::definedBy() -- Tells what config layer that gets to define a key PEAR_Config::deleteChannel() -- deleteChannel PEAR_Config::get() -- Returns a configuration value PEAR_Config::getConfFile() -- Gets the file used for storing the config for a layer PEAR_Config::getDefaultChannel() -- Retrieve the default channel. PEAR_Config::getDocs() -- Get the documentation for a config value PEAR_Config::getFTP() -- The ftp server is set in readFTPConfigFile(). It exists only if a remote configuration file has been specified PEAR_Config::getGroup() -- Get the parameter group for a config key PEAR_Config::getGroupKeys() -- Get the list of the parameters in a group PEAR_Config::getGroups() -- Get the list of parameter groups PEAR_Config::getKeys() -- Get all the current config keys PEAR_Config::getLayers() -- Returns the layers defined PEAR_Config::getPrompt() -- Get short documentation for a config value PEAR_Config::getRegistry() -- getRegistry PEAR_Config::getRemote() -- getRemote PEAR_Config::getREST() -- getREST PEAR_Config::getSetValues() -- Get the list of allowed set values for a config value PEAR_Config::getType() -- Get the type of a config value PEAR_Config::isDefined() -- Tells whether a key exists as config value PEAR_Config::isDefinedLayer() -- Tells whether a config layer exists PEAR_Config::mergeConfigFile() -- Merges data into a config layer from a file PEAR_Config::noRegistry() -- noRegistry PEAR_Config::readConfigFile() -- Reads configuration data from a file PEAR_Config::readFTPConfigFile() -- readFTPConfigFile PEAR_Config::remove() -- Remove a config key from a config layer PEAR_Config::removeLayer() -- Temporarily remove an entire config layer PEAR_Config::set() -- Set config value in specific layer PEAR_Config::setChannels() -- Set the list of channels. PEAR_Config::setInstallRoot() -- setInstallRoot PEAR_Config::setRegistry() -- This is to allow customization like the use of installroot PEAR_Config::singleton() -- Return a reference of a PEAR_Config object PEAR_Config::store() -- Stores configuration data in a layer PEAR_Config::toDefault() -- Revert value of config key to the system-defined one PEAR_Config::validConfiguration() -- Determine whether any configuration files have been detected, and whether a registry object can be retrieved from this configuration. PEAR_Config::writeConfigFile() -- Write data into config layer from file Class Trees for PEAR_Config() • PEAR • PEAR_Config PEAR_Config::PEAR_Config() PEAR_Config::PEAR_Config() -- Constructor Synopsis require_once 'PEAR/config.php'; void PEAR_Config::PEAR_Config ([string $user_file = '' [, string $system_file = '']]) Beschreibung Constructor Parameter string $user_file file to read user-defined options from string $system_file file to read system-wide defaults from Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::apiVersion() PEAR_Config::apiVersion() -- return API version (1.1 as of PEAR 1.4.0 Synopsis require_once '/Config.php'; (since PEAR 1.4.0) void PEAR_Config::apiVersion () Beschreibung Returns the Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::definedBy() PEAR_Config::definedBy() -- Tells what config layer that gets to define a key Synopsis require_once 'PEAR/config.php'; string PEAR_Config::definedBy (string $key) Beschreibung Tells what config layer that gets to define a key. Parameter string $key config key Rückgabewert string - the config layer, or an empty string if not found Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::deleteChannel() PEAR_Config::deleteChannel() -- deleteChannel Synopsis require_once '/Config.php'; (since PEAR 1.4.0) void PEAR_Config::deleteChannel (string $channel) Beschreibung remove a channel's configuration entirely. Parameter string $channel Channel name to delete (channel server). Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::get() PEAR_Config::get() -- Returns a configuration value Synopsis require_once 'PEAR/config.php'; mixed PEAR_Config::get (string $key [, mixed $layer = NULL]) Beschreibung Returns a configuration value, prioritizing layers as per the layers property. Parameter string $key config key mixed $layer layer key Rückgabewert mixed the config value, or NULL if not found Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getConfFile() PEAR_Config::getConfFile() -- Gets the file used for storing the config for a layer Synopsis require_once '/Config.php'; (since PEAR 1.4.0) void PEAR_Config::getConfFile (string $layer) Beschreibung Use this to retrieve the name of the configuration file that provides values for a particular configuration layer. Parameter string $layer user, system, or ftp Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getDefaultChannel() PEAR_Config::getDefaultChannel() -- Retrieve the default channel. Synopsis require_once '/Config.php'; (since PEAR 1.4.0) string|false PEAR_Config::getDefaultChannel ([string $layer = NULL]) Beschreibung On startup, channels are not initialized, so if the default channel is not pear.php.net, then initialize the config. Parameter string $layer layer from which to retrieve the registry, or null for the first to match Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getDocs() PEAR_Config::getDocs() -- Get the documentation for a config value Synopsis require_once 'PEAR/config.php'; string PEAR_Config::getDocs (string $key) Beschreibung Get the documentation for a config value. Parameter string $key config key Rückgabewert string - documentation string Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getFTP() PEAR_Config::getFTP() -- The ftp server is set in readFTPConfigFile(). It exists only if a remote configuration file has been specified Synopsis require_once '/Config.php'; (since PEAR 1.4.0) PEAR_FTP|false& PEAR_Config::getFTP () Beschreibung returns the object that can be used for accessing the remote FTP server, or false if none should be used. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getGroup() PEAR_Config::getGroup() -- Get the parameter group for a config key Synopsis require_once 'PEAR/config.php'; string PEAR_Config::getGroup (string $key) Beschreibung Get the parameter group for a config key. Parameter string $key config key Rückgabewert string - parameter group Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getGroupKeys() PEAR_Config::getGroupKeys() -- Get the list of the parameters in a group Synopsis require_once 'PEAR/config.php'; array PEAR_Config::getGroupKeys (string $group) Beschreibung Get the list of the parameters in a group. Parameter string $group parameter group Rückgabewert array list of parameters in $group Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getGroups() PEAR_Config::getGroups() -- Get the list of parameter groups Synopsis require_once 'PEAR/config.php'; array PEAR_Config::getGroups (void) Beschreibung Get the list of parameter groups. Rückgabewert array - list of parameter groups Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getKeys() PEAR_Config::getKeys() -- Get all the current config keys Synopsis require_once 'PEAR/config.php'; array PEAR_Config::getKeys (void) Beschreibung Get all the current config keys Rückgabewert array - simple array of config keys Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getLayers() PEAR_Config::getLayers() -- Returns the layers defined Synopsis require_once 'PEAR/config.php'; array PEAR_Config::getLayers (void) Beschreibung Returns the layers defined, except the 'default' one Rückgabewert array the defined layers Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getPrompt() PEAR_Config::getPrompt() -- Get short documentation for a config value Synopsis require_once 'PEAR/config.php'; string PEAR_Config::getPrompt (string $key) Beschreibung Get the short documentation for a config value. Parameter string $key config key Rückgabewert string short documentation string Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getRegistry() PEAR_Config::getRegistry() -- getRegistry Synopsis require_once '/Config.php'; (since PEAR 1.4.0) PEAR_Registry|false& PEAR_Config::getRegistry ([string $use = NULL]) Beschreibung Dieses Package ist noch nicht dokumentiert. Parameter string $use This parameter determines which layer will be used to retrieve a registry based on the php_dir configuration variable for that layer. The default value of null will use the first layer that contains a valid php_dir, whereas if specified as user, system or ftp, it will attempt to return the registry for that layer. On failure to retrieve a registry, it returns false Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getRemote() PEAR_Config::getRemote() -- getRemote Synopsis require_once '/Config.php'; (since PEAR 1.4.0) PEAR_Remote& PEAR_Config::getRemote () Beschreibung This returns a PEAR_Remote based on the current PEAR_Config object. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getREST() PEAR_Config::getREST() -- getREST Synopsis require_once '/Config.php'; PEAR_REST& PEAR_Config::getREST (string $version [, array $options = array()]) Beschreibung Dieses Package ist noch nicht dokumentiert. Parameter string $version This should be 1.0 in PEAR 1.4.0. array $options options for the PEAR_REST constructor Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getSetValues() PEAR_Config::getSetValues() -- Get the list of allowed set values for a config value Synopsis require_once 'PEAR/config.php'; array PEAR_Config::getSetValues (string $key) Beschreibung Get the list of allowed set values for a config value. Returns NULL for config values that are not sets. Parameter string $key config key Rückgabewert array - enumerated array of set values, or NULL if the config key is unknown or not a set Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::getType() PEAR_Config::getType() -- Get the type of a config value Synopsis require_once 'PEAR/config.php'; string PEAR_Config::getType (string $key) Beschreibung Get the type of a config value. Parameter string $key config key Rückgabewert string - type, one of „string“, „integer“, „file“, „directory“, „set“ or „password“. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::isDefined() PEAR_Config::isDefined() -- Tells whether a key exists as config value Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::isDefined (string $key) Beschreibung Tells whether a given key exists as a config value. Parameter string $key config key Rückgabewert bool - whether $key exists in this object Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::isDefinedLayer() PEAR_Config::isDefinedLayer() -- Tells whether a config layer exists Synopsis require_once 'config.php'; bool PEAR_Config::isDefinedLayer (string $layer) Beschreibung Tells whether a given config layer exists. Parameter string $layer config layer Rückgabewert bool - whether $layer exists in this object Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::mergeConfigFile() PEAR_Config::mergeConfigFile() -- Merges data into a config layer from a file Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::mergeConfigFile (string $file [, bool $override = TRUE [, string $layer = 'user']]) Beschreibung Merges data into a config layer from a file. Does the same thing as readConfigFile(), except it does not replace all existing values in the config layer. Parameter string $file file to read from boolean $override whether to overwrite existing data string $layer config layer to insert data into ('user' or 'system') Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::noRegistry() PEAR_Config::noRegistry() -- noRegistry Synopsis require_once '/Config.php'; (since PEAR 1.4.0) void PEAR_Config::noRegistry () Beschreibung Use this method to disable automatic creation of PEAR_Registry objects when reading from a configuration file or changing php_dir configuration variable. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::readConfigFile() PEAR_Config::readConfigFile() -- Reads configuration data from a file Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::readConfigFile ([string $file = NULL [, string $layer = 'user']]) Beschreibung Reads configuration data from a file. All existing values in the config layer are discarded and replaced with data from the file. Parameter string $file file to read from, if NULL or not specified, the last-used file for the same layer (second param) is used string $layer config layer to insert data into ('user' or 'system') Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::readFTPConfigFile() PEAR_Config::readFTPConfigFile() -- readFTPConfigFile Synopsis require_once '/Config.php'; (since PEAR 1.4.0) true|PEAR_Error PEAR_Config::readFTPConfigFile (string $path) Beschreibung Process a ftp configuration file by connecting to the server, retrieving the configuration file and parsing it normally. This function uses Net_FTP through the PEAR_FTP class. Parameter string $path url to the remote config file, like ftp://www.example.com/pear/config.ini Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::remove() PEAR_Config::remove() -- Remove a config key from a config layer Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::remove (string $key [, string $layer = 'user']) Beschreibung Remove a config key from a specific config layer. Parameter string $key config key string $layer config layer Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::removeLayer() PEAR_Config::removeLayer() -- Temporarily remove an entire config layer Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::removeLayer (string $layer) Beschreibung Temporarily remove an entire config layer. USE WITH CARE! Parameter string $layer config key Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::set() PEAR_Config::set() -- Set config value in specific layer Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::set (string $key, string $value [, string $layer = 'user']) Beschreibung Set a config value in a specific layer (defaults to 'user'). Enforces the types defined in the configuration_info array. An integer config variable will be cast to int, and a set config variable will be validated against its legal values. Parameter string $key config key string $value config value string $layer config layer Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::setChannels() PEAR_Config::setChannels() -- Set the list of channels. Synopsis require_once '/Config.php'; (since PEAR 1.4.0) bool PEAR_Config::setChannels (array $channels [, bool $merge = FALSE]) Beschreibung This should be set via a call to PEAR_Registry::listChannels(). A call to this function sets up empty arrays for each channel in configurations. Parameter array $channels a simple list of channel names. boolean $merge if true, then the list of channel is merged with the existing list, otherwise it replaces the existing list. Rückgabewert returns success of operation Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::setInstallRoot() PEAR_Config::setInstallRoot() -- setInstallRoot Synopsis require_once '/Config.php'; (since PEAR 1.4.0) void PEAR_Config::setInstallRoot (string|false $root) Beschreibung This is used to implement the --installroot option for installation. In earlier PEAR versions, this was implemented in PEAR_Installer::install(), but this makes it more difficult to track with the introduction of channels, and to satisfy better encapsulation, it has been moved to PEAR_Config. Pass in a full path. On retrieving any directory configuration variable, the value will be prepended with the installroot specified in this method. For example, if php_dir is /usr/lib/php, and setInstallRoot() is used with /hoopla/boo, the value returned from get() would be /hoopla/boo/usr/lib/php. Use an empty string '' to reset an installroot. Parameter string|FALSE $root installation directory to prepend to all _dir variables, or FALSE to disable Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::setRegistry() PEAR_Config::setRegistry() -- This is to allow customization like the use of installroot Synopsis require_once '/Config.php'; (since PEAR 1.4.0) bool PEAR_Config::setRegistry (PEAR_Registry|false &$reg [, string $layer = 'user']) Beschreibung Use this to override the automatic registry creation performed whenever the php_dir configuration variable is modified. If noRegistry() has been called, this call will be ignored and FALSE returned. In addition, it is not possible to set the registry for the ftp layer. Parameter PEAR_Registry|false &$reg The PEAR_Registry that will be used, or false to reset the registry. string $layer This must be either user or system Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::singleton() PEAR_Config::singleton() -- Return a reference of a PEAR_Config object Synopsis require_once 'PEAR/config.php'; object &PEAR_Config::singleton ([string $user_file = '' [, string $system_file = '']]) Beschreibung If you want to keep only one instance of this class in use, this method will give you a reference to the last created PEAR_Config object if one exists, or create a new object. Parameter string $user_file file to read user-defined options from string $system_file file to read system-wide defaults from Rückgabewert object - an existing or new PEAR_Config instance Siehe auch PEAR_Config::PEAR_Config() Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Config::store() PEAR_Config::store() -- Stores configuration data in a layer Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::store ([string $layer = 'user']) Beschreibung Stores configuration data in a layer. Parameter string $layer config layer to store Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::toDefault() PEAR_Config::toDefault() -- Revert value of config key to the system-defined one Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::toDefault (string $key) Beschreibung Unset the user-defined value of a config key, reverting the value to the system-defined one. Parameter string $key config key Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::validConfiguration() PEAR_Config::validConfiguration() -- Determine whether any configuration files have been detected, and whether a registry object can be retrieved from this configuration. Synopsis require_once '/Config.php'; (since PEAR 1.4.0) bool PEAR_Config::validConfiguration () Beschreibung This method can be used to ward off any real problems with the default configuration. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Config::writeConfigFile() PEAR_Config::writeConfigFile() -- Write data into config layer from file Synopsis require_once 'PEAR/config.php'; bool PEAR_Config::writeConfigFile ([string $file = NULL [, bool $layer = 'user']]) Beschreibung Writes data into a config layer from a file. Parameter string $file file to read from boolean $layer whether to overwrite existing data Rückgabewert bool - Gibt bei Erfolg TRUE zurück, bei einem Fehler ein Objekt der Klasse PEAR_Error. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency Inhaltsverzeichnis PEAR_Dependency::PEAR_Dependency() -- constructor PEAR_Dependency::callCheckMethod() -- Maps the xml dependency definition PEAR_Dependency::checkExtension() -- Check Extension dependency PEAR_Dependency::checkOS() -- Check Operating system dependency PEAR_Dependency::checkPackage() -- check Package dependency PEAR_Dependency::checkPHP() -- Check PHP version PEAR_Dependency::checkProgram() -- Check external program PEAR_Dependency::checkSAPI() -- Check SAPI backend PEAR_Dependency::checkZend() -- Check Zend version This class is deprecated by PEAR_Dependency2 in PEAR 1.4.0 PEAR_Dependency::PEAR_Dependency() PEAR_Dependency::PEAR_Dependency() -- constructor Synopsis require_once 'PEAR/Dependency.php'; void PEAR_Dependency::PEAR_Dependency (object &$registry) Beschreibung Constructor Parameter object &$registry a PEAR_Registry instance Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::callCheckMethod() PEAR_Dependency::callCheckMethod() -- Maps the xml dependency definition Synopsis require_once 'PEAR/Dependency.php'; void PEAR_Dependency::callCheckMethod (mixed &$errmsg, array $opts) Beschreibung This method maps the xml dependency definition to the PEAR_Dependency one. Parameter mixed &$errmsg this variable will contains an error message, if check fail array $opts An Array with all Dependency entries from the parsed XML package definition, ie: $opts => Array ( ['type'] => 'pkg', ['rel'] => 'ge', ['version'] => '3.4', ['name'] => 'HTML_Common' ); Rückgabewert mixed - FALSE if all dependencies could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependencies. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkExtension() PEAR_Dependency::checkExtension() -- Check Extension dependency Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkExtension (mixed &$errmsg, string $name [, string $req = NULL [, string $relation = 'has']]) Beschreibung Extension dependencies check method Parameter mixed &$errmsg this variable will contains an error message, if check fail string $name Name of the extension to test string $req Required extension version to compare with string $relation How to compare versions with eachother Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of an unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkOS() PEAR_Dependency::checkOS() -- Check Operating system dependency Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkOS (string &$errmsg, string $os) Beschreibung Operating system dependencies check method Parameter string &$errmsg this variable will contains an error message, if check fail string $os Name of the operating system Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkPackage() PEAR_Dependency::checkPackage() -- check Package dependency Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkPackage (mixed &$errmsg, string $name [, string $req = NULL [, string $relation = 'has']]) Beschreibung Package dependencies check method Parameter string &$errmsg this variable will contains an error message, if check fail string $name Name of the package to test string $req Required extension version to compare with string $relation How to compare versions with eachother Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkPHP() PEAR_Dependency::checkPHP() -- Check PHP version Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkPHP (mixed &$errmsg, string $req [, string $relation = 'ge']) Beschreibung PHP version check method Parameter mixed &$errmsg this variable will contains an error message, if check fail string $req which version to compare string $relation how to compare the version Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkProgram() PEAR_Dependency::checkProgram() -- Check external program Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkProgram (mixed &$errmsg, string $program) Beschreibung External program check method. Looks for executable files in directories listed in the PATH environment variable. Parameter mixed &$errmsg this variable will contains an error message, if check fail string $program which program to look for Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkSAPI() PEAR_Dependency::checkSAPI() -- Check SAPI backend Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkSAPI (mixed &$errmsg, string $name [, string $req = NULL [, string $relation = 'has']]) Beschreibung SAPI backend check method. Version comparison is not yet available here. Parameter mixed &$errmsg this variable will contains an error message, if check fail string $name name of SAPI backend string $req which version to compare (currently unused) string $relation how to compare versions (currently hardcoded to 'has') Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency::checkZend() PEAR_Dependency::checkZend() -- Check Zend version Synopsis require_once 'PEAR/Dependency.php'; mixed PEAR_Dependency::checkZend (mixed &$errmsg, string $req, string ''}[$relation = 'ge']) Beschreibung Zend version check method Parameter mixed &$errmsg this variable will contains an error message, if check fail string $req which version to compare string $relation how to compare the version Rückgabewert mixed - FALSE if dependency could be resolved successfully(!); or an PEAR_DEPENDENCY_* constant in case of unresolved dependency. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2 Inhaltsverzeichnis Class Summary PEAR_Dependency2 -- Dependency check for PEAR packages constructor PEAR_Dependency2::PEAR_Dependency2() -- PEAR_Dependency2 PEAR_Dependency2::normalizeDep() -- Convert a 1.0 dep into a 2.0 dep PEAR_Dependency2::validateArchDependency() -- Specify a complex dependency on an OS/processor/kernel version, Use OS for simple operating system dependency. PEAR_Dependency2::validateDependency1() -- validate a package.xml 1.0 dependency PEAR_Dependency2::validateExtensionDependency() -- validate a dependency on a PHP extension PEAR_Dependency2::validateOsDependency() -- Specify a dependency on an OS. Use arch for detailed os/processor information PEAR_Dependency2::validatePackage() -- validatePackage PEAR_Dependency2::validatePackageDependency() -- validatePackageDependency PEAR_Dependency2::validatePackageUninstall() -- validatePackageUninstall PEAR_Dependency2::validatePearinstallerDependency() -- validatePearinstallerDependenc y PEAR_Dependency2::validatePhpDependency() -- validatePhpDependency PEAR_Dependency2::validateSubpackageDependency() -- validateSubpackageDependency Class Summary PEAR_Dependency2 Class Summary PEAR_Dependency2 -- Dependency check for PEAR packages Dependency check for PEAR packages This class handles both version 1.0 and 2.0 dependencies and supersedes PEAR_Dependency since PEAR 1.4.0 Class Trees for PEAR_Dependency2 • PEAR_Dependency2 constructor PEAR_Dependency2::PEAR_Dependency2() constructor PEAR_Dependency2::PEAR_Dependency2() -- PEAR_Dependency2 Synopsis require_once '/Dependency2.php'; void constructor PEAR_Dependency2::PEAR_Dependency2 (PEAR_Config &$config, array $installoptions, array $package, int [$state = PEAR_VALIDATE_INSTALLING]) Beschreibung Dieses Package ist noch nicht dokumentiert. Parameter PEAR_Config &$config Current configuration object. array $installoptions installation options array $package The current package. For installation dependencies, this is the package that contains dependencies. For uninstallation dependencies, this is the package that is going to be uninstalled. format of PEAR_Registry::parsedPackageName() integer $state installation state (one of PEAR_VALIDATE_*) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::normalizeDep() PEAR_Dependency2::normalizeDep() -- Convert a 1.0 dep into a 2.0 dep Synopsis require_once '/Dependency2.php'; array PEAR_Dependency2::normalizeDep (array $dep) Beschreibung This converts an old-style package.xml 1.0 <dep> tag into the format used by package.xml 2.0. package.xml 2.0 can represent every kind of <dep> tag in its new syntax. Parameter array $dep The package.xml 1.0 <dep> as parsed from xml. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validateArchDependency() PEAR_Dependency2::validateArchDependency() -- Specify a complex dependency on an OS/processor/kernel version, Use OS for simple operating system dependency. Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validateArchDependency (array $dep) Beschreibung This is the only dependency that accepts an ereg()able pattern. The pattern will be matched against the php_uname() output parsed by OS_Guess As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the arch dependency is required). If the soft, force or ignore-errors options are specified, an array containing the error message will be returned instead. Parameter array $dep Contents of the dependency, as parsed from xml. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validateDependency1() PEAR_Dependency2::validateDependency1() -- validate a package.xml 1.0 dependency Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validateDependency1 (array $dep, array [$params = array()]) Beschreibung Validate a package.xml version 1.0 <dep> dependency. Parameter array $dep The contents of the <dep> tag as parsed from xml array $params The list of PEAR_Downloader_Package objects that will be installed. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validateExtensionDepende ncy() PEAR_Dependency2::validateExtensionDependency() -- validate a dependency on a PHP extension Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validateExtensionDependency (array $dep, bool [$required = true]) Beschreibung This validates against actual in-memory extensions, and will not attempt to locate extensions on disk. To do this, a dependency should be a package dependency with the <providesextension> tag. As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies. If the soft, force or ignore-errors options are specified, an array containing the error message will be returned instead. Parameter array $dep dependency contents as parsed from xml boolean $required Whether this is a required or optional dependency Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validateOsDependency() PEAR_Dependency2::validateOsDependency() -- Specify a dependency on an OS. Use arch for detailed os/processor information Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validateOsDependency (array $dep) Beschreibung There are two generic OS dependencies that will be the most common, unix and windows. Other options are linux, freebsd, darwin (OS X), sunos, irix, hpux, aix. As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the OS dependency is required). If the soft, force or ignoreerrors options are specified, an array containing the error message will be returned instead. Parameter array $dep Dependency contents as parsed from xml Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validatePackage() PEAR_Dependency2::validatePackage() -- validatePackage Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validatePackage (array| PEAR_PackageFile_v2|PEAR_Downloader_Package $pkg, PEAR_Common &$dl) Beschreibung As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the PEAR installer dependency is required). If the soft, force or ignore-errors options are specified, an array containing the error message will be returned instead. Parameter array|PEAR_PackageFile_v2|PEAR_Downloader_Package $pkg Either an array of format array('channel' => channelname, 'package' => package) or one of these objects. PEAR_Common &$dl Any object with a log() method that matches the signature of PEAR_Common Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validatePackageDependen cy() PEAR_Dependency2::validatePackageDependency() -- validatePackageDependency Synopsis require_once '/Dependency2.php'; array|true|PEAR_Error PEAR_Dependency2::validatePackageDependency (array $dep, boolean $required, array $params, bool [$depv1 = FALSE]) Beschreibung Validate a package-style dependency. Validation is performed in this sequence: 1. If the dependency package provides an extension through the <providesextension> tag, then see if it passes the extension validation test first and return if so. 2. If the list of packages to be installed contains a match for the dependency, use that to validate the dependency and return. 3. If the dependency package is already installed, make sure the installed version passes the conditions. 4. At this point, the dependency has failed. If the dependency is required, return a PEAR_Error containing the failure error message, otherwise return an array containing the error message. Parameter array $dep dependency array as defined by package.xml 2.0 boolean $required whether this is a required or optional dependency array $params array of PEAR_Downloader_Package objects representing packages to be downloaded that can be used to validate dependencies boolean $depv1 if TRUE, then deps on pear.php.net that fail will also check against pecl.php.net packages to accomodate extensions that have moved to pecl.php.net from pear.php.net Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validatePackageUninstall() PEAR_Dependency2::validatePackageUninstall() -- validatePackageUninstall Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validatePackageUninstall (PEAR_Installer &$dl) Beschreibung As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the PEAR installer dependency is required). If the soft, force or ignore-errors options are specified, an array containing the error message will be returned instead. Parameter PEAR_Installer &$dl This method retrieves the list of packages to be uninstalled from the PEAR_Installer object, and makes sure no dependencies with existing packages would be broken if the current package were to be uninstalled. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validatePearinstallerDepen dency() PEAR_Dependency2::validatePearinstallerDependency() -- validatePearinstallerDependency Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validatePearinstallerDependency (array $dep) Beschreibung Validate the running PEAR version against the dependency. This dependency is designed to prevent PEAR versions incompatible with the current package.xml from attempting to install it. As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the PEAR installer dependency is required). If the soft, force or ignore-errors options are specified, an array containing the error message will be returned instead. Parameter mixed $dep Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validatePhpDependency() PEAR_Dependency2::validatePhpDependency() -- validatePhpDependency Synopsis require_once '/Dependency2.php'; true|PEAR_Error|array PEAR_Dependency2::validatePhpDependency (array $dep) Beschreibung Validate the running PHP version against the dependency. The implicit assumption is that the installer's PHP version is the same as the final script's PHP version. As with all dependency validation, true is returned on success, PEAR_Error on failure for required dependencies (and the PHP dependency is required). If the soft, force or ignoreerrors options are specified, an array containing the error message will be returned instead. Parameter array $dep The dependency xml as represented in parsing Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Dependency2::validateSubpackageDepen dency() PEAR_Dependency2::validateSubpackageDependency() -- validateSubpackageDependency Synopsis require_once '/Dependency2.php'; array|true|PEAR_Error PEAR_Dependency2::validateSubpackageDependency (array $dep, bool $required, array $params) Beschreibung Validate a subpackage-style dependency. This is identical to a package dependency from a validation perspective, and so documentation for validatePackageDependency() should be referenced for details. Parameter array $dep dependency array as defined by package.xml 2.0 boolean $required whether this is a required or optional dependency array $params array of PEAR_Downloader_Package objects representing packages to be downloaded that can be used to validate dependencies Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB Inhaltsverzeichnis Class Summary PEAR_DependencyDB -- Track dependency relationships between installed packages PEAR_DependencyDB::assertDepsDB() -- Create the dependency database, if it doesn't exist. Error if the database is newer than the code reading it. PEAR_DependencyDB::dependsOn() -- Determine whether $parent depends on $child, near or deep PEAR_DependencyDB::getDependencies() -- Get a list of dependencies of this installed package PEAR_DependencyDB::getDependentPackageDependencies() -- Get a list of the actual dependencies of installed packages that depend on a package. PEAR_DependencyDB::getDependentPackages() -- Get a list of installed packages that depend on this package PEAR_DependencyDB::hasWriteAccess() -- determines whether a dependency DB can be modified PEAR_DependencyDB::installPackage() -- Register dependencies of a package that is being installed or upgraded PEAR_DependencyDB::rebuildDB() -- Rebuild the dependency DB by reading registry entries. PEAR_DependencyDB::setConfig() -- Set up the registry/location of dependency DB PEAR_DependencyDB::singleton() -- Get a raw dependency database. Calls setConfig() and assertDepsDB() PEAR_DependencyDB::uninstallPackage() -- Remove dependencies of a package that is being uninstalled, or upgraded. Class Summary PEAR_DependencyDB Class Summary PEAR_DependencyDB -- Track dependency relationships between installed packages Track dependency relationships between installed packages This provides sophisticated dependency handling relationships between installed packages and downloaded to-be-installed packages. Class Trees for PEAR_DependencyDB • PEAR_DependencyDB PEAR_DependencyDB::assertDepsDB() PEAR_DependencyDB::assertDepsDB() -- Create the dependency database, if it doesn't exist. Error if the database is newer than the code reading it. Synopsis require_once '/DependencyDB.php'; void|PEAR_Error PEAR_DependencyDB::assertDepsDB () Beschreibung Assert that the dependency database exists, and attempt to create it if it doesn't. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::dependsOn() PEAR_DependencyDB::dependsOn() -- Determine whether $parent depends on $child, near or deep Synopsis require_once '/DependencyDB.php'; void PEAR_DependencyDB::dependsOn (array|PEAR_PackageFile_v2| PEAR_PackageFile_v2 $parent, array|PEAR_PackageFile_v2| PEAR_PackageFile_v2 $child) Beschreibung This method is the central method of DependencyDB. Through the dependency database, it is possible to determine whether any two packages share a dependency relationship independent of how tightly bound the two packages are. In other words, if package A depends on package B depends on package C, this method can be used to determine that package A indirectly depends on package C. Parameter array|PEAR_PackageFile_v2|PEAR_PackageFile_v2 $parent The parent package (as in package A in the example above) This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> array|PEAR_PackageFile_v2|PEAR_PackageFile_v2 $child The child package (as in package B or package C in the example above) This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::getDependencies() PEAR_DependencyDB::getDependencies() -- Get a list of dependencies of this installed package Synopsis require_once '/DependencyDB.php'; array|false PEAR_DependencyDB::getDependencies (PEAR_PackageFile_v1| PEAR_PackageFile_v2|array &$pkg) Beschreibung get an array of all immediate package dependencies of an installed package. Parameter PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::getDependentPackageDe pendencies() PEAR_DependencyDB::getDependentPackageDependencies() -- Get a list of the actual dependencies of installed packages that depend on a package. Synopsis require_once '/DependencyDB.php'; array|false PEAR_DependencyDB::getDependentPackageDependencies (PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg) Beschreibung This returns the complete tree of extended dependencies of a single installed package. For instance, a real-world example. package SOAP depends on Mail_Mime, HTTP_Request, Net_URL, Net_DIME. package HTTP_Request depends on Net_URL, Net_Socket. This method will return an array similar to: <?php array( 'pear.php.net' => array( 'mail_mime' => array('name' => 'Mail_Mime', 'channel' => 'pear.php.net'), 'http_request' => array('name' => 'HTTP_Request', 'channel' => 'pear.php.net'), 'net_url' => array('name' => 'Net_URL', 'channel' => 'pear.php.net', 'min' => '1.0.12'), 'net_dime' => array('name' => 'Net_DIME', 'channel' => 'pear.php.net'), 'net_socket' => array('name' => 'Net_Socket', 'channel' => 'pear.php.net'), ), ); ?> Note that this should not be relied upon for exact dependencies. In the example above, the returned dependency will be that of HTTP_Request upon Net_URL, which is stricter than SOAP's dependency upon Net_URL. In other words, if there are two similar dependencies, the last one encountered will be returned. Parameter PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::getDependentPackages() PEAR_DependencyDB::getDependentPackages() -- Get a list of installed packages that depend on this package Synopsis require_once '/DependencyDB.php'; array|false PEAR_DependencyDB::getDependentPackages (PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg) Beschreibung This is most useful at uninstall-time. A list of installed packages that depend upon the package can be used to prevent uninstallation, and to emit warnings for optional dependencies. Parameter PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::hasWriteAccess() PEAR_DependencyDB::hasWriteAccess() -- determines whether a dependency DB can be modified Synopsis require_once '/DependencyDB.php'; bool PEAR_DependencyDB::hasWriteAccess () Beschreibung This method is used by the installer to prevent attempts to create/modify the dependency DB if the current user does not have write access to the registry. Without this method, simple read-only commands like pear info would not work. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::installPackage() PEAR_DependencyDB::installPackage() -- Register dependencies of a package that is being installed or upgraded Synopsis require_once '/DependencyDB.php'; void PEAR_DependencyDB::installPackage (PEAR_PackageFile_v2| PEAR_PackageFile_v2 &$package) Beschreibung This method is used by the registry when a package is installed or upgraded to register the package's dependencies in the dependency database. Parameter PEAR_PackageFile_v2|PEAR_PackageFile_v2 &$package This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::rebuildDB() PEAR_DependencyDB::rebuildDB() -- Rebuild the dependency DB by reading registry entries. Synopsis require_once '/DependencyDB.php'; true|PEAR_Error PEAR_DependencyDB::rebuildDB () Beschreibung This is used to create or re-create the dependency database by reading registry entries for each installed file to extract dependencies and save them in the dependency database. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::setConfig() PEAR_DependencyDB::setConfig() -- Set up the registry/location of dependency DB Synopsis require_once '/DependencyDB.php'; void PEAR_DependencyDB::setConfig (PEAR_Config|false &$config, string|false [$depdb = FALSE]) Beschreibung This crucial method is used to set the PEAR_Config object that should be used to retrieve both configuration information and a PEAR_Registry class for internal manipulation. Parameter PEAR_Config|FALSE &$config string|FALSE $depdb full path to the dependency database, or FALSE to use default Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_DependencyDB::singleton() PEAR_DependencyDB::singleton() -- Get a raw dependency database. Calls setConfig() and assertDepsDB() Synopsis require_once '/DependencyDB.php'; PEAR_DependencyDB |PEAR_Error & PEAR_DependencyDB::singleton (PEAR_Config &$config, string|false [$depdb = FALSE]) Beschreibung Return a single dependency database based on the location of the database on disk. In other words, 1 dependency database is created for each registry location. Parameter PEAR_Config &$config PEAR_Config object string|$false; $depdb full path to the dependency database, or FALSE to use default Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_DependencyDB::uninstallPackage() PEAR_DependencyDB::uninstallPackage() -- Remove dependencies of a package that is being uninstalled, or upgraded. Synopsis require_once '/DependencyDB.php'; void PEAR_DependencyDB::uninstallPackage (PEAR_PackageFile_v1| PEAR_PackageFile_v2|array &$pkg) Beschreibung This method is used by the registry when a package is uninstalled or upgraded to remove the package's dependencies from the dependency database. Upgraded packages first uninstall, then install Parameter PEAR_PackageFile_v1|PEAR_PackageFile_v2|array &$pkg This parameter, if an array, should be in format: <?php array( 'package' => 'packagename', 'channel' => 'channelname' ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Frontend Inhaltsverzeichnis Class Summary PEAR_Frontend -- Singleton-based frontend for PEAR user input/output PEAR_Frontend::addTempFile() -- This can be overridden to allow session-based temporary file management PEAR_Frontend::isIncludeable() -- isIncludeable PEAR_Frontend::log() -- log PEAR_Frontend::setConfig() -- setConfig PEAR_Frontend::setFrontendClass() -- setFrontendClass PEAR_Frontend::singleton() -- Retrieve the frontend object Class Summary PEAR_Frontend Class Summary PEAR_Frontend -- Singleton-based frontend for PEAR user input/output Singleton-based frontend for PEAR user input/output (since PEAR 1.4.0) This is also the base class for all frontends. Class Trees for PEAR_Frontend • PEAR • PEAR_Frontend PEAR_Frontend::addTempFile() PEAR_Frontend::addTempFile() -- This can be overridden to allow session-based temporary file management Synopsis require_once '/Frontend.php'; void PEAR_Frontend::addTempFile (mixed $file) Beschreibung By default, all files are deleted at the end of a session. The web installer needs to be able to sustain a list over many sessions in order to support user interaction with install scripts Parameter mixed $file Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Frontend::isIncludeable() PEAR_Frontend::isIncludeable() -- isIncludeable Synopsis require_once '/Frontend.php'; bool PEAR_Frontend::isIncludeable (string $path) Beschreibung Simple utility class used to determine whether a file can be included via include_path Parameter string $path relative or absolute include path Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Frontend::log() PEAR_Frontend::log() -- log Synopsis require_once '/Frontend.php'; void PEAR_Frontend::log (int $level, string $msg, bool [$append_crlf = TRUE]) Beschreibung Log a message in a frontend-specific way. By default, nothing is done. Parameter integer $level string $msg boolean $append_crlf Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Frontend::setConfig() PEAR_Frontend::setConfig() -- setConfig Synopsis require_once '/Frontend.php'; void PEAR_Frontend::setConfig (PEAR_Config &$config) Beschreibung Set the configuration object used by this frontend. Parameter PEAR_Config &$config Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Frontend::setFrontendClass() PEAR_Frontend::setFrontendClass() -- setFrontendClass Synopsis require_once '/Frontend.php'; void& PEAR_Frontend::setFrontendClass (string $uiclass) Beschreibung Set the kind of frontend that should be retrieved from the singleton() method. If the class does not exist, the method changes all underscores (_) into directory separators (like PEAR_Frontend_CLI to PEAR/Frontend/CLI) and appends .php and then checks to see if the file can be included. If the class does exist after all of this, a simple check is made to see if the userConfirm() method exists, and then a new frontend object is returned. Any failure causes a PEAR_Error to be returned. Parameter string $uiclass the full classname (like PEAR_Frontend_Web) Fehler-Meldungen throws PEAR_Error on any problem Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Frontend::singleton() PEAR_Frontend::singleton() -- Retrieve the frontend object Synopsis require_once '/Frontend.php'; PEAR_Frontend_CLI|PEAR_Frontend_Web|PEAR_Frontend_Gtk& PEAR_Frontend::singleton (mixed [$type = null]) Beschreibung Get a single unique copy of the current PEAR frontend object. Parameter string|NULL $type if being called for the first time, the user can specify the kind of frontend to return. Otherwise, this parameter is ignored, and the existing single frontend is returned. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Installer Inhaltsverzeichnis PEAR_Installer::PEAR_Installer() -- constructor PEAR_Installer::install() -- Installs package files Administration class used to install PEAR packages and maintain the installed package database. Class Trees for PEAR_Installer() • PEAR_Common • PEAR_Installer PEAR_Installer::PEAR_Installer() PEAR_Installer::PEAR_Installer() -- constructor Synopsis require_once 'PEAR/Installer.php'; void constructor PEAR_Installer::constructor PEAR_Installer (object &$ui) Beschreibung PEAR_Installer constructor. Parameter object &$ui user interface object (instance of PEAR_Frontend_*) Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Installer::install() PEAR_Installer::install() -- Installs package files Synopsis require_once 'PEAR/Installer.php'; array PEAR_Installer::install (string $pkgfile [, array $options = array()]) Beschreibung Installs the files within the package file specified. Parameter string $pkgfile path to the package file array $options installating options, to enable an option use the option name as array key and TRUE or 1 as value. • $options['force'] = 1 - force installation • $options['register-only'] = 1 - update registry but don't install files • $options['upgrade'] = 1 - upgrade existing install • $options['soft'] = 1 - fail silently Rückgabewert array package info if successful Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR Inhaltsverzeichnis Class Summary PEAR_PackageFile -- Abstraction for the package.xml package description file constructor PEAR_PackageFile::PEAR_PackageFile() -- PEAR_PackageFile PEAR_PackageFile::factory() -- factory PEAR_PackageFile::fromAnyFile() -- Returns package information from different sources PEAR_PackageFile::fromArray() -- Return a packagefile object from its toArray() method PEAR_PackageFile::fromPackageFile() -- Returns information about a package file. Expects the name of a package.xml file as input. PEAR_PackageFile::fromTgzFile() -- fromTgzFile PEAR_PackageFile::fromXmlString() -- fromXmlString PEAR_PackageFile::parserFactory() -- parserFactory PEAR_PackageFile::rawReturn() -- Turn off validation - return a parsed package.xml without checking it for errors PEAR_PackageFile::setLogger() -- setLogger Package PEAR Constants -- Constants defined in and used by PEAR Class Summary PEAR_PackageFile Class Summary PEAR_PackageFile -- Abstraction for the package.xml package description file Abstraction for the package.xml package description file Parse and retrieve a package.xml object from various sources. Class Trees for PEAR_PackageFile • PEAR_PackageFile constructor PEAR_PackageFile::PEAR_PackageFile() constructor PEAR_PackageFile::PEAR_PackageFile() -- PEAR_PackageFile Synopsis require_once '/PackageFile.php'; void constructor PEAR_PackageFile::PEAR_PackageFile (PEAR_Config &$config, bool [$debug = FALSE], string [$tmpdir = FALSE]) Beschreibung Prepare for parsing one or more package.xml files. Parameter PEAR_Config &$config The configuration to use for parsing and channel registry (needed for channelspecific validators). boolean $debug The debug logging level (this is usually the value of the verbose configuration variable). string $tmpdir The temporary directory to extract files in. By default, a new temporary directory is created using System::mktemp(). Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::factory() PEAR_PackageFile::factory() -- factory Synopsis require_once '/PackageFile.php'; PEAR_PackageFile_v1|PEAR_PackageFile_v2& PEAR_PackageFile::factory (string $version) Beschreibung Retrieve a raw PEAR_PackageFile_vX object where X is either 1 or 2. Parameter string $version The package.xml version represented (1 or 2) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::fromAnyFile() PEAR_PackageFile::fromAnyFile() -- Returns package information from different sources Synopsis require_once '/PackageFile.php'; string& PEAR_PackageFile::fromAnyFile (string $info, int $state) Beschreibung This method is able to extract information about a package from a .tgz archive or from a XML package definition file. Parameter string $info path to a file containing a package.xml (package archive or package.xml) integer $state package state (one of PEAR_VALIDATE_* constants) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_PackageFile::fromArray() PEAR_PackageFile::fromArray() -- Return a packagefile object from its toArray() method Synopsis require_once '/PackageFile.php'; PEAR_PackageFile_v1|PEAR_PackageFile_v2& PEAR_PackageFile::fromArray (array $arr) Beschreibung Warnung WARNING: no validation is performed, the array is assumed to be valid, always parse from xml if you want validation. Parameter array $arr Contents of a previously parsed package.xml object. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::fromPackageFile() PEAR_PackageFile::fromPackageFile() -- Returns information about a package file. Expects the name of a package.xml file as input. Synopsis require_once '/PackageFile.php'; array& PEAR_PackageFile::fromPackageFile (string $descfile, int $state, string|false [$archive = FALSE]) Beschreibung parse and return a package.xml object from a package.xml file, or a PEAR_Error object upon error. Parameter string $descfile name of package.xml file integer $state package state (one of PEAR_VALIDATE_* constants) string|FALSE $archive full path to the full package .tgz file containing the package.xml, or false for none. Rückgabewert returns array with package information Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_PackageFile::fromTgzFile() PEAR_PackageFile::fromTgzFile() -- fromTgzFile Synopsis require_once '/PackageFile.php'; PEAR_PackageFile_v1|PEAR_PackageFile_v2|PEAR_Error& PEAR_PackageFile::fromTgzFile (string $file, int $state) Beschreibung parse and return a package.xml object from a packaged archive, or a PEAR_Error object upon error. Parameter string $file name of packaged .tgz or .tar to extract and parse package.xml from integer $state package state (one of PEAR_VALIDATE_* constants) Rückgabewert returns success of parsing Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::fromXmlString() PEAR_PackageFile::fromXmlString() -- fromXmlString Synopsis require_once '/PackageFile.php'; PEAR_PackageFile_v1|PEAR_PackageFile_v2|PEAR_Error& PEAR_PackageFile::fromXmlString (string $data, int $state, string $file, string|false [$archive = FALSE]) Beschreibung parse and return a package.xml object, or a PEAR_Error object upon error. Parameter string $data contents of package.xml file integer $state package state (one of PEAR_VALIDATE_* constants) string $file full path to the package.xml file (and the files it references) string|FALSE $archive full path to the full package .tgz file containing the package.xml, or false for none. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::parserFactory() PEAR_PackageFile::parserFactory() -- parserFactory Synopsis require_once '/PackageFile.php'; PEAR_PackageFile_Parser_v1|PEAR_PackageFile_Parser_v2& PEAR_PackageFile::parserFactory (string $version) Beschreibung Return a package.xml parsing object appropriate for the selected package.xml version. Parameter string $version The package.xml version represented (1 or 2) Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::rawReturn() PEAR_PackageFile::rawReturn() -- Turn off validation - return a parsed package.xml without checking it for errors Synopsis require_once '/PackageFile.php'; void PEAR_PackageFile::rawReturn () Beschreibung This is used by the package-validate command Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_PackageFile::setLogger() PEAR_PackageFile::setLogger() -- setLogger Synopsis require_once '/PackageFile.php'; void PEAR_PackageFile::setLogger (PEAR_Common &$l) Beschreibung set a logging class that matches the signature of PEAR_Common's log() method. Parameter PEAR_Common &$l The PEAR_Common object. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. Package PEAR Constants Package PEAR Constants -- Constants defined in and used by PEAR All Constants Constants defined in PackageFile.php Tabelle 27-1. Constants defined in PackageFile.php Name Value Line Number PEAR_PACKAGEFILE_ERROR_INVALID_PACKAGEVERSION 2 35 PEAR_PACKAGEFILE_ERROR_NO_PACKAGEVERSION 1 30 PEAR_Packager Inhaltsverzeichnis PEAR_Packager::PEAR_Packager() -- constructor PEAR_Packager::package() -- Create Package archive Administration class used to make a PEAR release tarball. Class Trees for PEAR_Packager • PEAR_Common • PEAR_Packager PEAR_Packager::PEAR_Packager() PEAR_Packager::PEAR_Packager() -- constructor Synopsis require_once 'PEAR/Packager.php'; void PEAR_Packager:: PEAR_Packager (void) Beschreibung constructor Hinweise Diese Methode kann statisch aufgerufen werden. PEAR_Packager::package() PEAR_Packager::package() -- Create Package archive Synopsis require_once 'PEAR/Packager.php'; string PEAR_Packager::package ([string $pkgfile = NULL [, boolean $compress = TRUE]]) Beschreibung Creates a Package archive from package definition file and package files Parameter string $pkgfile path to package definition file boolean $compress if TRUE package archive will be compessed using gzip Rückgabewert string - name of the created package archive Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry Inhaltsverzeichnis PEAR_Registry::PEAR_Registry() -- constructor PEAR_Registry::addPackage() -- Registers a package to the registry PEAR_Registry::checkFileMap() -- Test whether a file belongs to a package PEAR_Registry::deletePackage() -- Remove Package from registry PEAR_Registry::listPackages() -- List all registered Packages PEAR_Registry::packageExists() -- Check for Package PEAR_Registry::packageInfo() -- Get Package information PEAR_Registry::rebuildDepsFile() -- Rebuild dependencies file PEAR_Registry::rebuildFileMap() -- Rebuild file map PEAR_Registry::removePackageDep() -- Remove dependency information of a Package PEAR_Registry::setPackageDep() -- Update or insert dependencies of a Package PEAR_Registry::updatePackage() -- Update Package information Administration class used to maintain the installed package database. Class Trees for PEAR_Registry • PEAR • PEAR_Registry PEAR_Registry::PEAR_Registry() PEAR_Registry::PEAR_Registry() -- constructor Synopsis require_once 'PEAR/Registry.php'; void PEAR_Registry::PEAR_Registry ([string $pear_install_dir = PEAR_INSTALL_DIR]) Beschreibung constructor Parameter string $pear_install_dir PEAR install directory (for .php files) Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::addPackage() PEAR_Registry::addPackage() -- Registers a package to the registry Synopsis require_once 'PEAR/Registry.php'; boolean PEAR_Registry::addPackage (string $package, array $info) Beschreibung Adds a Package entry to the registry Parameter string $package Package name array $info additional information for the package entry Rückgabewert boolean - FALSE if Package is already registered; Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::checkFileMap() PEAR_Registry::checkFileMap() -- Test whether a file belongs to a package Synopsis require_once 'PEAR/Registry.php'; string PEAR_Registry::checkFileMap (string $path) Beschreibung Test whether a file belongs to a package. Parameter string $path file path, absolute or relative to the pear install dir Rückgabewert string - name of the package the file belongs to, or an empty string if the file does not belong to an installed package Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::deletePackage() PEAR_Registry::deletePackage() -- Remove Package from registry Synopsis require_once 'PEAR/Registry.php'; boolean PEAR_Registry::deletePackage (string $package) Beschreibung Removes a Package entry from the registry. Parameter string $package Package name Rückgabewert boolean - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::listPackages() PEAR_Registry::listPackages() -- List all registered Packages Synopsis require_once 'PEAR/Registry.php'; array PEAR_Registry::listPackages (void) Beschreibung List all Packages registered in the registry. Rückgabewert array - list of package names Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::packageExists() PEAR_Registry::packageExists() -- Check for Package Synopsis require_once 'PEAR/Registry.php'; boolean PEAR_Registry::packageExists (string $package) Beschreibung Checks wether a Package is registered in the registry or not. Parameter string $package Package name Rückgabewert boolean - TRUE if package is registered Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::packageInfo() PEAR_Registry::packageInfo() -- Get Package information Synopsis require_once 'PEAR/Registry.php'; mixed PEAR_Registry::packageInfo ([string $package = NULL [, string $key = NULL]]) Beschreibung Returns (specific) information stored in the registry about a Package. Parameter string $package Package name string $key the name of a specific information to get Rückgabewert mixed - an array with all information, or a key specific information, if $key was used; NULL if Package or specific information does not exist Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::rebuildDepsFile() PEAR_Registry::rebuildDepsFile() -- Rebuild dependencies file Synopsis require_once 'PEAR/Registry.php'; void PEAR_Registry::rebuildDepsFile (void) Beschreibung Rebuilds the dependencies file of the registry. Use this function if had trouble while installing Packages or a damaged registry. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::rebuildFileMap() PEAR_Registry::rebuildFileMap() -- Rebuild file map Synopsis require_once 'PEAR/Registry.php'; void PEAR_Registry::rebuildFileMap (void) Beschreibung Rebuilds the registry filemap. Use this function if had trouble while installing Packages or a damaged registry. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::removePackageDep() PEAR_Registry::removePackageDep() -- Remove dependency information of a Package Synopsis require_once 'PEAR/Registry.php'; mixed PEAR_Registry::removePackageDep (string $package) Beschreibung Removes the dependency information of a Package from the registry. Parameter string $package Package name Rückgabewert mixed - TRUE if successful; or an array with a list of Packages depending on this Package Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::setPackageDep() PEAR_Registry::setPackageDep() -- Update or insert dependencies of a Package Synopsis require_once 'PEAR/Registry.php'; mixed PEAR_Registry::setPackageDep (string $package, string $new_version [, array $rel_deps = array()]) Beschreibung Update or insert a the dependencies of a package, prechecking that the package won't break any dependency in the process. (Dependencies of type 'pkg' only. Parameter string $package Package name string $new_version Version of the Package array $rel_deps Package dependencies Rückgabewert mixed - TRUE if no dependencies found; or array with names of missing or outdated Packages Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Registry::updatePackage() PEAR_Registry::updatePackage() -- Update Package information Synopsis require_once 'PEAR/Registry.php'; boolean PEAR_Registry::updatePackage (string $package, array $info [, bool $merge = TRUE]) Beschreibung Updates the existing information of a Package in the registry. Parameter string $package Package name array $info information to update mixed $merge if FALSE the old informations will be deleted completly an replaced with the new; if TRUE update only - unchanged values will remain. Rückgabewert boolean - Gibt bei Erfolg TRUE zurück, bei einem Fehler FALSE. Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Remote Inhaltsverzeichnis PEAR_Remote::PEAR_Remote() -- constructor PEAR_Remote::call() -- Execute a server function This is a class for doing remote operations against a PEAR Package Server. Class Trees for PEAR_Remote() • PEAR • PEAR_Remote PEAR_Remote::PEAR_Remote() PEAR_Remote::PEAR_Remote() -- constructor Synopsis require_once 'PEAR/Remote.php'; void PEAR_Remote::PEAR_Remote (object &$config) Beschreibung constructor Parameter object &$config an instance of PEAR_Config Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Remote::call() PEAR_Remote::call() -- Execute a server function Synopsis require_once 'PEAR/Remote.php'; mixed PEAR_Remote::call (string $method [, mixed $args,...]) Beschreibung Sends a remote procedure call to a package server and returns the result. Parameter string $method Name of the server method mixed $args,... server method specific parameters Rückgabewert mixed - result of the executed server method Fehler-Meldungen Tabelle 27-1. Mögliche Fehler-Arten Error code Error value Meaning Solution „“ Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST Inhaltsverzeichnis Class Summary PEAR_REST -- Intelligently retrieve data, following hyperlinks if necessary, and re-directing constructor PEAR_REST::PEAR_REST() -- PEAR_REST PEAR_REST::downloadHttp() -- Efficiently Download a file through HTTP. Returns downloaded file as a string in-memory This is best used for small files PEAR_REST::getCache() -- getCache PEAR_REST::getCacheId() -- getCacheId PEAR_REST::retrieveCacheFirst() -- Retrieve REST data, but always retrieve the local cache if it is available. PEAR_REST::retrieveData() -- Retrieve a remote REST resource PEAR_REST::saveCache() -- Save the value retrieved from a remote REST resource in the local cache. PEAR_REST::useLocalCache() -- useLocalCache Class Summary PEAR_REST Class Summary PEAR_REST -- Intelligently retrieve data, following hyperlinks if necessary, and re-directing Intelligently retrieve data, following hyperlinks if necessary, and re-directing (since PEAR 1.4.0) as well Class Trees for PEAR_REST • PEAR_REST constructor PEAR_REST::PEAR_REST() constructor PEAR_REST::PEAR_REST() -- PEAR_REST Synopsis require_once '/REST.php'; void constructor PEAR_REST::PEAR_REST (PEAR_Config &$config, array [$options = array()]) Beschreibung Dieses Package ist noch nicht dokumentiert. Parameter PEAR_Config &$config Configuration object array $options options passed to commands like install/download. The only option that affects PEAR_REST is offline, which causes all retrievals to look in the local cache without trying to retrieve a remote resource. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::downloadHttp() PEAR_REST::downloadHttp() -- Efficiently Download a file through HTTP. Returns downloaded file as a string in-memory This is best used for small files Synopsis require_once '/REST.php'; string|array PEAR_REST::downloadHttp (string $url, false|string|array [$lastmodified = null], false|array [$accept = false], string $save_dir) Beschreibung If an HTTP proxy has been configured (http_proxy PEAR_Config setting), the proxy will be used. Parameter string $url the URL to download FALSE|string|array $lastmodified header values to check against for caching use FALSE to return the header values from this download FALSE|array $accept Accept headers to send. This should be a list of MIME types like text/xml, frog/legs, etc. string $save_dir directory to save file in Rückgabewert returns Returns the contents of the downloaded file or a PEAR error on failure. If the error is caused by socket-related errors, the error object will have the fsockopen error code available through getCode(). If caching is requested, then return the header values. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::getCache() PEAR_REST::getCache() -- getCache Synopsis require_once '/REST.php'; mixed|false PEAR_REST::getCache (string $url) Beschreibung Retrieve the cache contents for a remote resource, or a PEAR_Error if the resource was not cached. Parameter string $url REST resource URL Fehler-Meldungen throws PEAR_Error object returned on error. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::getCacheId() PEAR_REST::getCacheId() -- getCacheId Synopsis require_once '/REST.php'; array|false PEAR_REST::getCacheId (string $url) Beschreibung Retrieve the HTTP caching information for a REST resource, or FALSE if no cache is found. Parameter string $url REST resource URL Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::retrieveCacheFirst() PEAR_REST::retrieveCacheFirst() -- Retrieve REST data, but always retrieve the local cache if it is available. Synopsis require_once '/REST.php'; string|array PEAR_REST::retrieveCacheFirst (string $url, array|false [$accept = false], boolean [$forcestring = false]) Beschreibung This is useful for elements that should never change, such as information on a particular release Parameter string $url full URL to this resource array|FALSE $accept contents of the accept-encoding header boolean $forcestring if TRUE, xml will be returned as a string, otherwise, xml will be parsed using PEAR_XMLParser Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::retrieveData() PEAR_REST::retrieveData() -- Retrieve a remote REST resource Synopsis require_once '/REST.php'; string|array PEAR_REST::retrieveData (string $url, array|false [$accept = false], bool [$forcestring = false]) Beschreibung retrieve the contents of a remote resource. Parameter string $url full URL to this resource array|false $accept contents of the accept-encoding header boolean $forcestring if TRUE, xml will be returned as a string, otherwise, xml will be parsed using PEAR_XMLParser Fehler-Meldungen throws PEAR_Error objects are returned on error. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::saveCache() PEAR_REST::saveCache() -- Save the value retrieved from a remote REST resource in the local cache. Synopsis require_once '/REST.php'; void PEAR_REST::saveCache (string $url, mixed $contents, array $lastmodified, bool [$nochange = false]) Beschreibung Use this to save a resource after retrieving. Since the cache_ttl configuration variable is used in determining when to check the remote server, and HTTP caching is used as well, it is possible for this scenario to arise: 1. retrieve REST resource 2. cache the resource 3. a few days later, retrieve the REST resource again 4. HTTP caching returns 304 not modified In this situation, it doesn't make much sense to save the resource contents redundantly. Instead, the last access time can be saved in the cache id by passing true into the last parameter. Parameter string $url The REST resource's URL mixed $contents Contents retrieved from the REST resource (ignored if the last parameter is true) array $lastmodified The ETag and LastModified headers retrieved from the remote server, used for HTTP caching. mixed $nochange If false, the cache is saved normally. If true, only the $lastmodified parameter is saved in the cache id file, registering an HTTP cache hit. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_REST::useLocalCache() PEAR_REST::useLocalCache() -- useLocalCache Synopsis require_once '/REST.php'; mixed PEAR_REST::useLocalCache (bool $url) Beschreibung Retrieve the contents of the local cached copy of a remote URL. FALSE is returned if there are any problems, under the assumption that REST contents will always be larger than a simple boolean due to HTTP overhead. Parameter string $url The URL to retrieve data for. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR Inhaltsverzeichnis Class Summary PEAR_RunTest -- Simplified version of PHP's test suite constructor PEAR_RunTest::PEAR_RunTest() -- Instantiate a PEAR_RunTest object. PEAR_RunTest::generate_diff() -- generate_diff PEAR_RunTest::run() -- run Class Summary PEAR_RunTest Class Summary PEAR_RunTest -- Simplified version of PHP's test suite Simplified version of PHP's test suite Try it with: $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; \ $o=$t->run("./pear_system.phpt");print_r($o);' Class Trees for PEAR_RunTest • PEAR_RunTest constructor PEAR_RunTest::PEAR_RunTest() constructor PEAR_RunTest::PEAR_RunTest() -- Instantiate a PEAR_RunTest object. Synopsis require_once '/RunTest.php'; void constructor PEAR_RunTest::PEAR_RunTest (PEAR_Common|null [$logger = NULL], array [$options = array()]) Beschreibung If no logger is specified, a new PEAR_Common object will be instantiated and used to print output to the screen. Parameter PEAR_Common|NULL $logger A class that contains a log() method matching the signature of PEAR_Common. array $options Currently supported options are simple and quiet. The simple option causes tests to simply print the title of the test and not the full path to the test file. The quiet option causes output of only failed tests. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_RunTest::generate_diff() PEAR_RunTest::generate_diff() -- generate_diff Synopsis require_once '/RunTest.php'; void PEAR_RunTest::generate_diff (string $wanted, string $output, array|false $return_value) Beschreibung Returns differences by line between the expected output ($wanted) and the actual output ($output). In addition, the value returned from the script can also be tested. The test should be performed outside generate_diff(). If the return value is as expected, pass in FALSE, otherwise pass in an array where the first element is the expected return value and the second is the actual return value. Parameter string $wanted Expected output string $output Actual output array|FALSE $return_value False if return value was correct, otherwise an array of format: <?php array( 1, // expected return 2, // actual return value ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_RunTest::run() PEAR_RunTest::run() -- run Synopsis require_once '/RunTest.php'; string|PEAR_Error PEAR_RunTest::run (string $file, string [$ini_settings = '']) Beschreibung Run a unit test. The return value is one of: • PASSED • SKIPPED • WARNED • FAILED Parameter string $file Full path to the test file to run. string $ini_settings Additional customized settings to pass on the command-line to the PHP instance used for testing. For example, requesting disabling use of php.ini or a testing php.ini can be specified. For a full list of possible settings, type: $ php -h Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate Inhaltsverzeichnis Class Summary PEAR_Validate -- Validation class for package.xml - channel-level advanced validation PEAR_Validate::_addFailure() -- _addFailure PEAR_Validate::_addWarning() -- _addWarning PEAR_Validate::getFailures() -- getFailures PEAR_Validate::getValidStates() -- Get a list of valid stability levels PEAR_Validate::setPackageFile() -- setPackageFile PEAR_Validate::validate() -- validate PEAR_Validate::validateChangelog() -- validateChangelog PEAR_Validate::validateDate() -- validateDate PEAR_Validate::validateDependencies() -- for package.xml 2.0 only - channels can't use package.xml 1.0 PEAR_Validate::validateDeps() -- validateDeps PEAR_Validate::validateDescription() -- validateDescription PEAR_Validate::validateFilelist() -- validateFilelist PEAR_Validate::validateLicense() -- validateLicense PEAR_Validate::validateMainFilelist() -- for package.xml 2.0 only PEAR_Validate::validateMaintainers() -- validateMaintainers PEAR_Validate::validateNotes() -- validateNotes PEAR_Validate::validatePackageName() -- validatePackageName PEAR_Validate::validateReleaseFilelist() -- for package.xml 2.0 only PEAR_Validate::validateStability() -- validateStability PEAR_Validate::validateState() -- validateState PEAR_Validate::validateSummary() -- validateSummary PEAR_Validate::validateTime() -- validateTime PEAR_Validate::validateVersion() -- protected function to validate a version PEAR_Validate::validGroupName() -- This validates a dependency group name, and dependency group names must conform to the PEAR naming convention, so the method is final and static. PEAR_Validate::validPackageName() -- utility method to validate a package name string PEAR_Validate::validState() -- Determine whether $state represents a valid stability level PEAR_Validate::validVersion() -- Determine whether a version is a properly formatted version number that can be used by version_compare() PEAR_Validate::_validPackageName() -- Override this method to handle validation of normal package names Package PEAR Constants -- Constants defined in and used by PEAR Class Summary PEAR_Validate Class Summary PEAR_Validate -- Validation class for package.xml - channel-level advanced validation Validation class for package.xml - channel-level advanced validation Dieses Package ist noch nicht dokumentiert. Class Trees for PEAR_Validate • PEAR_Validate PEAR_Validate::_addFailure() PEAR_Validate::_addFailure() -- _addFailure Synopsis require_once '/Validate.php'; void PEAR_Validate::_addFailure (string $field, string $reason) Beschreibung add a validation warning from one of the channel validation functions. Use this for a nonfatal warning of a potential problem situation. Parameter string $field The package.xml section being validated (such as version or dependencies) string $reason A human-readable reason that validation failed. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::_addWarning() PEAR_Validate::_addWarning() -- _addWarning Synopsis require_once '/Validate.php'; void PEAR_Validate::_addWarning (string $field, string $reason) Beschreibung add a validation warning from one of the channel validation functions. Use this for a nonfatal warning of a potential problem situation. Parameter string $field The package.xml section being validated (such as version or dependencies) string $reason A human-readable reason that validation failed. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::getFailures() PEAR_Validate::getFailures() -- getFailures Synopsis require_once '/Validate.php'; void PEAR_Validate::getFailures () Beschreibung Returns a list of failures recorded by the last validation attempt. The list is in format: <?php array( 'error' => array( array('field' => 'name', 'name must contain only letters, numbers or underscor ), 'warning' => array( array('field' => 'version', 'version should be less than 2.0'), ) ); ?> Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::getValidStates() PEAR_Validate::getValidStates() -- Get a list of valid stability levels Synopsis require_once '/Validate.php'; array PEAR_Validate::getValidStates () Beschreibung Utility function for future extensibility of the list of valid stability levels. Fehler-Meldungen throws no exceptions thrown Final final - this method must not be overridden Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Validate::setPackageFile() PEAR_Validate::setPackageFile() -- setPackageFile Synopsis require_once '/Validate.php'; void PEAR_Validate::setPackageFile (PEAR_PackageFile_v1| PEAR_PackageFile_v2 &$pf) Beschreibung Sets the packagefile object that will be used to retrieve data for validation. Parameter PEAR_PackageFile_v1|PEAR_PackageFile_v2 &$pf Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validate() PEAR_Validate::validate() -- validate Synopsis require_once '/Validate.php'; void PEAR_Validate::validate (int [$state = NULL]) Beschreibung Validate the package.xml passed into setPackageFile(). The parameter passed in is the installer state that should be used, and is one of PEAR_VALIDATE_INSTALLING, PEAR_VALIDATE_DOWNLOADING, PEAR_VALIDATE_NORMAL, PEAR_VALIDATE_UNINSTALLING, or PEAR_VALIDATE_PACKAGING. Parameter integer $state one of the PEAR_VALIDATE_* constants Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateChangelog() PEAR_Validate::validateChangelog() -- validateChangelog Synopsis require_once '/Validate.php'; void PEAR_Validate::validateChangelog () Beschreibung Override this in a channel-specific validator to validate the contents of the <changelog> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateDate() PEAR_Validate::validateDate() -- validateDate Synopsis require_once '/Validate.php'; void PEAR_Validate::validateDate () Beschreibung Override this in a channel-specific validator to validate the contents of the <date> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateDependencies() PEAR_Validate::validateDependencies() -- for package.xml 2.0 only - channels can't use package.xml 1.0 Synopsis require_once '/Validate.php'; void PEAR_Validate::validateDependencies () Beschreibung Override this in a channel-specific validator to validate the <dependencies> tag of a package.xml 2.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateDeps() PEAR_Validate::validateDeps() -- validateDeps Synopsis require_once '/Validate.php'; void PEAR_Validate::validateDeps () Beschreibung Override this in a channel-specific validator to validate the contents of <deps> in a package.xml 1.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateDescription() PEAR_Validate::validateDescription() -- validateDescription Synopsis require_once '/Validate.php'; void PEAR_Validate::validateDescription () Beschreibung Override this in a channel-specific validator to validate the contents of the <description> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateFilelist() PEAR_Validate::validateFilelist() -- validateFilelist Synopsis require_once '/Validate.php'; void PEAR_Validate::validateFilelist () Beschreibung Override this in a channel-specific validator to validate the contents of the <filelist> tag in a package.xml 1.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateLicense() PEAR_Validate::validateLicense() -- validateLicense Synopsis require_once '/Validate.php'; void PEAR_Validate::validateLicense () Beschreibung Override this method in a channel-specific validator to validate the contents of the <license> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateMainFilelist() PEAR_Validate::validateMainFilelist() -- for package.xml 2.0 only Synopsis require_once '/Validate.php'; void PEAR_Validate::validateMainFilelist () Beschreibung Override this in a channel-specific validator to validate the contents of the <contents> tag in package.xml 2.0-based releases. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateMaintainers() PEAR_Validate::validateMaintainers() -- validateMaintainers Synopsis require_once '/Validate.php'; void PEAR_Validate::validateMaintainers () Beschreibung Override this in a channel-specific validator to validate the contents of <maintainers> in a package.xml 1.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateNotes() PEAR_Validate::validateNotes() -- validateNotes Synopsis require_once '/Validate.php'; void PEAR_Validate::validateNotes () Beschreibung Override this in a channel-specific validator to validate the contents of release notes in a <notes> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validatePackageName() PEAR_Validate::validatePackageName() -- validatePackageName Synopsis require_once '/Validate.php'; void PEAR_Validate::validatePackageName () Beschreibung Override this in a channel-specific validator to validate a package name. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateReleaseFilelist() PEAR_Validate::validateReleaseFilelist() -- for package.xml 2.0 only Synopsis require_once '/Validate.php'; void PEAR_Validate::validateReleaseFilelist () Beschreibung Use this to validate the contents of a <filelist> tag in a package.xml 2.0-based package. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateStability() PEAR_Validate::validateStability() -- validateStability Synopsis require_once '/Validate.php'; void PEAR_Validate::validateStability () Beschreibung Override this in a channel-specific validator to validate the <stability> tag of a package.xml 2.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateState() PEAR_Validate::validateState() -- validateState Synopsis require_once '/Validate.php'; void PEAR_Validate::validateState () Beschreibung Override this in a channel-specific validator to validate the contents of a <state> tag in a package.xml 1.0-based release. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateSummary() PEAR_Validate::validateSummary() -- validateSummary Synopsis require_once '/Validate.php'; void PEAR_Validate::validateSummary () Beschreibung Override this in a channel-specific validator to validate the <summary> tag. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateTime() PEAR_Validate::validateTime() -- validateTime Synopsis require_once '/Validate.php'; void PEAR_Validate::validateTime () Beschreibung Override this method to validate the <time> tag in a channel-specific validator. Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validateVersion() PEAR_Validate::validateVersion() -- protected function to validate a version Synopsis require_once '/Validate.php'; void PEAR_Validate::validateVersion () Beschreibung Override this function in a channel validator in order to apply a different version validation scheme. An example of this use is in the PEAR_Validate_PECL class, which overrides validateVersion() to be less strict than the default PEAR_Validate::validateVersion(). Errors should be reported using _addFailure() method, and non-fatal errors (warnings) should be reported using the _addWarning() method. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validGroupName() PEAR_Validate::validGroupName() -- This validates a dependency group name, and dependency group names must conform to the PEAR naming convention, so the method is final and static. Synopsis require_once '/Validate.php'; void PEAR_Validate::validGroupName (string $name) Beschreibung Dependency groups are documented here Parameter string $name Dependency group name to validate Fehler-Meldungen throws no exceptions thrown Final final - this method should not be overridden. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Validate::validPackageName() PEAR_Validate::validPackageName() -- utility method to validate a package name string Synopsis require_once '/Validate.php'; void PEAR_Validate::validPackageName (string $name, string [$validatepackagename = FALSE]) Beschreibung Validate a package name string. The second parameter should be the name of the channel validation package, as defined by channel.xml for the current channel. If the package name being validated is the same as the validation package (case-insensitive), then it will be validated using the default rules for PEAR packages. Parameter string $name package name to validate string $validatepackagename name of channel-specific validation package Fehler-Meldungen throws no exceptions thrown Final final - this method should not be overridden. Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_Validate::validState() PEAR_Validate::validState() -- Determine whether $state represents a valid stability level Synopsis require_once '/Validate.php'; bool PEAR_Validate::validState (string $state) Beschreibung This utility method can be used to determine whether a string is a valid state. Currently, states must be one of snapshot, devel, alpha, beta, and stable. Parameter string $state State string to validate. Fehler-Meldungen throws no exceptions thrown Final final - this method should not be overridden. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Validate::validVersion() PEAR_Validate::validVersion() -- Determine whether a version is a properly formatted version number that can be used by version_compare() Synopsis require_once '/Validate.php'; bool PEAR_Validate::validVersion (string $ver) Beschreibung Use this method to test the validity of a version number string. All versions must be testable with PHP's version_compare(). Parameter string $ver Version string Fehler-Meldungen throws no exceptions thrown Final final - this method should not be overridden. Hinweise Diese Methode sollte statisch aufgerufen werden.. PEAR_Validate::_validPackageName() PEAR_Validate::_validPackageName() -- Override this method to handle validation of normal package names Synopsis require_once '/Validate.php'; bool PEAR_Validate::_validPackageName (string $name) Beschreibung This protected method can be used to change the normal package validation scheme. By default, all packages must begin with a letter and contain only letters, numbers and underscores. Using this method, it is possible to change this entirely to enforce another scheme. For instance, enforcing java-style com.blah.package package names can be done simply by this code: <?php require_once 'PEAR/Validate.php'; class MyChannel_Validate extends PEAR_Validate { function _validPackageName($name) { return preg_match('/[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*/', $name); } } ?> Then, by using a customized channel validation package, the installer will enforce javastyle package names for your channel. Parameter string $name package name string to test for validity. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. Package PEAR Constants Package PEAR Constants -- Constants defined in and used by PEAR All Constants Constants defined in Validate.php Tabelle 27-1. Constants defined in Validate.php Name Value Line Number PEAR_VALIDATE_DOWNLOADING 4 28 PEAR_VALIDATE_INSTALLING 1 25 PEAR_VALIDATE_NORMAL 3 27 PEAR_VALIDATE_PACKAGING 7 29 PEAR_VALIDATE_UNINSTALLING 2 26 PEAR Inhaltsverzeichnis Class Summary PEAR_XMLParser -- Parser for any xml file PEAR_XMLParser::getData() -- getData PEAR_XMLParser::parse() -- parse PEAR_XMLParser::preProcessStupidSaxon() -- pre-process xml to weed out characters/entities that would kill parsing Class Summary PEAR_XMLParser Class Summary PEAR_XMLParser -- Parser for any xml file Parser for any xml file Dieses Package ist noch nicht dokumentiert. Class Trees for PEAR_XMLParser • PEAR_XMLParser PEAR_XMLParser::getData() PEAR_XMLParser::getData() -- getData Synopsis require_once '/XMLParser.php'; array PEAR_XMLParser::getData () Beschreibung Return the array representation of XML as parsed by parse(). Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_XMLParser::parse() PEAR_XMLParser::parse() -- parse Synopsis require_once '/XMLParser.php'; true|PEAR_Error PEAR_XMLParser::parse (string $data) Beschreibung Return an array that matches the XML parsed. This code is lifted from Stephan Schmidt's XML_Unserializer class in the XML_Serializer package. As such, tags are represented by an associative array. Multiple tags are represented with a 0-based array of tag contents, and attributes are represented by an array index named attribs. If attributes are present, the array index _contents is used to hold the contents of the xml tag. Parameter string $data xml content Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. PEAR_XMLParser::preProcessStupidSaxon() PEAR_XMLParser::preProcessStupidSaxon() -- pre-process xml to weed out characters/entities that would kill parsing Synopsis require_once '/XMLParser.php'; string PEAR_XMLParser::preProcessStupidSaxon (string $data) Beschreibung This method examines xml data prior to parsing and replaces all entities like à with their equivalent (à in this case). It also scans the file for any non-ascii characters like à and replaces them with their entity equivalent (à). This prevents saxon in PHP 4 and PHP 5 from choking on non-ISO-8859-1 characters. Parameter string $data The xml data. Fehler-Meldungen throws no exceptions thrown Hinweise Diese Methode kann nicht statisch aufgerufen werden. VI. Packages Inhaltsverzeichnis 28. Authentication 29. Benchmarking 30. Caching 31. Configuration 32. Console 33. Database 34. Date and Time 35. Encryption 36. Event 37. File Formats 38. File System 39. Gtk 40. HTML 41. HTTP 42. Images 43. Internationalization 44. Logging 45. Mail 46. Math 47. Networking 48. Numbers 49. Payment 50. PEAR 51. PHP 52. Science 53. Streams 54. Structures 55. System 56. Text 57. Tools and Utilities 58. XML 59. Web Services Kapitel 28. Authentication Stellt Packages für die Benutzer-Authentifizierung bereit. Auth Inhaltsverzeichnis Konstanten -- Vordefinierte Konstanten Einführung -- Eine Beispielanwendung Speicher-Container -- Einführung Auth::Auth() -- constructor Auth::getAuth() -- check for an authenticated user Auth::getStatus() -- returns informations about the current authentication status Auth::getUsername() -- get the username of the current authentication session Auth::sessionValidThru() -- get the time up to the session is valid Auth::setSessionname() -- set a custom session name Auth::setShowLogin() -- controls if the login form will be displayed. Turned on by default Auth::setExpire() -- set expiration time for authentication Auth::setIdle() -- set maximum idle time for authentication Auth::start() -- start authentication Auth::checkAuth() -- check if a session with valid authentication information exists Stellt ein Framework für die Benutzerauthentifizierung zur Verfügung. Konstanten Konstanten -- Vordefinierte Konstanten AUTH_IDLED -1 AUTH_EXPIRED -2 AUTH_WRONG_LOGIN -3 Einführung Einführung -- Eine Beispielanwendung Auth-Tutorial Unser Ziel für dieses Mini-Tutorial ist es, ein System aufzusetzen, die Ihre Seite mit einer einfach zu benutzenden Authentifizierung versieht. Am Anfang der zu sichernden Seite platzieren Sie folgenden Code: Beispiel 28-1. Typische Benutzung von PEAR::Auth require_once "Auth.php"; function loginFunction() { /* * Change the HTML output so that it fits to your * application. */ echo "<form method=\"post\" action=\"test.php\">"; echo "<input type=\"text\" name=\"username\">"; echo "<input type=\"password\" name=\"password\">"; echo "<input type=\"submit\">"; echo "</form>"; } $dsn = "mysql://user:password@localhost/database"; $a = new Auth("DB", $dsn, "loginFunction"); $a->start(); if ($a->checkAuth()) { /* * The output of your site goes here. */ } Die wenigen Zeilen Code initialiseren die Authentifizierung. Die erste Zeile im obigen Skript inkludiert die Datei aus dem PEAR-Verzeichnis. Es enthält alle notwendigen Code, um PEAR::Auth auszuführen. Als nächstes wird eine Funktion definiert, die das Login-Formular darstellt, mit dem sich ein Besucher der Seite anmelden muss. Sie können die HTML-Formatierungen beliebig ändern. Da wir eine Datenbank benutzen wollen, um die Login-Daten zu überprüfen, benötigen wir einen korrekten DSN in der Variable $dsn. Er wird benutzt, um sich mit der Datenbank zu verbinden über PEAR::DB. Informationen zum Tabellenschema für die Datenbank oder für die Benutzung anderer Container finden Sie weiter unten. Danach erzeugen wir das Auth-Objekt. Der erste Parameter gibt den zuverwendenen Speicher-Container an. Da wir eine Datenbank benutzen, übergeben wir DB. Der zweite Parameter ist der Verbindungsparameter für den Speicher-Container. Wir setzen hier den DSN ein. Der dritte Parameter ist der Name der Funktion. die das Login-Formular enthält. Das Objekt wurde initialisiert und wir müssen prüfen, ob ein Benutzer angemeldet ist. Dazu rufen wir die Methde checkAuth() auf. Wenn sie TRUE zurückliefert, können wir den Inhalt der Seite weiter ausführen. Beispiel 28-2. Optionale Authentifizierung // In this test, the file is named "test.php". require_once "Auth.php"; function loginFunction() { /* * Change the HTML output so that it fits to your * application. */ echo "<form method=\"post\" action=\"test.php?login=1\">"; echo "<input type=\"text\" name=\"username\">"; echo "<input type=\"password\" name=\"password\">"; echo "<input type=\"submit\">"; echo "</form>"; } if (isset($_GET['login']) && $_GET['login'] == 1) { $optional = true; } else { $optional = false; } $dsn = "mysql://user:password@localhost/database"; $a = new Auth("DB", $dsn, "loginFunction", $optional); $a->start(); echo "Everybody can see this text!<br />"; if (!isset($_GET['login'])) { echo "<a href=\"test.php?login=1\">Click here to log in</a>\n"; } if ($a->getAuth()) { echo "One can only see this if he is logged in!"; } Da sist ein kleines Beispiel für einen optionalen Login: Der letzte Parameter $optional des Auth-Konstrukturs kann auf TRUE oder FALSE gesetzt werden. Setzen Sie ihn auf FALSE, dann wird das Login-Formular nicht angezeigt und der Benutzer sieht nur den Text "Everybody can see this text!". Klickt er auf den Link im Text, wird die Seite erneut geladen, aber mit dem GET-Parameter login=1. Jetzt kann er im Formular seine Login-Daten eingeben. Wird er erfolgreich eingeloggt, dann kann er den Text "Everybody can see this text!" sehen und zusätzlich "One can only see this if he is logged in!". Beispiel 28-3. Logout-Funktion Das folgende Beispiel führt einen „Logout“ aus für den aktuellen Benutzer und zeigt danach das Login-Formular erneut. $myauth->start(); if ($_GET['action'] == "logout" && $myauth->checkAuth()) { $myauth->logout(); $myauth->start(); } In der folgenden Passage betrachten wir die Methoden der Klasse PEAR::Auth genauer. Diese SQL-Anweisungen (unter MySQL) erzeugen eine Tabelle mit dem Standardschema für die Authentifizierung: CREATE TABLE auth ( username VARCHAR(50) default '' NOT NULL, password VARCHAR(32) default '' NOT NULL, PRIMARY KEY (username), KEY (password) ); Diese Tabelle und ihre Spaltenname sind erforderlich für eine funktionierende Authentifizerung über eine Datenbank notwendig. Wenn das Passwort per standardmäßig per MD5-Hash-Funktion kodiert wird, dann muss die Passwort-Spalte mindestens 32 Zeichen aufnehmen können. Wird eine andere Methode benutzt, wie z.B. DES („UNIX crypt“), dann muss die Größe entsprechend angepasst werden. Speicher-Container Speicher-Container -- Einführung Übersicht PEAR::Auth verwendet eine Anzahl an Speicher-Containern um Login-Daten zu speichern. Die folgenden Abschnitte bescheiben die Container. Wenn die Container Ihren Ansprüchen nicht genügen, können Sie auch einfach einen eigenen schreiben. Database PEAR::Auth benutzt PEAR::DB für den Datenbankzugriff. Damit haben können Sie alle DBMS benutzen, die von PEAR::DB unterstützt werden. Das speicherspezifische Argument für den Auth-Konstruktor() ist ein Array. Tabelle 28-1. Array Schlüssel und Werte Schlüssel Beschreibung Standardwert „dsn“ Ein korrekter DSN . „“ „table“ Der Name der Datenbanktabelle, in der die Login-Daten gespeichert werden. „auth“ „usernamecol Der Name der Spalte, die den Benutzernamen enthält. “ „username“ Der Name der Spalte, in der das MD5-kodierte Passwort „passwordcol enthält. Die Spalte muss mindestens 32 Zeichen aufnehmen „password“ “ können. File Das speicherspezifische Argument für den Auth-Konstruktor() ist der Name einer Datei gemäß File_Passwd file. SMBPasswd Dieser Container führt eine Authenifizierung gegen eine SAMBA smbpasswd-Datei durch. Das speicherspezifische Argument für den Auth-Konstruktor() ist der Name einer Datei gemäß dem SAMBA passwd-style file. IMAP Dieser Container verbindet sich mit einem IMAP-Server und versucht sich mit den Benutzerdaten daran anzumelden. Das speicherspezifische Argument für den Auth-Konstruktor() ist ein Array. Tabelle 28-2. Array Schlüssel und Werte Schlüssel Beschreibung Standardwert „host“ Der Hostname oder IP-Adresse des IMAP-Servers. „localhost“ „port“ Der Port, auf den der IMAP-Server hört. „143“ LDAP Das speicherspezifische Argument für den Auth-Konstruktor() ist ein Array. Tabelle 28-3. Array Schlüssel und Werte Schlüssel Beschreibung Standardwert „host“ Der Hostname oder die IP-Adresse des LDAPServers. „localhost“ „port“ Der Port auf den der LDAP-Servers hört. „389“ „basedn“ Der Base Distinguished Name „o=netsols,c=de“ „userattr“ Definiert die zu erfragenden Attribute. „uid“ POP3 Der Container verbindet sich mit einem POP3-Server und versucht sich mit den Benutzerdaten anzumelden. Das speicherspezifische Argument für den Auth-Konstruktor() ist eine Zeichenkette der Form host:port oder nur host. RADIUS Sie benötigen Auth_RADIUS und PECL::radius um die Container zu verwenden. Das speicherspezifische Argument für den Auth-Konstruktor() ist ein Array. Tabelle 28-4. Array Schlüssel und Werte Schlüssel Beschreibung Standardwert Ein Array mit den RADIUS-Server, die die Werte angeben: host, port, shared secret, timeout, maxtries. „servers“ Die Bedeutung der Parameter finden Sie in der Dokumentation zur RADIUS-Erweiterung. array(„localhost“, 0, „testing123“, 3, 3) Bis zu 10 Server können definiert werden. Diese werden dann nacheinander abgefragt bis eine gültige Antwort erfolgt oder die Anzahl der maximalen Versuche erreicht wurde Die Authentifizierungsmethode für die Prüfung der Anfrage. Mögliche Werte sind: PAP, CHAP_MD5, „authtype MSCHAPv1, MSCHAPv2. “ Es bestehen zusätzliche Abhängigkeiten für diese Methoden. Alle ausser POP benötigen das Crypt_CHAPPackage. Für MS-CHAP wird ausserdem die mhashExtension benötigt. „PAP“ SOAP Das speicherspezifische Argument für den Auth-Konstruktor() ist ein Array. Tabelle 28-5. Array-Schlüssel und -Werte Schlüssel Beschreibung „endpoint“ Die URI unter der der Service erreichbar ist. „namespace“ Der Namespace des Webservice. „method“ Die aufzurufende SOAP-Methode. „encoding“ Die zu benutzende Textcodierung (z.B. utf8). „usernamefield“ Der Name des Feldes, in dem der Benutzername übergeben wird. Standardwert Schlüssel Beschreibung „passwordfield“ Der Name des Feldes, in dem das Passwort übergeben wird. Standardwert vpopmail Der Container benutzt einen existierenden vpopmail-Service zur Überprüfung Er benötigt keine gesonderten Parameter. Speicher-Container selbst schreiben Beispiel für das Schreiben eines eigenen Speicher-Containers. Das ist das Skelett: Beispiel 28-1. CustomAuthContainer.php include_once 'Auth/Container.php'; class CustomAuthContainer extends Auth_Container { /** * Constructor */ function AuthContainerDatabase($params){ // Init Here } } function fetchData($username, $password){ // Check If valid etc if($isvalid){ // Perform Some Actions return true; } return false; } Die Anwendung: Beispiel 28-2. authcustom.php include_once 'CustomAuthContainer.php'; include_once 'Auth/Auth.php'; $auth_container = new CustomAuthContainer($params); $myauth = new Auth($auth_container); $myauth->start(); Auth::Auth() Auth::Auth() -- constructor Synopsis Auth::Auth (mixed $storageDriver = "DB", mixed $options = "", string $loginFunction = "" [, boolean $showLogin = TRUE]) Beschreibung Constructor for the authentication system. Parameter string $storageDriver name of the storage driver that should be used, alternatively you can pass a custom Auth_Container object. mixed $options the options that are passed to the storage container string $loginFunction the name of a user-defined function that prints the login screen boolean $showLogin defines if the login is optional or not Hinweise Diese Methode kann nicht statisch aufgerufen werden. Siehe auch Introduction - The storage drivers Beispiel Beispiel 28-1. Using different DB parameters <?php require_once "Auth/Auth.php"; function myOutput($username, $status) { ... /* See example 1 for the full listing */ } $params = array( "dsn" => "mysql://martin:test@localhost/auth", "table" => "myAuth", "usernamecol" => "myUserColumn", "passwordcol" => "myPasswordColumn" ); $a = new Auth("DB", $params, "myOutput"); $a->start(); if ($a->getAuth()) { echo "You have been authenticated successfully."; } ?> This example shows you how you can specifiy alternative names for the database table and the column names. In our example, we use the table myAuth, select the username from the field myUserColumn and the password from the field myPasswordColumn. The default values for this fields are auth, username and password. Note that you can also specify an existing DB object with the dsn parameter instead of a DSN. This feature is necessary if you want to use PEAR::Auth with a database layout that is different from the one PEAR::Auth uses by default. Beispiel Beispiel 28-2. Using different DB parameters <?php require_once "Auth/Auth.php"; function myOutput($username, $status) { ... /* See example 1 for the full listing */ } $a = new Auth(new CustomAuthContainer($options), null, "myOutput"); $a->start(); if ($a->getAuth()) { echo "You have been authenticated successfully."; } ?> This example shows you how you can pass your own storage container to Auth. If the storage containers supplied with Auth are not capable of fulfilling your requirements, you can easliy create your own storage container. Read the storage containers section for more info Introduction - The storage drivers Auth::getAuth() Auth::getAuth() -- check for an authenticated user Synopsis boolean Auth_HTTP::getAuth () Beschreibung Check if the user has been authenticated. Rückgabewert boolean - If the user has already been authenticated, the function returns TRUE. Otherwise it returns FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::getStatus() Auth::getStatus() -- returns informations about the current authentication status Synopsis string Auth::getStatus () Beschreibung This function returns the current status of PEAR::Auth. The return values are constants that are defined by PEAR::Auth. Rückgabewert string - possible values are AUTH_IDLED, AUTH_EXPIRED, AUTH_WRONG_LOGIN Hinweise Diese Methode kann nicht statisch aufgerufen werden. Siehe auch PEAR::Auth constants overview Auth::getUsername() Auth::getUsername() -- get the username of the current authentication session Synopsis string Auth::getUsername () Beschreibung Using this method, one can retrieve the username (often also referred to as the „user id“) of the user of the current authentication session. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::sessionValidThru() Auth::sessionValidThru() -- get the time up to the session is valid Synopsis void Auth::sessionValidThru () Beschreibung This method returns the time in seconds after which the idle time of the current authentication session has reached its limit, which will cause the user to be logged out automatically. If no maximum idle time is set, which is the default configuration of PEAR::Auth, this method will return 0. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::setSessionname() Auth::setSessionname() -- set a custom session name Synopsis void Auth::setSessionname (string name) Beschreibung This function can set a customized name for the session that is created during the login process. The default for this session name is "PHPSESSID". Parameter string $name the session name to use Hinweise Diese Methode kann nicht statisch aufgerufen werden. You have to use setSessionname(), if you are running two or more different applications with Auth on the same domain. If you don't use this function, a user who has once logged in at one of the applications can also use the other applications without logging in again! Auth::setShowLogin() Auth::setShowLogin() -- controls if the login form will be displayed. Turned on by default Synopsis void Auth::setShowLogin (bool $showLogin = true) Beschreibung Controls if the login page will be displayed to the user. Normally you might need to display the login form only on a certain page of your web application. Parameter string $showLogin true if you want to display the login form and false if you want to hide it. Hinweise Diese Methode kann nicht statisch aufgerufen werden. This is equivalent to the 4th paramether of Auth::Auth()() Auth::Auth() Auth::setExpire() Auth::setExpire() -- set expiration time for authentication Synopsis void Auth::setExpire (integer $time [, boolean $add = FALSE]) Beschreibung With this function you can set the maximum expire time that is used by auth to a new value. Parameter integer $time expiration time, number of seconds boolean $add if TRUE $time is added to the existing expiration time, if FALSE the exitsing time value will be replaced. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::setIdle() Auth::setIdle() -- set maximum idle time for authentication Synopsis void Auth::setIdle (integer $time [, boolean $add = FALSE]) Beschreibung With this function one can set the maximum idle time to a new value. The term „idle time“ describes the maximum time interval (in seconds) between two actions by the user. If the maximum idle time is reached, the user will be automatically logged out. If on the other hand the user performs any action within the maximum idle time interval, the idle time is reset. Parameter integer $time idle time in seconds boolean $add if TRUE $time is added to the existing idle time, if FALSE the existing time value will be replaced. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::start() Auth::start() -- start authentication Synopsis void Auth::start () Beschreibung Start the authentication process. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth::checkAuth() Auth::checkAuth() -- check if a session with valid authentication information exists Synopsis boolean Auth_HTTP::checkAuth () Beschreibung Checks if a HTTP session exists that contains valid authentication information. Rückgabewert boolean - If a session with valid authentication information exists, the function return TRUE. Otherwise it returns FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_HTTP Inhaltsverzeichnis Introduction -- to HTTP based authentication Auth_HTTP::Auth_HTTP() -- constructor Auth_HTTP Example -- Example: A simple password protected page Auth_HTTP Example 2 -- Example: A password protected page with multiple rows fetch and md5 password Auth_HTTP::getAuth() -- check for an authenticated user Auth_HTTP::getStatus() -- returns informations about the current authentication status Auth_HTTP::start() -- start authentication Provides a framework for user authentication (aka an "User-Login") based on the HTTP Introduction Introduction -- to HTTP based authentication Instead of generating an HTML driven form like PEAR::Auth does, this class sends header commands to the clients which cause them to present a login box like they are e.g. used in Apache's .htaccess mechanism. Starting with Auth_HTTP 2.1.0, HTTP Digest Authentication (RFC2617) is experimentally supported. Auth_HTTP::Auth_HTTP() Auth_HTTP::Auth_HTTP() -- constructor Synopsis void Auth_HTTP::Auth_HTTP ([string $storageDriver = "DB" [, mixed $options = ""]]) Beschreibung Constructor for the authentication system Parameter string $storageDriver name of the storage driver that should be used mixed $options a string containing some login information or an array containing a bunch of options for the storage driver Hinweise Diese Methode kann nicht statisch aufgerufen werden. Beispiel Beispiel 28-1. Using different DB parameters require_once "Auth/HTTP.php"; $a = new Auth_HTTP("DB", "mysql://test:test@localhost/test"); $a->start(); Auth_HTTP Example Auth_HTTP Example -- Example: A simple password protected page Beispiel <?php // example of Auth_HTTP basic implementation require_once("Auth/HTTP.php"); // setting the database connection options $AuthOptions = array( 'dsn'=>"pgsql://test:test@localhost/testdb", 'table'=>"testable", 'usernamecol'=>"username", 'passwordcol'=>"password", 'cryptType'=>"none", ); // // // // your table name the table username column the table password column password encryption type in your db $a = new Auth_HTTP("DB", $AuthOptions); $a->setRealm('yourrealm'); $a->setCancelText('<h2>Error 401</h2>'); $a->start(); // realm name // error message if authentication fails // starting the authentication process if($a->getAuth()) // checking for autenticated user { echo "Hello $a->username welcome to my secret page"; }; ?> Auth_HTTP Example 2 Auth_HTTP Example 2 -- Example: A password protected page with multiple rows fetch and md5 password Beispiel <?php // example of Auth_HTTP implementation with encrypted password and multiple columns fetch require_once("Auth/HTTP.php"); // setting the database connection options $AuthOptions = array( 'dsn'=>"pgsql://test:test@localhost/testdb", 'table'=>"testable", 'usernamecol'=>"username", 'passwordcol'=>"password", 'cryptType'=>"md5", 'db_fields'=>"*", ); // // // // // your table name the table username column the table password column password encryption type in your db enabling fetch for other db columns $a = new Auth_HTTP("DB", $AuthOptions); $a->setRealm('yourrealm'); $a->setCancelText('<h2>Error 401</h2>'); $a->start(); // realm name // error message if authentication fails // starting the authentication process if($a->getAuth()) // checking for autenticated user { echo "Hello $a->username welcome to my secret page <BR>"; echo "Your details on file are: <BR>"; echo $a->getAuthData('userid'); // retriving other details from the databa echo $a->getAuthData('telephone'); // in this example the user id, telephone echo $a->getAuthData('email'); // and email address }; ?> Auth_HTTP::getAuth() Auth_HTTP::getAuth() -- check for an authenticated user Synopsis boolean Auth_HTTP::getAuth () Beschreibung Check if the user has been authenticated. Rückgabewert boolean - If the user has already been authenticated, the function returns TRUE. Otherwise it returns FALSE. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_HTTP::getStatus() Auth_HTTP::getStatus() -- returns informations about the current authentication status Synopsis string Auth_HTTP::getStatus () Beschreibung This function returns the current status of PEAR::Auth. The return values are constants that are defined by PEAR Auth. Rückgabewert string - possible values are AUTH_IDLED, AUTH_EXPIRED, AUTH_EXPIRED Hinweise Diese Methode kann nicht statisch aufgerufen werden. Siehe auch PEAR Auth constants overview Auth_HTTP::start() Auth_HTTP::start() -- start authentication Synopsis void Auth_HTTP::start () Beschreibung Start the authentication process. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager Inhaltsverzeichnis Introduction to Auth_PrefManager -- Auth_PrefManager is a simple class to manage user or application preferences from a DB compatible database. Tutorial -- A short guide to using Auth_PrefManager constructor Auth_PrefManager::Auth_PrefManager() -- Constructor Auth_PrefManager::clearCache() -- Cleans out the cache. Auth_PrefManager::deleteDefaultPref() -- Deletes a preference for the default user. Auth_PrefManager::deletePref() -- Deletes a preference for the specified user. Auth_PrefManager::getDefaultPref() -- Retrieves a default value. Auth_PrefManager::getPref() -- Get a preference. Auth_PrefManager::setDefaultPref() -- Set the default value for a preference. Auth_PrefManager::setPref() -- Set a preference. Auth_PrefManager::setReturnDefaults() -- Set whether to return default values. Auth_PrefManager::useCache() -- Sets whether the cache should be used. Provides a framework for managing preferences in applications. Introduction to Auth_PrefManager Introduction to Auth_PrefManager -- Auth_PrefManager is a simple class to manage user or application preferences from a DB compatible database. A simple preference manager. Supported features include: • Setting of default values. • Serialization of values before saving to the database. • Support for any database supported by DB Tutorial Tutorial -- A short guide to using Auth_PrefManager Setting up the database The first step is to setup a database to store the values in. For this tutorial it's assumed that you already know the basics of using the PEAR DB class. To set up the default table layout run the following SQL statement: Beispiel 28-1. SQL to setup the table CREATE TABLE `preferences` ( `user_id` varchar( 255 ) NOT NULL default '', `pref_id` varchar( 32 ) NOT NULL default '', `pref_value` longtext NOT NULL , PRIMARY KEY ( `user_id` , `pref_id` ) ); Setting up your first PrefManager object To use Auth_PrefManager we must first create an instance of the base object, as shown below. Beispiel 28-2. Setting up the object <?php require_once('Auth/PrefManager.php'); $dsn = 'mysql://user:password@localhost/database'; // Change the DSN to fit your databas $options = array('serialize' => true); // Enable serialization of data befor $prefmanager = new Auth_PrefManager($dsn, $options); // Create the object. ?> Setting and displaying default preferences Now that we have a PrefManager object, we can make use of it to set some preferences. For this tutorial we're going to allow users to specify their country, and assume that any user who hasn't set their country is somewhere on Earth. First we need to set the default value, using setDefaultPref. Beispiel 28-3. Setting up the object <?php // Continued from example 1. $prefmanager->setDefaultPref("country", "Earth"); ?> Now that the default is set, we can create a (very) basic page, welcoming users with a customised message. Currently this message will only ever display "Welcome to the people of Earth!", since no users have their country set. Beispiel 28-4. Getting preferences $username = "guest"; <h1>Welcome to the people of <?=$prefmanager->getPref($username, "country")?>!</h1> Setting a user's preferences Finally we need a way for people to choose which country they're in. This is going to be done with a simple text box, and you should obviously be a little more careful in a real application about allowing users to set preferences for people! The Reset Country button will delete the user's preference, and cause the default to be displayed again. Beispiel 28-5. Getting preferences <h1>Set Country</h1> // Allow users to set their country and username. if (isset($_POST['submit'])) { $username = htmlspecialchars($_POST['username']); $prefmanager->setPref($username, 'country', $_POST['country']); } else if (isset($_POST['reset'])) { $username = htmlspecialchars($_POST['username']); $prefmanager->deletePref($username, 'country'); } else { $username = 'guest'; } ?> <h1>Welcome to the people of <?=$prefmanager->getPref($username, "country")?>!</h1> <h2>Set Country And Username</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>"> <label for="username">Username</label> <input name="username" value="<?=$username?>" />< <label for="country">Country</label> <input name="country" value="<?=$prefmanager->getPr <input type="submit" name="submit" value="Set Country" /> <input type="submit" name="res </form> Now once a user has entered their username, and their country, whenever they login they'll get a personalized welcome. Full sourcecode Beispiel 28-6. Sourcecode for the example page <h1>Set Country</h1> <?php require_once('Auth/PrefManager.php'); // Create the PrefManager object. // Change the DSN to fit your database. $dsn = 'mysql://user:password@localhost/database'; // Enable serialization of data before saving, this ensures that the values are retrieved $options = array('serialize' => true); // Create the object. $prefmanager = new Auth_PrefManager($dsn, $options); // Set the default value (this doesn't need to be done everytime the script is run). $prefmanager->setDefaultPref("country", "Earth"); // Allow users to set their country and username. if (isset($_POST['submit'])) { $username = htmlspecialchars($_POST['username']); $prefmanager->setPref($username, 'country', $_POST['country']); } else if (isset($_POST['reset'])) { $username = htmlspecialchars($_POST['username']); $prefmanager->deletePref($username, 'country'); } else { $username = 'guest'; } ?> <h1>Welcome to the people of <?=$prefmanager->getPref($username, "country")?>!</h1> <h2>Set Country And Username</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>"> <label for="username">Username</label> <input name="username" value="<?=$username?>" />< <label for="country">Country</label> <input name="country" value="<?=$prefmanager->getPr <input type="submit" name="submit" value="Set Country" /> <input type="submit" name="res </form> constructor Auth_PrefManager::Auth_PrefManager() constructor Auth_PrefManager::Auth_PrefManager() -- Constructor Synopsis require_once '/PrefManager.php'; bool constructor Auth_PrefManager::Auth_PrefManager (string $dsn, array [$properties = NULL], string $defaultUser) Beschreibung The $properties property should be an associative array, with the structure below. Any options not set will be set to the default. 'table' The table to retrieve preferences from. [preferences] 'userColumn' The field to use for matching user IDs. [user_id] 'nameColumn' The field to use for matching preference names. [pref_name] 'valueColumn' The field to retrieve preference values from. [pref_value] 'defaultUser' The user ID to use for retrieving default values. [__default__] 'cacheName' The key to use for the cache in $_SESSION. [prefsCache] 'useCache' Should values be cached for later use. [true] 'serialize' Should values be serialized before saving to the database, and unserialized on retrieval. [false] Options: table: The table to get prefs from. [preferences] userColumn: The field name to search for userid's [user_id] nameColumn: The field name to search for preference names [pref_name] valueColumn: The field name to search for preference values [pref_value] defaultUser: The userid assigned to default values [__default__] cacheName: The name of cache in the session variable ($_SESSION[cacheName]) [prefsCache] useCache: Whether or not values should be cached. serialize: Should preference values be serialzed before saving? Parameter string $dsn The DSN of the database connection to make, or a DB object. array $properties An array of properties to set. string $defaultUser The default user to manage for. Rückgabewert returns Success or failure. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Users with preferences created using Auth_PrefManager 1.0.4 or earlier shouldn't enable the serialize option, as it may result in data loss. Auth_PrefManager::clearCache() Auth_PrefManager::clearCache() -- Cleans out the cache. Synopsis require_once '/PrefManager.php'; void Auth_PrefManager::clearCache () Beschreibung Clears the cache of preferences stored in the current user's session. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::deleteDefaultPref() Auth_PrefManager::deleteDefaultPref() -- Deletes a preference for the default user. Synopsis require_once '/PrefManager.php'; bool Auth_PrefManager::deleteDefaultPref (string $pref_id) Beschreibung Deletes the default value for the preference passed as $pref_id. Parameter string $pref_id The preference to delete. Rückgabewert returns Success/Failure Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::deletePref() Auth_PrefManager::deletePref() -- Deletes a preference for the specified user. Synopsis require_once '/PrefManager.php'; bool Auth_PrefManager::deletePref (string $user_id, string $pref_id) Beschreibung Deletes the preference $pref_id for $user_id if one is set. Parameter string $user_id The userid of the user to delete from. string $pref_id The preference to delete. Rückgabewert returns Success/Failure Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::getDefaultPref() Auth_PrefManager::getDefaultPref() -- Retrieves a default value. Synopsis require_once '/PrefManager.php'; mixed Auth_PrefManager::getDefaultPref (string $pref_id) Beschreibung Retrieves the default value for $pref_id, even if there is currently a user ID set for the object being used. Parameter string $pref_id The name of the preference to get. Rückgabewert returns The value if it's found, or NULL if it isn't. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::getPref() Auth_PrefManager::getPref() -- Get a preference. Synopsis require_once '/PrefManager.php'; mixed Auth_PrefManager::getPref (string $user_id, string $pref_id, bool [$showDefaults = TRUE]) Beschreibung Retrieves the preference specified for a user, or, if returning default values is enabled, the default. Parameter string $user_id The user to get the preference for. string $pref_id The preference to get. boolean $showDefaults Should default values be searched (overrides the global setting). Rückgabewert returns The value if it's found, or NULL if it isn't. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::setDefaultPref() Auth_PrefManager::setDefaultPref() -- Set the default value for a preference. Synopsis require_once '/PrefManager.php'; bool Auth_PrefManager::setDefaultPref (string $pref_id, mixed $value) Beschreibung Sets the default value for $pref_id, which will be retrieved if a user doesn't have the preference set. Parameter string $pref_id The name of the preference to set. mixed $value The value to set it to. Rückgabewert returns Sucess or failure. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::setPref() Auth_PrefManager::setPref() -- Set a preference. Synopsis require_once '/PrefManager.php'; bool Auth_PrefManager::setPref (string $user_id, string $pref_id, mixed $value) Beschreibung Sets the value for $pref_id. Parameter string $user_id The user to set for. string $pref_id The preference to set. mixed $value The value it should be set to. Rückgabewert returns Sucess or failure. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. Auth_PrefManager::setReturnDefaults() Auth_PrefManager::setReturnDefaults() -- Set whether to return default values. Synopsis require_once '/PrefManager.php'; void Auth_PrefManager::setReturnDefaults (mixed [$returnDefaults = TRUE]) Beschreibung Set whether a default value should be returned by getPref() if no value was set for the specified user. Parameter mixed $returnDefaults Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. getDefaultPref() will always return the default value. Auth_PrefManager::useCache() Auth_PrefManager::useCache() -- Sets whether the cache should be used. Synopsis require_once '/PrefManager.php'; void Auth_PrefManager::useCache (bool [$use = TRUE]) Beschreibung Sets whether the caching system should be used or not. If the cache is enabled then any values retrieved will be saved in the user's session to reduce load on the database. Parameter boolean $use Should the cache be used. Fehler-Meldungen Es werden keine Exceptions ausgelöst. Hinweise Diese Methode kann nicht statisch aufgerufen werden. LiveUser Inhaltsverzeichnis LiveUser -- Getting started guide. LiveUser LiveUser -- Getting started guide. LiveUser and LiveUser_Admin LiveUser is an advanced authentication and permission framework that comes with a large array of out of the box features which can be used optionally. LiveUser is split in two packages. The base package is called LiveUser and is often refered to as the "client" and is what will be commonly be used to authenticate a specific user and then optionally make permission checks on this user. The other is the LiveUser_Admin package which provides various ways to manage all relevant data, like users, groups/roles, rights and their relations. LiveUser provides the following key features: The LiveUser class takes care of the login process and can be configured to use a certain permission container and one or more different auth containers. That means, you can have your users' data scattered amongst many data containers and have the LiveUser class try each defined container until the user is found. For example, you can have all website users who can apply for a new account online on the webserver's local database. Also, you want to enable all your company's employees to login to the site without the need to create new accounts for all of them. To achieve that, a second container can be defined to be used by the LiveUser class. You can also define a permission container of your choice that will manage the rights for each user. Depending on the container, you can implement any kind of permission schemes for your application while having one consistent API. Using different permission and auth containers, it's easily possible to integrate newly written applications with older ones that have their own ways of storing permissions and user data. Just make a new container type and you're ready to go! Currently available are containers using: PEAR::DB, PEAR::MDB, PEAR::MDB2, PEAR::XML_Tree and PEAR::Auth. LiveUser_Admin provides the following key features You'll be able to add/edit/delete/get things like: • Rights • Users • Groups • Areas • Applications • Subgroups • ImpliedRights And all other entities within LiveUser. At the moment we support the following storage containers: • DB • MDB • MDB2 Aside from the normal ressources provided in PEAR you can contact the dedicated LiveUser mailinglist: [email protected] http://mailman.21sthq.de/mailman/listinfo/liveuser.url There is also an external wiki dedicated to LiveUser: http://oss.backendmedia.com/LiveUser/ At this point LiveUser is still in beta stage. Even so LiveUser is already being used on a wide range of production websites. A non exaustive list can be found here: http://oss.backendmedia.com/LiveUser/References The current roadmap for LiveUser can be viewed here: http://oss.backendmedia.com/LiveUser/Client The current roadmap for LiveUser_Admin can be viewed here: http://oss.backendmedia.com/LiveUser/Admin A detailed introduction to the core concepts of LiveUser can be found in the following phpmag article: http://www.phpmag.net/magphpde/magphpde_article/psecom,id,595,nodeid,21.html This article was published in april 2004 and is therefore not entirely uptodate. However the core principles remain unchanged and most of the recent changes resolve around making the API more consistent and flexible. As a result the APi examples are mostly out of date. The article also fails to mention the fact that the permission containers are now separated in a logic and a storage layer. This was done to remove logic duplication as well as to allow the implementation of a stackable storage approach, where users could configure LiveUser to first call a cache storage layer, which in turn would fetch the necessary data on demand from the actual storage layer. Furthermore the article also does not mention the SQL generator used in the LiveUser_Admin package. This feature has made the API much more flexible since now the entire storage schema is configurable and extensible. It also means that more or less any sort of filtering can be applied with on demand joining. On overview of this API can be found here: http://oss.backendmedia.com/LiveUser/AdminFilters Before you can use LiveUser you will need to setup the necessary data structures for the chosen container. Through the use of the configuration options it is possible to customize alot of the aspects of the storage layer. Most notably it is possible to alias field and table names. This should make it possible to integrate any legacy data into LiveUser. Depending on the container chosen you may have to use the database schema installer. The installer requires the MDB2_Schema and MDB2 packages and is able to handle most configuration options properly to be able to install the database schema directly into your database. You can find the install class in "[PEAR]/data/misc/schema/install.php". There is some sample code which is partially commented out at the top. Basically its a two step process for both the auth and perm: (1) generate the schema xml file, (2) install the schema. During the installation process the installer will create backup files of the installed schema. These files will enable the installer to attempt to alter the database if run again with a different configuration. However if these files exist the installer will always attempt to alter instead of creating the tables from scratch as long as you are using the sam DSN. If for some reason you need to create the tables from scratch again then please delete the backup files with the matching DSN. You can find the installer inside the data directory of your pear install directory. Its called install.php and at the top of the file you will find a number of sample API calls which are commented out. An ER diagram of the database structure can be found here: http://www.backendmedia.com/LiveUser/liveuser_db_schema.png The diagram details what tables are needed for what permission complexity level. If you want to prevent the installer from installing tables you dont need you can modify the "tables" property of the instance of the permission container you pass to the generateSchema() method in the installer. In order to get started with LiveUser the following two articles should help in getting off the ground: http://jystewart.net/process/archives/2005/07/configuring-liveuser http://jystewart.net/process/archives/2005/08/getting-started-with-liveuserpermissions/ The observer support in LiveUser allows users to automatically have LiveUser call certain callbacks on a number of internal events. It is documented here: http://oss.backendmedia.com/LiveUser/Observers Both packages also ship with a wide range of examples. These will be installed into the "docs" directory in your PEAR install directory. They try to illustrate various usage scenarios. The database examples come with a schema file please see the demodata.php in the examples root folder of the LiveUser package for details on how to install these schema files from the command line or from a browser. You will once again need MDB2_Schema to be able to install the schema files. LiveUser package: • • • • example1 illustrates using only a single authentication source (in this case XML) with several aliased fields and a custom field. example2 illustrates using a single authentication with permissions (in this case XML) with the optional remember me feature and several aliased fields example4 illustrates using multiple authentication sources (XML and database) with permissions (database) in a more real world news administration scenario example4 illustrates using single authentication sources (database) with permissions (database) in a more real world news administration scenario LiveUser_Admin package: • • example 1 illustrates various API calls to most methods in the admin API and custom fields example3 illustrates using single authentication sources (database) with permissions (database) and the optional remember me feature in a more real world restricted page access scenario Kapitel 29. Benchmarking Stellt Packages für Benchmarking und Profiling bereit. Kapitel 30. Caching Stellt Packages für Caches bereit. Cache_Lite Inhaltsverzeichnis Einführung -- Einführung zu Cache_Lite constructor Cache_Lite::Cache_Lite() -- Constructor Cache_Lite::get() -- Test if a cache is available and (if yes) return it Cache_Lite::save() -- Save some data in a cache file Cache_Lite::remove() -- Remove a cache file Cache_Lite::clean() -- Clean the cache Cache_Lite::setToDebug() -- Set to debug mode Cache_Lite::setLifeTime() -- Set a new life time Cache_Lite::saveMemoryCachingState() -Cache_Lite::getMemoryCachingState() -Cache_Lite::lastModified() -- Return the cache last modification time