openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit a7454a14516981d10bb673c6ddb8dc3c9c8250be
parent 42acf4d2ae5d97ec8825afe3e9c43365e6c7191f
Author: dankert <devnull@localhost>
Date:   Mon, 27 Dec 2010 23:54:20 +0100

Service-Klassen verschieben: serviceClasses -> util

Diffstat:
do.php | 2+-
serviceClasses/.htaccess | 3---
serviceClasses/AbstractTree.class.php | 171-------------------------------------------------------------------------------
serviceClasses/AdministrationTree.class.php | 471-------------------------------------------------------------------------------
serviceClasses/Api.class.php | 121-------------------------------------------------------------------------------
serviceClasses/ArchiveTar.class.php | 398-------------------------------------------------------------------------------
serviceClasses/ArchiveUnzip.class.php | 448-------------------------------------------------------------------------------
serviceClasses/ArchiveZip.class.php | 90-------------------------------------------------------------------------------
serviceClasses/Code.class.php | 54------------------------------------------------------
serviceClasses/Dynamic.class.php | 150-------------------------------------------------------------------------------
serviceClasses/FileUtils.class.php | 76----------------------------------------------------------------------------
serviceClasses/Ftp.class.php | 246-------------------------------------------------------------------------------
serviceClasses/GlobalFunctions.class.php | 72------------------------------------------------------------------------
serviceClasses/Html.class.php | 147-------------------------------------------------------------------------------
serviceClasses/Http.class.php | 499-------------------------------------------------------------------------------
serviceClasses/JSON.class.php | 809-------------------------------------------------------------------------------
serviceClasses/Ldap.class.php | 185-------------------------------------------------------------------------------
serviceClasses/Line.class.php | 153-------------------------------------------------------------------------------
serviceClasses/Logger.class.php | 195-------------------------------------------------------------------------------
serviceClasses/Mail.class.php | 572-------------------------------------------------------------------------------
serviceClasses/OpenId.class.php | 468-------------------------------------------------------------------------------
serviceClasses/Preferences.class.php | 60------------------------------------------------------------
serviceClasses/ProjectTree.class.php | 477-------------------------------------------------------------------------------
serviceClasses/Publish.class.php | 365-------------------------------------------------------------------------------
serviceClasses/Session.class.php | 226-------------------------------------------------------------------------------
serviceClasses/Sql.class.php | 335-------------------------------------------------------------------------------
serviceClasses/TemplateEngine.class.php | 508-------------------------------------------------------------------------------
serviceClasses/Text.class.php | 416-------------------------------------------------------------------------------
serviceClasses/Transformer.class.php | 95-------------------------------------------------------------------------------
serviceClasses/TreeElement.class.php | 74--------------------------------------------------------------------------
serviceClasses/Upload.class.php | 110-------------------------------------------------------------------------------
serviceClasses/XML.class.php | 170-------------------------------------------------------------------------------
serviceClasses/include.inc.php | 65-----------------------------------------------------------------
util/.htaccess | 3+++
util/AbstractTree.class.php | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/AdministrationTree.class.php | 471+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Api.class.php | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/ArchiveTar.class.php | 398+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/ArchiveUnzip.class.php | 448+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/ArchiveZip.class.php | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Code.class.php | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Dynamic.class.php | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/FileUtils.class.php | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Ftp.class.php | 246+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/GlobalFunctions.class.php | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Html.class.php | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Http.class.php | 499+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/JSON.class.php | 809+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Ldap.class.php | 185+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Line.class.php | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Logger.class.php | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Mail.class.php | 572+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/OpenId.class.php | 468+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Preferences.class.php | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/ProjectTree.class.php | 477+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Publish.class.php | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Session.class.php | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Sql.class.php | 335+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/TemplateEngine.class.php | 508+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Text.class.php | 416+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Transformer.class.php | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/TreeElement.class.php | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/Upload.class.php | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/XML.class.php | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
util/include.inc.php | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
65 files changed, 8230 insertions(+), 8230 deletions(-)

diff --git a/do.php b/do.php @@ -43,7 +43,7 @@ define('OR_TYPE_FOLDER','folder'); define('OR_ACTIONCLASSES_DIR' ,'./action/' ); define('OR_FORMCLASSES_DIR' ,'./formClasses/' ); define('OR_OBJECTCLASSES_DIR' ,'./model/' ); -define('OR_SERVICECLASSES_DIR','./serviceClasses/' ); +define('OR_SERVICECLASSES_DIR','./util/' ); define('OR_LANGUAGE_DIR' ,'./language/' ); define('OR_DBCLASSES_DIR' ,'./db/' ); define('OR_DYNAMICCLASSES_DIR','./dynamicClasses/' ); diff --git a/serviceClasses/.htaccess b/serviceClasses/.htaccess @@ -1,2 +0,0 @@ -order deny,allow -deny from all- \ No newline at end of file diff --git a/serviceClasses/AbstractTree.class.php b/serviceClasses/AbstractTree.class.php @@ -1,170 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Darstellen einer Baumstruktur mit Funktion zum Laden, Oeffnen und Schliessen - * von Teilbaeumen - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class AbstractTree -{ - /** - * Alle Elemente des Baumes - */ - var $elements = array(); - - var $tempElements = array(); - var $userIsAdmin = false; - - var $autoOpen = array(0,1); - - var $opened = array(); - - /** - * Hoechste Element-Id - * @type Integer - */ - var $maxId; - - // Konstruktor - function AbstractTree() - { - // Feststellen, ob der angemeldete Benutzer ein Administrator ist - $user = Session::getUser(); - $this->userIsAdmin = $user->isAdmin; - - // Wurzel-Element laden - $this->root(); - $this->elements[0] = $this->tempElements[0]; - $this->tempElements = array(); - $this->maxId = 0; - - foreach( $this->autoOpen as $openId ) - $this->open($openId); - } - - function refresh() { - - $this->elements = array(); - - // Wurzel-Element laden - $this->root(); - $this->elements[0] = $this->tempElements[0]; - $this->tempElements = array(); - $this->maxId = 0; - - $oids = $this->opened; - $this->opened = array(); - foreach( $oids as $oid) - { - if ( isset($this->elements[$oid]) ) - $this->open($oid); - } - } - - - - function all() { - - $this->elements = array(); - $this->opened = array(); - - // Wurzel-Element laden - $this->root(); - $this->elements[0] = $this->tempElements[0]; - $this->tempElements = array(); - $this->maxId = 0; - - for( $eid=0;isset($this->elements[$eid]); $eid++) - { - $this->open($eid); - } - } - - - /** - * Oeffnen eines Teilbaumes. Es wird der eindeutige Name des zu oeffnenden Teilbaumes als - * Parameter uebergeben - * @param elementName der Name des Elementes, welches zu oeffnen ist - */ - function open( $elementId ) - { - $k = array_search($elementId,$this->opened); - if ( $k !== false ) - return; // Ist schon offen. Evtl. Reload gedrückt? - - $this->opened[] = $elementId; - $funcName = $this->elements[$elementId]->type; - if ( empty($funcName) ) - return; - - $this->$funcName( $this->elements[$elementId]->internalId ); - - // Wenn keine Unterelemente gefunden, dann die ?ffnen-Funktion deaktivieren - if ( count( $this->tempElements ) == 0 ) - $this->elements[$elementId]->type = ''; - - foreach( $this->tempElements as $treeElement ) - { - $this->maxId++; - $this->elements[$elementId]->subElementIds[] = $this->maxId; - $this->elements[$this->maxId] = $treeElement; - } - - if ( count($this->tempElements)==1 ) - { - $this->tempElements = array(); - $this->open($this->maxId); - } - - $this->tempElements = array(); - } - - - /** - * Schliessen eines Teilbaumes - * @param elementName der Name des Elementes, welches zu schliessen ist - */ - - function close( $elementId ) - { - $this->elements[$elementId]->subElementIds = array(); - - $k = array_search($elementId,$this->opened); - if ( $k !== false ) - unset($this->opened[$k]); - } - - - /** - * Hinzufuegen eines Baum-Elementes - * @param TreeElement Hinzuzufuegendes Baumelement - */ - function addTreeElement( $treeElement ) - { - $this->tempElements[] = $treeElement; - } - - -} - -?>- \ No newline at end of file diff --git a/serviceClasses/AdministrationTree.class.php b/serviceClasses/AdministrationTree.class.php @@ -1,470 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Darstellen einer Baumstruktur mit Administrationfunktionen - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class AdministrationTree extends AbstractTree -{ - /** - * Alle Elemente des Baumes - */ - var $elements; - var $confCache = array(); - - function root() - { - if ( !$this->userIsAdmin ) - Http::notAuthorized('Administration-Tree is only visible for admins.'); - - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_ADMINISTRATION'); - $treeElement->description = lang('GLOBAL_ADMINISTRATION'); - $treeElement->type = 'administration'; - $treeElement->icon = 'administration'; - - $this->addTreeElement( $treeElement ); - $this->autoOpen[] = 2; - } - - - - function administration() - { - global $conf; - $conf_config = $conf['interface']['config']; - - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_PROJECTS'); - $treeElement->description = lang('GLOBAL_PROJECTS'); - $treeElement->url = Html::url('project','listing',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'project_list'; - $treeElement->type = 'projects'; - $treeElement->target = 'cms_main'; - - $this->addTreeElement( $treeElement ); - - - $treeElement = new TreeElement(); - $treeElement->text = lang('USER_AND_GROUPS'); - $treeElement->description = lang('USER_AND_GROUPS'); - $treeElement->icon = 'user_list'; - $treeElement->type = 'userandgroups'; - - $this->addTreeElement( $treeElement ); -// $this->userandgroups(0);; - - if ( $conf_config['enable'] ) - { - $treeElement = new TreeElement(); - $treeElement->text = lang('PREFERENCES'); - $treeElement->description = lang('PREFERENCES'); - $treeElement->icon = 'config_folder'; - $treeElement->type = 'prefs'; - - $this->addTreeElement( $treeElement ); - } - - // Wechseln zu: Projekte... - /* - foreach( Project::getAll() as $id=>$name ) - { - $treeElement = new TreeElement(); - - $treeElement->text = lang('PROJECT').' '.$name; - $treeElement->url = Html::url(array('action' =>'tree', - 'subaction' =>'reload', - 'projectid' =>$id )); - $treeElement->icon = 'project'; - $treeElement->description = ''; - $treeElement->target = 'cms_tree'; - - $this->addTreeElement( $treeElement ); - } - */ - } - - - - function userandgroups( $id ) - { - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_USER'); - $treeElement->description = lang('GLOBAL_USER'); - $treeElement->url = Html::url('user','listing',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'user_list'; - $treeElement->target = 'cms_main'; - $treeElement->type = 'users'; - - $this->addTreeElement( $treeElement ); - - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_GROUPS'); - $treeElement->description = lang('GLOBAL_GROUPS'); - $treeElement->url = Html::url('group','listing',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'user_list'; - $treeElement->target = 'cms_main'; - $treeElement->type = 'groups'; - - $this->addTreeElement( $treeElement ); - } - - - function projects( $id ) - { - // Schleife ueber alle Projekte - foreach( Project::getAll() as $id=>$name ) - { - $treeElement = new TreeElement(); - - $treeElement->internalId = $id; - $treeElement->text = $name; - $treeElement->url = Html::url('project','edit',$id,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'project'; - $treeElement->description = ''; - $treeElement->target = 'cms_main'; - - $this->addTreeElement( $treeElement ); - } - } - - - - function prefs_system( $id ) - { - $system = array( 'time' => date('r'), - 'os' => php_uname('s'), - 'host' => php_uname('n'), - 'release'=> php_uname('r'), - 'machine'=> php_uname('m'), - 'owner' => get_current_user(), - 'pid' => getmypid() ); - - foreach( $system as $key=>$value ) - { - $treeElement = new TreeElement(); - $treeElement->text = $key.'='.$value; - $treeElement->icon = 'config_property'; - $this->addTreeElement( $treeElement ); - $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); - } - - if ( function_exists('getrusage') ) // Funktion existiert auf WIN32 nicht. - { - foreach( getrusage() as $name=>$value ); - { - $treeElement = new TreeElement(); - $treeElement->text = $name.':'.$value; - $treeElement->description = lang('SETTING')." '".$name."'".(!empty($value)?': '.$value:''); - $treeElement->icon = 'config_property'; - $this->addTreeElement( $treeElement ); - } - } - } - - - - - function prefs_php( $id ) - { - $php_prefs = array( 'version' => phpversion(), - 'SAPI' => php_sapi_name(), - 'session-name' => session_name(), - 'magic_quotes_gpc' => get_magic_quotes_gpc(), - 'magic_quotes_runtime'=> get_magic_quotes_runtime() ); - - foreach( array('upload_max_filesize', - 'file_uploads', - 'memory_limit', - 'max_execution_time', - 'post_max_size', - 'display_errors', - 'register_globals' - ) as $iniName ) - $php_prefs[ $iniName ] = ini_get( $iniName ); - - foreach( $php_prefs as $key=>$value ) - { - $treeElement = new TreeElement(); - $treeElement->text = $key.'='.$value; - $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); - $treeElement->icon = 'config_property'; - $this->addTreeElement( $treeElement ); - } - } - - - - function prefs_extensions( $id ) - { - $extensions = get_loaded_extensions(); - asort( $extensions ); - - foreach( $extensions as $id=>$extensionName ) - { - $treeElement = new TreeElement(); - $treeElement->text = $extensionName; - $treeElement->icon = 'config_property'; - $treeElement->internalId = $id; - $this->addTreeElement( $treeElement ); - } - } - - - - function prefs_extension( $id ) - { - $extensions = get_loaded_extensions(); - $functions = get_extension_funcs( $extensions[$id] ); - asort( $functions ); - - foreach( $functions as $functionName ) - { - $treeElement = new TreeElement(); - $treeElement->text = $functionName; - $treeElement->icon = 'config_property'; - $this->addTreeElement( $treeElement ); - } - } - - - /** - * Anzeigen von Einstellungen. - * - * @param $id - */ - function prefs( $id ) - { - global $conf; - - if ( !@$conf['security']['show_system_info'] ) - return; - - $conf_config = $conf['interface']['config']; - - - $treeElement = new TreeElement(); - - $treeElement->internalId = 0; - $treeElement->text = 'OpenRat'; - $treeElement->icon = 'config_folder'; - - if ( !empty($conf_config['file_manager_url']) ) - $treeElement->url = $conf_config['file_manager_url']; - $treeElement->target = '_blank'; - $treeElement->description = ''; - $treeElement->type = 'prefs_cms'; - $this->addTreeElement( $treeElement ); - - - - if ( !empty($conf_config['show_system']) ) - { - $treeElement = new TreeElement(); - - $treeElement->internalId = 0; - $treeElement->text = lang('GLOBAL_SYSTEM'); - $treeElement->icon = 'config_folder'; - - $treeElement->description = ''; - $treeElement->target = 'cms_main'; - $treeElement->type = 'prefs_system'; - $this->addTreeElement( $treeElement ); - } - - - if ( !empty($conf_config['show_interpreter']) ) - { - $treeElement = new TreeElement(); - - $treeElement->internalId = 0; - $treeElement->text = lang('GLOBAL_PHP'); - $treeElement->icon = 'config_folder'; - - $treeElement->description = ''; - $treeElement->target = 'cms_main'; - $treeElement->type = 'prefs_php'; - $this->addTreeElement( $treeElement ); - } - - - if ( !empty($conf_config['show_extensions']) ) - { - $treeElement = new TreeElement(); - - $treeElement->internalId = 0; - $treeElement->text = lang('GLOBAL_EXTENSIONS'); - $treeElement->icon = 'config_folder'; - - $treeElement->description = ''; - $treeElement->target = 'cms_main'; - $treeElement->type = 'prefs_extensions'; - $this->addTreeElement( $treeElement ); - } - } - - - function prefs_cms( $id ) - { - global $conf; - - if ( $id == 0 ) - { - $tmpConf = $conf; - } - else - $tmpConf = $this->confCache[$id]; - - if ( !is_array($tmpConf) ) - $tmpConf = array('unknown'); - - foreach( $tmpConf as $key=>$value ) - { - if ( is_array($value) ) - { - $this->confCache[crc32($key)] = $value; - - $treeElement = new TreeElement(); - - $treeElement->internalId = crc32($key); - $treeElement->text = $key; -// if ( $id == 0 ) -// $treeElement->url = Html::url('main','prefs',0,array('conf'=>$key)); - $treeElement->icon = 'config_folder'; - - $treeElement->description = count($value).' '.lang('SETTINGS'); - $treeElement->target = 'cms_main'; - $treeElement->type = 'prefs_cms'; - $this->addTreeElement( $treeElement ); - } - else - { - // Die PHP-funktion 'parse_ini_file()' liefert alle Einstellungen leider nur als String - // Daher weiß man hier nicht, ob '1' nun '1' oder 'true' heißen soll. - if ( $value=='' ) - // Anzeige 'Leer' - $value = lang('EMPTY'); - elseif ( $value=='0' ) - // Anzeige 'Nein' - $value = $value.' ('.lang('IS_NO').')'; - elseif ( $value=='1' ) - // Anzeige 'Ja' - $value = '+'.$value.' ('.lang('IS_YES').')'; - elseif ( is_numeric($value) ) - // Anzeige numerische Werte - $value = ($value>0?'+':'').$value; - else - // Anzeige von Zeichenketten - $value = $value; - - $this->confCache[crc32($key)] = $value; - - if ( strpos($key,'pass') !== FALSE ) - $value = '***'; // Kennwörter nicht anzeigen - - $treeElement = new TreeElement(); - $treeElement->text = $key.': '.$value; - $treeElement->icon = 'config_property'; - $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); - - $this->addTreeElement( $treeElement ); - } - } - } - - - function users( $id ) - { - foreach( User::getAllUsers() as $user ) - { - $treeElement = new TreeElement(); - - $treeElement->internalId = $user->userid; - $treeElement->text = $user->name; - $treeElement->url = Html::url('user','edit', - $user->userid,array(REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = 'user'; - - $desc = $user->fullname; - - if ( $user->isAdmin ) - $desc .= ' ('.lang('USER_ADMIN').') '; - if ( $user->desc == "" ) - $desc .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - else - $desc .= ' - '.$user->desc; - - $treeElement->description = $desc; - $treeElement->target = 'cms_main'; - - $this->addTreeElement( $treeElement ); - } - } - - - function groups( $id ) - { - - foreach( Group::getAll() as $id=>$name ) - { - $treeElement = new TreeElement(); - - $g = new Group( $id ); - $g->load(); - - $treeElement->internalId = $id; - $treeElement->text = $g->name; - $treeElement->url = Html::url('group','edit',$id, - array(REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = 'group'; - $treeElement->description = lang('GLOBAL_GROUP').' '.$g->name.': '.implode(', ',$g->getUsers()); - $treeElement->target = 'cms_main'; - $treeElement->type = 'userofgroup'; - - $this->addTreeElement( $treeElement ); - } - } - - - function userofgroup( $id ) - { - $g = new Group( $id ); - - foreach( $g->getUsers() as $id=>$name ) - { - $treeElement = new TreeElement(); - - $u = new User( $id ); - $u->load(); - $treeElement->text = $u->name; - $treeElement->url = Html::url('user','edit',$id,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'user'; - $treeElement->description = $u->fullname; - $treeElement->target = 'cms_main'; - - $this->addTreeElement( $treeElement ); - } - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Api.class.php b/serviceClasses/Api.class.php @@ -1,120 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// DaCMS Content Management System -// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.5 2004-11-10 22:50:10 dankert -// Neue Methode execute() -// -// Revision 1.4 2004/10/06 09:53:39 dankert -// Benutzung auch nicht-statisch -// -// Revision 1.3 2004/05/03 20:21:34 dankert -// neu: setObjectId() -// -// Revision 1.2 2004/05/02 15:04:16 dankert -// Einf?gen package-name (@package) -// -// Revision 1.1 2004/04/24 17:03:29 dankert -// Initiale Version -// -// --------------------------------------------------------------------------- - -/** - * Service-Klasse fuer allgemeine Interface-Methoden. Insbesondere - * in Code-Elementen kann und soll auf diese Methoden zurueckgegriffen - * werden. - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Api -{ - var $output = ''; - var $objectid = 0; - var $page; - - function db() - { - return db_connection(); - } - - function pageid() - { - echo 'WARNING: pageid() deprecated!<br>'; - global $SESS; - return $SESS['objectid']; - } - - function getObjectId() - { - return $this->objectid; - } - - function setObjectId( $objectid ) - { - $this->objectid = $objectid; - } - - function getRootObjectId() - { - return Folder::getRootObjectId(); - } - - function folderid() - { - global $SESS; - return $SESS['folderid']; - } - - - function execute( $code ) - { - global $conf_tmpdir; - $code = "<?php\n".$code."\n?>"; - - $tmp = $conf_tmpdir.'/'.md5(microtime()).'.tmp'; - $f = fopen( $tmp,'w' ); - fwrite( $f,$code ); - fclose( $f ); - - require( $tmp ); // Ausfuehren des temporaeren PHP-Codes - - unlink( $tmp ); - $inhalt = Api::getOutput(); - $this->output( $inhalt ); - } - - function delOutput() - { - $this->output = ''; - } - - function output( $text ) - { - $this->output .= $text; - } - - - function getOutput() - { - return $this->output; - } -}- \ No newline at end of file diff --git a/serviceClasses/ArchiveTar.class.php b/serviceClasses/ArchiveTar.class.php @@ -1,397 +0,0 @@ -<?php -/* -======================================================================= -Name: - tar Class - -Author: - Josh Barger <joshb@npt.com> - -Description: - This class reads and writes Tape-Archive (TAR) Files and Gzip - compressed TAR files, which are mainly used on UNIX systems. - This class works on both windows AND unix systems, and does - NOT rely on external applications!! Woohoo! - -Usage: - Copyright (C) 2002 Josh Barger - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details at: - http://www.gnu.org/copyleft/lesser.html - - If you use this script in your application/website, please - send me an e-mail letting me know about it :) - -Bugs: - Please report any bugs you might find to my e-mail address - at joshb@npt.com. If you have already created a fix/patch - for the bug, please do send it to me so I can incorporate it into my release. - -Version History: - 1.0 04/10/2002 - InitialRelease - - 2.0 04/11/2002 - Merged both tarReader and tarWriter - classes into one - - Added support for gzipped tar files - Remember to name for .tar.gz or .tgz - if you use gzip compression! - :: THIS REQUIRES ZLIB EXTENSION :: - - Added additional comments to - functions to help users - - Added ability to remove files and - directories from archive - 2.1 04/12/2002 - Fixed serious bug in generating tar - - Created another example file - - Added check to make sure ZLIB is - installed before running GZIP - compression on TAR - 2.2 05/07/2002 - Added automatic detection of Gzipped - tar files (Thanks go to J�rgen Falch - for the idea) - - Changed "private" functions to have - special function names beginning with - two underscores -======================================================================= -*/ - - -class ArchiveTar -{ - // Unprocessed Archive Information - var $filename; - var $isGzipped; - var $tar_file; - - // Processed Archive Information - var $files; - var $directories; - var $numFiles; - var $numDirectories; - - - // Class Constructor -- Does nothing... - function tar() { - return true; - } - - - // Computes the unsigned Checksum of a file's header - // to try to ensure valid file - // PRIVATE ACCESS FUNCTION - function __computeUnsignedChecksum($bytestring) - { - $unsigned_chksum=0; - for($i=0; $i<512; $i++) - $unsigned_chksum += ord($bytestring[$i]); - for($i=0; $i<8; $i++) - $unsigned_chksum -= ord($bytestring[148 + $i]); - $unsigned_chksum += ord(" ") * 8; - - return $unsigned_chksum; - } - - - // Converts a NULL padded string to a non-NULL padded string - // PRIVATE ACCESS FUNCTION - function __parseNullPaddedString($string) - { - $position = strpos($string,chr(0)); - return substr($string,0,$position); - } - - - // This function parses the current TAR file - // PRIVATE ACCESS FUNCTION - function __parseTar() - { - // Read Files from archive - $this->numFiles=0; - $tar_length = strlen($this->tar_file); - $main_offset = 0; - while($main_offset < $tar_length) { - // If we read a block of 512 nulls, we are at the end of the archive - if(substr($this->tar_file,$main_offset,512) == str_repeat(chr(0),512)) - break; - - // Parse file name - $file_name = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset,100)); - - // Parse the file mode - $file_mode = substr($this->tar_file,$main_offset + 100,8); - - // Parse the file user ID - $file_uid = octdec(substr($this->tar_file,$main_offset + 108,8)); - - // Parse the file group ID - $file_gid = octdec(substr($this->tar_file,$main_offset + 116,8)); - - // Parse the file size - $file_size = octdec(substr($this->tar_file,$main_offset + 124,12)); - - // Parse the file update time - unix timestamp format - $file_time = octdec(substr($this->tar_file,$main_offset + 136,12)); - - // Parse Checksum - $file_chksum = octdec(substr($this->tar_file,$main_offset + 148,6)); - - // Parse user name - $file_uname = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 265,32)); - - // Parse Group name - $file_gname = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 297,32)); - - // Make sure our file is valid - if($this->__computeUnsignedChecksum(substr($this->tar_file,$main_offset,512)) != $file_chksum) - return false; - - // Parse File Contents - $file_contents = substr($this->tar_file,$main_offset + 512,$file_size); - - /* ### Unused Header Information ### - $activeFile["typeflag"] = substr($this->tar_file,$main_offset + 156,1); - $activeFile["linkname"] = substr($this->tar_file,$main_offset + 157,100); - $activeFile["magic"] = substr($this->tar_file,$main_offset + 257,6); - $activeFile["version"] = substr($this->tar_file,$main_offset + 263,2); - $activeFile["devmajor"] = substr($this->tar_file,$main_offset + 329,8); - $activeFile["devminor"] = substr($this->tar_file,$main_offset + 337,8); - $activeFile["prefix"] = substr($this->tar_file,$main_offset + 345,155); - $activeFile["endheader"] = substr($this->tar_file,$main_offset + 500,12); - */ - - if($file_size > 0) { - // Increment number of files - $this->numFiles++; - - // Create us a new file in our array - $activeFile = &$this->files[]; - - // Asign Values - $activeFile["name"] = $file_name; - $activeFile["mode"] = $file_mode; - $activeFile["size"] = $file_size; - $activeFile["time"] = $file_time; - $activeFile["user_id"] = $file_uid; - $activeFile["group_id"] = $file_gid; - $activeFile["user_name"] = $file_uname; - $activeFile["group_name"] = $file_gname; - $activeFile["checksum"] = $file_chksum; - $activeFile["file"] = $file_contents; - - } else { - // Increment number of directories - $this->numDirectories++; - - // Create a new directory in our array - $activeDir = &$this->directories[]; - - // Assign values - $activeDir["name"] = $file_name; - $activeDir["mode"] = $file_mode; - $activeDir["time"] = $file_time; - $activeDir["user_id"] = $file_uid; - $activeDir["group_id"] = $file_gid; - $activeDir["user_name"] = $file_uname; - $activeDir["group_name"] = $file_gname; - $activeDir["checksum"] = $file_chksum; - } - - // Move our offset the number of blocks we have processed - $main_offset += 512 + (ceil($file_size / 512) * 512); - } - - return true; - } - - - // Read a non gzipped tar file in for processing - // PRIVATE ACCESS FUNCTION - function __readTar($filename='') - { - // Set the filename to load - // Read in the TAR file - - if($this->tar_file[0] == chr(31) && $this->tar_file[1] == chr(139) && $this->tar_file[2] == chr(8)) { - if(!function_exists("gzinflate")) - return false; - - $this->isGzipped = TRUE; - - $this->tar_file = gzinflate(substr($this->tar_file,10,-4)); - } - - // Parse the TAR file - $this->__parseTar(); - - return true; - } - - - // Generates a TAR file from the processed data - // PRIVATE ACCESS FUNCTION - function __generateTAR() - { - // Clear any data currently in $this->tar_file - unset($this->tar_file); - - // Generate Records for each directory, if we have directories - if($this->numDirectories > 0) { - foreach($this->directories as $key => $information) { - unset($header); - - // Generate tar header for this directory - // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end - $header .= str_pad($information["name"],100,chr(0)); - $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct(0),11,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0); - $header .= str_repeat(" ",8); - $header .= "5"; - $header .= str_repeat(chr(0),100); - $header .= str_pad("ustar",6,chr(32)); - $header .= chr(32) . chr(0); - $header .= str_pad("",32,chr(0)); - $header .= str_pad("",32,chr(0)); - $header .= str_repeat(chr(0),8); - $header .= str_repeat(chr(0),8); - $header .= str_repeat(chr(0),155); - $header .= str_repeat(chr(0),12); - - // Compute header checksum - $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT); - for($i=0; $i<6; $i++) { - $header[(148 + $i)] = substr($checksum,$i,1); - } - $header[154] = chr(0); - $header[155] = chr(32); - - // Add new tar formatted data to tar file contents - $this->tar_file .= $header; - } - } - - // Generate Records for each file, if we have files (We should...) - if($this->numFiles > 0) - { - foreach($this->files as $key => $information) - { - unset($header); - $header = ''; - - // Generate the TAR header for this file - // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end - $header .= str_pad($information["name"],100,chr(0)); - $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["size"]),11,"0",STR_PAD_LEFT) . chr(0); - $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0); - $header .= str_repeat(" ",8); - $header .= "0"; - $header .= str_repeat(chr(0),100); - $header .= str_pad("ustar",6,chr(32)); - $header .= chr(32) . chr(0); - $header .= str_pad($information["user_name"],32,chr(0)); // How do I get a file's user name from PHP? - $header .= str_pad($information["group_name"],32,chr(0)); // How do I get a file's group name from PHP? - $header .= str_repeat(chr(0),8); - $header .= str_repeat(chr(0),8); - $header .= str_repeat(chr(0),155); - $header .= str_repeat(chr(0),12); - - // Compute header checksum - $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT); - for($i=0; $i<6; $i++) - { - $header[(148 + $i)] = substr($checksum,$i,1); - } - $header[154] = chr(0); - $header[155] = chr(32); - - // Pad file contents to byte count divisible by 512 - $file_contents = str_pad($information["file"],(ceil($information["size"] / 512) * 512),chr(0)); - - // Add new tar formatted data to tar file contents - $this->tar_file .= $header . $file_contents; - } - } - - // Add 512 bytes of NULLs to designate EOF - $this->tar_file .= str_repeat(chr(0),512); - - return true; - } - - - // Open a TAR file - function openTAR($value) - { - // Clear any values from previous tar archives - unset($this->filename); - unset($this->isGzipped); - unset($this->tar_file); - unset($this->files); - unset($this->directories); - unset($this->numFiles); - unset($this->numDirectories); - - $this->filename = 'none'; - $this->tar_file = $value; - // Parse this file - $this->__readTar(); - - return true; - } - - - // Write the currently loaded tar archive to disk - function saveTar() - { - if(!$this->filename) - return false; - - // Write tar to current file using specified gzip compression - $this->toTar($this->filename,$this->isGzipped); - - return true; - } - - - // Saves tar archive to a different file than the current file - function toTar($filename,$useGzip) - { - if(!$filename) - return false; - - // Encode processed files into TAR file format - $this->__generateTar(); - - // GZ Compress the data if we need to - if($useGzip) { - // Make sure we have gzip support - if(!function_exists("gzencode")) - return false; - - $file = gzencode($this->tar_file); - } else { - $file = $this->tar_file; - } - - // Write the TAR file - $fp = fopen($filename,"wb"); - fwrite($fp,$file); - fclose($fp); - - return true; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/ArchiveUnzip.class.php b/serviceClasses/ArchiveUnzip.class.php @@ -1,447 +0,0 @@ -<?php -// 28/11/2005 (2.4) -// - dUnzip2 is now compliant with wrong placed "Data Description", made by some compressors, -// like the classes ZipLib and ZipLib2 by 'Hasin Hayder'. Thanks to Ricardo Parreno for pointing it. -// 09/11/2005 (2.3) -// - Added optional parameter '$stopOnFile' on method 'getList()'. -// If given, file listing will stop when find given filename. (Useful to open and unzip an exact file) -// 06/11/2005 (2.21) -// - Added support to PK00 file format (Packed to Removable Disk) (thanks to Lito [PHPfileNavigator]) -// - Method 'getExtraInfo': If requested file doesn't exist, return FALSE instead of Array() -// 31/10/2005 (2.2) -// - Removed redundant 'file_name' on centralDirs declaration (thanks to Lito [PHPfileNavigator]) -// - Fixed redeclaration of file_put_contents when in PHP4 (not returning true) - -############################################################## -# Class dUnzip2 v2.4 -# -# Author: Alexandre Tedeschi (d) -# E-Mail: alexandrebr at gmail dot com -# Londrina - PR / Brazil -# -# Objective: -# This class allows programmer to easily unzip files on the fly. -# -# Requirements: -# This class requires extension ZLib Enabled. It is default -# for most site hosts around the world, and for the PHP Win32 dist. -# -# To do: -# * Error handling -# * Write a PHP-Side gzinflate, to completely avoid any external extensions -# * Write other decompress algorithms -# -# If you modify this class, or have any ideas to improve it, please contact me! -# You are allowed to redistribute this class, if you keep my name and contact e-mail on it. -############################################################## - -class ArchiveUnzip{ - - // Public - var $files = array(); - var $value = ''; - var $fileName; - var $compressedList; // You will problably use only this one! - var $centralDirList; // Central dir list... It's a kind of 'extra attributes' for a set of files - var $endOfCentral; // End of central dir, contains ZIP Comments - var $debug; - - // Private - var $fh; - var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature - var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature - var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature - - // Public - Function ArchiveUnzip() - { - $this->compressedList = - $this->centralDirList = - $this->endOfCentral = Array(); - } - - function open( $value ) - { - $this->fileName = tempnam('/tmp','unzip'); -// echo $this->fileName; - $fo = fopen( $this->fileName,'w'); - fwrite($fo,$value); - $this->unzipAll(); - } - - - Function getList($stopOnFile=false){ - if(sizeof($this->compressedList)){ - $this->debugMsg(1, "Returning already loaded file list."); - return $this->compressedList; - } - - // Open file, and set file handler - $fh = fopen($this->fileName, "r"); - $this->fh = &$fh; - if(!$fh){ - $this->debugMsg(2, "Failed to load file."); - return false; - } - - // Loop the file, looking for files and folders - $ddTry = false; - fseek($fh, 0); - for(;;){ - // Check if the signature is valid... - $signature = fread($fh, 4); - if(feof($fh)){ -# $this->debugMsg(1, "Reached end of file"); - break; - } - - // If signature is a 'Packed to Removable Disk', just ignore it and move to the next. - if($signature == 'PK00'){ - $this->debugMsg(1, "Found PK00: Packed to Removable Disk"); - continue; - } - - // If signature of a 'Local File Header' - if($signature == $this->zipSignature){ - # $this->debugMsg(1, "Zip Signature!"); - - // Get information about the zipped file - $file['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract - $file['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag - $file['compression_method'] = unpack("v", fread($fh, 2)); // compression method - $file['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time - $file['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date - $file['crc-32'] = fread($fh, 4); // crc-32 - $file['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size - $file['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size - $fileNameLength = unpack("v", fread($fh, 2)); // filename length - $extraFieldLength = unpack("v", fread($fh, 2)); // extra field length - $file['file_name'] = fread($fh, $fileNameLength[1]); // filename - $file['extra_field'] = $extraFieldLength[1]?fread($fh, $extraFieldLength[1]):''; // extra field - $file['contents-startOffset']= ftell($fh); - - // Bypass the whole compressed contents, and look for the next file - fseek($fh, $file['compressed_size'][1], SEEK_CUR); - - // Convert the date and time, from MS-DOS format to UNIX Timestamp - $BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT); - $BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT); - $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980; - $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4)); - $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5)); - $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5)); - $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6)); - $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5)); - - // Mount file table - $this->compressedList[$file['file_name']] = Array( - 'file_name' =>$file['file_name'], - 'compression_method'=>$file['compression_method'][1], - 'version_needed' =>$file['version_needed'][1], - 'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY), - 'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT), - 'compressed_size' =>$file['compressed_size'][1], - 'uncompressed_size' =>$file['uncompressed_size'][1], - 'extra_field' =>$file['extra_field'], - 'general_bit_flag' =>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT), - 'contents-startOffset'=>$file['contents-startOffset'] - ); - - if($stopOnFile) if($file['file_name'] == $stopOnFile){ - $this->debugMsg(1, "Stopping on file..."); - break; - } - } - - // If signature of a 'Central Directory Structure' - elseif($signature == $this->dirSignature){ - # $this->debugMsg(1, "Dir Signature!"); - - $dir['version_madeby'] = unpack("v", fread($fh, 2)); // version made by - $dir['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract - $dir['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag - $dir['compression_method'] = unpack("v", fread($fh, 2)); // compression method - $dir['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time - $dir['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date - $dir['crc-32'] = fread($fh, 4); // crc-32 - $dir['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size - $dir['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size - $fileNameLength = unpack("v", fread($fh, 2)); // filename length - $extraFieldLength = unpack("v", fread($fh, 2)); // extra field length - $fileCommentLength = unpack("v", fread($fh, 2)); // file comment length - $dir['disk_number_start'] = unpack("v", fread($fh, 2)); // disk number start - $dir['internal_attributes'] = unpack("v", fread($fh, 2)); // internal file attributes-byte1 - $dir['external_attributes1']= unpack("v", fread($fh, 2)); // external file attributes-byte2 - $dir['external_attributes2']= unpack("v", fread($fh, 2)); // external file attributes - $dir['relative_offset'] = unpack("V", fread($fh, 4)); // relative offset of local header - $dir['file_name'] = fread($fh, $fileNameLength[1]); // filename - $dir['extra_field'] = $extraFieldLength[1] ?fread($fh, $extraFieldLength[1]) :''; // extra field - $dir['file_comment'] = $fileCommentLength[1]?fread($fh, $fileCommentLength[1]):''; // file comment - - // Convert the date and time, from MS-DOS format to UNIX Timestamp - $BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT); - $BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT); - $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980; - $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4)); - $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5)); - $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5)); - $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6)); - $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5)); - - $this->centralDirList[$dir['file_name']] = Array( - 'version_madeby'=>$dir['version_madeby'][1], - 'version_needed'=>$dir['version_needed'][1], - 'general_bit_flag'=>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT), - 'compression_method'=>$dir['compression_method'][1], - 'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY), - 'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT). - str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT), - 'compressed_size'=>$dir['compressed_size'][1], - 'uncompressed_size'=>$dir['uncompressed_size'][1], - 'disk_number_start'=>$dir['disk_number_start'][1], - 'internal_attributes'=>$dir['internal_attributes'][1], - 'external_attributes1'=>$dir['external_attributes1'][1], - 'external_attributes2'=>$dir['external_attributes2'][1], - 'relative_offset'=>$dir['relative_offset'][1], - 'file_name'=>$dir['file_name'], - 'extra_field'=>$dir['extra_field'], - 'file_comment'=>$dir['file_comment'], - ); - } - - elseif($signature == $this->dirSignatureE){ - # $this->debugMsg(1, "EOF Dir Signature!"); - - $eodir['disk_number_this'] = unpack("v", fread($fh, 2)); // number of this disk - $eodir['disk_number'] = unpack("v", fread($fh, 2)); // number of the disk with the start of the central directory - $eodir['total_entries_this'] = unpack("v", fread($fh, 2)); // total number of entries in the central dir on this disk - $eodir['total_entries'] = unpack("v", fread($fh, 2)); // total number of entries in - $eodir['size_of_cd'] = unpack("V", fread($fh, 4)); // size of the central directory - $eodir['offset_start_cd'] = unpack("V", fread($fh, 4)); // offset of start of central directory with respect to the starting disk number - $zipFileCommentLenght = unpack("v", fread($fh, 2)); // zipfile comment length - $eodir['zipfile_comment'] = $zipFileCommentLenght[1]?fread($fh, $zipFileCommentLenght[1]):''; // zipfile comment - $this->endOfCentral = Array( - 'disk_number_this'=>$eodir['disk_number_this'][1], - 'disk_number'=>$eodir['disk_number'][1], - 'total_entries_this'=>$eodir['total_entries_this'][1], - 'total_entries'=>$eodir['total_entries'][1], - 'size_of_cd'=>$eodir['size_of_cd'][1], - 'offset_start_cd'=>$eodir['offset_start_cd'][1], - 'zipfile_comment'=>$eodir['zipfile_comment'], - ); - } - else{ - if(!$ddTry){ - $this->debugMsg(1, "Unexpected header. Trying to detect wrong placed 'Data Descriptor'...\n"); - $ddTry = true; - fseek($fh, 12-4, SEEK_CUR); // Jump over 'crc-32'(4) 'compressed-size'(4), 'uncompressed-size'(4) - continue; - } - $this->debugMsg(1, "Unexpected header, ending loop at offset ".ftell($fh)); - break; - } - $ddTry = false; - } - - if($this->debug){ - #------- Debug compressedList - $kkk = 0; - echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>"; - foreach($this->compressedList as $fileName=>$item){ - if(!$kkk && $kkk=1){ - echo "<tr style='background: #ADA'>"; - foreach($item as $fieldName=>$value) - echo "<td>$fieldName</td>"; - echo '</tr>'; - } - echo "<tr style='background: #CFC'>"; - foreach($item as $fieldName=>$value){ - if($fieldName == 'lastmod_datetime') - echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>"; - else - echo "<td title='$fieldName' nowrap='nowrap'>$value</td>"; - } - echo "</tr>"; - } - echo "</table>"; - - #------- Debug centralDirList - $kkk = 0; - if(sizeof($this->centralDirList)){ - echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>"; - foreach($this->centralDirList as $fileName=>$item){ - if(!$kkk && $kkk=1){ - echo "<tr style='background: #AAD'>"; - foreach($item as $fieldName=>$value) - echo "<td>$fieldName</td>"; - echo '</tr>'; - } - echo "<tr style='background: #CCF'>"; - foreach($item as $fieldName=>$value){ - if($fieldName == 'lastmod_datetime') - echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>"; - else - echo "<td title='$fieldName' nowrap='nowrap'>$value</td>"; - } - echo "</tr>"; - } - echo "</table>"; - } - - #------- Debug endOfCentral - $kkk = 0; - if(sizeof($this->endOfCentral)){ - echo "<table border='0' style='font: 11px Verdana' style='border: 1px solid #000'>"; - echo "<tr style='background: #DAA'><td colspan='2'>dUnzip - End of file</td></tr>"; - foreach($this->endOfCentral as $field=>$value){ - echo "<tr>"; - echo "<td style='background: #FCC'>$field</td>"; - echo "<td style='background: #FDD'>$value</td>"; - echo "</tr>"; - } - echo "</table>"; - } - } - - return $this->compressedList; - } - - - Function getExtraInfo($compressedFileName) - { - return - isset($this->centralDirList[$compressedFileName])? - $this->centralDirList[$compressedFileName]: - false; - } - - - Function getZipInfo($detail=false) - { - return $detail? - $this->endOfCentral[$detail]: - $this->endOfCentral; - } - - - Function unzip($compressedFileName, $targetFileName=false){ - $fdetails = &$this->compressedList[$compressedFileName]; - - if(!sizeof($this->compressedList)){ - $this->debugMsg(1, "Trying to unzip before loading file list... Loading it!"); - $this->getList(false, $compressedFileName); - } - if(!isset($this->compressedList[$compressedFileName])){ - $this->debugMsg(2, "File '<b>$compressedFileName</b>' is not compressed in the zip."); - return false; - } - if(substr($compressedFileName, -1) == "/"){ - $this->debugMsg(2, "Trying to unzip a folder name '<b>$compressedFileName</b>'."); - return false; - } - if(!$fdetails['uncompressed_size']){ - $this->debugMsg(1, "File '<b>$compressedFileName</b>' is empty."); - return ""; - } - - fseek($this->fh, $fdetails['contents-startOffset']); - return $this->uncompress( - fread($this->fh, $fdetails['compressed_size']), - $fdetails['compression_method'], - $fdetails['uncompressed_size'] ); - } - - - Function unzipAll($targetDir=false, $baseDir="", $maintainStructure=true, $chmod=false){ - if($targetDir === false) - $targetDir = dirname(__FILE__)."/"; - - $lista = $this->getList(); - if(sizeof($lista)) foreach($lista as $fileName=>$trash){ - $dirname = dirname($fileName); - $outDN = "$targetDir/$dirname"; - - if(substr($dirname, 0, strlen($baseDir)) != $baseDir) - continue; - - if(!is_dir($outDN) && $maintainStructure){ - $str = ""; - $folders = explode("/", $dirname); - foreach($folders as $folder){ - $str = $str?"$str/$folder":$folder; - if(!is_dir("$targetDir/$str")){ - $this->debugMsg(1, "Creating folder: $targetDir/$str"); - mkdir("$targetDir/$str"); - if($chmod) - chmod("$targetDir/$str", $chmod); - } - } - } - if(substr($fileName, -1, 1) == "/") - continue; - - $maintainStructure? - $this->unzip($fileName, "$targetDir/$fileName"): - $this->unzip($fileName, "$targetDir/".basename($fileName)); - - if($chmod) - chmod($maintainStructure?"$targetDir/$fileName":"$targetDir/".basename($fileName), $chmod); - } - } - - Function close(){ // Free the file resource - if($this->fh) - fclose($this->fh); - } - - // Private (you should NOT call these methods): - Function uncompress($content, $mode, $uncompressedSize, $targetFileName=false){ - switch($mode){ - case 0: - // Not compressed - return $content; - case 1: - $this->debugMsg(2, "Shrunk mode is not supported... yet?"); - return false; - case 2: - case 3: - case 4: - case 5: - $this->debugMsg(2, "Compression factor ".($mode-1)." is not supported... yet?"); - return false; - case 6: - $this->debugMsg(2, "Implode is not supported... yet?"); - return false; - case 7: - $this->debugMsg(2, "Tokenizing compression algorithm is not supported... yet?"); - return false; - case 8: - // Deflate - return gzinflate($content, $uncompressedSize); - case 9: - $this->debugMsg(2, "Enhanced Deflating is not supported... yet?"); - return false; - case 10: - $this->debugMsg(2, "PKWARE Date Compression Library Impoloding is not supported... yet?"); - return false; - default: - $this->debugMsg(2, "Unknown uncompress method: $mode"); - return false; - } - } - - - Function debugMsg($level, $string){ - if($this->debug) - if($level == 1) - echo "<b style='color: #777'>dUnzip2:</b> $string<br>"; - if($level == 2) - echo "<b style='color: #F00'>dUnzip2:</b> $string<br>"; - } -} -?>- \ No newline at end of file diff --git a/serviceClasses/ArchiveZip.class.php b/serviceClasses/ArchiveZip.class.php @@ -1,89 +0,0 @@ -<?php - - -/** - * This source is taken from http://www.zend.com/zend/spotlight/creating-zip-files1.php - * Thank you! - */ -class ArchiveZip -{ - var $datasec = array(); - var $ctrl_dir = array(); - var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; - var $old_offset = 0; - - - function add_file($data, $name) - { - $name = str_replace("\\", "/", $name); - $unc_len = strlen($data); - $crc = crc32($data); - $zdata = gzcompress($data); - $zdate = substr ($zdata, 2, -4); - $c_len = strlen($zdata); - - - - $fr = "\x50\x4b\x03\x04"; - $fr .= "\x14\x00"; - $fr .= "\x00\x00"; - $fr .= "\x08\x00"; - $fr .= "\x00\x00\x00\x00"; - $fr .= pack("V",$crc); - $fr .= pack("V",$c_len); - $fr .= pack("V",$unc_len); - $fr .= pack("v", strlen($name) ); - $fr .= pack("v", 0 ); - $fr .= $name; - $fr .= $zdata; - $fr .= pack("V",$crc); - $fr .= pack("V",$c_len); - $fr .= pack("V",$unc_len); - - $this -> datasec[] = $fr; - - - - $new_offset = strlen(implode("", $this->datasec)); - - $cdrec = "\x50\x4b\x01\x02"; - $cdrec .="\x00\x00"; - $cdrec .="\x14\x00"; - $cdrec .="\x00\x00"; - $cdrec .="\x08\x00"; - $cdrec .="\x00\x00\x00\x00"; - $cdrec .= pack("V",$crc); - $cdrec .= pack("V",$c_len); - $cdrec .= pack("V",$unc_len); - $cdrec .= pack("v", strlen($name) ); - $cdrec .= pack("v", 0 ); - $cdrec .= pack("v", 0 ); - $cdrec .= pack("v", 0 ); - $cdrec .= pack("v", 0 ); - $cdrec .= pack("V", 32 ); - $cdrec .= pack("V", $this -> old_offset ); - - $this -> old_offset = $new_offset; - - $cdrec .= $name; - $this -> ctrl_dir[] = $cdrec; - } - - - function file() { - $data = implode("", $this -> datasec); - $ctrldir = implode("", $this -> ctrl_dir); - - return - $data. - $ctrldir. - $this -> eof_ctrl_dir. - pack("v", sizeof($this -> ctrl_dir)). - pack("v", sizeof($this -> ctrl_dir)). - pack("V", strlen($ctrldir)). - pack("V", strlen($data)). - "\x00\x00"; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Code.class.php b/serviceClasses/Code.class.php @@ -1,53 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// DaCMS Content Management System -// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.1 2004-12-15 23:14:21 dankert -// *** empty log message *** -// -// --------------------------------------------------------------------------- - -/** - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Code extends Dynamic -{ - var $code = ''; - - function execute() - { - if ( substr($this->code,0,5) != '<?php' ) - $this->code = "<?php\n".$this->code."\n?>"; - - $tmp = Object::getTempDir().'/openratDynamic'; - $tmp .= '.code.php.tmp'; - - $f = fopen( $tmp,'w' ); - fwrite( $f,$this->code ); - fclose( $f ); - - require( $tmp ); // Ausfuehren des temporaeren PHP-Codes - - unlink( $tmp ); - } -}- \ No newline at end of file diff --git a/serviceClasses/Dynamic.class.php b/serviceClasses/Dynamic.class.php @@ -1,149 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// DaCMS Content Management System -// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.4 2005-01-03 19:38:03 dankert -// Neue Methode outputLn -// -// Revision 1.3 2004/12/19 21:49:02 dankert -// Methode pathToObject() -// -// Revision 1.2 2004/12/19 15:25:12 dankert -// Anpassung Session-Funktionen -// -// Revision 1.1 2004/12/15 23:14:21 dankert -// *** empty log message *** -// -// Revision 1.5 2004/11/10 22:50:10 dankert -// Neue Methode execute() -// -// Revision 1.4 2004/10/06 09:53:39 dankert -// Benutzung auch nicht-statisch -// -// Revision 1.3 2004/05/03 20:21:34 dankert -// neu: setObjectId() -// -// Revision 1.2 2004/05/02 15:04:16 dankert -// Einf?gen package-name (@package) -// -// Revision 1.1 2004/04/24 17:03:29 dankert -// Initiale Version -// -// --------------------------------------------------------------------------- - -/** - * Service-Klasse fuer allgemeine Interface-Methoden. Insbesondere - * in Code-Elementen kann und soll auf diese Methoden zurueckgegriffen - * werden. - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Dynamic -{ - var $project; - var $output = ''; - var $objectid = 0; - var $page; - var $parameters = array(); - var $description = ''; - - - function db() - { - return db_connection(); - } - - function getObjectId() - { - return $this->objectid; - } - - function &getObject() - { - return Session::getObject(); - } - - function setObjectId( $objectid ) - { - $this->objectid = $objectid; - } - - function getRootObjectId() - { - $project = Session::getProject(); - return $project->getRootObjectId(); - } - - function folderid() - { - global $SESS; - return $SESS['folderid']; - } - - - function execute() - { - // overwrite this in subclasses - } - - function delOutput() - { - $this->output = ''; - } - - function output( $text ) - { - $this->output .= $text; - } - - function outputLn( $text ) - { - $this->output .= $text."\n"; - } - - - function getOutput() - { - return $this->output; - } - - function setSessionVar( $var,$value ) - { - Session::set( $var,$value ); - } - - - function getSessionVar( $var ) - { - return Session::get( $var ); - } - - - function pathToObject( $obj ) - { - if ( is_object($obj) ) - return $this->page->path_to_object($obj->objectid); - else - return $this->page->path_to_object($obj); - } - -}- \ No newline at end of file diff --git a/serviceClasses/FileUtils.class.php b/serviceClasses/FileUtils.class.php @@ -1,75 +0,0 @@ -<?php - -/** - * Werkzeugklasse f�r Datei-Operationen. - * - */ -class FileUtils -{ - /** - * Fuegt einen Slash ("/") an das Ende an, sofern nicht bereits vorhanden. - * - * @param String $pfad - * @return Pfad mit angeh�ngtem Slash. - */ - function slashify($pfad) - { - if ( substr($pfad,-1,1) == '/') - return $pfad; - else - return $pfad.'/'; - } - - - /** - * Ermittelt das tempor�re Verzeichnis. - * - * @return String - */ - function getTempDir() - { - $tmpFilename = tempnam(ini_get('upload_tmp_dir'),"bla"); - @unlink($tmpFilename); - return FileUtils::slashify( dirname($tmpFilename) ); - } - - - - /** - * Liest die Dateien aus dem angegebenen Ordner in ein Array. - * - * @param $dir Verzeichnis, welches gelesen werden soll - * @return Array Liste der Dateien im Ordner - */ - function readDir($dir) - { - $dir = FileUtils::slashify($dir); - $dateien = array(); - - if ( !is_dir($dir) ) - { - return false; - } - - if ( $dh = opendir($dir) ) - { - while( ($verzEintrag = readdir($dh)) !== false ) - { - if ( substr($verzEintrag,0,1) != '.' ) - { - $dateien[] = $verzEintrag; - } - } - closedir($dh); - - return $dateien; - } - else - { - die('unable to open directory: '.$dir); - } - - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Ftp.class.php b/serviceClasses/Ftp.class.php @@ -1,245 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Darstellen einer FTP-Verbindung, das beinhaltet - * das Login, das Kopieren von Dateien sowie praktische - * FTP-Funktionen - * - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Ftp -{ - var $verb; - var $url; - var $log = array(); - - var $passive = false; - - var $ok = true; - - - // Konstruktor - function Ftp( $url ) - { - $this->connect( $url ); - } - - - // Aufbauen der Verbindung - function connect( $url ) - { - $this->url = $url; - - global $conf; - - $conf_ftp = $conf['publish']['ftp']; - $ftp = parse_url( $this->url ); - - // Die projektspezifischen Werte gewinnen bei �berschneidungen mit den Default-Werten - $ftp = array_merge($conf_ftp,$ftp); - - // Nur FTP und FTPS (seit PHP 4.3) erlaubt - if ( !ereg('^ftps?$',$ftp['scheme']) ) - { - $this->log[] = 'Unknown scheme in FTP Url: '.$ftp['scheme']; - $this->log[] = 'Only FTP (and FTPS, if compiled in) are supported'; - $this->ok = false; - return; - } - - if ( function_exists('ftp_ssl_connect') && $ftp['scheme'] == 'ftps' ) - $this->verb = @ftp_ssl_connect( $ftp['host'],$ftp['port'] ); - else - $this->verb = @ftp_connect( $ftp['host'],$ftp['port'] ); - - if ( !$this->verb ) - { - $this->log[] = 'Cannot connect to '.$ftp['scheme'].'-server: '.$ftp['host'].':'.$ftp['port']; - $this->ok = false; - - Logger::error('Cannot connect to '.$ftp['host'].':'.$ftp['port']); - return; - } - - $this->log[] = 'Connected to FTP server '.$ftp['host'].':'.$ftp['port']; - - if ( empty($ftp['user']) ) - { - $ftp['user'] = 'anonymous'; - $ftp['pass'] = 'openrat@openrat.de'; - } - - if ( ! ftp_login( $this->verb,$ftp['user'],$ftp['pass'] ) ) - { - $this->log[] = 'Unable to login as user '.$ftp['user']; - $this->ok = false; - return; - } - - $this->log[] = 'Logged in as user '.$ftp['user']; - - $pasv = (!empty($ftp['fragment']) && $ftp['fragment'] == 'passive' ); - - $this->log[] = 'entering passive mode '.($pasv?'on':'off'); - if ( ! ftp_pasv($this->verb,true) ) - { - $this->log[] = 'cannot switch PASV mode'; - $this->ok = false; - return; - } - - if ( !empty($ftp['query']) ) - { - parse_str( $ftp['query'],$ftp_var ); - - if ( isset( $ftp_var['site'] ) ) - { - $site_commands = explode( ',',$ftp_var['site'] ); - foreach( $site_commands as $cmd ) - { - $this->log .= 'executing SITE command: '.$cmd; - - if ( ! @ftp_site( $this->verb,$cmd ) ) - { - $this->log[] = 'unable to do SITE command: '.$cmd; - $this->ok = false; - return; - } - } - } - } - - $this->path = ereg_replace( '\/$','',$ftp['path']); - - $this->log[] = 'Changing directory to '.$this->path; - - if ( ! @ftp_chdir( $this->verb,$this->path ) ) - { - $this->log[] = 'unable CHDIR to directory: '.$this->path; - $this->ok = false; - return; - } - } - - - /** - * Kopieren einer Datei vom lokalen System auf den FTP-Server. - * - * @param String Quelle - * @param String Ziel - * @param int FTP-Mode (BINARY oder ASCII) - */ - function put( $source,$dest ) - { - if ( ! $this->ok ) - return; - - $ftp = parse_url( $this->url ); - - $dest = $this->path.'/'.$dest; - - $this->log .= "Copying file: $source -&gt; $dest ...\n"; - - $mode = FTP_BINARY; - $p = strrpos( basename($dest),'.' ); // Letzten Punkt suchen - - if ($p!==false) // Wennn letzten Punkt gefunden, dann dort aufteilen - { - $extension = substr( basename($dest),$p+1 ); - $type = config('mime-types',$extension); - if ( substr($type,0,5) == 'text/') - $mode = FTP_ASCII; - } - - Logger::debug("FTP PUT target:$dest mode:".(($mode==FTP_ASCII)?'ascii':'binary')); - - if ( !@ftp_put( $this->verb,$dest,$source,$mode ) ) - { - if ( !$this->mkdirs( dirname($dest) ) ) - return; // Fehler. - - ftp_chdir( $this->verb,$this->path ); - - if ( ! @ftp_put( $this->verb,$dest,$source,$mode ) ) - { - $this->ok = false; - $this->log[] = 'FTP PUT failed...'; - $this->log[] = 'source : '.$source; - $this->log[] = 'destination: '.$dest; - return; - } - - } - } - - - - /** - * Private Methode zum rekursiven Anlegen von Verzeichnissen. - * - * @param String Pfad - * @return boolean true, wenn ok - */ - function mkdirs( $strPath ) - { - if ( @ftp_chdir($this->verb,$strPath) ) - return true; // Verzeichnis existiert schon :) - - $pStrPath = dirname($strPath); - - if ( !$this->mkdirs($pStrPath) ) - return false; - - if ( ! @ftp_mkdir($this->verb,$strPath) ) - { - $this->ok = false; - $this->log[] = "failed to create remote directory: $strPath"; - } - - return $this->ok; - } - - - - /** - * Schlie�en der FTP-Verbindung.<br> - * Sollte unbedingt aufgerufen werden, damit keine unn�tigen Sockets aufbleiben. - */ - function close() - { - if ( !$this->ok ) // Noch alles ok? - return; - - if ( ! @ftp_quit( $this->verb ) ) - { - // Das Schlie�en der Verbindung hat nicht funktioniert. - // Eigentlich k�nnten wir das ignorieren, aber wir sind anst�ndig und melden eine Fehler. - $this->log[] = 'failed to close connection'; - $this->ok = false; - return; - } - } -} - - -?>- \ No newline at end of file diff --git a/serviceClasses/GlobalFunctions.class.php b/serviceClasses/GlobalFunctions.class.php @@ -1,71 +0,0 @@ -<?php - -/** - * Bereitstellen von globalen Funktionen - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class GlobalFunctions -{ - function getIsoCodes() - { - global $conf_php; - - $iso = parse_ini_file( './language/lang.ini.'.$conf_php ); - asort( $iso ); - return $iso; - } - - - function lang( $text ) - { - global $SESS; - $text = strtoupper($text); - - if ( isset( $SESS['lang'][$text] ) ) - { - return $SESS['lang'][$text]; - } - else - { - return( '?'.$text.'?' ); - } - } - - - # Spracheinstellungen laden - - function language_from_http() - { - global $SESS, - $HTTP_SERVER_VARS, - $conf_php, - $conf; - - $languages = $HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE']; - $languages = explode(',',$languages); - foreach( $languages as $l ) - { - $l = substr($l,0,2); - if ( file_exists("./language/$l.ini.$conf_php") ) - return( $l ); - } - - // Keine passende Sprache im HTTP-Header gefunden - return $conf['global']['default_language']; - } - - - function language_read( $l='' ) - { - global $SESS, - $HTTP_SERVER_VARS, - $conf_php; - - $l = language_from_http(); - $SESS['lang'] = parse_ini_file( "./language/$l.ini.$conf_php" ); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Html.class.php b/serviceClasses/Html.class.php @@ -1,146 +0,0 @@ -<?php - -/** - * Bereitstellen von Methoden fuer die Darstellung von HTML-Elementen - * - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Html -{ - function error( $field ) - { - global $inputErrors; - - if ( isset($inputErrors[$field]) ) - return '<span class="error">'.lang($inputErrors[$field]).'</span'; - } - - - - /** - * Ausgabe eines Variablenwertes.<br> - */ - function debug( $wert, $text='' ) - { - echo "<strong>DEBUG: $text (".gettype($wert).")</strong><br/>"; - echo "<pre>"; - print_r($wert); - echo "</pre>"; - } - - - /** - * Erzeugt eine relative Url innerhalb von Openrat - * - * @param Aktion, die aufgerufen werden soll - * @param Unteraktion, die innerhalb der Aktion aufgerufen werden soll - * @param Id fuer diesen Aufruf - * @param Weitere beliebige Parameter - */ - function url( $action,$subaction='',$id='',$params=array() ) - { - if ( intval($id)==0 ) - $id='-'; - - global $conf; - - if ( is_array($action) ) - { - $params = $action; - - if ( isset($params['callAction']) ) - { - $params['subaction'] = $params['callAction']; - unset( $params['callAction'] ); - unset( $params['callSubaction'] ); - } - - - if ( !isset($params['action' ])) $params['action' ] = ''; - if ( !isset($params['subaction'])) $params['subaction'] = ''; - if ( !isset($params['id' ])) $params['id' ] = ''; - $action = $params['action' ]; - $subaction = $params['subaction']; - $id = $params['id' ]; - unset( $params['action' ] ); - unset( $params['subaction'] ); - unset( $params['id' ] ); - $params['old']='true'; - } - - // Session-Id ergaenzen - if ( $conf['interface']['url']['add_sessionid'] ) - $params[ session_name() ] = session_id(); - - $fake_urls = $conf['interface']['url']['fake_url' ]; - $url_format = $conf['interface']['url']['url_format']; - - if ( isset($params['objectid']) && !isset($params['id']) ) - $params['id'] = $params['objectid']; - - if ( $fake_urls ) - { -// if ( $id != '' ) -// $id = '.'.$id; - } - else - { - global $view; - $params[REQ_PARAM_ACTION ] = $action; - $params[REQ_PARAM_SUBACTION] = $subaction; - $params[REQ_PARAM_ID ] = $id; - - if ( !isset($params[REQ_PARAM_TARGET])) - $params[REQ_PARAM_TARGET ] = $view; - } - - if ( count($params) > 0 ) - { - $urlParameterList = array(); - foreach( $params as $var=>$value ) - { - $urlParameterList[] = urlencode($var).'='.urlencode($value); - } - $urlParameter = '?'.implode('&amp;',$urlParameterList); - } - else - { - $urlParameter = ''; - } - - if ( @$conf['interface']['url']['index'] ) - $controller_file_name = ''; - else - $controller_file_name = OR_CONTROLLER_FILE.'.'.PHP_EXT; - - $prefix = './'; - - if ( $fake_urls ) - $src = sprintf( $url_format,$action,$subaction,$id,session_id() ).$urlParameter; - else - $src = $prefix.$controller_file_name.$urlParameter; - - return $src; - } - - - - function open_tag($tagname,$attributes) - { - $text = '<'.$tagname; - foreach( $attributes as $attribute_name=>$attribute_value ) - if ( !empty($attribute_value) ) - $text .= ' '.$attribute_name.'="'.$attribute_value.'"'; - $text .= '>'; - return $text; - } - - - function close_tag($tagname) - { - return '</'.$tagname.'>'; - } -} -?>- \ No newline at end of file diff --git a/serviceClasses/Http.class.php b/serviceClasses/Http.class.php @@ -1,498 +0,0 @@ -<?php - -/** - * Kapselung einer HTTP-Anfrage.<br> - * Unter Beruecksichtigung von RFC 1945.<br> - * - * @author Jan Dankert - * @package openrat.services - */ -class Http -{ - var $url = array(); - var $header = array(); - var $responseHeader = array(); - var $requestParameter = array(); - var $urlParameter = array(); - - /** - * HTTP-Request-Typ.<br> - * Muss entweder "GET" oder "POST" sein.<br> - * Default: "GET". - * - * @var String Request-Typ - */ - var $method = 'GET'; - var $error = ''; - var $status = ''; - var $body = ''; - - var $httpCmd = ''; - - - - /** - * Erzeugt eine HTTP-Anfrage. - * - * @param String URL - * @return Http - */ - function Http( $url = '' ) - { - $this->setURL( $url ); - $this->header['User-Agent'] = 'Mozilla/5.0 (OpenRat CMS)'; - $this->header['Connection'] = 'close'; - } - - - - /** - * Setzt die URL. - * - * @param String URL - */ - function setURL( $url ) - { - $this->url = parse_url($url); - - if ( empty($this->url['host']) && !empty($this->url['path']) ) - { - $this->url['host'] = basename($this->url['path']); - $this->url['path'] = '/'; - } - - if ( empty($this->url['path']) ) - $this->url['path'] = '/'; - - if ( !isset($this->url['port']) ) - if ( !isset($this->url['scheme']) ) - { - $this->url['scheme'] = 'http'; // Standard-Port. - $this->url['port'] = 80; // Standard-Port. - } - elseif ( $this->url['scheme'] == 'https' ) - $this->url['port'] = 443; // SSL-Port. - else - $this->url['port'] = 80; // Standard-Port. - - if ( !empty($this->url['query']) ) - parse_str( $this->url['query'],$this->urlParameter ); - - } - - - - /** - * Setzt Authentisierungsinformationen in den HTTP-Request.<br> - * - * @param String Benutzername - * @param String Kennwort - */ - function setBasicAuthentication( $user, $password ) - { - $this->header['Authorization'] = 'Basic '.base64_encode($user.':'.$password); - } - - - - /** - * Erzeugt eine Zeichenkette mit allen Parametern. - * @param withPraefixQuestionMark Praefix mit Fragezeichen (f�r GET-Anfragen) - * @return String URL-Parameter - */ - function getParameterString( $withPraefixQuestionMark=false ) - { - $parameterString = ''; - $parameter = $this->urlParameter + $this->requestParameter; - - if ( ! empty($parameter) ) - { - foreach( $this->requestParameter as $paramName => $paramValue ) - { - if ( strlen($parameterString) > 0) - $parameterString .= '&'; - elseif ( $withPraefixQuestionMark ) - $parameterString .= '?'; - - $parameterString .= urlencode($paramName) . '=' .urlencode($paramValue); - } - } - - return $parameterString; - } - - - /** - * Sendet eine Redirect-Anweisung an den Browser. - * @return String URL - */ - function getUrl() - { - $location = $this->url['scheme']; - $location .= '://'; - $location .= $this->url['host']; - if ( $this->url['scheme'] == 'http' && $this->url['port'] != 80 || - $this->url['scheme'] == 'https' && $this->url['port'] != 443 ) - $location .= ':'.$this->url['port']; - $location .= $this->url['path']; - - $location .= $this->getParameterString(true); - - if ( isset($this->url['fragment']) ) - $location .= '#'.$this->url['fragment']; - - return $location; - } - - - /** - * Sendet eine Redirect-Anweisung mit der aktuellen URL an den Browser. - */ - function sendRedirect() - { - $location = $this->getUrl(); - - header('Location: '.$location); - exit; - } - - - /** - * Erzeugt den HTTP-Request - * - * @return boolean Erfolg der Anfrage. - */ - function request() - { - $this->error = ''; - $this->status = ''; - - $errno = 0; - $errstr = ''; - - if ( empty($this->url['host']) ) - { - $this->error = "No hostname specified"; - return false; - } - - foreach( $this->header as $header_key=>$header_value ) - { - if ( is_numeric( $header_key ) ) - { - $dp = strpos($header_value,':'); - if ( $dp!==FALSE) - $this->header[substr($header_value,0,$dp)] = substr($header_value,$dp+1); - unset($this->header[$header_key]); - } - } - - $parameterString = $this->getParameterString(); - - if ( $this->method == 'POST' ) - { - $this->header['Content-Type' ] = 'application/x-www-form-urlencoded'; - $this->header['Content-Length'] = strlen($parameterString); - } - - // Accept-Header setzen, falls noch nicht vorhanden. - if ( !array_key_exists('Accept',$this->header) ) - $this->header['Accept'] = '*/*'; - - $this->responseHeader = array(); - - // RFC 1945 (Section 9.3) says: - // A user agent should never automatically redirect a request - // more than 5 times, since such redirections usually indicate an infinite loop. - for( $r=1; $r<=5; $r++ ) - { - $this->header['Host'] = $this->url['host']; - - // Die Funktion fsockopen() erwartet eine Protokollangabe (bei TCP optional, bei SSL notwendig). - if ( $this->url['scheme'] == 'https' || $this->url['port'] == '443' ) - $prx_proto = 'ssl://'; // SSL - else - $prx_proto = 'tcp://'; // Default - - $fp = @fsockopen ($prx_proto.$this->url['host'],$this->url['port'], $errno, $errstr, 30); - - if ( !$fp || !is_resource($fp) ) - { - // Keine Verbindung zum Host moeglich. - $this->error = "Connection refused: '".$prx_proto.$this->url['host'].':'.$this->url['port']." - $errstr ($errno)"; - return false; - } - else - { - - $lb = "\r\n"; - $http_get = $this->url['path']; - - $request_header = array( $this->method.' '.$http_get.' HTTP/1.0'); - - foreach($this->header as $header_key=>$header_value) - $request_header[] = $header_key.': '.$header_value; - - $http_request = implode($lb,$request_header).$lb.$lb; - - if ( $this->method == 'GET') - if ( !empty($parameterString) ) - $http_get .= '?'.$parameterString; - - if ( $this->method == 'POST' ) - $http_request .= $parameterString; - - if (!is_resource($fp)) { - $this->error = 'Connection lost after connect: '.$prx_proto.$this->url['host'].':'.$this->url['port']; - return false; - } - fputs($fp, $http_request); // Die HTTP-Anfrage zum Server senden. - - // Jetzt erfolgt das Auslesen der HTTP-Antwort. - $isHeader = true; - - // RFC 1945 (Section 6.1) schreibt als Statuszeile folgendes Format vor - // "HTTP/" 1*DIGIT "." 1*DIGIT SP 3DIGIT SP - if (!is_resource($fp)) { - $this->error = 'Connection lost during transfer: '.$this->url['host'].':'.$this->url['port']; - return false; - } - elseif (!feof($fp)) { - $line = fgets($fp,1028); - $this->status = substr($line,9,3); - } - else - { - $this->error = 'Unexpected EOF while reading HTTP-Response'; - return false; - } - - $this->body = ''; - while (!feof($fp)) { - $line = fgets($fp,1028); - if ( $isHeader && trim($line)=='' ) // Leerzeile nach Header. - { - $isHeader = false; - } - elseif( $isHeader ) - { - list($headerName,$headerValue) = explode(': ',$line) + array(1=>''); - $this->responseHeader[$headerName] = trim($headerValue); - } - else - { - $this->body .= $line; - } - } - fclose($fp); // Verbindung brav schlie�en. - - - // RFC 1945 (Section 6.1.1) schreibt - // "[...] However, applications must understand the class of any status code, as - // indicated by the first digit" - // Daher interessiert uns nur die erste Stelle des 3-stelligen HTTP-Status. - - // 301 Moved Permanently - // 302 Moved Temporarily - if ( $this->status == '301' || - $this->status == '302' ) - { - $location = @$this->responseHeader['Location']; - if ( empty($location) ) - { - $this->error = '301/302 Response without Location-header'; - return false; - } - - //Html::debug($this->url,"alte URL"); - //Html::debug($location,"NEUES REDIRECT AUF"); - $this->setURL($location); - continue; // Naechster Versuch mit umgeleiteter Adresse. - } - - // RFC 1945 (Section 6.1.1) schreibt - // "2xx: Success - The action was successfully received, understood, and accepted." - elseif ( substr($this->status,0,1) == '2' ) - { - return true; - } - elseif ( substr($this->status,0,1) == '4' ) - { - $this->error = 'Client Error: '.$this->status; - return false; - } - elseif ( substr($this->status,0,1) == '5' ) - { - $this->error = 'Server Error: '.$this->status; - return false; - } - else - { - $this->error = 'Unexpected HTTP-Status: '.$this->status. '; this is mostly a client error, sorry.'; - return false; - } - } - - $this->error = 'Too much redirects, infinite loop assumed. Exiting. Last URL: '.$http_get; - return false; - - } - - } - - - /** - * Aus dem HTTP-Header werden die vom Browser angeforderten Sprachen - * gelesen.<br> - * Es wird eine Liste von Sprachen erzeugt.<br> - * Beispiel: 'de_DE','de','en_GB','en' ... usw.<br> - * Wenn der Browser 'de_DE' anfordert, wird hier auch 'de' (als Fallback) ermittelt. - * - * @static - * @return Array - */ - function getLanguages() - { - global $HTTP_SERVER_VARS; - - $languages = array(); - $http_languages = @$HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE']; - foreach( explode(',',$http_languages) as $l ) - { - list($part) = explode(';',$l); // Priorit�ten ignorieren. - $languages[] = trim($part); - - // Aus "de_DE" das "de" extrahieren. - $languages[] = current(explode('_',str_replace('-','_',trim($part)))); - } - - return array_unique( $languages ); - } - - - /** - * Ermittelt die aktuelle URL des Requests (ohne Datei). - * - * @static - * @return String URL - */ - function getServer() - { - $https = getenv('HTTPS'); - - if ( $https ) - $server = 'https://'; - else - $server = 'http://'; - - $server .= getenv('SERVER_NAME').dirname(getenv('REQUEST_URI')); - - return $server; - } - - - - /** - * Server-Fehlermeldung anzeigen.<br> - * - * Erzeugt einen "HTTP 501 Internal Server Error". Zu�tzlich - * wird ein 'rollback' auf der Datenbank ausgef�hrt. - * - * @param String $message Eigener Hinweistext - */ - function serverError($message,$reason='') - { - $db = db_connection(); - if ( is_object( $db ) ) - $db->rollback(); - - Http::sendStatus(501,'Internal Server Error',$message,$reason); - } - - - - /** - * Der Benutzer ist nicht autorisiert, eine Aktion auszufuehren. - * Diese Funktion erzeugt einen "HTTP 403 Not Authorized" und das - * Skript wird beendet. - * - * @param String $message Eigener Hinweistext - */ - function notAuthorized($message) - { - - Http::sendStatus(403,'Not Authorized',$message); - } - - - - /** - * Schickt einen HTTP-Status zum Client und beendet das Skript. - * - * @param Integer $status HTTP-Status - * @param String $text HTTP-Meldung - * @param String $message Eigener Hinweistext - */ - function sendStatus( $status=501,$text='Internal Server Error',$message='',$reason='' ) - { - if ( headers_sent() ) - { - echo "$status $text\n$message"; - exit; - } - - header('HTTP/1.0 '.intval($status).' '.$text); - - - $types = Http::getAccept(); - - if ( sizeof($types)==1 && in_array('application/json',$types) ) - { - header('Content-Type: application/json'); - require_once( OR_SERVICECLASSES_DIR."JSON.class.".PHP_EXT ); - $json = new JSON(); - echo $json->encode( array('status'=>$status,'error'=>$text,'description'=>$message) ); - } - elseif ( sizeof($types)==1 && in_array('application/xml',$types) ) - { - header('Content-Type: application/xml'); - require_once( OR_SERVICECLASSES_DIR."XML.class.".PHP_EXT ); - $xml = new XML(); - $xml->root='error'; - echo $xml->encode( array('status'=>$status,'error'=>$text,'description'=>$message) ); - } - else - { - header('Content-Type: text/html'); - $message = htmlentities($message); - $reason = htmlentities($reason ); - $signature = OR_TITLE.' '.OR_VERSION.' '.getenv('SERVER_SOFTWARE'); - echo <<<HTML -<html> -<head><title>$status $text - OpenRat</title></head> -<body> -<h1>$text</h1> -<p>$message</p> -<pre>$reason</pre> -<hr> -<address>$signature</adddress> -</body> -</html> -HTML; - } - exit; - } - - - /** - * - * @return Array Mime-Typen, welche vom User-Agent akzeptiert werden. - */ - function getAccept() - { - $httpAccept = getenv('HTTP_ACCEPT'); - return $types = explode(',',$httpAccept); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/JSON.class.php b/serviceClasses/JSON.class.php @@ -1,809 +0,0 @@ -<?php -/** - * Converts to and from JSON format. - * - * JSON (JavaScript Object Notation) is a lightweight data-interchange - * format. It is easy for humans to read and write. It is easy for machines - * to parse and generate. It is based on a subset of the JavaScript - * Programming Language, Standard ECMA-262 3rd Edition - December 1999. - * This feature can also be found in Python. JSON is a text format that is - * completely language independent but uses conventions that are familiar - * to programmers of the C-family of languages, including C, C++, C#, Java, - * JavaScript, Perl, TCL, and many others. These properties make JSON an - * ideal data-interchange language. - * - * This package provides a simple encoder and decoder for JSON notation. It - * is intended for use with client-side Javascript applications that make - * use of HTTPRequest to perform server communication functions - data can - * be encoded into JSON notation for use in a client-side javascript, or - * decoded from incoming Javascript requests. JSON format is native to - * Javascript, and can be directly eval()'ed with no further parsing - * overhead - * - * All strings should be in ASCII or UTF-8 format! - * - * LICENSE: 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. - * - * THIS SOFTWARE IS PROVIDED ``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 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. - * - * @category - * @package Services_JSON - * @author Michal Migurski <mike-json@teczno.com> - * @author Matt Knapp <mdknapp[at]gmail[dot]com> - * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> - * @author Jan Dankert - * @copyright 2005 Michal Migurski - * @version CVS: $Id$ - * @license http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 - */ - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_INDENT', "\t"); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_SLICE', 1); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_STR', 2); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_ARR', 3); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_OBJ', 4); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_CMT', 5); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_LOOSE_TYPE', 16); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_SUPPRESS_ERRORS', 32); - -/** - * Converts to and from JSON format. - * - * Brief example of use: - * - * <code> - * // create a new instance of Services_JSON - * $json = new Services_JSON(); - * - * // convert a complexe value to JSON notation, and send it to the browser - * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); - * $output = $json->encode($value); - * - * print($output); - * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] - * - * // accept incoming POST data, assumed to be in JSON notation - * $input = file_get_contents('php://input', 1000000); - * $value = $json->decode($input); - * </code> - */ -class JSON -{ - /** - * constructs a new JSON instance - * - * @param int $use object behavior flags; combine with boolean-OR - * - * possible values: - * - SERVICES_JSON_LOOSE_TYPE: loose typing. - * "{...}" syntax creates associative arrays - * instead of objects in decode(). - * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. - * Values which can't be encoded (e.g. resources) - * appear as NULL instead of throwing errors. - * By default, a deeply-nested resource will - * bubble up with an error, so all return values - * from encode() should be checked with isError() - */ - function Services_JSON() - { - $this->use = SERVICES_JSON_LOOSE_TYPE; - } - - /** - * convert a string from one UTF-16 char to one UTF-8 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf16 UTF-16 character - * @return string UTF-8 character - * @access private - */ - function utf162utf8($utf16) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); - } - - $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); - - switch(true) { - case ((0x7F & $bytes) == $bytes): - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x7F & $bytes); - - case (0x07FF & $bytes) == $bytes: - // return a 2-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) - . chr(0x80 | ($bytes & 0x3F)); - - case (0xFFFF & $bytes) == $bytes: - // return a 3-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) - . chr(0x80 | (($bytes >> 6) & 0x3F)) - . chr(0x80 | ($bytes & 0x3F)); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * convert a string from one UTF-8 char to one UTF-16 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf8 UTF-8 character - * @return string UTF-16 character - * @access private - */ - function utf82utf16($utf8) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); - } - - switch(strlen($utf8)) { - case 1: - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return $utf8; - - case 2: - // return a UTF-16 character from a 2-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x07 & (ord($utf8{0}) >> 2)) - . chr((0xC0 & (ord($utf8{0}) << 6)) - | (0x3F & ord($utf8{1}))); - - case 3: - // return a UTF-16 character from a 3-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr((0xF0 & (ord($utf8{0}) << 4)) - | (0x0F & (ord($utf8{1}) >> 2))) - . chr((0xC0 & (ord($utf8{1}) << 6)) - | (0x7F & ord($utf8{2}))); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * encodes an arbitrary variable into JSON format - * - * @param mixed $var any number, boolean, string, array, or object to be encoded. - * see argument 1 to Services_JSON() above for array-parsing behavior. - * if var is a strng, note that encode() always expects it - * to be in ASCII or UTF-8 format! - * - * @return mixed JSON string representation of input var or an error if a problem occurs - * @access public - */ - function encode($var) - { - static $indentNr = 0; - - $indent = str_repeat(SERVICES_JSON_INDENT,$indentNr); - - switch (gettype($var)) { - case 'boolean': - return $var ? 'true' : 'false'; - - case 'NULL': - return 'null'; - - case 'integer': - return (int) $var; - - case 'double': - case 'float': - return (float) $var; - - case 'string': - // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT - $ascii = ''; - $strlen_var = strlen($var); - - /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ - for ($c = 0; $c < $strlen_var; ++$c) { - - $ord_var_c = ord($var{$c}); - - switch (true) { - case $ord_var_c == 0x08: - $ascii .= '\b'; - break; - case $ord_var_c == 0x09: - $ascii .= '\t'; - break; - case $ord_var_c == 0x0A: - $ascii .= '\n'; - break; - case $ord_var_c == 0x0C: - $ascii .= '\f'; - break; - case $ord_var_c == 0x0D: - $ascii .= '\r'; - break; - - case $ord_var_c == 0x22: - case $ord_var_c == 0x2F: - case $ord_var_c == 0x5C: - // double quote, slash, slosh - $ascii .= '\\'.$var{$c}; - break; - - case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): - // characters U-00000000 - U-0000007F (same as ASCII) - $ascii .= $var{$c}; - break; - - case (($ord_var_c & 0xE0) == 0xC0): - // characters U-00000080 - U-000007FF, mask 110XXXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, ord($var{$c + 1})); - $c += 1; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF0) == 0xE0): - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2})); - $c += 2; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF8) == 0xF0): - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3})); - $c += 3; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFC) == 0xF8): - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4})); - $c += 4; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFE) == 0xFC): - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4}), - ord($var{$c + 5})); - $c += 5; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - } - } - - return '"'.$ascii.'"'; - - case 'array': - /* - * As per JSON spec if any array key is not an integer - * we must treat the the whole array as an object. We - * also try to catch a sparsely populated associative - * array with numeric keys here because some JS engines - * will create an array with empty indexes up to - * max_index which can cause memory issues and because - * the keys, which may be relevant, will be remapped - * otherwise. - * - * As per the ECMA and JSON specification an object may - * have any string as a property. Unfortunately due to - * a hole in the ECMA specification if the key is a - * ECMA reserved word or starts with a digit the - * parameter is only accessible using ECMAScript's - * bracket notation. - */ - - // treat as a JSON object - if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { - $indentNr++; - $properties = array_map(array($this, 'name_value'), - array_keys($var), - array_values($var)); - $indentNr--; - - foreach($properties as $property) { - if(JSON::isError($property)) { - return $property; - } - } - - return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) ."\n$indent".'}'."\n$indent"; - } - - // treat it like a regular array - $indentNr++; - $elements = array_map(array($this, 'encode'), $var); - $indentNr--; - - foreach($elements as $element) { - if(JSON::isError($element)) { - return $element; - } - } - - return "\n$indent".'['."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $elements) . "\n$indent".']'."\n$indent"; - - case 'object': - $vars = get_object_vars($var); - - $indentNr++; - $properties = array_map(array($this, 'name_value'), - array_keys($vars), - array_values($vars)); - $indentNr--; - - foreach($properties as $property) { - if(JSON::isError($property)) { - return $property; - } - } - - return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) . "\n$indent".'}'."\n$indent"; - - default: - return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) - ? 'null' - : new JSON_Error(gettype($var)." can not be encoded as JSON string"); - } - } - - - - /** - * array-walking function for use in generating JSON-formatted name-value pairs - * - * @param string $name name of key to use - * @param mixed $value reference to an array element to be encoded - * - * @return string JSON-formatted name-value pair, like '"name":value' - * @access private - */ - function name_value($name, $value ) - { - $encoded_value = $this->encode($value); - - if(JSON::isError($encoded_value)) { - return $encoded_value; - } - - return $this->encode(strval($name)) . ':' . $encoded_value; - } - - /** - * reduce a string by removing leading and trailing comments and whitespace - * - * @param $str string string value to strip of comments and whitespace - * - * @return string string value stripped of comments and whitespace - * @access private - */ - function reduce_string($str) - { - $str = preg_replace(array( - - // eliminate single line comments in '// ...' form - '#^\s*//(.+)$#m', - - // eliminate multi-line comments in '/* ... */' form, at start of string - '#^\s*/\*(.+)\*/#Us', - - // eliminate multi-line comments in '/* ... */' form, at end of string - '#/\*(.+)\*/\s*$#Us' - - ), '', $str); - - // eliminate extraneous space - return trim($str); - } - - /** - * decodes a JSON string into appropriate variable - * - * @param string $str JSON-formatted string - * - * @return mixed number, boolean, string, array, or object - * corresponding to given JSON input string. - * See argument 1 to Services_JSON() above for object-output behavior. - * Note that decode() always returns strings - * in ASCII or UTF-8 format! - * @access public - */ - function decode($str) - { - $str = $this->reduce_string($str); - - switch (strtolower($str)) { - case 'true': - return true; - - case 'false': - return false; - - case 'null': - return null; - - default: - $m = array(); - - if (is_numeric($str)) { - // Lookie-loo, it's a number - - // This would work on its own, but I'm trying to be - // good about returning integers where appropriate: - // return (float)$str; - - // Return float or int, as appropriate - return ((float)$str == (integer)$str) - ? (integer)$str - : (float)$str; - - } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { - // STRINGS RETURNED IN UTF-8 FORMAT - $delim = substr($str, 0, 1); - $chrs = substr($str, 1, -1); - $utf8 = ''; - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c < $strlen_chrs; ++$c) { - - $substr_chrs_c_2 = substr($chrs, $c, 2); - $ord_chrs_c = ord($chrs{$c}); - - switch (true) { - case $substr_chrs_c_2 == '\b': - $utf8 .= chr(0x08); - ++$c; - break; - case $substr_chrs_c_2 == '\t': - $utf8 .= chr(0x09); - ++$c; - break; - case $substr_chrs_c_2 == '\n': - $utf8 .= chr(0x0A); - ++$c; - break; - case $substr_chrs_c_2 == '\f': - $utf8 .= chr(0x0C); - ++$c; - break; - case $substr_chrs_c_2 == '\r': - $utf8 .= chr(0x0D); - ++$c; - break; - - case $substr_chrs_c_2 == '\\"': - case $substr_chrs_c_2 == '\\\'': - case $substr_chrs_c_2 == '\\\\': - case $substr_chrs_c_2 == '\\/': - if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || - ($delim == "'" && $substr_chrs_c_2 != '\\"')) { - $utf8 .= $chrs{++$c}; - } - break; - - case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): - // single, escaped unicode character - $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) - . chr(hexdec(substr($chrs, ($c + 4), 2))); - $utf8 .= $this->utf162utf8($utf16); - $c += 5; - break; - - case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): - $utf8 .= $chrs{$c}; - break; - - case ($ord_chrs_c & 0xE0) == 0xC0: - // characters U-00000080 - U-000007FF, mask 110XXXXX - //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 2); - ++$c; - break; - - case ($ord_chrs_c & 0xF0) == 0xE0: - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 3); - $c += 2; - break; - - case ($ord_chrs_c & 0xF8) == 0xF0: - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 4); - $c += 3; - break; - - case ($ord_chrs_c & 0xFC) == 0xF8: - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 5); - $c += 4; - break; - - case ($ord_chrs_c & 0xFE) == 0xFC: - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 6); - $c += 5; - break; - - } - - } - - return $utf8; - - } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { - // array, or object notation - - if ($str{0} == '[') { - $stk = array(SERVICES_JSON_IN_ARR); - $arr = array(); - } else { - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = array(); - } else { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = new stdClass(); - } - } - - array_push($stk, array('what' => SERVICES_JSON_SLICE, - 'where' => 0, - 'delim' => false)); - - $chrs = substr($str, 1, -1); - $chrs = $this->reduce_string($chrs); - - if ($chrs == '') { - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } else { - return $obj; - - } - } - - //print("\nparsing {$chrs}\n"); - - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c <= $strlen_chrs; ++$c) { - - $top = end($stk); - $substr_chrs_c_2 = substr($chrs, $c, 2); - - if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { - // found a comma that is not inside a string, array, etc., - // OR we've reached the end of the character list - $slice = substr($chrs, $top['where'], ($c - $top['where'])); - array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); - //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - // we are in an array, so just push an element onto the stack - array_push($arr, $this->decode($slice)); - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - // we are in an object, so figure - // out the property name and set an - // element in an associative array, - // for now - $parts = array(); - - if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // "name":value pair - $key = $this->decode($parts[1]); - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // name:value pair, where name is unquoted - $key = $parts[1]; - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } - - } - - } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { - // found a quote, and we are not inside a string - array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); - //print("Found start of string at {$c}\n"); - - } elseif (($chrs{$c} == $top['delim']) && - ($top['what'] == SERVICES_JSON_IN_STR) && - ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { - // found a quote, we're in a string, and it's not escaped - // we know that it's not escaped becase there is _not_ an - // odd number of backslashes at the end of the string so far - array_pop($stk); - //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '[') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-bracket, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); - //print("Found start of array at {$c}\n"); - - } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { - // found a right-bracket, and we're in an array - array_pop($stk); - //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '{') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-brace, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); - //print("Found start of object at {$c}\n"); - - } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { - // found a right-brace, and we're in an object - array_pop($stk); - //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($substr_chrs_c_2 == '/*') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a comment start, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); - $c++; - //print("Found start of comment at {$c}\n"); - - } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { - // found a comment end, and we're in one now - array_pop($stk); - $c++; - - for ($i = $top['where']; $i <= $c; ++$i) - $chrs = substr_replace($chrs, ' ', $i, 1); - - //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } - - } - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - return $obj; - - } - - } - } - } - - /** - * @todo Ultimately, this should just call PEAR::isError() - */ - function isError($data, $code = null) - { - if (class_exists('pear')) { - return PEAR::isError($data, $code); - } elseif (is_object($data) && (get_class($data) == 'json_error' || - is_subclass_of($data, 'json_error'))) { - return true; - } - - return false; - } -} - - - /** - * @todo Ultimately, this class shall be descended from PEAR_Error - */ - class JSON_Error - { - function JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - - } - } - - -?> diff --git a/serviceClasses/Ldap.class.php b/serviceClasses/Ldap.class.php @@ -1,184 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Bereitstellen von LDAP-Funktionen. - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Ldap -{ - var $connection; - var $timeout; - var $aliases; - - - /** - * - */ - function Ldap() - { - global $conf; - - $this->timeout = intval($conf['ldap']['search']['timeout']); - - if ( $conf['ldap']['search']['aliases'] ) - $this->aliases = LDAP_DEREF_ALWAYS; - else - $this->aliases = LDAP_DEREF_NEVER; - } - - - - /** - * Verbindung �ffnen. - */ - function connect() - { - global $conf; - - $ldapHost = $conf['ldap']['host']; - $ldapPort = $conf['ldap']['port']; - - // Verbindung zum LDAP-Server herstellen - $this->connection = @ldap_connect( $ldapHost,$ldapPort ); - - // siehe http://bugs.php.net/bug.php?id=15637 - // Unter bestimmten Bedingungen wird trotz nicht erreichbarem LDAP-Server eine PHP-Resource - // zurueck gegeben. Dann erscheint zwar keine Fehlermeldung, aber zumindestens misslingt - // der nachfolgende Bind-Befehl. - if ( !is_resource($this->connection) || $this->connection === false ) - { - Logger::error( "connect to ldap server '$ldapHost:$ldapPort' failed" ); - // Abbruch, wenn LDAP-Server nicht erreichbar - die( "Connection failed to $ldapHost:$ldapPort (".ldap_errno().'/'.ldap_error().'). Please contact your administrator.' ); - } - - // Protokollversion setzen. - $j = ldap_set_option( $this->connection, LDAP_OPT_PROTOCOL_VERSION,intval($conf['ldap']['protocol']) ); - if ( ! $j ) - die( 'LDAP error while setting protocol version'.ldap_errno().'/'.ldap_error().')' ); - - } - - - - /** - * Ein Binding auf den LDAP-Server durchf�hren. - */ - function bind( $user,$pw ) - { - return @ldap_bind( $this->connection,$user,$pw); - } - - - - /** - * Ein Binding auf den LDAP-Server durchf�hren. - */ - function bindAnonymous() - { - return @ldap_bind( $this->connection ); - } - - - - /** - * Das Bindung wird entfernt. - */ - function unbind() - { - ldap_unbind( $this->connection ); - } - - - - /** - * Eine Suche auf den LDAP-Server durchf�hren. - */ - function searchUser( $username ) - { - global $conf; - - $techUser = $conf['ldap']['search']['user']; - $techPass = $conf['ldap']['search']['password']; - - if ( $conf['ldap']['search']['anonymous'] ) - $this->bindAnonymous(); - else - $this->bind( $techUser, $techPass ); - - $dn = $conf['ldap']['search']['basedn']; - $filter = $conf['ldap']['search']['filter']; - $filter = str_replace('{user}', $username, $filter); - - $s = @ldap_search( $this->connection,$dn,$filter,array(),0,1,$this->timeout,$this->aliases ); - - if ( ! is_resource($s) ) - return null; - - $dn = @ldap_get_dn($this->connection, ldap_first_entry($this->connection,$s) ); - - return $dn; - } - - - - /** - * Ein Binding auf den LDAP-Server durchf�hren. - */ - function searchAttribute( $filter,$attr ) - { - global $conf; - - $timeout = intval($conf['ldap']['search']['timeout']); - - if ( $conf['ldap']['search']['aliases'] ) - $aliases = LDAP_DEREF_ALWAYS; - else - $aliases = LDAP_DEREF_NEVER; - - - $base_dn = $conf['ldap']['search']['basedn']; - $s = ldap_search( $this->connection,$base_dn,$filter,array(),0,0,$this->timeout,$this->aliases ); - $ergebnisse = ldap_get_entries($this->connection,$s); - - $liste = array(); -// Html::debug($ergebnisse); - for( $i=0; $i<=$ergebnisse['count']-1; $i++ ) - $liste[] = $ergebnisse[$i][$attr][0]; - - return $liste; - } - - - - /** - * Verbindung schlie�en. - */ - function close() - { - // Verbindung zum LDAP-Server brav beenden - ldap_close( $this->connection ); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Line.class.php b/serviceClasses/Line.class.php @@ -1,152 +0,0 @@ -<?php - -/** - * Darstellung einer Zeile in einem Freitext.<br> - * <br> - * Im Konstruktor wird die Zeile analysiert und es wird festgestellt, was - * die Zeile für einen Inhalt hat (z.B. ein Listenelement, eine Überschrift, usw.)<br> - * - * @author Jan Dankert - * @version $Revision$ - * @package openrat.services - */ -class Line -{ - var $source; // Der ursprüngliche Inhalt - var $value; // Der textuelle Inhalt (sofern vorhanden) - - var $isDefinition = false; // Definitionseintrag - var $isList = false; // nicht-numerierte Liste - var $isNumberedList = false; // numerierte Liste - var $indent = 0; // Einschubtiefe der Liste - - var $isHeadline = false; // Überschrift - var $isHeadlineUnderline = false; // unterstrichene Überschrift - var $headlineLevel = 0; // Grad der Überschrift (1,2,3...) - - - var $isTableOfContent = false; // Inhaltsverzeichnis - var $isTable = false; // Tabelle - var $isCode = false; // Code - var $isQuote = false; // Zitat - var $isQuotePraefix = false; // Zitatbeginn/-ende - - var $isUnparsed = false; - - var $isEmpty = false; // Zeile ist leer - var $isNormal = false; // Zeile ist ohne besonderen Inhalt, d.h. keine Tabelle, kein Zitat, usw. - - - - /** - * Erzeugt einen Zeilenobjekt, der Text im Parameter wird dabei geparst. - */ - function Line( $s ) - { - global $conf; - $text_markup = $conf['editor']['text-markup']; -// Html::debug($text_markup); - - $list_numbered = $text_markup['list-numbered' ]; - $list_unnumbered = $text_markup['list-unnumbered']; - $headline = $text_markup['headline' ]; - - $this->source = $s; - $this->value = $s; - - $this->isList = $this->isAnErsterStelle(ltrim($s),$list_unnumbered); - $this->isNumberedList = $this->isAnErsterStelle(ltrim($s),$list_numbered ); - $this->indent = strlen($s) - strlen(ltrim($s)) + 1; - - if ( $this->isList || $this->isNumberedList ) - $this->value = ltrim(substr($s,$this->indent)); - - $this->level = strspn( $s,$headline ); - $this->isHeadline = $this->level >= 1; - - if ( $this->isHeadline ) - $this->value = ltrim(substr($s,$this->level)); - - - $hl = array( 1 => $text_markup['headline_level1_underline'], - 2 => $text_markup['headline_level2_underline'], - 3 => $text_markup['headline_level3_underline'] ); - - foreach($hl as $lev=>$char ) - { - if ( substr($s,0,3*strlen($char))==str_repeat($char,3*strlen($char)) ) - { - $this->isHeadlineUnderline = true; - $this->isNormal = true; - $this->level = intval($lev); - } - } - - if ( $this->isAnErsterStelle($s,$text_markup['table-of-content']) ) - { - $this->isTableOfContent = true; - $this->isNumberedList = false; - $this->isList = false; - $this->value = ''; - } - elseif - ( $this->isHeadline || - $this->isHeadlineUnderline || - $this->isList || - $this->isNumberedList ) - { - ; - } - elseif ( $this->isAnErsterStelle($s,$text_markup['table-cell-sep']) ) - { - $this->isTable = true; - $this->value = ''; - } - elseif ( $this->isAnErsterStelle($s,$text_markup['pre-begin']) && !$this->isHeadlineUnderline ) - { - $this->isCode = true; - $this->value = substr($s,strlen($text_markup['pre-begin'])); - } - elseif ( strpos($s, $text_markup['definition-sep'])!== false ) - { - $this->isDefinition = true; - } - elseif ( trim($s)==$text_markup['quote-line-begin'] ) - { - $this->isQuote = true; - } - elseif ( $this->isAnErsterStelle($s,$text_markup['quote']) && strlen(trim($s))>1 ) - { - $this->isQuotePraefix = true; - $this->value = ltrim(substr($s,strlen($text_markup['quote']))); - $this->level = strspn( str_replace(' ','',$s),$text_markup['quote'] ); - } - elseif ( $this->isAnErsterStelle($s,'`') ) - { - $this->isUnparsed = true; - $this->value = substr($this->value,1); - } - elseif ( $s == '' ) - { - $this->isEmpty = true; - } - else - { - $this->isNormal = true; - } - } - - - /** - * Stellt fest, ob $wort am Anfang von $text steht. - */ - function isAnErsterStelle( $text,$wort ) - { -// Html::debug($text,"Text"); -// Html::debug($wort,"Wort"); -// Html::debug(substr($text,0,strlen($wort))==$wort,'Ergebnis'); - return substr($text,0,strlen($wort))==$wort; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Logger.class.php b/serviceClasses/Logger.class.php @@ -1,194 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// OpenRat Content Management System -// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.5 2007-11-08 21:32:06 dankert -// Aktion-Name mitloggen. -// -// Revision 1.4 2004/11/10 22:50:37 dankert -// Benutzen von Konstanten zur Performancesteigerung -// -// Revision 1.3 2004/10/04 19:57:17 dankert -// Bugfix und trace() -// -// Revision 1.2 2004/05/02 15:04:16 dankert -// Einf?gen package-name (@package) -// -// Revision 1.1 2004/04/24 17:03:28 dankert -// Initiale Version -// -// --------------------------------------------------------------------------- - - -switch( strtolower($conf['log']['level']) ) -{ - case 'trace': - define('OR_LOG_LEVEL_TRACE',true ); - - case 'debug': - define('OR_LOG_LEVEL_DEBUG',true ); - - case 'info': - define('OR_LOG_LEVEL_INFO' ,true ); - - case 'warn': - define('OR_LOG_LEVEL_WARN' ,true ); - - case 'error': - define('OR_LOG_LEVEL_ERROR',true ); -} - -if ( !defined('OR_LOG_LEVEL_TRACE') ) define('OR_LOG_LEVEL_TRACE',false ); -if ( !defined('OR_LOG_LEVEL_DEBUG') ) define('OR_LOG_LEVEL_DEBUG',false ); -if ( !defined('OR_LOG_LEVEL_INFO' ) ) define('OR_LOG_LEVEL_INFO' ,false ); -if ( !defined('OR_LOG_LEVEL_WARN' ) ) define('OR_LOG_LEVEL_WARN' ,false ); -if ( !defined('OR_LOG_LEVEL_ERROR') ) define('OR_LOG_LEVEL_ERROR',false ); - - - -/** - * Schreiben eines Eintrages in die Logdatei - * - * @author $Author$ - * @version $Rev: $ - * @package openrat.services - */ -class Logger -{ - /** - * Schreiben einer Trace-Meldung in die Logdatei - * - * @param message Log-Text - */ - function trace( $message ) - { - if ( OR_LOG_LEVEL_TRACE ) - Logger::doLog( 'trace',$message ); - } - - - /** - * Schreiben einer Debug-Meldung in die Logdatei - * - * @param message Log-Text - */ - function debug( $message ) - { - if ( OR_LOG_LEVEL_DEBUG ) - Logger::doLog( 'debug',$message ); - } - - - /** - * Schreiben einer Information in die Logdatei - * - * @param message Log-Text - */ - function info( $message ) - { - if ( OR_LOG_LEVEL_INFO ) - Logger::doLog( 'info',$message ); - } - - - /** - * Schreiben einer Warnung in die Logdatei - * - * @param message Log-Text - */ - function warn( $message ) - { - if ( OR_LOG_LEVEL_WARN ) - Logger::doLog( 'warn',$message ); - } - - - /** - * Schreiben einer normalen Fehlermeldung in die Logdatei - * - * @param message Log-Text - */ - function error( $message ) - { - if ( OR_LOG_LEVEL_ERROR ) - Logger::doLog( 'error',$message ); - } - - - /** - * Schreiben der Meldung in die Logdatei - * - * @author $Author$ - * @param facility Schwere dieses Logdatei-Eintrages (z.B. warning) - * @param message Log-Text - * @access private - */ - function doLog( $facility,$message ) - { - global $conf; - global $SESS; - - $filename = $conf['log']['file']; - - if ( $filename == '' ) - return; - - if ( ! is_writable($filename) ) - Http::serverError( "logfile $filename is not writable by the server" ); - - $thisLevel = strtoupper($facility); - - $user = Session::getUser(); - if ( is_object($user) ) - $username = $user->name; - else - $username = '-'; - - $text = $conf['log']['format']; // Format der Logdatei lesen - - // Ersetzen von Variablen - if ( $conf['log']['dns_lookup'] ) - $text = str_replace( '%host',gethostbyaddr(getenv('REMOTE_ADDR')),$text ); - else - $text = str_replace( '%host',getenv('REMOTE_ADDR'),$text ); - - $action = Session::get('action'); - if ( empty($action) ) - $action = '-'; - - $action = Session::get('action'); - if ( empty($action) ) - $action = '-'; - - $text = str_replace( '%user' ,str_pad($username ,8),$text ); - $text = str_replace( '%level' ,str_pad($thisLevel,5),$text ); - $text = str_replace( '%agent' ,getenv('HTTP_USER_AGENT'),$text ); - $text = str_replace( '%action',str_pad($action,12),$text ); - $text = str_replace( '%text' ,$message,$text ); - $text = str_replace( '%time' ,date($conf['log']['date_format']),$text ); - $text = str_replace( "\n" ,"\n ",$text ); - - // Schreiben in Logdatei - error_log( $text."\n",3,$filename ); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Mail.class.php b/serviceClasses/Mail.class.php @@ -1,572 +0,0 @@ -<?php -/* -OpenRat Content Management System -Copyright (C) Jan Dankert - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -or 3 of the License. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, see <http://www.gnu.org/licenses/>. -*/ - -/** - * Erzeugen und Versender einer E-Mail gemaess RFC 822.<br> - * <br> - * Die E-Mail kann entweder �ber - * - die interne PHP-Funktion "mail()" versendet werden oder - * - direkt per SMTP-Protokoll an einen SMTP-Server.<br> - * Welcher Weg gew�hlt wird, kann konfiguriert werden.<br> - * <br> - * Prinzipiell spricht nichts gegen die interne PHP-Funktion mail(), wenn diese - * aber nicht zu Verf�gung steht oder PHP ungeeignet konfiguriert ist, so kann - * SMTP direkt verwendet werden. Hierbei sollte wenn m�glich ein Relay-Host - * eingesetzt werden. Die Mail kann zwar auch direkt an Mail-Exchanger (MX) des - * Empf�ngers geschickt werden, falls dieser aber Greylisting einsetzt ist eine - * Zustellung nicht m�glich.<br> - * <br> - * - * @author Jan Dankert - * @version $Id$ - * @package serviceClasses - */ -class Mail -{ - var $from = ''; - var $to = ''; - var $bcc = ''; - var $cc = ''; - var $subject = ''; - var $text = ''; - var $header = array(); - var $nl = ''; - - /** - * Falls beim Versendern der E-Mail etwas schiefgeht, steht hier drin - * die technische Fehlermeldung. - * - * @var String Fehler - */ - var $error = array(); - - /** - * Set to true for debugging. - * If true, All SMTP-Commands are written to error log. - * - * @var unknown_type - */ - var $debug = true; - - - /** - * Konstruktor. - * Es werden folgende Parameter erwartet - * @param String $to Empf�nger - * @param String der Textschl�ssel - * @param String unbenutzt. - * @return Mail - */ - function Mail( $to,$text,$xy='' ) - { - global $conf; - - // Zeilenumbruch CR/LF gem. RFC 822. - $this->nl = chr(13).chr(10); - - if ( !empty($conf['mail']['from']) ) - $this->from = $this->header_encode($conf['mail']['from']); - - // Priorit�t definieren (sofern konfiguriert) - if ( !empty($conf['mail']['priority']) ) - $this->header[] = 'X-Priority: '.$conf['mail']['priority']; - - $this->header[] = 'X-Mailer: '.$this->header_encode(OR_TITLE.' '.OR_VERSION); - $this->header[] = 'Content-Type: text/plain; charset='.lang( 'CHARSET' ); - $this->subject = $this->header_encode(lang( 'mail_subject_'.$text )); - $this->to = $this->header_encode($to); - - $this->text = $this->nl.wordwrap(str_replace(';',$this->nl,lang('mail_text_'.$text)),70,$this->nl).$this->nl; - - // Signatur anhaengen (sofern konfiguriert) - if ( !empty($conf['mail']['signature']) ) - { - $this->text .= $this->nl.'-- '.$this->nl; - $this->text .= str_replace(';',$this->nl,$conf['mail']['signature']); - $this->text .= $this->nl; - } - - // Kopie-Empf�nger - if ( !empty($conf['mail']['cc']) ) - $this->cc = $this->header_encode($conf['mail']['cc']); - - // Blindkopie-Empf�nger - if ( !empty($conf['mail']['bcc']) ) - $this->bcc = $this->header_encode($conf['mail']['bcc']); - } - - - - /** - * Kodiert einen Text in das Format "Quoted-printable".<br> - * See RFC 2045. - * @param String $text Eingabe - * @return Text im quoted-printable-Format - */ - function quoted_printable_encode( $text ) - { - $text = str_replace(' ','=20',$text); - - for( $i=128; $i<=255; $i++ ) - { - $text = str_replace( chr($i),'='.dechex($i),$text ); - } - - return $text; - } - - - - /** - * Setzen einer Variablen in den Mail-Inhalt. - */ - function setVar( $varName,$varInhalt) - { - $this->text = str_replace( '{'.$varName.'}', $varInhalt, $this->text ); - } - - - /** - * Mail absenden. - * Die E-Mail wird versendet. - * - * @return boolean Erfolg - */ - function send() - { - global $conf; - - $to_domain = array_pop( explode('@',$this->to) ); - - // Prüfen gegen die Whitelist - $white = @$conf['mail']['whitelist']; - - if ( !empty($white) ) - { - if ( ! $this->containsDomain($to_domain,$white) ) - { - // Wenn Domain nicht in Whitelist gefunden, dann Mail nicht verschicken. - $this->error[] = 'Mail-Domain is not whitelisted'; - return false; - } - } - - // Prüfen gegen die Blacklist - $black = @$conf['mail']['blacklist']; - - if ( !empty($black) ) - { - if ( $this->containsDomain($to_domain,$black) ) - { - // Wenn Domain in Blacklist gefunden, dann Mail nicht verschicken. - $this->error[] = 'Mail-Domain is blacklisted'; - return false; - } - } - - // Header um Adressangaben erg�nzen. - if ( !empty($this->from ) ) - $this->header[] = 'From: '.$this->from; - - if ( !empty($this->cc ) ) - $this->header[] = 'Cc: '.$this->cc; - - if ( !empty($this->bcc ) ) - $this->header[] = 'Bcc: '.$this->bcc; - - // Mail versenden - if ( strtolower(@$conf['mail']['client']) == 'php' ) - { - // PHP-interne Mailfunktion verwenden. - $result = @mail( $this->to, // Empf�nger - $this->subject, // Betreff - $this->text, // Inhalt - // Lt. RFC822 müssen Header mit CRLF enden. - // ABER: Der Parameter "additional headers" verlangt offenbar \n am Zeilenende. - implode("\n",$this->header) ); - if ( !$result ) - // Die E-Mail wurde nicht akzeptiert. - // Genauer geht es leider nicht, da mail() nur einen boolean-Wert - // zur�ck liefert. - $this->error[] = 'Mail was NOT accepted by mail()'; - - return $result; - } - else - { - // eigenen SMTP-Dialog verwenden. - $smtpConf = $conf['mail']['smtp']; - - if ( !empty($smtpConf['host'])) - { - // Eigenen Relay-Host verwenden. - $mxHost = $smtpConf['host']; - $mxPort = intval($smtpConf['port']); - } - else - { - // Mail direkt zustellen. - $mxHost = $this->getMxHost($this->to); - - if ( empty($mxHost) ) - { - $this->error[] = "No MX-Entry found. Mail could not be sent."; - return false; - } - - if ($smtpConf['ssl']) - $mxPort = 465; - else - $mxPort = 25; - } - - - if ( !empty($smtpConf['localhost'])) - { - $myHost = $smtpConf['localhost']; - } - else - { - $myHost = gethostbyaddr(getenv('REMOTE_ADDR')); - } - - if ( $smtpConf['ssl']) - $proto = 'ssl'; - else - $proto = 'tcp'; - - //connect to the host and port - $smtpSocket = fsockopen($proto.'://'.$mxHost,$mxPort, $errno, $errstr, intval($smtpConf['timeout'])); - - if ( !is_resource($smtpSocket) ) - { - $this->error[] = 'Connection failed to: '.$proto.'://'.$mxHost.':'.$mxPort.' ('.$errstr.'/'.$errno.')'; - return false; - } - - $smtpResponse = fgets($smtpSocket, 4096); - if ( $this->debug) - $this->error[] = trim($smtpResponse); - - if ( substr($smtpResponse,0,3) != '220' ) - { - $this->error[] = 'No 220: '.trim($smtpResponse); - return false; - } - - if ( !is_resource($smtpSocket) ) - { - $this->error[] = 'Connection failed to: '.$smtpConf['host'].':'.$smtpConf['port'].' ('.$smtpResponse.')'; - return false; - } - - //you have to say HELO again after TLS is started - $smtpResponse = $this->sendSmtpCommand($smtpSocket,'HELO '.$myHost); - - if ( substr($smtpResponse,0,3) != '250' ) - { - $this->error[] = "No 2xx after HELO, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - if ( $smtpConf['tls'] ) - { - $smtpResponse = $this->sendSmtpCommand($smtpSocket,'STARTTLS'); - if ( substr($smtpResponse,0,3) == '220' ) - { - // STARTTLS ist gelungen. - //you have to say HELO again after TLS is started - $smtpResponse = $this->sendSmtpCommand($smtpSocket,'HELO '.$myHost); - - if ( substr($smtpResponse,0,3) != '250' ) - { - $this->error[] = "No 2xx after HELO, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - } - else - { - // STARTTLS ging in die Hose. Einfach weitermachen. - } - } - - // request for auth login - if ( isset($smtpConf['auth_username']) && !empty($smtpConf['host']) && !empty($smtpConf['auth_username'])) - { - $smtpResponse = $this->sendSmtpCommand($smtpSocket,"AUTH LOGIN"); - if ( substr($smtpResponse,0,3) != '334' ) - { - $this->error[] = "No 334 after AUTH_LOGIN, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - if ( $this->debug) - $this->error[] = 'Login for '.$smtpConf['auth_username']; - - //send the username - $smtpResponse = $this->sendSmtpCommand($smtpSocket, base64_encode($smtpConf['auth_username'])); - if ( substr($smtpResponse,0,3) != '334' ) - { - $this->error[] = "No 3xx after setting username, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - //send the password - $smtpResponse = $this->sendSmtpCommand($smtpSocket, base64_encode($smtpConf['auth_password'])); - if ( substr($smtpResponse,0,3) != '235' ) - { - $this->error[] = "No 235 after sending password, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - } - - //email from - $smtpResponse = $this->sendSmtpCommand($smtpSocket, 'MAIL FROM: <'.$conf['mail']['from'].'>'); - if ( substr($smtpResponse,0,3) != '250' ) - { - $this->error[] = "No 2xx after MAIL_FROM, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - //email to - $smtpResponse = $this->sendSmtpCommand($smtpSocket, 'RCPT TO: <'.$this->to.'>'); - if ( substr($smtpResponse,0,3) != '250' ) - { - $this->error[] = "No 2xx after RCPT_TO, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - //the email - $smtpResponse = $this->sendSmtpCommand($smtpSocket, "DATA"); - if ( substr($smtpResponse,0,3) != '354' ) - { - $this->error[] = "No 354 after DATA, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - $this->header[] = 'To: '.$this->to; - $this->header[] = 'Subject: '.$this->subject; - $this->header[] = 'Date: '.date('r'); - $this->header[] = 'Message-Id: '.'<'.getenv('REMOTE_ADDR').'.'.time().'.openrat@'.getenv('SERVER_NAME').'.'.getenv('HOSTNAME').'>'; - - //observe the . after the newline, it signals the end of message - $smtpResponse = $this->sendSmtpCommand($smtpSocket, implode($this->nl,$this->header).$this->nl.$this->nl.$this->text.$this->nl.'.'); - if ( substr($smtpResponse,0,3) != '250' ) - { - $this->error[] = "No 2xx after putting DATA, server says: ".$smtpResponse; - $this->sendSmtpQuit($smtpSocket); - return false; - } - - // say goodbye - $this->sendSmtpQuit($smtpSocket); - return true; - } - } - - - /** - * Sendet ein SMTP-Kommando zum SMTP-Server. - * - * @access private - * @param Resource $socket TCP/IP-Socket zum SMTP-Server - * @param unknown_type $cmd SMTP-Kommando - * @return Server-Antwort - */ - function sendSmtpCommand( $socket,$cmd ) - { - if ( $this->debug ) - $this->error[] = 'CLIENT: >>> '.trim($cmd); - if ( !is_resource($socket) ) - { - // Die Verbindung ist geschlossen. Dies kann bei dieser - // Implementierung eigentlich nur dann passieren, wenn - // der Server die Verbindung schlie�t. - // Dieser Client trennt die Verbindung nur nach einem "QUIT". - $this->error[] = "Connection lost"; - return; - } - - fputs($socket,$cmd.$this->nl); - $response = trim(fgets($socket, 4096)); - if ( $this->debug ) - $this->error[] = 'SERVER: <<< '.$response; - return $response; - } - - - - /** - * Sendet ein QUIT zum SMTP-Server, wartet die Antwort ab und - * schlie�t danach die Verbindung. - * - * @param Resource Socket - */ - function sendSmtpQuit( $socket ) - { - - if ( $this->debug ) - $this->error[] = "CLIENT: >>> QUIT"; - if ( !is_resource($socket) ) - return; - // Wenn die Verbindung nicht mehr da ist, brauchen wir - // auch kein QUIT mehr :) - - - fputs($socket,'QUIT'.$this->nl); - $response = trim(fgets($socket, 4096)); - if ( $this->debug ) - $this->error[] = 'SERVER: <<< '.$response; - - if ( substr($response,0,3) != '221' ) - $this->error[] = 'QUIT FAILED: '.$response; - - fclose($socket); - } - - - - /** - * Umwandlung von 8-bit-Zeichen in MIME-Header gemaess RFC 2047.<br> - * Header d�rfen nur 7-bit-Zeichen enthalten. 8-bit-Zeichen m�ssen kodiert werden. - * - * @param String $text - * @return String - */ - function header_encode( $text ) - { - global $conf; - - if ( empty($conf['mail']['header_encoding']) ) - return $text; - - $woerter = explode(' ',$text); - $neu = array(); - - - foreach( $woerter as $wort ) - { - $type = strtolower(substr($conf['mail']['header_encoding'],0,1)); - $neu_wort = ''; - - if ( $type == 'b' ) - $neu_wort = base64_encode($wort); - elseif ( $type == 'q' ) - $neu_wort = $this->quoted_printable_encode($wort); - else - Logger::error( 'Mail-Configuratin broken: UNKNOWN Header-Encoding type: '.$type); - - if ( strlen($wort)==strlen($neu_wort) ) - $neu[] = $wort; - else - $neu[] = '=?'.lang('CHARSET').'?'.$type.'?'.$neu_wort.'?='; - } - - return implode(' ',$neu); - } - - - /** - * Ermittelt den MX-Eintrag zu einer E-Mail-Adresse.<br> - * Es wird der Eintrag mit der h�chsten Priorit�t ermittelt. - * - * @param String E-Mail-Adresse des Empf�ngers. - * @return MX-Eintrag - */ - function getMxHost( $to ) - { - list($user,$host) = explode('@',$to.'@'); - - if ( empty($host) ) - { - $this->error[] = 'Illegal mail address - No hostname found.'; - return ""; - } - - list($host) = explode('>',$host); - - $mxHostsName = array(); - $mxHostsPrio = array(); - getmxrr($host,$mxHostsName,$mxHostsPrio); - - $mxList = array(); - foreach( $mxHostsName as $id=>$mxHostName ) - { - $mxList[$mxHostName] = $mxHostsPrio[$id]; - } - asort($mxList); - return key($mxList); - } - - - - /** - * Stellt fest, ob die E-Mail-Adresse eine gueltige Syntax besitzt. - * - * Es wird nur die Syntax geprüft. Ob die Adresse wirklich existiert, steht dadurch noch lange - * nicht fest. Dazu müsste man die MX-Records auflösen und einen Zustellversuch unternehmen. - * - * @param $email_address Adresse - * @return true, falls Adresse OK, sonst false - */ - function checkAddress( $email_address ) - { - // Source: de.php.net/ereg - return ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $email_address); - } - - - - /** - * Prüft, ob eine Domain in einer List von Domains enthalten ist. - * - * @param $checkDomain zu prüfende Domain - * @param $domain_list Liste von Domains als kommaseparierte Liste - * @return true, falls vorhanden, sonst false - */ - function containsDomain($checkDomain, $domain_list) - { - $domains = explode(',',$domain_list); - - foreach( $domains as $domain ) - { - $domain = trim($domain); - - if (empty($domain)) - continue; - - if ($domain == substr($checkDomain,-strlen($domain))) - { - return true; - } - } - return false; - } -} - - -?> diff --git a/serviceClasses/OpenId.class.php b/serviceClasses/OpenId.class.php @@ -1,467 +0,0 @@ -<?php - - -/** - * Open-Id Authentisierung gem�� OpenId-Spezifikation 1.0. - * - */ -class OpenId -{ - /** - * Open-Id Server, an den die Authentisierungsanfrage gestellt wird. - * - * @var String - */ - var $server; - - - /** - * Informationen zum Benutzer. - * - * @var Array - */ - var $info; - - /** - * Open-Id Identity. - * - * @var String - */ - var $identity; - - /** - * Fehlermeldung (falls vorhanden). - * - * @var String - */ - var $error; - - /** - * OpenId-Benutzername. - * - * @var String - */ - var $user; - - /** - * OpenId-Provider. - * - * @var String - */ - var $provider; - - - var $supportAX; - var $supportSREG; - var $supportOpenId1_1; - var $supportOpenId2_0; - - - /** - * Neue Open-Id Anfrage. - * - * @param String $user - * @return OpenId - */ - function OpenId( $provider='',$user='' ) - { - $this->provider = $provider; - $this->user = $user; - } - - - /** - * Stellt fest, ob der Server vertrauensw�rdig ist. - * - * @return true, wenn vertrauensw�rdig. - */ - function serverOk() - { - global $conf; - $servers = $conf['security']['openid']['trusted_server']; - - if ( empty($servers) ) - { - return true; - } - else - { - $serverList = explode(',',$servers); - - $http = new Http($this->server); - if ( !in_array($http->url['host'],$serverList) ) - { - $this->error = 'Server '.$this->server.' is not trusted'; - return false; - } - else - return true; - } - - } - - - - /** - * Authentisierung Schritt 1.<br> - * Ermitteln der Identity. - * - * @return boolean TRUE, wenn Identity ermittelt wurde. - */ - function login() - { - if ( $this->provider != 'identity' ) - { - $this->user = config('security','openid','provider.'.$this->provider.'.xrds_uri'); - $this->identity = 'http://specs.openid.net/auth/2.0/identifier_select'; - } - $this->supportSREG = config('security','openid','provider.'.$this->provider.'.sreg_1_0'); - $this->supportAX = config('security','openid','provider.'.$this->provider.'.ax_1_0' ); - - // Schritt 1: Identity aus Yadis-Dokument laden. - $this->getIdentityFromYadis(); - - // Schritt 2: Fallback auf HTML-Dokument. - if ( empty($this->server) ) - { - $this->getIdentityFromHtmlMetaData(); - } - - // Falls immer noch kein Servername gefunden wurde, dann Abbruch. - if ( empty($this->server) ) - { - if ( empty($this->error) ) - $this->error = 'Unable to locate OpenId-Server in URL'; - return false; - } - - if ( !$this->serverOk() ) - return false; // Server nicht vertrauenswuerdig. - - if ( empty($this->identity) ) - // Falls die Identity bis hierher nicht deligiert wurde... - // Lt. Spezifikation mit Prefix "http://". - $this->identity = 'http://'.$this->user; - - return true; - } - - - - /** - * Erzeugt einen HTTP-Redirect auf den OpenId-Provider. - */ - function redirect() - { - global $conf; - - $this->handle = md5(microtime().session_id()); - - $redirHttp = new Http($this->server); - - if ( $this->supportOpenId2_0 ) - $redirHttp->requestParameter['openid.ns' ] = 'http://specs.openid.net/auth/2.0'; - - $redirHttp->requestParameter['openid.mode' ] = 'checkid_setup'; - $redirHttp->requestParameter['openid.identity' ] = $this->identity; - - if ( $this->supportOpenId2_0 ) - $redirHttp->requestParameter['openid.claimed_id'] = $this->identity; - - - // Profilangaben anfordern. E-Mail wird ben�tigt, Name und Sprache sind optional. - - if ( $this->supportAX ) - { - Logger::info("OpenId-Server is using OpenID Attribute Exchange 1.0"); - $redirHttp->requestParameter['openid.ns.ax' ] = 'http://openid.net/srv/ax/1.0'; - $redirHttp->requestParameter['openid.ax.mode' ] = 'fetch_request'; - $redirHttp->requestParameter['openid.ax.type.email' ] = 'http://axschema.org/contact/email'; - $redirHttp->requestParameter['openid.ax.type.username' ] = 'http://axschema.org/namePerson/friendly'; - $redirHttp->requestParameter['openid.ax.type.fullname' ] = 'http://axschema.org/namePerson'; - $redirHttp->requestParameter['openid.ax.type.language' ] = 'http://axschema.org/pref/language'; - $redirHttp->requestParameter['openid.ax.required' ] = 'username,email'; - $redirHttp->requestParameter['openid.ax.if_available' ] = 'language,fullname'; - } - - if ( $this->supportSREG ) - { - Logger::info("OpenId-Server is using OpenID Simple Registration Extension 1.0"); - $redirHttp->requestParameter['openid.ns.sreg' ] = 'http://openid.net/sreg/1.0'; - $redirHttp->requestParameter['openid.sreg.required'] = 'email,nickname'; - $redirHttp->requestParameter['openid.sreg.optional'] = 'fullname,language'; - } - - $trustRoot = @$conf['security']['openid']['trust_root']; - $server = Http::getServer(); - if ( empty($trustRoot) ) - $trustRoot = $server; - - $redirHttp->requestParameter['openid.trust_root' ] = slashify($trustRoot); - $redirHttp->requestParameter['openid.return_to' ] = slashify($server).'openid.'.PHP_EXT; - //$redirHttp->requestParameter['openid.realm' ] = slashify($server).'openid.'.PHP_EXT; - $redirHttp->requestParameter['openid.assoc_handle' ] = $this->handle; - - $redirHttp->sendRedirect(); // Browser umleiten. - exit; // Ende. - } - - - - /** - * Ermittelt OpenId-Server und OpenId-Identity aus Yadis-Dokument.<br> - * - * @return unknown - */ - function getIdentityFromYadis() - { - $http = new Http($this->user); -// $http->url['host'] = $this->user; - - $http->header[] = 'Accept: application/xrds+xml'; - if ( ! $http->request() ) - { - $this->error = 'Unable to get XML delegate information'; - return false; - } - - Logger::debug("OpenId: Found YADIS-document for ".$http->getUrl()); - //die(); - $p = xml_parser_create(); - $ok = xml_parse_into_struct($p, $http->body, $vals, $index); - xml_parser_free($p); - - foreach( $vals as $tag ) - { - if ( strtolower($tag['tag']) == 'type' ) - { - if ( $tag['value'] == 'http://openid.net/srv/ax/1.0' ) - $this->supportAX = true; - - if ( $tag['value'] == 'http://openid.net/sreg/1.0' ) - $this->supportSREG = true; - - if ( $tag['value'] == 'http://openid.net/signon/1.1' ) - $this->supportOpenId1_1 = true; - - if ( $tag['value'] == 'http://specs.openid.net/auth/2.0/server' ) - $this->supportOpenId2_0 = true; - } - - if ( strtolower($tag['tag']) == 'uri' ) - { - $this->server = $tag['value']; - } - - if ( strtolower($tag['tag']) == 'openid:delegate' ) - { - $this->identity = $tag['value']; - } - } - - if ( !$this->supportOpenId1_1 && !$this->supportOpenId2_0 ) - { - $this->error = 'Only OpenId 1.1 and 2.0 is supported but this identity-provider does not seem to support any of these.'; - return false; - } - if ( !$this->supportAX && !$this->supportSREG ) - { - $this->error = 'The identity-provider must support either Attribute-Exchange (AX) oder Simple-Registration (SREG), but it does not seem to support any of these.'; - return false; - } - } - - - /** - * Ermittelt OpenId-Server und OpenId-Identity aus HTML Meta-Tags.<br> - */ - function getIdentityFromHtmlMetaData() - { - $http = new Http($this->user); -// $http = new Http(); -// $http->url['host'] = $this->user; - $http->header[] = 'Accept: text/html'; - - if ( ! $http->request() ) - { - $this->error = 'Unable to get HTML delegate information'; - return false; - } - - $seite = $http->body; - - // Die Meta-Tags mit regulaerem Ausdruck auslesen. - $treffer = array(); - preg_match('/rel="openid.server"\s+href="(\S+)"/',$seite,$treffer); - if ( count($treffer) >= 1 ) - { - $this->server = $treffer[1]; - $this->supportOpenId1_1 = true; - } - - $treffer = array(); - preg_match('/rel="openid2.provider"\s+href="(\S+)"/',$seite,$treffer); - if ( count($treffer) >= 1 ) - { - $this->supportOpenId2_0 = true; - $this->server = $treffer[1]; - } - - $treffer = array(); - preg_match('/rel="openid.delegate"\s+href="(\S+)"/',$seite,$treffer); - if ( count($treffer) >= 1 ) - $this->identity = $treffer[1]; - } - - - /** - * Ermittelt den Hostnamen aus der Identity. - * - * @return String - */ - function getUserFromIdentiy() - { - if ( $this->provider == 'identity' ) - { - $http = new Http($this->identity); - return $http->url['host']; - } - else - { - $attribute_name = config('security','openid','provider.'.$this->provider.'.map_attribute'); - return $this->info[$attribute_name]; - } - } - - - /** - * Open-Id Login, �berpr�fen der Anmeldung.<br> - * Spezifikation: http://openid.net/specs/openid-authentication-1_1.html<br> - * Kapitel "4.4. check_authentication"<br> - * <br> - * Im 2. Schritt (Mode "id_res") erfolgte ein Redirect vom Open-Id Provider an OpenRat zur�ck.<br> - * Wir befinden uns nun im darauf folgenden Request des Browsers.<br> - * <br> - * Es muss noch beim OpenId-Provider die Best�tigung eingeholt werden, danach ist der - * Benutzer angemeldet.<br> - */ - function checkAuthentication() - { - $queryVars = $this->getQueryParamList(); - - if ( $queryVars['openid.invalidate_handle'] != $this->handle ) - { - $this->error = 'Association-Handle mismatch.'; - return false; - } - - if ( $queryVars['openid.mode'] != 'id_res' ) - { - $this->error ='Open-Id: Unknown mode:'.$queryVars['openid.mode']; - return false; - } - - if ( $this->provider=='identity' && $queryVars['openid.identity'] != $this->identity ) - { - $this->error ='Open-Id: Identity mismatch. Wrong identity:'.$queryVars['openid.identity']; - return false; - } - - - $params = array(); - - if ( $this->supportAX ) - // Den Namespace-Prefix für AX (attribute exchange) herausfinden. - // Leider kann das ein anderer Prefix sein, als wir im Request verwendet haben. - foreach( $queryVars as $request_key=>$request_value ) - if ( substr($request_key,0,10)=='openid.ns.' && $request_value == 'http://openid.net/srv/ax/1.0' ) - $axPrefix = substr($request_key,10); - - foreach( $queryVars as $request_key=>$request_value ) - { - // Benutzer-Attribute ermitteln. - // Benutzer-Attribute über SREG ermitteln. - if ( $this->supportSREG && substr($request_key,0,12)=='openid.sreg.' ) - $this->info[ substr($request_key,12) ] = $request_value; - // Benutzer-Attribute über AX ermitteln. - elseif ( $this->supportAX && substr($request_key,0,14+strlen($axPrefix))=='openid.'.$axPrefix.'.value.' ) - $this->info[ substr($request_key,14+strlen($axPrefix)) ] = $request_value; - - // Alle OpenId-Parameter in den Check-Authentication-Request übertragen. - if ( substr($request_key,0,7)=='openid.' ) - $params['openid.'.substr($request_key,7) ] = $request_value; - } - $params['openid.mode'] = 'check_authentication'; - - $checkRequest = new Http($this->server); - - $checkRequest->method = 'POST'; // Spezifikation verlangt POST. - $checkRequest->header['Accept'] = 'text/plain'; - $checkRequest->requestParameter = $params; - - if ( ! $checkRequest->request() ) - { - // Der HTTP-Request ging in die Hose. - $this->error = $checkRequest->error; - return false; - } - //Html::debug($checkRequest); - - // Analyse der HTTP-Antwort, Parsen des BODYs. - // Die Anmeldung ist best�tigt, wenn im BODY die Zeile "is_valid:true" vorhanden ist. - // Siehe Spezifikation Kapitel 4.4.2 - $result = array(); - foreach( explode("\n",$checkRequest->body) as $line ) - { - $pair = explode(':',trim($line)); - if (count($pair)==2) - $result[strtolower($pair[0])] = strtolower($pair[1]); - } - - if ( !array_key_exists('is_valid',$result) ) - { - // Zeile nicht gefunden. - $this->error = 'Undefined Open-Id response: "is_valid" expected, but not found'; - return false; - } - elseif ( $result['is_valid'] == 'true' ) - { - // Anmeldung wurde mit "is_valid:true" best�tigt. - return true; - } - else - { - // Bestaetigung wurde durch den OpenId-Provider abgelehnt. - $this->error = 'Server refused login.'; - return false; - } - } - - - /** - * Liefert die Query-Parameter aus der aktuellen URL.<br> - * <br> - * PHP hat leider die sehr bescheuerte Angewohnheit, Punkte und Leerzeichen in Request-Variablen - * durch Unterstriche zu ersetzen. Diese Funktion liefert die GET-Parameter ohne diese Ersetzung. - * - * @return Parameter der aktuellen URL - */ - function getQueryParamList() - { - // Quelle: php.net - $str = $_SERVER['QUERY_STRING']; - $op = array(); - $pairs = explode("&", $str); - foreach ($pairs as $pair) - { - list($k, $v) = array_map("urldecode", explode("=", $pair)); - $op[$k] = $v; - } - - return $op; - } - - -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Preferences.class.php b/serviceClasses/Preferences.class.php @@ -1,59 +0,0 @@ -<?php - -/** - * Bereitstellen von Methoden fuer das Lesen von Einstellungen - * - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Preferences -{ - /** - * Liest die Konfigurationsdateien im angegebenen Ordner. - * - * @param $dir Verzeichnis, welche gelesen wird. Optional. Falls nicht gesetzt, wird - * das Standard-Konfigurationsverzeichnis verwendet. - * @return Array - */ - function load( $dir='' ) - { - if ( !defined('QUOTE') ) - define('QUOTE','"'); - - $values = array(); - - // Bei erstem (nicht-rekursiven) Aufruf der Methoden das Konfigurationsverzeichnis voreinstellen - if ( empty($dir) ) - { - if ( isset($_GET['config']) ) - $dir = basename( $_GET['config'] ).'/'; - else - $dir = OR_PREFERENCES_DIR; - } - - if ( !is_dir($dir) ) - { - Http::sendStatus(501,'Internal Server Error','not a directory: '.$dir); - exit; - } - - $dateien = FileUtils::readDir($dir); - - foreach( $dateien as $datei ) - { - $filename = $dir.$datei; - - if ( is_file($filename) && eregi('\.(ini.*|conf)$',$datei) ) - { - $nameBestandteile = explode('.',$datei); - $values[$nameBestandteile[0]] = parse_ini_file( $filename,true ); - } - } - - ksort($values); - - return $values; - } -} -?>- \ No newline at end of file diff --git a/serviceClasses/ProjectTree.class.php b/serviceClasses/ProjectTree.class.php @@ -1,476 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Darstellen der Projektstruktur - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class ProjectTree extends AbstractTree -{ - var $projectId; - var $userIsProjectAdmin = false; - - function root() - { - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_PROJECT'); - $treeElement->description = lang('GLOBAL_PROJECT'); - $treeElement->type = 'project'; - $treeElement->icon = 'project'; - - $this->addTreeElement( $treeElement ); - } - - - - function pageelements( $id ) - { - $page = new Page( $id ); - $page->load(); - - $template = new Template( $page->templateid ); - - foreach( $template->getElementIds() as $elementid ) - { - $element = new Element( $elementid ); - $element->load(); - - if ( $element->isWritable() ) - { - $treeElement = new TreeElement(); - $treeElement->text = $element->name; - $treeElement->url = Html::url('pageelement','edit', - $id, - array('elementid'=>$elementid, - REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'el_'.$element->type; - - $treeElement->description = lang('EL_'.$element->type); - if ( $element->desc != '' ) - $treeElement->description .= ' - '.Text::maxLaenge( 25,$element->desc ); - else - $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - $treeElement->target = 'content'; - - if ( in_array($element->type,array('link','list','include') ) ) - { - $treeElement->type = 'value'; - $value = new Value(); - $value->pageid = $page->pageid; - $value->element = $element; - $value->load(); - $treeElement->internalId = $value->valueid; - } - - $this->addTreeElement( $treeElement ); - } - } - } - - - function value( $id ) - { - //echo "id: $id"; - if ( $id != 0 ) - { - $value = new Value(); - $value->loadWithId( $id ); - - $objectid = intval($value->linkToObjectId); - if ( $objectid != 0 ) - { - $object = new Object( $objectid ); - $object->load(); - - $treeElement = new TreeElement(); - $treeElement->text = $object->name; - if ( in_array($object->getType(),array('page','folder'))) - { - $treeElement->type = $object->getType(); - $treeElement->internalId = $object->objectid; - } - $treeElement->url = Html::url($object->getType(),'',$objectid); - $treeElement->icon = $object->getType(); - - $treeElement->description = lang('GLOBAL_'.$object->getType()); - if ( $object->desc != '' ) - $treeElement->description .= ' - '.Text::maxLaenge( 25,$object->desc ); - else - $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - $treeElement->target = 'content'; - - $this->addTreeElement( $treeElement ); - } - } - } - - - function link( $id ) - { - $link = new Link( $id ); - $link->load(); - - if ( $link->isLinkToObject ) - { - $o = new Object( $link->linkedObjectId ); - $o->load(); - - $treeElement = new TreeElement(); - $treeElement->internalId = $o->objectid; - $treeElement->target = 'content'; - $treeElement->text = $o->name; - $treeElement->description= lang( 'GLOBAL_'.$o->getType() ).' '.$id; - - if ( $o->desc != '' ) - $treeElement->description .= ': '.$o->desc; - else - $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - - $treeElement->url = Html::url($o->getType(),'',$o->objectid,array(REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = $o->getType(); - - // Besonderheiten fuer bestimmte Objekttypen - - if ( $o->isPage ) - { - // Nur wenn die Seite beschreibbar ist, werden die - // Elemente im Baum angezeigt - if ( $o->hasRight( ACL_WRITE ) ) - $treeElement->type='pageelements'; - } - $this->addTreeElement( $treeElement ); - } - } - - - /** - * Laedt Elemente zu einem Ordner - * @return Array - */ - function folder( $id ) - { - global - $SESS, - $projectid; - - $f = new Folder( $id ); - $t = time(); - - foreach( $f->getObjects() as $o ) - { - // Wenn keine Leseberechtigung - if ( !$o->hasRight( ACL_READ ) ) - continue; - - $treeElement = new TreeElement(); - $treeElement->internalId = $o->objectid; - $treeElement->target = 'content'; - $treeElement->text = $o->name; - $treeElement->description= lang( 'GLOBAL_'.$o->getType() ).' '.$o->objectid; - - if ( $o->desc != '' ) - $treeElement->description .= ': '.$o->desc; - else - $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - - $treeElement->url = Html::url( $o->getType(),'',$o->objectid,array('readit'=>'__OID__'.$o->objectid.'__',REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = $o->getType(); - - // Besonderheiten fuer bestimmte Objekttypen - - if ( $o->isLink ) - { - $treeElement->type='link'; - } - - if ( $o->isPage ) - { - // Nur wenn die Seite beschreibbar ist, werden die - // Elemente im Baum angezeigt - if ( $o->hasRight( ACL_WRITE ) ) - $treeElement->type='pageelements'; - } - - if ( $o->isFile ) - { - $file = new File( $o->objectid ); - $file->load(); - - if ( substr($file->mimeType(),0,6) == 'image/' ) - $treeElement->icon = 'image'; - else $treeElement->icon = 'file'; - } - - if ( $o->isFolder ) - { - $treeElement->type = 'folder'; - } - - - $this->addTreeElement( $treeElement ); - } - } - - - function project() - { - $language = Session::getProjectLanguage(); - $model = Session::getProjectModel(); - $user = Session::getUser(); - - $project = Session::getProject(); - $this->projectid = $project->projectid; - - // Hoechster Ordner der Projektstruktur - $folder = new Folder( $project->getRootObjectId() ); - $folder->load(); - - - // Ermitteln, ob der Benutzer Projektadministrator ist - // Projektadministratoren haben das Recht, im Root-Ordner die Eigenschaften zu aendern. - if ( $folder->hasRight( ACL_PROP ) ) - $this->userIsProjectAdmin = true; - - if ( $folder->hasRight( ACL_READ ) ) - { - $treeElement = new TreeElement(); -// $treeElement->text = $folder->name; - $treeElement->text = lang('FOLDER_ROOT'); - $treeElement->description = lang('FOLDER_ROOT_DESC'); - $treeElement->icon = 'folder'; - $treeElement->url = Html::url( 'folder','',$folder->objectid,array(REQ_PARAM_TARGET=>'content') ); - $treeElement->target = 'content'; - $treeElement->type = 'folder'; - $treeElement->internalId = $folder->objectid; - $this->addTreeElement( $treeElement ); - } - - - if ( $this->userIsProjectAdmin ) - { - // Templates - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_TEMPLATES'); - $treeElement->url = Html::url('template','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); - $treeElement->description= lang('GLOBAL_TEMPLATES_DESC'); - $treeElement->icon = 'template_list'; - $treeElement->target = 'content'; - $treeElement->type = 'templates'; - $this->addTreeElement( $treeElement ); - } - - - // Sprachen - $treeElement = new TreeElement(); - $treeElement->description= ''; - $treeElement->text = lang('GLOBAL_LANGUAGES'); - $treeElement->url = Html::url('language','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'language_list'; - $treeElement->description= lang('GLOBAL_LANGUAGES_DESC'); - $treeElement->target = 'content'; - - // Nur fuer Projekt-Administratoren aufklappbar - if ( $this->userIsProjectAdmin ) - $treeElement->type = 'languages'; - - $this->addTreeElement( $treeElement ); - - - // Projektmodelle - $treeElement = new TreeElement(); - $treeElement->description= ''; - - // Nur fuer Projekt-Administratoren aufklappbar - if ( $this->userIsProjectAdmin ) - $treeElement->type = 'models'; - - $treeElement->description= lang('GLOBAL_MODELS_DESC'); - $treeElement->text = lang('GLOBAL_MODELS'); - $treeElement->url = Html::url('model','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'model_list'; - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - - - // Sonstiges -// $treeElement = new TreeElement(); -// $treeElement->text = lang('GLOBAL_OTHER'); -// $treeElement->description= lang('GLOBAL_OTHER_DESC'); -// $treeElement->icon = 'other'; -// $treeElement->type = 'other'; -// $this->addTreeElement( $treeElement ); - - // Suche - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_SEARCH'); - $treeElement->url = Html::url('search','',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'search'; - $treeElement->description = lang('GLOBAL_SEARCH_DESC'); - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - - } - - - function templates() - { - foreach( Template::getAll() as $id=>$name ) - { - $treeElement = new TreeElement(); - - $t = new Template( $id ); - $t->load(); - $treeElement->text = $t->name; - $treeElement->url = Html::url('template','src',$id,array(REQ_PARAM_TARGETSUBACTION=>'src',REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'template'; - $treeElement->target = 'content'; - $treeElement->internalId = $id; - $treeElement->type = 'template'; - $treeElement->description = $t->name.' ('.lang('GLOBAL_TEMPLATE').' '.$id.'): '.htmlentities(Text::maxLaenge( 40,$t->src )); - $this->addTreeElement( $treeElement ); - } - } - - - function template( $id ) - { - - $t = new Template( $id ); - $t->load(); - - // Anzeigen der Template-Elemente - // - foreach( $t->getElementIds() as $elementid ) - { - $e = new Element( $elementid ); - $e->load(); - - // "Code"-Element nur fuer Administratoren - if ( $e->type == 'code' && !$this->userIsAdmin ) - continue; - - $treeElement = new TreeElement(); - $treeElement->text = $e->name; - $treeElement->url = Html::url('element','',$elementid,array(REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = 'el_'.$e->type; - - if ( $e->desc == '' ) - $desc = lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); - else - $desc = $e->desc; - $treeElement->description = $e->name.' ('.lang('EL_'.$e->type).'): '.Text::maxLaenge( 40,$desc ); - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - } - } - - - /** - * Sprachen - */ - function languages() - { - // Sprachvarianten - // - $l = Session::getProjectLanguage(); - $languages = $l->getAll(); - - foreach( $languages as $languageid=>$name ) - { - $treeElement = new TreeElement(); - $treeElement->text = $name; - $treeElement->url = Html::url('language','edit',$languageid, - array(REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content') ); - $treeElement->icon = 'language'; - $treeElement->description = ''; - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - } - } - - - // Projektvarianten - // - function models() - { - $m = Session::getProjectModel(); - $models = $m->getAll(); - - foreach( $models as $id=>$name ) - { - $treeElement = new TreeElement(); - $treeElement->text = $name; - $treeElement->url = Html::url('model','edit',$id, - array(REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'model'; - $treeElement->description = ''; - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - } - } - - - function other() - { -// Deaktiviert, da -// - Dateien auf den Server laden unverst�ndlich/undurchsichtig erscheint -// - M�glichkeit zum Entpacken von ZIP/TAR online besteht. -// if ( $this->userIsProjectAdmin ) -// { -// $treeElement = new TreeElement(); -// $treeElement->text = lang('GLOBAL_FILE_TRANSFER'); -// $treeElement->description = lang('GLOBAL_FILE_TRANSFER_DESC'); -// $treeElement->url = Html::url('main','transfer'); -// $treeElement->icon = 'transfer'; -// $treeElement->target = 'content'; -// $this->addTreeElement( $treeElement ); -// } - - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_SEARCH'); - $treeElement->url = Html::url('search'); - $treeElement->icon = 'search'; - $treeElement->description = lang('GLOBAL_SEARCH_DESC'); - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - - - $treeElement = new TreeElement(); - $treeElement->text = lang('USER_YOURPROFILE'); - $treeElement->url = Html::url('profile','edit',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'user'; - $treeElement->description = lang('USER_PROFILE_DESC'); - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - - - $treeElement = new TreeElement(); - $treeElement->text = lang('GLOBAL_PROJECTS'); - $treeElement->url = Html::url('index','projectmenu',0,array(REQ_PARAM_TARGET=>'content')); - $treeElement->icon = 'project'; - $treeElement->description = lang('GLOBAL_PROJECTS'); - $treeElement->target = 'content'; - $this->addTreeElement( $treeElement ); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Publish.class.php b/serviceClasses/Publish.class.php @@ -1,364 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Diese Klasse kapselt das Veroeffentlichen von Dateien.<br> - * <br> - * Hier werden<br> - * - Dateien in das Zielverzeichnis kopiert<br> - * - Dateien per FTP veroeffentlicht<br> - * - Zielverzeichnisse aufgeraeumt<br> - * - Systembefehle ausgefuehrt. - * - * @author Jan Dankert - * @package openrat.services - */ -class Publish -{ - /** - * Enthaelt bei Bedarf das FTP-Objekt. N�mlich dann, wenn - * zu einem FTP-Server veroeffentlicht werden soll. - * @var Object - */ - var $ftp; - - /** - * Flag, ob in das lokale Dateisystem veroeffentlicht werden soll. - * @var boolean - */ - var $with_local = false; - - /** - * Flag, ob zu einem FTP-Server ver�ffentlicht werden soll. - * @var boolean - */ - var $with_ftp = false; - - var $local_destdir = ''; - - /** - * Enthaelt die gleichnamige Einstellung aus dem Projekt. - * @var boolean - */ - var $content_negotiation = false; - - /** - * Enthaelt die gleichnamige Einstellung aus dem Projekt. - * @var boolean - */ - var $cut_index = false; - - /** - * Enthaelt die gleichnamige Einstellung aus dem Projekt. - * @var String - */ - var $cmd_after_publish = ''; - - /** - * Enthaelt am Ende der Ver�ffentlichung ein Array mit den ver�ffentlichten Objekten. - * @var Array - */ - var $publishedObjects = array(); - - /** - * Enthaelt im Fehlerfall (wenn 'ok' auf 'false' steht) eine - * Fehlermeldung. - * - * @var String - */ - var $log = array(); - - /** - * Stellt nach der Ver�ffentlichung fest, ob der Vorgang erfolgreich ist. - * Falls nicht, enth�lt die Variable 'log' eine Fehlermeldung. - * @var boolean - */ - var $ok = true; - - /** - * Konstruktor.<br> - * <br> - * Oeffnet ggf. Verbindungen. - * - * @return Publish - */ - function Publish() - { - global $conf; - $conf_project = $conf['publish']['project']; - - if ( $conf['security']['nopublish'] ) - { - $this->ok = false; - $this->log[] = 'publishing is disabled.'; - return; - } - - $project = Session::getProject(); - - // Feststellen, ob FTP benutzt wird. - // Dazu muss FTP aktiviert sein (enable=true) und eine URL vorhanden sein. - if ( @$conf['publish']['ftp']['enable'] && - ( !empty($project->ftp_url) || - isset($conf['publish']['ftp']['host']) ) ) - { - $this->with_ftp = true; - $this->ftp = new Ftp( $project->ftp_url ); // Aufbauen einer FTP-Verbindung - - if ( ! $this->ftp->ok ) // FTP-Verbindung ok? - { - $this->ok = false; - $this->log = $this->ftp->log; - return; // Ende. Ohne FTP brauchen wir nicht weitermachen. - } - - $this->ftp->passive = ( $project->ftp_passive == '1' ); - } - - $localDir = ereg_replace( '\/$','',$project->target_dir); - if ( empty( $localDir)) - $localDir = $project->name; - - if ( $conf_project['override_publish_dir'] && $localDir != basename($localDir) ) - $this->local_destdir = $localDir; - else - $this->local_destdir = $conf_project['publish_dir'].$localDir; - - - // Sofort pruefen, ob das Zielverzeichnis ueberhaupt beschreibbar ist. - if ( $this->local_destdir != '' ) - { - if ( !is_writeable( $this->local_destdir ) ) - { - $this->ok = false; - $this->log[] = 'directory not writable: '.$this->local_destdir; - $this->log[] = 'please correct the file permissions.'; - return; - } - - $this->with_local = true; - } - - $this->content_negotiation = ( $project->content_negotiation == '1' ); - $this->cut_index = ( $project->cut_index == '1' ); - - if ( $conf_project['override_system_command'] && !empty($project->cmd_after_publish) ) - $this->cmd_after_publish = $project->cmd_after_publish; - else - $this->cmd_after_publish = @$conf_project['system_command']; - - // Im Systemkommando Variablen ersetzen - $this->cmd_after_publish = str_replace('{name}' ,$project->name ,$this->cmd_after_publish); - $this->cmd_after_publish = str_replace('{dir}' ,$this->local_destdir ,$this->cmd_after_publish); - $this->cmd_after_publish = str_replace('{dirbase}',basename($this->local_destdir),$this->cmd_after_publish); - } - - - - /** - * Kopieren einer Datei aus dem tempor�ren Verzeichnis in das Zielverzeichnis.<br> - * Falls notwenig, wird ein Hochladen per FTP ausgef�hrt. - * - * @param String $tmp_filename - * @param String $dest_filename - */ - function copy( $tmp_filename,$dest_filename,$lastChangeDate=null ) - { - if ( !$this->ok) - return; - - global $conf; - $source = $tmp_filename; - - if ( $this->with_local ) - { - $dest = $this->local_destdir.'/'.$dest_filename; - - if (!@copy( $source,$dest )); - { - if ( ! $this->mkdirs( dirname($dest) ) ) - return; // Fehler bei Verzeichniserstellung, also abbrechen. - - if (!@copy( $source,$dest )) - { - $this->ok = false; - $this->log[] = 'failed copying local file:'; - $this->log[] = 'source : '.$source; - $this->log[] = 'destination: '.$dest; - return; // Fehler beim Kopieren, also abbrechen. - } - if ( ! is_null($lastChangeDate) ) - touch( $dest,$lastChangeDate ); - } - - if (!empty($conf['security']['chmod'])) - { - // CHMOD auf der Datei ausfuehren. - if ( ! @chmod($dest,octdec($conf['security']['chmod'])) ) - { - $this->ok = false; - $this->log[] = 'Unable to CHMOD file '.$dest; - return; - } - } - } - - if ( $this->with_ftp ) // Falls FTP aktiviert - { - $dest = $dest_filename; - $this->ftp->put( $source,$dest ); - - if ( ! $this->ftp->ok ) - { - $this->ok = false; - $this->log[] = $this->ftp->log; - } - } - } - - - - /** - * Rekursives Anlagen von Verzeichnisse - * Nett gemacht. - * Quelle: http://de3.php.net/manual/de/function.mkdir.php - * Thx to acroyear at io dot com - * - * @param String Verzeichnis - * @return boolean - */ - function mkdirs( $strPath ) - { - global $conf; - - if ( is_dir($strPath) ) - return true; - - $pStrPath = dirname($strPath); - if ( !$this->mkdirs($pStrPath) ) - return false; - - if ( ! @mkdir($strPath,0777) ) - { - $this->ok = false; - $this->log[] = 'Cannot create directory: '.$strPath; - return false; - } - - // CHMOD auf dem Verzeichnis ausgef�hren. - if (!empty($conf['security']['chmod_dir'])) - { - if ( ! @chmod($strPath,octdec($conf['security']['chmod_dir'])) ) - { - $this->ok = false; - $this->log[] = 'Unable to CHMOD directory: '.$strPath; - return false; - } - } - - - return $this->ok; - } - - - - /** - * Beenden des Ver�ffentlichungs-Vorganges.<br> - * Eine vorhandene FTP-Verbindung wird geschlossen.<br> - * Falls entsprechend konfiguriert, wird ein Systemkommando ausgef�hrt. - */ - function close() - { - if ( $this->with_ftp ) - { - $this->ftp->close(); - } - - // Ausf�hren des Systemkommandos. - if ( !empty($this->cmd_after_publish) && $this->ok ) - { - $ausgabe = array(); - $rc = false; - exec( $this->cmd_after_publish,$ausgabe,$rc ); - - if ( $rc != 0 ) // Wenn Returncode ungleich 0, dann Ausgabe ins Log schreiben und Fehler melden. - { - $this->log = $ausgabe; - $this->log[] = 'OpenRat: System command failed - returncode is '.$rc; - $this->ok = false; - } - } - } - - - - /** - * Aufraeumen des Zielverzeichnisses.<br><br> - * Es wird der komplette Zielordner samt Unterverzeichnissen durchsucht. Jede - * Datei, die laenger existiert als der aktuelle Request alt ist, wird geloescht.<br> - * Natuerlich darf diese Funktion nur nach einem Gesamt-Veroeffentlichen ausgefuehrt werden. - */ - function clean() - { - if ( $this->ok ) - return; - - if ( !empty($this->local_destdir) ) - $this->cleanFolder($this->local_destdir); - } - - - - /** - * Aufr�umen eines Verzeichnisses.<br><br> - * Dateien, die l�nger existieren als der aktuelle Request alt ist, werden gel�scht.<br> - * - * @param String Verzeichnis - */ - function cleanFolder( $folderName ) - { - $dh = opendir( $folderName ); - - while( $file = readdir($dh) ) - { - if ( $file != '.' && $file != '..') - { - $fullpath = $folderName.'/'.$file; - - // Wenn eine Datei beschreibbar und entsprechend alt - // ist, dann entfernen - if ( is_file($fullpath) && - is_writable($fullpath) && - filemtime($fullpath) < START_TIME ) - unlink($fullpath); - - // Bei Ordnern rekursiv absteigen - if ( is_dir( $fullpath) ) - { - $this->cleanFolder($fullpath); - @rmdir($fullpath); - } - } - } - } - -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Session.class.php b/serviceClasses/Session.class.php @@ -1,225 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// OpenRat Content Management System -// Copyright (C) 2002-2004 Jan Dankert, cms@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - - -// PHP-Versionsunabhaengiges Array fuer die Session-Variablen ermitteln -if (isset($_SESSION)) - $SESS = &$_SESSION; -else $SESS = &$HTTP_SESSION_VARS; - -if ( isset($_FILES) ) - $FILES = &$_FILES; -else $FILES = &$HTTP_POST_FILES; - - -/** - * Session-Funktionen zum Lesen/Schreiben in/von HTTP-Session - * In der Session werden folgende Daten abgelegt - * - Ausgewaehltes Projekt - * - Ausgewaehlte Projectsprache - * - Ausgewaehlte Projektvariante - * - Angemeldeter Benutzer - * - Auswahlbaum - * - Geladene Sprachelemente - * - Ausgewaehlter Ordner - * - Ausgewaehltes Objekt - * - Datenbankobjekt - * Die Methoden dieser Klassen koennen statisch aufgerufen werden - * - * @author $Author$ - * @version $Revision$ - * @package openrat.service - */ - -class Session -{ - function get( $var ) - { - global $SESS; - if ( isset($SESS['ors_'.$var]) ) - return $SESS['ors_'.$var]; - else - return ''; - } - - function set( $var,$value ) - { - global $SESS; - $SESS[ 'ors_'.$var ] = $value; - } - - - - function getConfig() - { - return Session::get('config'); - } - - function setConfig( $var ) - { - Session::set('config',$var); - } - - - - function getProjectModel() - { - return Session::get('project_model'); - } - - function setProjectModel( $var ) - { - Session::set('project_model',$var); - } - - - - function getProjectLanguage() - { - return Session::get('project_language'); - } - - function setProjectLanguage( $var ) - { - Session::set('project_language',$var); - } - - - - function getObject() - { - return Session::get('object'); - } - - function setObject( $var ) - { - Session::set('object',$var); - } - - - - function getFolder() - { - return Session::get('folder'); - } - - function setFolder( $var ) - { - Session::set('folder',$var); - } - - - - function getTree() - { - return Session::get('tree'); - } - - function setTree( $var ) - { - Session::set('tree',$var); - } - - - - function getElement() - { - return Session::get('element'); - } - - function setElement( $var ) - { - Session::set('element',$var); - } - - - - function getProject() - { - return Session::get('project'); - } - - function setProject( $var ) - { - Session::set('project',$var); - } - - - - function getUser() - { - return Session::get('userObject'); - } - - function setUser( $var ) - { - Session::set('userObject',$var); - } - - - function getDatabase() - { - return Session::get('database'); - } - - function setDatabase( $var ) - { - Session::set('database',$var); - } - - - function getSubaction() - { - return Session::get('subaction'); - } - - function setSubaction( $var ) - { - Session::set('subaction',$var); - } - - - function getClipboard() - { - return Session::get('clipboard'); - } - - function setClipboard( $var ) - { - Session::set('clipboard',$var); - } - - - /** - * Schliesst die aktuelle Session - * - * Diese Funktion sollte so schnell wie moeglich aufgerufen werden, da vorher - * keine andere Seite (im Frameset!) geladen werden kann - * Nach Aufruf dieser Methode sind keine Session-Zugriffe ueber diese Klasse mehr - * moeglich. - */ - function close() - { - session_write_close(); - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Sql.class.php b/serviceClasses/Sql.class.php @@ -1,334 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// OpenRat Content Management System -// Copyright (C) 2002-2006 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- - - - -/** - * SQL-Anweisung.<br> - * <br> - * Darstellen eines SQL-Statements incl. Methoden zum Fuellen von - * Platzhaltern im SQL-Befehl.<br> - * <br> - * Beispiel<br> - * <pre> - * // Neues Objekt erzeugen mit SQL-Anweisung - * $sql = new Sql('SELECT * FROM xy WHERE id={uid} AND name={name}'); - * - * // Parameter f�llen - * $sql->setInt ('uid' ,1 ); - * $sql->setString('name','peter'); - * - * // Fertige SQL-Anweisung verwenden - * $xy->execute( $sql->query ); - * </pre> - * <br> - * Ziele dieser Klasse sind:<br> - * - Schreiben einfacher SQL-Anweisungen ohne Stringverarbeitung<br> - * - Verhindern von SQL-Injection.<br> - * <br> - * - * @author Jan Dankert, $Author$ - * @version $Revision$ - * @package openrat.services - */ - -class Sql -{ - /** - * Urspr�ngliche SQL-Anweisung. - */ - var $src = ''; - - /** - * Auszuf�hrende Abfrage. - */ - var $query = ''; - - var $raw = ''; - - - /** - * Zwischenspeicher f�r Parameterwerte. - */ - var $data = Array(); - - /** - * Ein 2-dimensionales Array mit den Positionen der Parameter.<br> - * <br> - * Beispiel:<br> - * <pre> - * - * Array - * ( - * [lid] => Array - * ( - * [0] => 65 - * [1] => 81 - * ) - * [oid] => Array - * ( - * [0] => 123 - * ) - * ) - * </pre> - * In der ersten Dimension sind die Parameter vorhanden, jeder Parameter hat eine Liste von Positionen, an denen er steht.<br> - * Ein Parameter kann n�mlich mehrfach vorkommen! - */ - var $param = array(); - - - var $dbid = ''; - - - /** - * Erzeugt ein SQL-Objekt und analysiert die SQL-Anfrage. - */ - function Sql( $query = '', $dbid='' ) - { - $this->dbid = $dbid; - $this->parseSourceQuery( $query ); - - $this->data = array(); - } - - - - /** - * Die SQL-Anfrage wird auf Parameter untersucht. - */ - function parseSourceQuery( $query ) - { - $this->src = $query; // Wir merken uns die Ur-Abfrage, evtl. f�r Fehlermeldungen interessant. - - while( true ) // Schleife wird solange durchlaufen, solange Parameter gefunden werden. - { - $posKlLinks = strpos($query,'{'); - $posKlRechts = strpos($query,'}'); - - if ( $posKlLinks === false ) - break; // Schleife abbrechen, wenn kein Parameter mehr gefunden wird. - - $nameParam = substr($query,$posKlLinks+1,$posKlRechts-$posKlLinks-1); // Name Parameter - - if ( !isset($this->param[$nameParam ])) - $this->param [$nameParam ] = array(); - - $this->param[$nameParam ][] = $posKlLinks; - - $query = substr($query,0,$posKlLinks).substr($query,$posKlRechts+1); - } - - $this->query = $query; -// $merkeParam = $this->param; - - // Tabellennamen in die Platzhalter setzen. - // Dies ist noch OpenRat-spezifisch und sollte bei einer sauberen Abstraktion woanders gemacht werden. Aber wo? - foreach( table_names($this->dbid) as $t=>$name ) - { - $this->setParam($t,$name,false ); - - unset( $this->param[$t] ); - - } - - $this->raw = $this->query; - //$this->param = $merkeParam; - - } - - - - /** - * Setzt eine neue SQL-Abfrage.<br> - * Bereits vorhandene Parameter werden automatisch wieder gesetzt. - */ - function setQuery( $query = '' ) - { - $this->parseSourceQuery( $query ); - - // Bereits vorhande Parameter setzen. - foreach( $this->data as $name=>$data ) - { - if ( $data['type']=='string' ) $this->setString ($name,$data['value'] ); - if ( $data['type']=='int' ) $this->setInt ($name,$data['value'] ); - if ( $data['type']=='null' ) $this->setNull ($name ); - } - } - - - - /** - * Setzt einen Parameter.<br> - * Diese Methode sollte nur intern aufgerufen werden!<br> - * - * @param name Name des Parameters - * @param value Inhalt - * @param dieIfUnknown wenn <code>true</code> und Parameter unbekannt, dann Abbruch. - * @access private - */ - function setParam( $name,$value,$dieIfUnknown=true) - { - - // Nett gemeint, f�hrt aber aktuell zu Fehlern, weil an vielen Stellen zu viele Parameter gef�llt werden. - // Daher erstmal deaktiviert. - // if ( !isset($this->param[$name]) ) - // { - // if ( $dieIfUnknown ) - // die("parameter '$name' unknown. SQL=".$this->src); - // else - // return; - // } - - if ( !isset($this->param[$name]) ) - return; // Parameter nicht vorhanden. - - if ( is_array($this->param[$name]) ) - { - foreach( $this->param[$name] as $idx=>$xyz ) - { - $pos = $this->param[$name][$idx]; - - $this->query = substr( $this->query,0,$pos ).$value.substr( $this->query,$pos ); - - foreach( $this->param as $pn=>$par) - { - foreach( $par as $i=>$p ) - { - if ( $p > $pos ) - $this->param[$pn][$i]=$p+strlen($value); - } - } - - } - } - } - - - - /** - * Setzt einen Parameter.<br> - * Der Typ des Parameters wird automatisch ermittelt.<br> - * - * @param name Name des Parameters - * @param value Inhalt - */ - function setVar( $name,$value ) - { - if ( is_string($value) ) - $this->setString( $name,$value ); - - if ( is_null($value) ) - $this->setNull( $name ); - - if ( is_int($value) ) - $this->setInt( $name,$value ); - } - - - - /** - * Setzt eine Ganzzahl als Parameter.<br> - * - * @param name Name des Parameters - * @param value Inhalt - */ - function setInt( $name,$value ) - { - $this->data[ $name ] = array( 'type'=>'int','value'=>(int)$value ); - } - - - - /** - * Setzt eine Zeichenkette als Parameter.<br> - * - * @param name Name des Parameters - * @param value Inhalt - */ - function setString( $name,$value ) - { - $this->data[ $name ] = array( 'type'=>'string','value'=>$value ); - } - - - - /** - * Setzt einen bool'schen Wert als Parameter.<br> - * Ist der Parameterwert wahr, dann wird eine 1 gesetzt. Sonst 0.<br> - * - * @param name Name des Parameters - * @param value Inhalt - */ - function setBoolean( $name,$value ) - { - if ( $value ) - $this->setInt( $name,1 ); - else $this->setInt( $name,0 ); - } - - - - /** - * Setzt einen Parameter auf den Wert <code>null</code>.<br> - * - * @param name Name des Parameters - */ - function setNull( $name ) - { - $this->data[ $name ] = array( 'type'=>'null' ); - } - - - - /** - * Ermittelt die fertige SQL-Anfrage.<br> - * Alias zu #getQuery() - */ - function &query() - { - return $this->getQuery(); - } - - - - /** - * Ermittelt die fertige SQL-Anfrage. - * @param Name einer Funktion, die eine Zeichenkette für die - * Datenbank schuetzt. Dies kann je nach verwendetem RDBMS - * unterschiedlich sein, daher diese Funktionsreferenz. - */ - function &getQuery( $escape_function ) - { - // Bereits gesetzte Parameter setzen. - foreach( $this->data as $name=>$data ) - { - if ( $data['type']=='string' ) $this->setParam($name,"'".$escape_function($data['value'])."'" ); - elseif ( $data['type']=='int' ) $this->setParam($name,(int)$data['value'] ); - elseif ( $data['type']=='null' ) $this->setParam($name,'NULL' ); - } - - return $this->query; - } -} - - -?>- \ No newline at end of file diff --git a/serviceClasses/TemplateEngine.class.php b/serviceClasses/TemplateEngine.class.php @@ -1,507 +0,0 @@ -<?php -# -# OpenRat Content Management System -# Copyright (C) 2002-2009 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Wandelt eine Vorlage in ein PHP-Skript um. - * - * Die Vorlage wird gesparst, Elemente werden geladen und in die Zieldatei kopiert. - * - * @author Jan Dankert - * @package openrat.services - */ -class TemplateEngine -{ - var $actualTagName = ''; - - /** - * Name Template. - * - * @var String - */ - var $tplName; - - /** - * Erzeugt einen Templateparser. - * - * @param String $tplName Name des Templates, das umgewandelt werden soll. - */ - function TemplateEngine( $tplName='' ) - { - $this->tplName = $tplName; - } - - - /** - * Wandelt eine Vorlage um - * @param filename Dateiname der Datei, die erstellt werden soll. - */ - function compile( $tplName = '') - { - if ( empty($tplName) ) - $tplName = $this->tplName; - - global $conf; - $srcOrmlFilename = 'themes/default/templates/'.$tplName.'.tpl.src.'.PHP_EXT; - $srcXmlFilename = 'themes/default/templates/'.$tplName.'.tpl.src.xml'; - - if ( is_file($srcOrmlFilename) ) - $srcFilename = $srcOrmlFilename; - elseif ( is_file($srcXmlFilename) ) - $srcFilename = $srcXmlFilename; - else - // Wenn Vorlage (noch) nicht existiert - die( get_class($this).': Template not found: "'.$tplName.'"' ); - - $filename = 'themes/default/pages/html/'.$tplName.'.tpl.'.PHP_EXT; - - // Wenn Vorlage gaendert wurde, dann Umwandlung erneut ausf�hren. - if ( $conf['theme']['compiler']['cache'] && is_file($filename) && filemtime($srcFilename) <= filemtime($filename)) - return; - - if ( is_file($filename) && !is_writable($filename) ) - die( get_class($this).': File is read-only: '.$filename); - - Logger::debug("Compile template: ".$srcFilename.' to '.$filename); - - // Vorlage und Zieldatei oeffnen - $document = $this->loadDocument( $srcFilename ); - - // Prüfen, ob Zielverzeichnis existiert, falls nicht: Anlegen. - if ( ! is_dir(dirname($filename)) ) - { - $rc = mkdir( dirname($filename) ); - if ( ! $rc ) - Http::serverError('Unable to create directory: '.dirname($filename)); - } - - $outFile = @fopen($filename,'w'); - - if ( !is_resource($outFile) ) - Http::serverError( get_class($this).': Unable to open file for writing: '.$filename); - - $openCmd = array(); - $depth = 0; - - foreach( $document as $line ) - { - // Initialisieren der m�glichen Element-Inhalte - $type = ''; - $attributes = array(); - $value = ''; - $tag = ''; - - - // Setzt: $tag, $attributes, $value, $type - extract( $line ); - - $this->actualTagName = $tag; - - if ($type == 'complete' || $type == 'open') - $attributes = $this->checkAttributes($tag,$attributes); - - if ( $type == 'open' ) - $this->copyFileContents( $tag,$outFile,$attributes,++$depth ); - elseif ( $type == 'complete' ) - { - $this->copyFileContents( $tag ,$outFile,$attributes,$depth+1 ); - $this->copyFileContents( $tag.'-end',$outFile,array() ,$depth+1 ); - } - elseif ( $type == 'close' ) - $this->copyFileContents( $tag.'-end',$outFile,array(),--$depth ); - } - - fclose($outFile); - - // CHMOD ausf�hren. - if ( !empty($conf['theme']['compiler']['chmod'])) - if ( !@chmod($filename,octdec($conf['theme']['compiler']['chmod'])) ) - die( "CHMOD failed on file ".$filename ); - } - - - - function getElementValue( $elFilename,$attributes ) - { - extract($attributes); - require($elFilename); - return $value; - } - - - - function attributeValueOpenPHP($value) - { - $erg = $this->attributeValue($value); - - // Für statische Texte muss kein PHP-Abschnitt geoeffnet werden. - if (substr($erg,0,1) == "'" && strpos($erg,'$')===FALSE ) - return substr($erg,1,-1); - else - return '<'.'?php echo '.$erg.' ?>'; - } - - - - function attributeValue( $value ) - { - $parts = explode( ':', $value, 2 ); - - if ( count($parts) < 2 ) - $parts = array('',$value); - - list( $type,$value ) = $parts; - - $invert = ''; - if ( substr($type,0,1)=='!' ) - { - $type = substr($type,1); - $invert = '! '; - } - - switch( $type ) - { - case 'var': - return $invert.'$'.$value; - case 'text': - case '': - // Sonderf�lle f�r die Attributwerte "true" und "false". - // Hinweis: Die Zeichenkette "false" entspricht in PHP true. - // Siehe http://de.php.net/manual/de/language.types.boolean.php - if ( $value == 'true' || $value == 'false' ) - return $value; - else - // macht aus "text1{var}text2" => "text1".$var."text2" - return "'".preg_replace('/{(\w+)\}/','\'.$\\1.\'',$value)."'"; - case 'method': - return $invert.'$this->'.$value.'()'; - case 'size': - return '@count($'.$value.')'; - case 'property': - return $invert.'$this->'.$value; - case 'message': -// return 'lang('."'".$value."'".')'; - // macht aus "text1{var}text2" => "text1".$var."text2" - return 'lang('."'".preg_replace('/{(\w+)\}/','\'.$\\1.\'',$value)."'".')'; - case 'messagevar': - return 'lang($'.$value.')'; - case 'mode': - return $invert.'$mode=="'.$value.'"'; - case 'arrayvar': - list($arr,$key) = explode(':',$value.':none'); - return $invert.'@$'.$arr.'['.$key.']'; - case 'config': - $config_parts = explode('/',$value); - return $invert.'@$conf['."'".implode("'".']'.'['."'",$config_parts)."'".']'; - - default: - Http::serverError( get_class($this).': Unknown type "'.$type.'" in attribute. Allowed: var|method|property|message|messagevar|config or none'); - } - } - - - - /** - * Ein Baustein wird in die neue Vorlagedatei kopiert. - */ - function copyFileContents( $infile,$outFileHandler,$attr,$depth ) - { - global $conf; - $hash = $depth; - - $inFileName = OR_THEMES_DIR.$conf['interface']['theme'].'/include/html/'.$infile.'.inc.'.PHP_EXT; - $elFileName = OR_THEMES_DIR.$conf['interface']['theme'].'/include/html/'.$infile.'.el.' .PHP_EXT; - if ( !is_file($inFileName) ) - if ( count($attr)==0 ) - return; - else - // Baustein nicht vorhanden, Abbbruch. - die( get_class($this).': Compile failed, file not found: '.$inFileName ); - - $values = array(); - foreach( $attr as $attrName=>$attrValue ) - { - $values[] = "'".$attrName."'=>".$this->attributeValue($attrValue); - } - - // Variablen $attr_* setzen - if ( count($attr) > 0 ) - { - fwrite( $outFileHandler,'<?php '); - foreach( $attr as $attrName=>$attrValue ) - fwrite( $outFileHandler,'$a'.$hash.'_'.$attrName."=".$this->attributeValue($attrValue).';'); - fwrite( $outFileHandler,' ?>'); - } - - $file = file( $inFileName ); - $ignore = false; - $linebreaks = true; - - foreach( $file as $line ) - { - // Ignoriere Zeilen, die fuer ein nicht vorhandenes Attribut gelten. - if ( strpos($line,'#IF-ATTR')!==FALSE ) - { - $found = false; - foreach( $attr as $attrName=>$attrValue ) - { - if ( strpos($line,'#IF-ATTR '.$attrName.'#')!==FALSE ) - $found = true; - if ( strpos($line,'#IF-ATTR-VALUE '.$attrName.':'.$attrValue.'#')!==FALSE ) - $found = true; - } - if ( ! $found ) - $ignore = true; - } - // Nach einem IF-Block ertmal alles wieder anzeigen. - if ( strpos($line,'#END-IF')!==FALSE ) - { - $ignore = false; - } - - if ( strpos($line,'#ELSE')!==FALSE ) - { - $ignore = !$ignore; - } - - // Zeilenumbr�che nicht setzen. - if ( strpos($line,'#SET-LINEBREAK-OFF')!==FALSE ) - $linebreaks = false; - - // Zeilenumbr�che setzen. - if ( strpos($line,'#SET-LINEBREAK-ON')!==FALSE ) - $linebreaks = true; - - // Ignoriere Zeilen, die zu ignorieren sind (logisch). - // Dies sind Blöcke, die nur fuer ein Attribut gueltig sind, welches - // aber nicht gesetzt ist. - if ( $ignore ) - continue; - - // Ignoriere Leerzeilen - if ( strlen(trim($line)) == 0) - continue; - // Ignoriere Kommentarzeilen - if ( in_array(substr(ltrim($line),0,2),array('//','/*','<!') ) || substr(ltrim($line),0,1) == '#') - continue; - // Ignoriere Kommentarzeilen - if ( in_array(substr(rtrim($line),-3),array('-->',' */') ) ) - continue; - - if ( !$linebreaks ) - $line = rtrim($line); - - // Die Variablen "$attr_*" muessen pro Ebene eindeutig sein, daher wird an den - // Variablennamen die Tiefe angehangen. - $line = str_replace('$attr_','$a'.$hash.'_',$line); - - foreach( $attr as $attrName=>$attrValue ) - $line = str_replace('%'.$attrName.'%',$this->attributeValueOpenPHP($attrValue),$line); - - - fwrite( $outFileHandler,$line ); - } - - // Variablen $attr_* entfernen. - $unset_attr = array(); - foreach( $attr as $attrName=>$attrValue ) - $unset_attr[] = '$a'.$hash.'_'.$attrName; - - if ( count($unset_attr) > 0 ) - fwrite( $outFileHandler,'<?php unset('.implode(',',$unset_attr).') ?>'); - - if ( is_file($elFileName) ) - { - fwrite( $outFileHandler, $this->getElementValue( $elFileName,$attr) ); - } - } - - - - /** - * Diese Funktion pr�ft, ob die Attribute zu einem Element g�ltig sind.<br> - * Falls ein ung�ltiges Attribut oder ein ung�ltiger Wert entdeckt wird, - * so wird das Skript abgebrochen. - * @return �berpr�fte und mit Default-Werten angereicherte Attribute - */ - function checkAttributes( $cmd,$attr ) - { - global $conf; - $elements = parse_ini_file( OR_THEMES_DIR.$conf['interface']['theme'].'/include/elements.ini.'.PHP_EXT); - - if ( !isset($elements[$cmd]) ) - Http::serverError( get_class($this).': Parser error, unknown element "'.$cmd.'". Allowed: '.implode(',',array_keys($elements)) ); - - $checkedAttr = array(); - - // Schleife �ber alle Attribute. - foreach( explode(',',$elements[$cmd]) as $al ) - { - $al=trim($al); - if ( $al=='') - continue; // Leeres Attribut... nicht zu gebrauchen. - - - $pair = explode(':',$al,2); - if ( count($pair) == 1 ) $pair[] = null; - list($a,$default) = $pair; - - if ( is_string($default)) - $default = str_replace('COMMA',',',$default); // Komma in Default-Werten ersetzen. - - if ( isset($attr[$a])) - $checkedAttr[$a]=$attr[$a]; // Attribut ist bereits vorhanden, alles ok. - elseif ( $default=='*') // Pflichtfeld! - die( get_class($this).': Element "'.$cmd.'" needs the required attribute "'.$a.'"' ); - elseif ( !is_null($default) ) - $checkedAttr[$a]=$default; - else - ; - - unset( $attr[$a] ); // Damit am Ende das Urprungsarray leer wird. - } - - if ( count($attr) > 0 ) - { - foreach($attr as $name=>$value) - Http::serverError( get_class($this).': Unknown attribute "'.$name.'" in element "'.$cmd.'". Allowed: '.$elements[$cmd]."\n" ); - } - - return $checkedAttr; - - } - - - /** - * Diese Funktion l�dt die passende Vorlagedatei. - */ - function loadDocument( $filename ) - { - if ( substr($filename,-4)=='.xml') - return $this->loadXmlDocument( $filename ); - else - return $this->loadOrmlDocument( $filename ); - } - - - /** - * Laden und Parsen eines XML-Dokumentes. - */ - function loadXmlDocument( $filename ) - { - $index = array(); - $vals = array(); - $p = xml_parser_create(); - xml_parser_set_option ( $p, XML_OPTION_CASE_FOLDING,false ); - xml_parser_set_option ( $p, XML_OPTION_SKIP_WHITE,false ); - xml_parse_into_struct($p, implode('',file($filename)), $vals, $index); - xml_parser_free($p); - - return $vals; - } - - - /** - * Laden und Parsen eines Dokumentes im Openrat-eigenem Format.<br> - * ("ORML"=Openrat Meta Language) - */ - function loadOrmlDocument( $filename ) - { - $vals = array(); - - $openCmd = array(); - - foreach( file($filename) as $line ) - { - $indent = strlen($line)-strlen(ltrim($line)); // Einzugstiefe - $line = trim($line); // Inhalt der Zeile ohne Einzug - - if ( empty($line) ) // Leerzeilen in Vorlage - { - continue; - } - - if ( substr($line,0,1)=='#' || substr($line,0,2)=='//') - continue; - - $openCmdCopy = $openCmd; - krsort($openCmdCopy); - foreach($openCmdCopy as $idx=>$ccmd) - { - if ( $idx >= $indent ) - { - $vals[] = array( 'tag' =>$ccmd, - 'type' =>'close', - 'value' =>'', - 'attributes' => array(), - 'level' => $indent ); - unset($openCmd[$idx]); - } - } - - // Zeile parsen - $li = explode(' ',$line); - $attr = array(); - foreach( $li as $nr=>$part ) - { - if ($nr==0) - $cmd = $part; - else - { - $el = explode(':',$part,2); - if ( count($el) < 2 ) - die( 'parser error in line: '.$line ); - - list($a,$b) = $el; - $attr[$a]=$b; - } - - } - // $cmd => enthaelt das Kommando - // $attr => enthaelt die Attribute - - $openCmd[$indent]=$cmd; - - $vals[] = array( 'tag'=>$cmd, - 'type'=>'open', - 'value'=>'', - 'attributes'=>$attr, - 'level'=>$indent ); - } - - // Am Ende der Datei alle offenen Tags schlie�en - $openCmdCopy = $openCmd; - krsort($openCmdCopy); - foreach($openCmdCopy as $idx=>$ccmd) - { - $vals[] = array( 'tag'=>$ccmd, - 'type'=>'close', - 'value'=>'', - 'attributes'=>array(), - 'level'=>$indent ); - - unset($openCmd[$idx]); - } - - - return $vals; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Text.class.php b/serviceClasses/Text.class.php @@ -1,415 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// DaCMS Content Management System -// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.10 2009-04-18 00:56:14 dankert -// Beim Verarbeiten von if-empty-Bereichen der Seitenvorlage keine regulären Ausdrücke mehr verwenden (da Binärausgaben wie PDF-Dokumente dabei beschädigt werden). -// -// Revision 1.9 2007-11-27 21:16:33 dankert -// Bugfix in "encodeHtmlSpecialChars()" -// -// Revision 1.8 2007-11-27 21:10:35 dankert -// Verschieben von "replaceHtmlChars()" nach Klasse Text. -// -// Revision 1.7 2007-11-24 13:22:04 dankert -// Neue Methode "encodeHtmlSpecialChars()" -// -// Revision 1.6 2007-11-17 13:36:06 dankert -// Methode "textdiff()" in Text-Klasse verschoben. -// -// Revision 1.5 2006/12/09 16:56:40 dankert -// Methode "encodeHtml()" ersetzt nun auch Umlaute gem. Konfiguration. -// -// Revision 1.4 2005/04/16 22:26:15 dankert -// Erweiterung Methode maxLength() -// -// Revision 1.3 2005/02/17 21:22:22 dankert -// Weitere Funktionen f?r HTML und BB-Code -// -// Revision 1.2 2004/05/02 15:04:16 dankert -// Einf�gen package-name (@package) -// -// Revision 1.1 2004/04/24 17:03:28 dankert -// Initiale Version -// -// --------------------------------------------------------------------------- - - -/** - * Nuetzliche Funktionen fuer das Bearbeiten von Texten/Zeichenketten - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Text -{ - /** - * Alias fuer Methode maxLength() - * - * @deprecated use maxlength() ! - */ - function maxLaenge( $laenge,$text ) - { - return Text::maxLength($text,$laenge); - } - - - /** - * Einen Text auf eine bestimmte Laenge begrenzen. - * - * Ist der Text zu lang, so wird abgeschnitten und - * eine Zeichenkette angehaengt. - * - * @param String Text, der zu begrenzen ist - * @param Integer maximale Laenge des Textes (optional) - * @param Text, der an gekuerzten Text angehangen wird (optional) - */ - function maxLength( $text,$laenge=20,$append='...',$where=STR_PAD_RIGHT ) - { - if ( strlen($text) > $laenge ) - { - if ( $where == STR_PAD_RIGHT ) - $text = substr($text,0,$laenge).$append; - elseif ( $where == STR_PAD_BOTH ) - $text = substr($text,0,$laenge/2).$append.substr($text,strlen($text)-($laenge/2)); - } - - return $text; - } - - - /** - * Umwandeln von BB-Code in Wiki-Textauszeichnungen - * - * @param text zu bearbeitender Text - * - * @return String Ausgabe - */ - function bbCode2Wiki( $inhalt ) - { - $inhalt = eregi_replace('\[b\]([^\[]*)\[\/b\]' , '*\\1*' ,$inhalt); - $inhalt = eregi_replace('\[i\]([^\[]*)\[\/i\]' , '_\\1_' ,$inhalt); - $inhalt = eregi_replace('\[code\]([^\[]*)\[\/code\]' , '=\\1=' ,$inhalt); - - $inhalt = eregi_replace('\[url\]([^\[]*)[\/url\]' ,'"\\1"->"\\1"' ,$inhalt); - $inhalt = eregi_replace('\[url=([^\[]*)\]([^\[]*)\[\/url\]','"\\2"->"\\1"' ,$inhalt); - - return $inhalt; - } - - - /** - * Umwandeln von einfachen HTML-Befehlen in Wiki-Textauszeichnungen - * - * @param text zu bearbeitender Text - * - * @return String Ausgabe - */ - function Html2Wiki( $inhalt ) - { - $inhalt = eregi_replace('<b(.*)>(.*)</b>','*\\2*' ,$inhalt); - $inhalt = eregi_replace('<i(.*)>(.*)</i>','_\\2_' ,$inhalt); - $inhalt = eregi_replace('<a(.*)href="(.*)">(.*)</a>','"\\3"->"\\2"' ,$inhalt); - - return $inhalt; - } - - - /** - * HTML-Entitaeten fuer HTML-Tags verwenden - * - * @param String Text, in dem HTML-Tags umgewandelt werden sollen - * @return String Ausgabe - */ - function encodeHtml( $inhalt ) - { - $inhalt = str_replace('&','&amp;',$inhalt); - $inhalt = str_replace('"','&quot;',$inhalt); - $inhalt = str_replace('<','&lt;' ,$inhalt); - $inhalt = str_replace('>','&gt;' ,$inhalt); - - return $inhalt; - } - - - - /** - * Ersetzt Sonderzeichen durch HTML-�quivalente.<br> - * Z.B. Ersetzt "(c)" durch "&copy;". - */ - function replaceHtmlChars( $text ) - { - global $conf; - - foreach( explode(' ',$conf['editor']['html']['replace']) as $repl ) - { - list( $ersetze, $mit ) = explode(':',$repl.':'); - $text = str_replace($ersetze, $mit, $text); - } - - return $text; - } - - - - /** - * HTML-Entitaeten fuer HTML-Tags verwenden - * - * @param String Text, in dem HTML-Tags umgewandelt werden sollen - * @return String Ausgabe - */ - function encodeHtmlSpecialChars( $inhalt ) - { - return Text::replaceHtmlChars( $inhalt ); - } - - - - /** - * Vergleicht 2 Text-Arrays und ermittelt eine Darstellung der Unterschiede - * - */ - function diff( $from_text,$to_text ) - { - // Zaehler pro Textarray - $pos_from = -1; - $pos_to = -1; - - // Ergebnis-Arrays - $from_out = array(); - $to_out = array(); - - while( true ) - { - $pos_from++; - $pos_to ++; - - if ( !isset($from_text[$pos_from]) && - !isset($to_text [$pos_to ]) ) - { - // Text in ist 'neu' und 'alt' zuende. Ende der Schleife. - break; - } - elseif - ( isset($from_text[$pos_from]) && - !isset($to_text [$pos_to]) ) - { - // Text in 'neu' ist zuende, die Restzeilen von 'alt' werden ausgegeben - while( isset($from_text[$pos_from]) ) - { - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'old'); - $to_out [] = array(); - $pos_from++; - } - break; - } - elseif - ( !isset($from_text[$pos_from]) && - isset($to_text [$pos_to]) ) - { - // Umgekehrter Fall: Text in 'alt' ist zuende, Restzeilen aus 'neu' werden ausgegeben - while( isset($to_text[$pos_to]) ) - { - $from_out[] = array(); - $to_out [] = array('text'=>$to_text[$pos_to],'line'=>$pos_to+1,'type'=>'new'); - $pos_to++; - } - break; - } - elseif - ( rtrim($from_text[$pos_from]) != rtrim($to_text[$pos_to]) ) - { - // Zeilen sind vorhanden, aber ungleich - // Wir suchen jetzt die naechsten beiden Zeilen, die gleich sind. - $max_entf = min(count($from_text)-$pos_from-1,count($to_text)-$pos_to-1); - - #echo "suche start, max_entf=$max_entf, pos_from=$pos_from, pos_to=$pos_to<br/>"; - - for ( $a=0; $a<=$max_entf; $a++ ) - { - #echo "a ist $a<br/>"; - for ( $b=0; $b<=$max_entf; $b++ ) - { - #echo "b ist $b<br/>"; - if ( trim($from_text[$pos_from+$b]) != '' && - $from_text[$pos_from+$b] == $to_text[$pos_to+$a] ) - { - $pos_gef_from = $pos_from+$b; - $pos_gef_to = $pos_to +$a; - break; - } - - if ( trim($from_text[$pos_from+$a]) != '' && - $from_text[$pos_from+$a] == $to_text[$pos_to+$b] ) - { - $pos_gef_from = $pos_from+$a; - $pos_gef_to = $pos_to +$b; - break; - } - } - - if ( $b <=$max_entf) - { - break; - } - } - - if ( $a<=$max_entf ) - { - // Gleiche Zeile gefunden - #echo "gefunden, pos_gef_from=$pos_gef_from, pos_gef_to=$pos_gef_to<br/>"; - - if ( $pos_gef_from - $pos_from == 0 ) - $type = 'new'; - elseif - ( $pos_gef_to - $pos_to == 0 ) - $type = 'old'; - else - $type = 'notequal'; - - while( $pos_gef_from - $pos_from > 0 && - $pos_gef_to - $pos_to > 0 ) - { - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>$type); - $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>$type); - - $pos_from++; - $pos_to++; - } - - while( $pos_gef_from - $pos_from > 0 ) - { - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>$type); - $to_out [] = array(); - $pos_from++; - } - - while( $pos_gef_to - $pos_to > 0 ) - { - $from_out[] = array(); - $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>$type); - $pos_to++; - } - $pos_from--; - $pos_to--; - } - else - { - // Keine gleichen Zeilen gefunden - #echo "nicht gefunden, i=$i, j=$j, pos_from war $pos_from, pos_to war $pos_to<br/>"; - - while( true ) - { - if ( !isset($from_text[$pos_from]) && - !isset($to_text [$pos_to ]) ) - { - break; - } - elseif - ( isset($from_text[$pos_from]) && - !isset($to_text [$pos_to ]) ) - { - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'notequal'); - $to_out [] = array(); - } - elseif - ( !isset($from_text[$pos_from]) && - isset($to_text [$pos_to ]) ) - { - $from_out[] = array(); - $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'notequal'); - } - else - { - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'notequal'); - $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'notequal'); - } - $pos_from++; - $pos_to++; - } - } - } - else - { - // Zeilen sind gleich - $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'equal'); - $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'equal'); - } - } - - return( array($from_out,$to_out) ); - } - - - /** - * Entfernt einen Text-Bereich aus einer Zeichenkette.<br> - * Es wird angegeben, von wo bis wo entfernt werden soll. - * - * @param $text Text, aus dem entfernt wird - * @param $von der Text, AB dem entfernt wird - * @param $bis der Text, BIS ZU DEM entfernt wird - * @return String Text - */ - function entferneVonBis($text,$von,$bis) - { - $beg = strpos($text,$von); - $end = strpos($text,$bis); - if ( $beg!==false && $end !==false ) - $text = substr($text,0,$beg).substr($text,$end+strlen($bis)); - return $text; - } - - - /** - * Saeubert eine Zeichenkette. - * - * Es werden ungueltige Zeichen aus einer Zeichenkette entfernt. Es wird mit einer Whitelist - * gearbeitet, d.h. die erlaubten Zeichen werden angegeben. - * - * @param $eingabe Die Eingabe-Zeichenkette, aus der ungueltige Zeichen entfernt werden sollen. - * @param $erlaubt Die erlaubten Zeichen (eine "White-List") - * @return String die aufgeräumte Zeichenkette - */ - function clean( $eingabe, $erlaubt ) - { - $first = strtr( $eingabe, $erlaubt, str_repeat("\x01", strlen($erlaubt)) ); - $second = strtr( $eingabe, $first , str_repeat("\x00", strlen($first )) ); - return str_replace("\x00",'',$second); - } - - - - function parseOID( $text ) - { - $oids = array(); - $treffer = array(); - - preg_match_all('/\"([^\"]*)__OID__([0-9]+)__([^\"]*)\"/', $text, $treffer,PREG_SET_ORDER); - - foreach( $treffer as $t ) - $oids[$t[2]] = $t[0]; - - return $oids; - } -} - - -?>- \ No newline at end of file diff --git a/serviceClasses/Transformer.class.php b/serviceClasses/Transformer.class.php @@ -1,94 +0,0 @@ -<?php - -/** - * Transformieren eines Textes.<br> - * Ein Text wird geparst und neu gerendert. - * - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Transformer -{ - var $text = ''; - var $doc; - var $page; - var $element; - - function transform() - { - $this->parseDocument(); - $this->renderDocument(); - - $this->text = $this->renderedText; - } - - - - /** - * Parsen eines Textes.<br> - * Der Text muss in der Eigenschaft 'text' bereits zur Verf�gung stehen.<br> - * Der Text wird geparst und als DOM (Document object model) intern gespeichert. - */ - - function parseDocument() - { - // Den Text zeilenweise aufteilen. - $zeilen = explode("\n",$this->text); - - // Dokument erzeugen und den Text parsen. - $parser = new WikiParser(); - $this->doc = new DocumentElement(); - $this->doc->element = $this->element; - $this->doc->parse( $zeilen ); - $this->doc->page = $this->page; - } - - - - /** - * Das interne Dokumente wird gerendet.<br> - * Die fertige Ausgabe steht anschliessend in der Eigenschaft "renderedText" zur Verf�gung. - */ - function renderDocument() - { - $this->doc->encodeHtml = !$this->element->html; - - $text = $this->doc->render( $this->page->mimeType() ); - - // Liste der verlinkten Objekt-Ids. - // Die Objekt-Ids werden absteigend sortiert, damit z.B. '33' vor '3' ersetzt wird. - $linkedObjectIds = $this->doc->linkedObjectIds; - rsort( $linkedObjectIds,SORT_NUMERIC ); - - // Links object:nnn ersetzen - // - // Das Dokument-Objekt hat keine Information ueber die aktuelle Seite, - // daher werden die Links auf Objekte hier gesetzt. - foreach( $linkedObjectIds as $objectId ) - { - $targetPath = $this->page->path_to_object( $objectId ); - - // Hack: Sonderzeichen muessen in URLs maskiert werden, aber nur bei URLs die aus Link-Objekten kommen, bei allem - // anderen (insbesondere Preview-Links zu andereen Seiten) darf die Umsetzung nicht erfolgen. - // Der Renderer kann dies nicht tun, denn der erzeugt nur "object://..."-URLs. - // Beispiel: "...?a=1&b=2" wird zu "...?a=1&amp;b=2" - $o = new Object($objectId); - $o->load(); - if ( $o->isLink ) - { - $l = new Link($objectId); - $l->load(); - if ( $l->isLinkToUrl && $this->page->mimeType() == 'text/html' ) - $targetPath = htmlspecialchars($targetPath); - } - - $text = str_replace( 'object:' .$objectId, $targetPath, $text ); - $text = str_replace( 'object://'.$objectId, $targetPath, $text ); - } - - $this->renderedText = $text; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/TreeElement.class.php b/serviceClasses/TreeElement.class.php @@ -1,73 +0,0 @@ -<?php -# -# DaCMS Content Management System -# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -# - -/** - * Darstellen eines Elementes in einer Baumstruktur - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class TreeElement -{ - /** - * @type Integer - */ - var $id; - - var $internalId = 0; - - /** - * Text des Baumelementes - * @type String - */ - var $text = ""; - - /** - * Beschreibung - * @type String - */ - var $description = ""; - var $url = ""; - var $icon = ""; - var $target = ""; - - /** - * Unterelemente - * Ein Array von Ids - * @type Array - */ - var $subElementIds = array(); - - /** - * Typ des Elementes - * In der Tree-Klasse muss es eine Methode mit diesem Namen geben, die das - * Element laedt. - * @type String - */ - var $type = ""; - - - // Konstruktor - function TreeElement() - { - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/Upload.class.php b/serviceClasses/Upload.class.php @@ -1,109 +0,0 @@ -<?php -// --------------------------------------------------------------------------- -// $Id$ -// --------------------------------------------------------------------------- -// OpenRat Content Management System -// Copyright (C) 2002-2004 Jan Dankert, jandankert@jandankert.de -// -// This program is free software; you can redistribute it and/or -// modify it under the terms of the GNU General Public License -// as published by the Free Software Foundation; either version 2 -// of the License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with this program; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -// --------------------------------------------------------------------------- -// $Log$ -// Revision 1.5 2007-11-22 21:20:21 dankert -// Fehlerhandling, wenn Upload misslingt. -// -// Revision 1.4 2007-10-25 22:28:18 dankert -// Filemanager f?r den FCK-Editor mit Zugriff auf OpenRat-Verzeichnis. -// -// Revision 1.3 2007-10-02 21:13:44 dankert -// Men?punkt "Neu" mit direktem Hinzuf?gen von Objekten. -// -// Revision 1.2 2004/05/02 15:04:16 dankert -// Einfügen package-name (@package) -// -// Revision 1.1 2004/04/24 17:03:28 dankert -// Initiale Version -// -// Revision 1.1 2003/10/27 23:21:55 dankert -// Methode(n) hinzugefügt: savevalue(), save() -// -// --------------------------------------------------------------------------- - -/** - * Methoden fuer den Upload einer Datei - * - * @author $Author$ - * @version $Revision$ - * @package openrat.services - */ -class Upload -{ - var $filename; - var $extension; - var $value; - var $size; - var $error = ''; - - - /** - * Stellt fest, ob der Upload geklappt hat. - * - * @return boolean - */ - function isValid() - { - return empty($this->error); - } - - - - /** - * Bearbeitet den Upload einer Datei.<br> - * Bei der Objekterzeugung wird die Datei bereits geladen.<br> - * - * @return Upload - */ - function Upload( $name='file' ) // Konstruktor - { - global $FILES; - - if ( !isset($FILES[$name]) || - !isset($FILES[$name]['tmp_name']) || - !is_file($FILES[$name]['tmp_name']) ) - { - $this->error = 'No file received.'; - return; - } - - $this->size = filesize($FILES[$name]['tmp_name']); - - $fh = fopen( $FILES[$name]['tmp_name'],'r' ); - - $this->value = fread($fh,$this->size); - fclose( $fh ); - - $this->filename = $FILES[$name]['name']; - $this->extension = ''; - - $p = strrpos( $this->filename,'.' ); // Letzten Punkt suchen - - if ($p!==false) // Wennn letzten Punkt gefunden, dann dort aufteilen - { - $this->extension = substr( $this->filename,$p+1 ); - $this->filename = substr( $this->filename,0,$p ); - } - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/XML.class.php b/serviceClasses/XML.class.php @@ -1,169 +0,0 @@ -<?php -/** - * Multidimensional Array-to-XML. - * - * Example: - * $xml = new XML(); - * header('Content-Type: application/xml'); - * echo $xml->encode( $yourBigArray ); - * exit; - * - * Author: Honor� Vasconcelos, Jan Dankert - * - * Original from: - * Clean XML To Array: http://www.phpclasses.org/browse/package/3598.html - * - * License of this class: BSD-Licence. - * - * 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 Author(s) 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 COPYRIGHT OWNER 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. - */ -class XML -{ - /** - * Parse multidimentional array to XML. - * - * @param array $array - * @return String - */ - var $xmlText = ''; - - - /** - * Name of the root element. - * - * @var String - */ - var $root = 'xml'; - - /* - * Char to indent with. - * - * @var String - */ - var $indentChar = "\t"; - - - /** - * Newline-Char - * @var String - */ - var $nl = "\n"; - - /** - * Encode a array to XML. - * - * @param Array $array - * @return String (serialized XML) - */ - function encode($array) - { - //star and end the XML document - $this->xmlText = '<?xml version="1.0" encoding="utf-8"?>'.$this->nl; - $this->xmlText .= '<'.$this->root.'>'.$this->nl; - $this->array_transform($array,1); - $this->xmlText .='</'.$this->root.'>'; - - return $this->xmlText; - } - - - /** - * @access private - */ - function array_transform($array,$depth){ - - foreach($array as $key => $value) - { - $attr = array(); - if ( is_numeric($key) ) - { - // Array-Einträge mit numerischen Index können nicht direkt in ein XML-Element - // umgewandelt werden, da nur-numerische Element-Namen nicht erlaubt sind. - // Daher verwenden wir dann 'entry' als Elementnamen. - $attr['id'] = $key; - $key = 'entry'; - } - - $indent = str_repeat($this->indentChar,$depth); - - if ( empty($value) ) - { - $this->xmlText .= $indent.$this->shortTag($key,$attr).$this->nl; - } - elseif ( is_object($value) ) - { - // Der Inhalt ist ein Array, daher rekursiv verzweigen. - $this->xmlText .= $indent.$this->openTag($key,$attr).$this->nl; - $prop = get_object_vars($value); - $this->array_transform($prop,$depth+1); // Rekursiver Aufruf - $this->xmlText .= $indent.$this->closeTag($key).$this->nl; - } - elseif ( is_array($value) ) - { - // Der Inhalt ist ein Array, daher rekursiv verzweigen. - $this->xmlText .= $indent.$this->openTag($key,$attr).$this->nl; - $this->array_transform($value,$depth+1); // Rekursiver Aufruf - $this->xmlText .= $indent.$this->closeTag($key).$this->nl; - } - else - { - // Der Inhalt ist ein einfacher Inhalt (kein Array). - $this->xmlText .= $indent.$this->openTag($key,$attr); - $this->xmlText .= $value; - $this->xmlText .= $this->closeTag($key).$this->nl; - } - } - } - - - function openTag($key,$attr) - { - $tag = '<'.$key; - foreach( $attr as $attr_name=>$attr_value ) - $tag .= ' '.$attr_name.'="'.$attr_value.'"'; - $tag .= '>'; - return $tag; - } - - - - function shortTag($key,$attr) - { - $tag = '<'.$key; - foreach( $attr as $attr_name=>$attr_value ) - $tag .= ' '.$attr_name.'="'.$attr_value.'"'; - $tag .= ' />'; - return $tag; - } - - - - function closeTag($key) - { - return '</'.$key.'>'; - } -} - -?>- \ No newline at end of file diff --git a/serviceClasses/include.inc.php b/serviceClasses/include.inc.php @@ -1,64 +0,0 @@ -<?php - -require_once( OR_SERVICECLASSES_DIR."GlobalFunctions.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Http.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Html.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Text.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Mail.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Ldap.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."TemplateEngine.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."Preferences.class.".PHP_EXT ); -require_once( OR_SERVICECLASSES_DIR."FileUtils.class.".PHP_EXT ); - -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('tree')) ) -{ - require_once( OR_SERVICECLASSES_DIR."TreeElement.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."AbstractTree.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."AdministrationTree.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."ProjectTree.class.".PHP_EXT ); -} - -// Login -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('index')) ) -{ - require_once( OR_SERVICECLASSES_DIR."OpenId.class.".PHP_EXT ); -} - -// Veroeffentlichung -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','page','pageelement','folder')) ) -{ - require_once( OR_SERVICECLASSES_DIR."Publish.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."Ftp.class.".PHP_EXT ); -} - -// Nur bei der Erzeugung von Seiten notwendig. -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('pageelement','page','folder','element')) ) -{ - require_once( OR_SERVICECLASSES_DIR."Dynamic.class.".PHP_EXT ); -} - -// Nur bei der Erzeugung von Seiten notwendig. -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('pageelement','page','folder')) ) -{ - require_once( OR_SERVICECLASSES_DIR."Api.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."Code.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."Transformer.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."Line.class.".PHP_EXT ); -} - - -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','folder','filebrowser')) ) -{ - require_once( OR_SERVICECLASSES_DIR."Upload.class.".PHP_EXT ); -} - - -//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','folder')) ) -{ - require_once( OR_SERVICECLASSES_DIR."Upload.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."ArchiveTar.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."ArchiveUnzip.class.".PHP_EXT ); - require_once( OR_SERVICECLASSES_DIR."ArchiveZip.class.".PHP_EXT ); -} - -?>- \ No newline at end of file diff --git a/util/.htaccess b/util/.htaccess @@ -0,0 +1,2 @@ +order deny,allow +deny from all+ \ No newline at end of file diff --git a/util/AbstractTree.class.php b/util/AbstractTree.class.php @@ -0,0 +1,170 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Darstellen einer Baumstruktur mit Funktion zum Laden, Oeffnen und Schliessen + * von Teilbaeumen + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class AbstractTree +{ + /** + * Alle Elemente des Baumes + */ + var $elements = array(); + + var $tempElements = array(); + var $userIsAdmin = false; + + var $autoOpen = array(0,1); + + var $opened = array(); + + /** + * Hoechste Element-Id + * @type Integer + */ + var $maxId; + + // Konstruktor + function AbstractTree() + { + // Feststellen, ob der angemeldete Benutzer ein Administrator ist + $user = Session::getUser(); + $this->userIsAdmin = $user->isAdmin; + + // Wurzel-Element laden + $this->root(); + $this->elements[0] = $this->tempElements[0]; + $this->tempElements = array(); + $this->maxId = 0; + + foreach( $this->autoOpen as $openId ) + $this->open($openId); + } + + function refresh() { + + $this->elements = array(); + + // Wurzel-Element laden + $this->root(); + $this->elements[0] = $this->tempElements[0]; + $this->tempElements = array(); + $this->maxId = 0; + + $oids = $this->opened; + $this->opened = array(); + foreach( $oids as $oid) + { + if ( isset($this->elements[$oid]) ) + $this->open($oid); + } + } + + + + function all() { + + $this->elements = array(); + $this->opened = array(); + + // Wurzel-Element laden + $this->root(); + $this->elements[0] = $this->tempElements[0]; + $this->tempElements = array(); + $this->maxId = 0; + + for( $eid=0;isset($this->elements[$eid]); $eid++) + { + $this->open($eid); + } + } + + + /** + * Oeffnen eines Teilbaumes. Es wird der eindeutige Name des zu oeffnenden Teilbaumes als + * Parameter uebergeben + * @param elementName der Name des Elementes, welches zu oeffnen ist + */ + function open( $elementId ) + { + $k = array_search($elementId,$this->opened); + if ( $k !== false ) + return; // Ist schon offen. Evtl. Reload gedrückt? + + $this->opened[] = $elementId; + $funcName = $this->elements[$elementId]->type; + if ( empty($funcName) ) + return; + + $this->$funcName( $this->elements[$elementId]->internalId ); + + // Wenn keine Unterelemente gefunden, dann die ?ffnen-Funktion deaktivieren + if ( count( $this->tempElements ) == 0 ) + $this->elements[$elementId]->type = ''; + + foreach( $this->tempElements as $treeElement ) + { + $this->maxId++; + $this->elements[$elementId]->subElementIds[] = $this->maxId; + $this->elements[$this->maxId] = $treeElement; + } + + if ( count($this->tempElements)==1 ) + { + $this->tempElements = array(); + $this->open($this->maxId); + } + + $this->tempElements = array(); + } + + + /** + * Schliessen eines Teilbaumes + * @param elementName der Name des Elementes, welches zu schliessen ist + */ + + function close( $elementId ) + { + $this->elements[$elementId]->subElementIds = array(); + + $k = array_search($elementId,$this->opened); + if ( $k !== false ) + unset($this->opened[$k]); + } + + + /** + * Hinzufuegen eines Baum-Elementes + * @param TreeElement Hinzuzufuegendes Baumelement + */ + function addTreeElement( $treeElement ) + { + $this->tempElements[] = $treeElement; + } + + +} + +?>+ \ No newline at end of file diff --git a/util/AdministrationTree.class.php b/util/AdministrationTree.class.php @@ -0,0 +1,470 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Darstellen einer Baumstruktur mit Administrationfunktionen + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class AdministrationTree extends AbstractTree +{ + /** + * Alle Elemente des Baumes + */ + var $elements; + var $confCache = array(); + + function root() + { + if ( !$this->userIsAdmin ) + Http::notAuthorized('Administration-Tree is only visible for admins.'); + + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_ADMINISTRATION'); + $treeElement->description = lang('GLOBAL_ADMINISTRATION'); + $treeElement->type = 'administration'; + $treeElement->icon = 'administration'; + + $this->addTreeElement( $treeElement ); + $this->autoOpen[] = 2; + } + + + + function administration() + { + global $conf; + $conf_config = $conf['interface']['config']; + + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_PROJECTS'); + $treeElement->description = lang('GLOBAL_PROJECTS'); + $treeElement->url = Html::url('project','listing',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'project_list'; + $treeElement->type = 'projects'; + $treeElement->target = 'cms_main'; + + $this->addTreeElement( $treeElement ); + + + $treeElement = new TreeElement(); + $treeElement->text = lang('USER_AND_GROUPS'); + $treeElement->description = lang('USER_AND_GROUPS'); + $treeElement->icon = 'user_list'; + $treeElement->type = 'userandgroups'; + + $this->addTreeElement( $treeElement ); +// $this->userandgroups(0);; + + if ( $conf_config['enable'] ) + { + $treeElement = new TreeElement(); + $treeElement->text = lang('PREFERENCES'); + $treeElement->description = lang('PREFERENCES'); + $treeElement->icon = 'config_folder'; + $treeElement->type = 'prefs'; + + $this->addTreeElement( $treeElement ); + } + + // Wechseln zu: Projekte... + /* + foreach( Project::getAll() as $id=>$name ) + { + $treeElement = new TreeElement(); + + $treeElement->text = lang('PROJECT').' '.$name; + $treeElement->url = Html::url(array('action' =>'tree', + 'subaction' =>'reload', + 'projectid' =>$id )); + $treeElement->icon = 'project'; + $treeElement->description = ''; + $treeElement->target = 'cms_tree'; + + $this->addTreeElement( $treeElement ); + } + */ + } + + + + function userandgroups( $id ) + { + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_USER'); + $treeElement->description = lang('GLOBAL_USER'); + $treeElement->url = Html::url('user','listing',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'user_list'; + $treeElement->target = 'cms_main'; + $treeElement->type = 'users'; + + $this->addTreeElement( $treeElement ); + + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_GROUPS'); + $treeElement->description = lang('GLOBAL_GROUPS'); + $treeElement->url = Html::url('group','listing',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'user_list'; + $treeElement->target = 'cms_main'; + $treeElement->type = 'groups'; + + $this->addTreeElement( $treeElement ); + } + + + function projects( $id ) + { + // Schleife ueber alle Projekte + foreach( Project::getAll() as $id=>$name ) + { + $treeElement = new TreeElement(); + + $treeElement->internalId = $id; + $treeElement->text = $name; + $treeElement->url = Html::url('project','edit',$id,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'project'; + $treeElement->description = ''; + $treeElement->target = 'cms_main'; + + $this->addTreeElement( $treeElement ); + } + } + + + + function prefs_system( $id ) + { + $system = array( 'time' => date('r'), + 'os' => php_uname('s'), + 'host' => php_uname('n'), + 'release'=> php_uname('r'), + 'machine'=> php_uname('m'), + 'owner' => get_current_user(), + 'pid' => getmypid() ); + + foreach( $system as $key=>$value ) + { + $treeElement = new TreeElement(); + $treeElement->text = $key.'='.$value; + $treeElement->icon = 'config_property'; + $this->addTreeElement( $treeElement ); + $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); + } + + if ( function_exists('getrusage') ) // Funktion existiert auf WIN32 nicht. + { + foreach( getrusage() as $name=>$value ); + { + $treeElement = new TreeElement(); + $treeElement->text = $name.':'.$value; + $treeElement->description = lang('SETTING')." '".$name."'".(!empty($value)?': '.$value:''); + $treeElement->icon = 'config_property'; + $this->addTreeElement( $treeElement ); + } + } + } + + + + + function prefs_php( $id ) + { + $php_prefs = array( 'version' => phpversion(), + 'SAPI' => php_sapi_name(), + 'session-name' => session_name(), + 'magic_quotes_gpc' => get_magic_quotes_gpc(), + 'magic_quotes_runtime'=> get_magic_quotes_runtime() ); + + foreach( array('upload_max_filesize', + 'file_uploads', + 'memory_limit', + 'max_execution_time', + 'post_max_size', + 'display_errors', + 'register_globals' + ) as $iniName ) + $php_prefs[ $iniName ] = ini_get( $iniName ); + + foreach( $php_prefs as $key=>$value ) + { + $treeElement = new TreeElement(); + $treeElement->text = $key.'='.$value; + $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); + $treeElement->icon = 'config_property'; + $this->addTreeElement( $treeElement ); + } + } + + + + function prefs_extensions( $id ) + { + $extensions = get_loaded_extensions(); + asort( $extensions ); + + foreach( $extensions as $id=>$extensionName ) + { + $treeElement = new TreeElement(); + $treeElement->text = $extensionName; + $treeElement->icon = 'config_property'; + $treeElement->internalId = $id; + $this->addTreeElement( $treeElement ); + } + } + + + + function prefs_extension( $id ) + { + $extensions = get_loaded_extensions(); + $functions = get_extension_funcs( $extensions[$id] ); + asort( $functions ); + + foreach( $functions as $functionName ) + { + $treeElement = new TreeElement(); + $treeElement->text = $functionName; + $treeElement->icon = 'config_property'; + $this->addTreeElement( $treeElement ); + } + } + + + /** + * Anzeigen von Einstellungen. + * + * @param $id + */ + function prefs( $id ) + { + global $conf; + + if ( !@$conf['security']['show_system_info'] ) + return; + + $conf_config = $conf['interface']['config']; + + + $treeElement = new TreeElement(); + + $treeElement->internalId = 0; + $treeElement->text = 'OpenRat'; + $treeElement->icon = 'config_folder'; + + if ( !empty($conf_config['file_manager_url']) ) + $treeElement->url = $conf_config['file_manager_url']; + $treeElement->target = '_blank'; + $treeElement->description = ''; + $treeElement->type = 'prefs_cms'; + $this->addTreeElement( $treeElement ); + + + + if ( !empty($conf_config['show_system']) ) + { + $treeElement = new TreeElement(); + + $treeElement->internalId = 0; + $treeElement->text = lang('GLOBAL_SYSTEM'); + $treeElement->icon = 'config_folder'; + + $treeElement->description = ''; + $treeElement->target = 'cms_main'; + $treeElement->type = 'prefs_system'; + $this->addTreeElement( $treeElement ); + } + + + if ( !empty($conf_config['show_interpreter']) ) + { + $treeElement = new TreeElement(); + + $treeElement->internalId = 0; + $treeElement->text = lang('GLOBAL_PHP'); + $treeElement->icon = 'config_folder'; + + $treeElement->description = ''; + $treeElement->target = 'cms_main'; + $treeElement->type = 'prefs_php'; + $this->addTreeElement( $treeElement ); + } + + + if ( !empty($conf_config['show_extensions']) ) + { + $treeElement = new TreeElement(); + + $treeElement->internalId = 0; + $treeElement->text = lang('GLOBAL_EXTENSIONS'); + $treeElement->icon = 'config_folder'; + + $treeElement->description = ''; + $treeElement->target = 'cms_main'; + $treeElement->type = 'prefs_extensions'; + $this->addTreeElement( $treeElement ); + } + } + + + function prefs_cms( $id ) + { + global $conf; + + if ( $id == 0 ) + { + $tmpConf = $conf; + } + else + $tmpConf = $this->confCache[$id]; + + if ( !is_array($tmpConf) ) + $tmpConf = array('unknown'); + + foreach( $tmpConf as $key=>$value ) + { + if ( is_array($value) ) + { + $this->confCache[crc32($key)] = $value; + + $treeElement = new TreeElement(); + + $treeElement->internalId = crc32($key); + $treeElement->text = $key; +// if ( $id == 0 ) +// $treeElement->url = Html::url('main','prefs',0,array('conf'=>$key)); + $treeElement->icon = 'config_folder'; + + $treeElement->description = count($value).' '.lang('SETTINGS'); + $treeElement->target = 'cms_main'; + $treeElement->type = 'prefs_cms'; + $this->addTreeElement( $treeElement ); + } + else + { + // Die PHP-funktion 'parse_ini_file()' liefert alle Einstellungen leider nur als String + // Daher weiß man hier nicht, ob '1' nun '1' oder 'true' heißen soll. + if ( $value=='' ) + // Anzeige 'Leer' + $value = lang('EMPTY'); + elseif ( $value=='0' ) + // Anzeige 'Nein' + $value = $value.' ('.lang('IS_NO').')'; + elseif ( $value=='1' ) + // Anzeige 'Ja' + $value = '+'.$value.' ('.lang('IS_YES').')'; + elseif ( is_numeric($value) ) + // Anzeige numerische Werte + $value = ($value>0?'+':'').$value; + else + // Anzeige von Zeichenketten + $value = $value; + + $this->confCache[crc32($key)] = $value; + + if ( strpos($key,'pass') !== FALSE ) + $value = '***'; // Kennwörter nicht anzeigen + + $treeElement = new TreeElement(); + $treeElement->text = $key.': '.$value; + $treeElement->icon = 'config_property'; + $treeElement->description = lang('SETTING')." '".$key."'".(!empty($value)?': '.$value:''); + + $this->addTreeElement( $treeElement ); + } + } + } + + + function users( $id ) + { + foreach( User::getAllUsers() as $user ) + { + $treeElement = new TreeElement(); + + $treeElement->internalId = $user->userid; + $treeElement->text = $user->name; + $treeElement->url = Html::url('user','edit', + $user->userid,array(REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = 'user'; + + $desc = $user->fullname; + + if ( $user->isAdmin ) + $desc .= ' ('.lang('USER_ADMIN').') '; + if ( $user->desc == "" ) + $desc .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + else + $desc .= ' - '.$user->desc; + + $treeElement->description = $desc; + $treeElement->target = 'cms_main'; + + $this->addTreeElement( $treeElement ); + } + } + + + function groups( $id ) + { + + foreach( Group::getAll() as $id=>$name ) + { + $treeElement = new TreeElement(); + + $g = new Group( $id ); + $g->load(); + + $treeElement->internalId = $id; + $treeElement->text = $g->name; + $treeElement->url = Html::url('group','edit',$id, + array(REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = 'group'; + $treeElement->description = lang('GLOBAL_GROUP').' '.$g->name.': '.implode(', ',$g->getUsers()); + $treeElement->target = 'cms_main'; + $treeElement->type = 'userofgroup'; + + $this->addTreeElement( $treeElement ); + } + } + + + function userofgroup( $id ) + { + $g = new Group( $id ); + + foreach( $g->getUsers() as $id=>$name ) + { + $treeElement = new TreeElement(); + + $u = new User( $id ); + $u->load(); + $treeElement->text = $u->name; + $treeElement->url = Html::url('user','edit',$id,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'user'; + $treeElement->description = $u->fullname; + $treeElement->target = 'cms_main'; + + $this->addTreeElement( $treeElement ); + } + } +} + +?>+ \ No newline at end of file diff --git a/util/Api.class.php b/util/Api.class.php @@ -0,0 +1,120 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// DaCMS Content Management System +// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.5 2004-11-10 22:50:10 dankert +// Neue Methode execute() +// +// Revision 1.4 2004/10/06 09:53:39 dankert +// Benutzung auch nicht-statisch +// +// Revision 1.3 2004/05/03 20:21:34 dankert +// neu: setObjectId() +// +// Revision 1.2 2004/05/02 15:04:16 dankert +// Einf?gen package-name (@package) +// +// Revision 1.1 2004/04/24 17:03:29 dankert +// Initiale Version +// +// --------------------------------------------------------------------------- + +/** + * Service-Klasse fuer allgemeine Interface-Methoden. Insbesondere + * in Code-Elementen kann und soll auf diese Methoden zurueckgegriffen + * werden. + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Api +{ + var $output = ''; + var $objectid = 0; + var $page; + + function db() + { + return db_connection(); + } + + function pageid() + { + echo 'WARNING: pageid() deprecated!<br>'; + global $SESS; + return $SESS['objectid']; + } + + function getObjectId() + { + return $this->objectid; + } + + function setObjectId( $objectid ) + { + $this->objectid = $objectid; + } + + function getRootObjectId() + { + return Folder::getRootObjectId(); + } + + function folderid() + { + global $SESS; + return $SESS['folderid']; + } + + + function execute( $code ) + { + global $conf_tmpdir; + $code = "<?php\n".$code."\n?>"; + + $tmp = $conf_tmpdir.'/'.md5(microtime()).'.tmp'; + $f = fopen( $tmp,'w' ); + fwrite( $f,$code ); + fclose( $f ); + + require( $tmp ); // Ausfuehren des temporaeren PHP-Codes + + unlink( $tmp ); + $inhalt = Api::getOutput(); + $this->output( $inhalt ); + } + + function delOutput() + { + $this->output = ''; + } + + function output( $text ) + { + $this->output .= $text; + } + + + function getOutput() + { + return $this->output; + } +}+ \ No newline at end of file diff --git a/util/ArchiveTar.class.php b/util/ArchiveTar.class.php @@ -0,0 +1,397 @@ +<?php +/* +======================================================================= +Name: + tar Class + +Author: + Josh Barger <joshb@npt.com> + +Description: + This class reads and writes Tape-Archive (TAR) Files and Gzip + compressed TAR files, which are mainly used on UNIX systems. + This class works on both windows AND unix systems, and does + NOT rely on external applications!! Woohoo! + +Usage: + Copyright (C) 2002 Josh Barger + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details at: + http://www.gnu.org/copyleft/lesser.html + + If you use this script in your application/website, please + send me an e-mail letting me know about it :) + +Bugs: + Please report any bugs you might find to my e-mail address + at joshb@npt.com. If you have already created a fix/patch + for the bug, please do send it to me so I can incorporate it into my release. + +Version History: + 1.0 04/10/2002 - InitialRelease + + 2.0 04/11/2002 - Merged both tarReader and tarWriter + classes into one + - Added support for gzipped tar files + Remember to name for .tar.gz or .tgz + if you use gzip compression! + :: THIS REQUIRES ZLIB EXTENSION :: + - Added additional comments to + functions to help users + - Added ability to remove files and + directories from archive + 2.1 04/12/2002 - Fixed serious bug in generating tar + - Created another example file + - Added check to make sure ZLIB is + installed before running GZIP + compression on TAR + 2.2 05/07/2002 - Added automatic detection of Gzipped + tar files (Thanks go to J�rgen Falch + for the idea) + - Changed "private" functions to have + special function names beginning with + two underscores +======================================================================= +*/ + + +class ArchiveTar +{ + // Unprocessed Archive Information + var $filename; + var $isGzipped; + var $tar_file; + + // Processed Archive Information + var $files; + var $directories; + var $numFiles; + var $numDirectories; + + + // Class Constructor -- Does nothing... + function tar() { + return true; + } + + + // Computes the unsigned Checksum of a file's header + // to try to ensure valid file + // PRIVATE ACCESS FUNCTION + function __computeUnsignedChecksum($bytestring) + { + $unsigned_chksum=0; + for($i=0; $i<512; $i++) + $unsigned_chksum += ord($bytestring[$i]); + for($i=0; $i<8; $i++) + $unsigned_chksum -= ord($bytestring[148 + $i]); + $unsigned_chksum += ord(" ") * 8; + + return $unsigned_chksum; + } + + + // Converts a NULL padded string to a non-NULL padded string + // PRIVATE ACCESS FUNCTION + function __parseNullPaddedString($string) + { + $position = strpos($string,chr(0)); + return substr($string,0,$position); + } + + + // This function parses the current TAR file + // PRIVATE ACCESS FUNCTION + function __parseTar() + { + // Read Files from archive + $this->numFiles=0; + $tar_length = strlen($this->tar_file); + $main_offset = 0; + while($main_offset < $tar_length) { + // If we read a block of 512 nulls, we are at the end of the archive + if(substr($this->tar_file,$main_offset,512) == str_repeat(chr(0),512)) + break; + + // Parse file name + $file_name = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset,100)); + + // Parse the file mode + $file_mode = substr($this->tar_file,$main_offset + 100,8); + + // Parse the file user ID + $file_uid = octdec(substr($this->tar_file,$main_offset + 108,8)); + + // Parse the file group ID + $file_gid = octdec(substr($this->tar_file,$main_offset + 116,8)); + + // Parse the file size + $file_size = octdec(substr($this->tar_file,$main_offset + 124,12)); + + // Parse the file update time - unix timestamp format + $file_time = octdec(substr($this->tar_file,$main_offset + 136,12)); + + // Parse Checksum + $file_chksum = octdec(substr($this->tar_file,$main_offset + 148,6)); + + // Parse user name + $file_uname = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 265,32)); + + // Parse Group name + $file_gname = $this->__parseNullPaddedString(substr($this->tar_file,$main_offset + 297,32)); + + // Make sure our file is valid + if($this->__computeUnsignedChecksum(substr($this->tar_file,$main_offset,512)) != $file_chksum) + return false; + + // Parse File Contents + $file_contents = substr($this->tar_file,$main_offset + 512,$file_size); + + /* ### Unused Header Information ### + $activeFile["typeflag"] = substr($this->tar_file,$main_offset + 156,1); + $activeFile["linkname"] = substr($this->tar_file,$main_offset + 157,100); + $activeFile["magic"] = substr($this->tar_file,$main_offset + 257,6); + $activeFile["version"] = substr($this->tar_file,$main_offset + 263,2); + $activeFile["devmajor"] = substr($this->tar_file,$main_offset + 329,8); + $activeFile["devminor"] = substr($this->tar_file,$main_offset + 337,8); + $activeFile["prefix"] = substr($this->tar_file,$main_offset + 345,155); + $activeFile["endheader"] = substr($this->tar_file,$main_offset + 500,12); + */ + + if($file_size > 0) { + // Increment number of files + $this->numFiles++; + + // Create us a new file in our array + $activeFile = &$this->files[]; + + // Asign Values + $activeFile["name"] = $file_name; + $activeFile["mode"] = $file_mode; + $activeFile["size"] = $file_size; + $activeFile["time"] = $file_time; + $activeFile["user_id"] = $file_uid; + $activeFile["group_id"] = $file_gid; + $activeFile["user_name"] = $file_uname; + $activeFile["group_name"] = $file_gname; + $activeFile["checksum"] = $file_chksum; + $activeFile["file"] = $file_contents; + + } else { + // Increment number of directories + $this->numDirectories++; + + // Create a new directory in our array + $activeDir = &$this->directories[]; + + // Assign values + $activeDir["name"] = $file_name; + $activeDir["mode"] = $file_mode; + $activeDir["time"] = $file_time; + $activeDir["user_id"] = $file_uid; + $activeDir["group_id"] = $file_gid; + $activeDir["user_name"] = $file_uname; + $activeDir["group_name"] = $file_gname; + $activeDir["checksum"] = $file_chksum; + } + + // Move our offset the number of blocks we have processed + $main_offset += 512 + (ceil($file_size / 512) * 512); + } + + return true; + } + + + // Read a non gzipped tar file in for processing + // PRIVATE ACCESS FUNCTION + function __readTar($filename='') + { + // Set the filename to load + // Read in the TAR file + + if($this->tar_file[0] == chr(31) && $this->tar_file[1] == chr(139) && $this->tar_file[2] == chr(8)) { + if(!function_exists("gzinflate")) + return false; + + $this->isGzipped = TRUE; + + $this->tar_file = gzinflate(substr($this->tar_file,10,-4)); + } + + // Parse the TAR file + $this->__parseTar(); + + return true; + } + + + // Generates a TAR file from the processed data + // PRIVATE ACCESS FUNCTION + function __generateTAR() + { + // Clear any data currently in $this->tar_file + unset($this->tar_file); + + // Generate Records for each directory, if we have directories + if($this->numDirectories > 0) { + foreach($this->directories as $key => $information) { + unset($header); + + // Generate tar header for this directory + // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end + $header .= str_pad($information["name"],100,chr(0)); + $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct(0),11,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0); + $header .= str_repeat(" ",8); + $header .= "5"; + $header .= str_repeat(chr(0),100); + $header .= str_pad("ustar",6,chr(32)); + $header .= chr(32) . chr(0); + $header .= str_pad("",32,chr(0)); + $header .= str_pad("",32,chr(0)); + $header .= str_repeat(chr(0),8); + $header .= str_repeat(chr(0),8); + $header .= str_repeat(chr(0),155); + $header .= str_repeat(chr(0),12); + + // Compute header checksum + $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT); + for($i=0; $i<6; $i++) { + $header[(148 + $i)] = substr($checksum,$i,1); + } + $header[154] = chr(0); + $header[155] = chr(32); + + // Add new tar formatted data to tar file contents + $this->tar_file .= $header; + } + } + + // Generate Records for each file, if we have files (We should...) + if($this->numFiles > 0) + { + foreach($this->files as $key => $information) + { + unset($header); + $header = ''; + + // Generate the TAR header for this file + // Filename, Permissions, UID, GID, size, Time, checksum, typeflag, linkname, magic, version, user name, group name, devmajor, devminor, prefix, end + $header .= str_pad($information["name"],100,chr(0)); + $header .= str_pad(decoct($information["mode"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["size"]),11,"0",STR_PAD_LEFT) . chr(0); + $header .= str_pad(decoct($information["time"]),11,"0",STR_PAD_LEFT) . chr(0); + $header .= str_repeat(" ",8); + $header .= "0"; + $header .= str_repeat(chr(0),100); + $header .= str_pad("ustar",6,chr(32)); + $header .= chr(32) . chr(0); + $header .= str_pad($information["user_name"],32,chr(0)); // How do I get a file's user name from PHP? + $header .= str_pad($information["group_name"],32,chr(0)); // How do I get a file's group name from PHP? + $header .= str_repeat(chr(0),8); + $header .= str_repeat(chr(0),8); + $header .= str_repeat(chr(0),155); + $header .= str_repeat(chr(0),12); + + // Compute header checksum + $checksum = str_pad(decoct($this->__computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT); + for($i=0; $i<6; $i++) + { + $header[(148 + $i)] = substr($checksum,$i,1); + } + $header[154] = chr(0); + $header[155] = chr(32); + + // Pad file contents to byte count divisible by 512 + $file_contents = str_pad($information["file"],(ceil($information["size"] / 512) * 512),chr(0)); + + // Add new tar formatted data to tar file contents + $this->tar_file .= $header . $file_contents; + } + } + + // Add 512 bytes of NULLs to designate EOF + $this->tar_file .= str_repeat(chr(0),512); + + return true; + } + + + // Open a TAR file + function openTAR($value) + { + // Clear any values from previous tar archives + unset($this->filename); + unset($this->isGzipped); + unset($this->tar_file); + unset($this->files); + unset($this->directories); + unset($this->numFiles); + unset($this->numDirectories); + + $this->filename = 'none'; + $this->tar_file = $value; + // Parse this file + $this->__readTar(); + + return true; + } + + + // Write the currently loaded tar archive to disk + function saveTar() + { + if(!$this->filename) + return false; + + // Write tar to current file using specified gzip compression + $this->toTar($this->filename,$this->isGzipped); + + return true; + } + + + // Saves tar archive to a different file than the current file + function toTar($filename,$useGzip) + { + if(!$filename) + return false; + + // Encode processed files into TAR file format + $this->__generateTar(); + + // GZ Compress the data if we need to + if($useGzip) { + // Make sure we have gzip support + if(!function_exists("gzencode")) + return false; + + $file = gzencode($this->tar_file); + } else { + $file = $this->tar_file; + } + + // Write the TAR file + $fp = fopen($filename,"wb"); + fwrite($fp,$file); + fclose($fp); + + return true; + } +} + +?>+ \ No newline at end of file diff --git a/util/ArchiveUnzip.class.php b/util/ArchiveUnzip.class.php @@ -0,0 +1,447 @@ +<?php +// 28/11/2005 (2.4) +// - dUnzip2 is now compliant with wrong placed "Data Description", made by some compressors, +// like the classes ZipLib and ZipLib2 by 'Hasin Hayder'. Thanks to Ricardo Parreno for pointing it. +// 09/11/2005 (2.3) +// - Added optional parameter '$stopOnFile' on method 'getList()'. +// If given, file listing will stop when find given filename. (Useful to open and unzip an exact file) +// 06/11/2005 (2.21) +// - Added support to PK00 file format (Packed to Removable Disk) (thanks to Lito [PHPfileNavigator]) +// - Method 'getExtraInfo': If requested file doesn't exist, return FALSE instead of Array() +// 31/10/2005 (2.2) +// - Removed redundant 'file_name' on centralDirs declaration (thanks to Lito [PHPfileNavigator]) +// - Fixed redeclaration of file_put_contents when in PHP4 (not returning true) + +############################################################## +# Class dUnzip2 v2.4 +# +# Author: Alexandre Tedeschi (d) +# E-Mail: alexandrebr at gmail dot com +# Londrina - PR / Brazil +# +# Objective: +# This class allows programmer to easily unzip files on the fly. +# +# Requirements: +# This class requires extension ZLib Enabled. It is default +# for most site hosts around the world, and for the PHP Win32 dist. +# +# To do: +# * Error handling +# * Write a PHP-Side gzinflate, to completely avoid any external extensions +# * Write other decompress algorithms +# +# If you modify this class, or have any ideas to improve it, please contact me! +# You are allowed to redistribute this class, if you keep my name and contact e-mail on it. +############################################################## + +class ArchiveUnzip{ + + // Public + var $files = array(); + var $value = ''; + var $fileName; + var $compressedList; // You will problably use only this one! + var $centralDirList; // Central dir list... It's a kind of 'extra attributes' for a set of files + var $endOfCentral; // End of central dir, contains ZIP Comments + var $debug; + + // Private + var $fh; + var $zipSignature = "\x50\x4b\x03\x04"; // local file header signature + var $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature + var $dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature + + // Public + Function ArchiveUnzip() + { + $this->compressedList = + $this->centralDirList = + $this->endOfCentral = Array(); + } + + function open( $value ) + { + $this->fileName = tempnam('/tmp','unzip'); +// echo $this->fileName; + $fo = fopen( $this->fileName,'w'); + fwrite($fo,$value); + $this->unzipAll(); + } + + + Function getList($stopOnFile=false){ + if(sizeof($this->compressedList)){ + $this->debugMsg(1, "Returning already loaded file list."); + return $this->compressedList; + } + + // Open file, and set file handler + $fh = fopen($this->fileName, "r"); + $this->fh = &$fh; + if(!$fh){ + $this->debugMsg(2, "Failed to load file."); + return false; + } + + // Loop the file, looking for files and folders + $ddTry = false; + fseek($fh, 0); + for(;;){ + // Check if the signature is valid... + $signature = fread($fh, 4); + if(feof($fh)){ +# $this->debugMsg(1, "Reached end of file"); + break; + } + + // If signature is a 'Packed to Removable Disk', just ignore it and move to the next. + if($signature == 'PK00'){ + $this->debugMsg(1, "Found PK00: Packed to Removable Disk"); + continue; + } + + // If signature of a 'Local File Header' + if($signature == $this->zipSignature){ + # $this->debugMsg(1, "Zip Signature!"); + + // Get information about the zipped file + $file['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract + $file['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag + $file['compression_method'] = unpack("v", fread($fh, 2)); // compression method + $file['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time + $file['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date + $file['crc-32'] = fread($fh, 4); // crc-32 + $file['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size + $file['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size + $fileNameLength = unpack("v", fread($fh, 2)); // filename length + $extraFieldLength = unpack("v", fread($fh, 2)); // extra field length + $file['file_name'] = fread($fh, $fileNameLength[1]); // filename + $file['extra_field'] = $extraFieldLength[1]?fread($fh, $extraFieldLength[1]):''; // extra field + $file['contents-startOffset']= ftell($fh); + + // Bypass the whole compressed contents, and look for the next file + fseek($fh, $file['compressed_size'][1], SEEK_CUR); + + // Convert the date and time, from MS-DOS format to UNIX Timestamp + $BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT); + $BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT); + $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980; + $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4)); + $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5)); + $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5)); + $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6)); + $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5)); + + // Mount file table + $this->compressedList[$file['file_name']] = Array( + 'file_name' =>$file['file_name'], + 'compression_method'=>$file['compression_method'][1], + 'version_needed' =>$file['version_needed'][1], + 'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY), + 'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT), + 'compressed_size' =>$file['compressed_size'][1], + 'uncompressed_size' =>$file['uncompressed_size'][1], + 'extra_field' =>$file['extra_field'], + 'general_bit_flag' =>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT), + 'contents-startOffset'=>$file['contents-startOffset'] + ); + + if($stopOnFile) if($file['file_name'] == $stopOnFile){ + $this->debugMsg(1, "Stopping on file..."); + break; + } + } + + // If signature of a 'Central Directory Structure' + elseif($signature == $this->dirSignature){ + # $this->debugMsg(1, "Dir Signature!"); + + $dir['version_madeby'] = unpack("v", fread($fh, 2)); // version made by + $dir['version_needed'] = unpack("v", fread($fh, 2)); // version needed to extract + $dir['general_bit_flag'] = unpack("v", fread($fh, 2)); // general purpose bit flag + $dir['compression_method'] = unpack("v", fread($fh, 2)); // compression method + $dir['lastmod_time'] = unpack("v", fread($fh, 2)); // last mod file time + $dir['lastmod_date'] = unpack("v", fread($fh, 2)); // last mod file date + $dir['crc-32'] = fread($fh, 4); // crc-32 + $dir['compressed_size'] = unpack("V", fread($fh, 4)); // compressed size + $dir['uncompressed_size'] = unpack("V", fread($fh, 4)); // uncompressed size + $fileNameLength = unpack("v", fread($fh, 2)); // filename length + $extraFieldLength = unpack("v", fread($fh, 2)); // extra field length + $fileCommentLength = unpack("v", fread($fh, 2)); // file comment length + $dir['disk_number_start'] = unpack("v", fread($fh, 2)); // disk number start + $dir['internal_attributes'] = unpack("v", fread($fh, 2)); // internal file attributes-byte1 + $dir['external_attributes1']= unpack("v", fread($fh, 2)); // external file attributes-byte2 + $dir['external_attributes2']= unpack("v", fread($fh, 2)); // external file attributes + $dir['relative_offset'] = unpack("V", fread($fh, 4)); // relative offset of local header + $dir['file_name'] = fread($fh, $fileNameLength[1]); // filename + $dir['extra_field'] = $extraFieldLength[1] ?fread($fh, $extraFieldLength[1]) :''; // extra field + $dir['file_comment'] = $fileCommentLength[1]?fread($fh, $fileCommentLength[1]):''; // file comment + + // Convert the date and time, from MS-DOS format to UNIX Timestamp + $BINlastmod_date = str_pad(decbin($file['lastmod_date'][1]), 16, '0', STR_PAD_LEFT); + $BINlastmod_time = str_pad(decbin($file['lastmod_time'][1]), 16, '0', STR_PAD_LEFT); + $lastmod_dateY = bindec(substr($BINlastmod_date, 0, 7))+1980; + $lastmod_dateM = bindec(substr($BINlastmod_date, 7, 4)); + $lastmod_dateD = bindec(substr($BINlastmod_date, 11, 5)); + $lastmod_timeH = bindec(substr($BINlastmod_time, 0, 5)); + $lastmod_timeM = bindec(substr($BINlastmod_time, 5, 6)); + $lastmod_timeS = bindec(substr($BINlastmod_time, 11, 5)); + + $this->centralDirList[$dir['file_name']] = Array( + 'version_madeby'=>$dir['version_madeby'][1], + 'version_needed'=>$dir['version_needed'][1], + 'general_bit_flag'=>str_pad(decbin($file['general_bit_flag'][1]), 8, '0', STR_PAD_LEFT), + 'compression_method'=>$dir['compression_method'][1], + 'lastmod_datetime' =>mktime($lastmod_timeH, $lastmod_timeM, $lastmod_timeS, $lastmod_dateM, $lastmod_dateD, $lastmod_dateY), + 'crc-32' =>str_pad(dechex(ord($file['crc-32'][3])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][2])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][1])), 2, '0', STR_PAD_LEFT). + str_pad(dechex(ord($file['crc-32'][0])), 2, '0', STR_PAD_LEFT), + 'compressed_size'=>$dir['compressed_size'][1], + 'uncompressed_size'=>$dir['uncompressed_size'][1], + 'disk_number_start'=>$dir['disk_number_start'][1], + 'internal_attributes'=>$dir['internal_attributes'][1], + 'external_attributes1'=>$dir['external_attributes1'][1], + 'external_attributes2'=>$dir['external_attributes2'][1], + 'relative_offset'=>$dir['relative_offset'][1], + 'file_name'=>$dir['file_name'], + 'extra_field'=>$dir['extra_field'], + 'file_comment'=>$dir['file_comment'], + ); + } + + elseif($signature == $this->dirSignatureE){ + # $this->debugMsg(1, "EOF Dir Signature!"); + + $eodir['disk_number_this'] = unpack("v", fread($fh, 2)); // number of this disk + $eodir['disk_number'] = unpack("v", fread($fh, 2)); // number of the disk with the start of the central directory + $eodir['total_entries_this'] = unpack("v", fread($fh, 2)); // total number of entries in the central dir on this disk + $eodir['total_entries'] = unpack("v", fread($fh, 2)); // total number of entries in + $eodir['size_of_cd'] = unpack("V", fread($fh, 4)); // size of the central directory + $eodir['offset_start_cd'] = unpack("V", fread($fh, 4)); // offset of start of central directory with respect to the starting disk number + $zipFileCommentLenght = unpack("v", fread($fh, 2)); // zipfile comment length + $eodir['zipfile_comment'] = $zipFileCommentLenght[1]?fread($fh, $zipFileCommentLenght[1]):''; // zipfile comment + $this->endOfCentral = Array( + 'disk_number_this'=>$eodir['disk_number_this'][1], + 'disk_number'=>$eodir['disk_number'][1], + 'total_entries_this'=>$eodir['total_entries_this'][1], + 'total_entries'=>$eodir['total_entries'][1], + 'size_of_cd'=>$eodir['size_of_cd'][1], + 'offset_start_cd'=>$eodir['offset_start_cd'][1], + 'zipfile_comment'=>$eodir['zipfile_comment'], + ); + } + else{ + if(!$ddTry){ + $this->debugMsg(1, "Unexpected header. Trying to detect wrong placed 'Data Descriptor'...\n"); + $ddTry = true; + fseek($fh, 12-4, SEEK_CUR); // Jump over 'crc-32'(4) 'compressed-size'(4), 'uncompressed-size'(4) + continue; + } + $this->debugMsg(1, "Unexpected header, ending loop at offset ".ftell($fh)); + break; + } + $ddTry = false; + } + + if($this->debug){ + #------- Debug compressedList + $kkk = 0; + echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>"; + foreach($this->compressedList as $fileName=>$item){ + if(!$kkk && $kkk=1){ + echo "<tr style='background: #ADA'>"; + foreach($item as $fieldName=>$value) + echo "<td>$fieldName</td>"; + echo '</tr>'; + } + echo "<tr style='background: #CFC'>"; + foreach($item as $fieldName=>$value){ + if($fieldName == 'lastmod_datetime') + echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>"; + else + echo "<td title='$fieldName' nowrap='nowrap'>$value</td>"; + } + echo "</tr>"; + } + echo "</table>"; + + #------- Debug centralDirList + $kkk = 0; + if(sizeof($this->centralDirList)){ + echo "<table border='0' style='font: 11px Verdana; border: 1px solid #000'>"; + foreach($this->centralDirList as $fileName=>$item){ + if(!$kkk && $kkk=1){ + echo "<tr style='background: #AAD'>"; + foreach($item as $fieldName=>$value) + echo "<td>$fieldName</td>"; + echo '</tr>'; + } + echo "<tr style='background: #CCF'>"; + foreach($item as $fieldName=>$value){ + if($fieldName == 'lastmod_datetime') + echo "<td title='$fieldName' nowrap='nowrap'>".date("d/m/Y H:i:s", $value)."</td>"; + else + echo "<td title='$fieldName' nowrap='nowrap'>$value</td>"; + } + echo "</tr>"; + } + echo "</table>"; + } + + #------- Debug endOfCentral + $kkk = 0; + if(sizeof($this->endOfCentral)){ + echo "<table border='0' style='font: 11px Verdana' style='border: 1px solid #000'>"; + echo "<tr style='background: #DAA'><td colspan='2'>dUnzip - End of file</td></tr>"; + foreach($this->endOfCentral as $field=>$value){ + echo "<tr>"; + echo "<td style='background: #FCC'>$field</td>"; + echo "<td style='background: #FDD'>$value</td>"; + echo "</tr>"; + } + echo "</table>"; + } + } + + return $this->compressedList; + } + + + Function getExtraInfo($compressedFileName) + { + return + isset($this->centralDirList[$compressedFileName])? + $this->centralDirList[$compressedFileName]: + false; + } + + + Function getZipInfo($detail=false) + { + return $detail? + $this->endOfCentral[$detail]: + $this->endOfCentral; + } + + + Function unzip($compressedFileName, $targetFileName=false){ + $fdetails = &$this->compressedList[$compressedFileName]; + + if(!sizeof($this->compressedList)){ + $this->debugMsg(1, "Trying to unzip before loading file list... Loading it!"); + $this->getList(false, $compressedFileName); + } + if(!isset($this->compressedList[$compressedFileName])){ + $this->debugMsg(2, "File '<b>$compressedFileName</b>' is not compressed in the zip."); + return false; + } + if(substr($compressedFileName, -1) == "/"){ + $this->debugMsg(2, "Trying to unzip a folder name '<b>$compressedFileName</b>'."); + return false; + } + if(!$fdetails['uncompressed_size']){ + $this->debugMsg(1, "File '<b>$compressedFileName</b>' is empty."); + return ""; + } + + fseek($this->fh, $fdetails['contents-startOffset']); + return $this->uncompress( + fread($this->fh, $fdetails['compressed_size']), + $fdetails['compression_method'], + $fdetails['uncompressed_size'] ); + } + + + Function unzipAll($targetDir=false, $baseDir="", $maintainStructure=true, $chmod=false){ + if($targetDir === false) + $targetDir = dirname(__FILE__)."/"; + + $lista = $this->getList(); + if(sizeof($lista)) foreach($lista as $fileName=>$trash){ + $dirname = dirname($fileName); + $outDN = "$targetDir/$dirname"; + + if(substr($dirname, 0, strlen($baseDir)) != $baseDir) + continue; + + if(!is_dir($outDN) && $maintainStructure){ + $str = ""; + $folders = explode("/", $dirname); + foreach($folders as $folder){ + $str = $str?"$str/$folder":$folder; + if(!is_dir("$targetDir/$str")){ + $this->debugMsg(1, "Creating folder: $targetDir/$str"); + mkdir("$targetDir/$str"); + if($chmod) + chmod("$targetDir/$str", $chmod); + } + } + } + if(substr($fileName, -1, 1) == "/") + continue; + + $maintainStructure? + $this->unzip($fileName, "$targetDir/$fileName"): + $this->unzip($fileName, "$targetDir/".basename($fileName)); + + if($chmod) + chmod($maintainStructure?"$targetDir/$fileName":"$targetDir/".basename($fileName), $chmod); + } + } + + Function close(){ // Free the file resource + if($this->fh) + fclose($this->fh); + } + + // Private (you should NOT call these methods): + Function uncompress($content, $mode, $uncompressedSize, $targetFileName=false){ + switch($mode){ + case 0: + // Not compressed + return $content; + case 1: + $this->debugMsg(2, "Shrunk mode is not supported... yet?"); + return false; + case 2: + case 3: + case 4: + case 5: + $this->debugMsg(2, "Compression factor ".($mode-1)." is not supported... yet?"); + return false; + case 6: + $this->debugMsg(2, "Implode is not supported... yet?"); + return false; + case 7: + $this->debugMsg(2, "Tokenizing compression algorithm is not supported... yet?"); + return false; + case 8: + // Deflate + return gzinflate($content, $uncompressedSize); + case 9: + $this->debugMsg(2, "Enhanced Deflating is not supported... yet?"); + return false; + case 10: + $this->debugMsg(2, "PKWARE Date Compression Library Impoloding is not supported... yet?"); + return false; + default: + $this->debugMsg(2, "Unknown uncompress method: $mode"); + return false; + } + } + + + Function debugMsg($level, $string){ + if($this->debug) + if($level == 1) + echo "<b style='color: #777'>dUnzip2:</b> $string<br>"; + if($level == 2) + echo "<b style='color: #F00'>dUnzip2:</b> $string<br>"; + } +} +?>+ \ No newline at end of file diff --git a/util/ArchiveZip.class.php b/util/ArchiveZip.class.php @@ -0,0 +1,89 @@ +<?php + + +/** + * This source is taken from http://www.zend.com/zend/spotlight/creating-zip-files1.php + * Thank you! + */ +class ArchiveZip +{ + var $datasec = array(); + var $ctrl_dir = array(); + var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00"; + var $old_offset = 0; + + + function add_file($data, $name) + { + $name = str_replace("\\", "/", $name); + $unc_len = strlen($data); + $crc = crc32($data); + $zdata = gzcompress($data); + $zdate = substr ($zdata, 2, -4); + $c_len = strlen($zdata); + + + + $fr = "\x50\x4b\x03\x04"; + $fr .= "\x14\x00"; + $fr .= "\x00\x00"; + $fr .= "\x08\x00"; + $fr .= "\x00\x00\x00\x00"; + $fr .= pack("V",$crc); + $fr .= pack("V",$c_len); + $fr .= pack("V",$unc_len); + $fr .= pack("v", strlen($name) ); + $fr .= pack("v", 0 ); + $fr .= $name; + $fr .= $zdata; + $fr .= pack("V",$crc); + $fr .= pack("V",$c_len); + $fr .= pack("V",$unc_len); + + $this -> datasec[] = $fr; + + + + $new_offset = strlen(implode("", $this->datasec)); + + $cdrec = "\x50\x4b\x01\x02"; + $cdrec .="\x00\x00"; + $cdrec .="\x14\x00"; + $cdrec .="\x00\x00"; + $cdrec .="\x08\x00"; + $cdrec .="\x00\x00\x00\x00"; + $cdrec .= pack("V",$crc); + $cdrec .= pack("V",$c_len); + $cdrec .= pack("V",$unc_len); + $cdrec .= pack("v", strlen($name) ); + $cdrec .= pack("v", 0 ); + $cdrec .= pack("v", 0 ); + $cdrec .= pack("v", 0 ); + $cdrec .= pack("v", 0 ); + $cdrec .= pack("V", 32 ); + $cdrec .= pack("V", $this -> old_offset ); + + $this -> old_offset = $new_offset; + + $cdrec .= $name; + $this -> ctrl_dir[] = $cdrec; + } + + + function file() { + $data = implode("", $this -> datasec); + $ctrldir = implode("", $this -> ctrl_dir); + + return + $data. + $ctrldir. + $this -> eof_ctrl_dir. + pack("v", sizeof($this -> ctrl_dir)). + pack("v", sizeof($this -> ctrl_dir)). + pack("V", strlen($ctrldir)). + pack("V", strlen($data)). + "\x00\x00"; + } +} + +?>+ \ No newline at end of file diff --git a/util/Code.class.php b/util/Code.class.php @@ -0,0 +1,53 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// DaCMS Content Management System +// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.1 2004-12-15 23:14:21 dankert +// *** empty log message *** +// +// --------------------------------------------------------------------------- + +/** + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Code extends Dynamic +{ + var $code = ''; + + function execute() + { + if ( substr($this->code,0,5) != '<?php' ) + $this->code = "<?php\n".$this->code."\n?>"; + + $tmp = Object::getTempDir().'/openratDynamic'; + $tmp .= '.code.php.tmp'; + + $f = fopen( $tmp,'w' ); + fwrite( $f,$this->code ); + fclose( $f ); + + require( $tmp ); // Ausfuehren des temporaeren PHP-Codes + + unlink( $tmp ); + } +}+ \ No newline at end of file diff --git a/util/Dynamic.class.php b/util/Dynamic.class.php @@ -0,0 +1,149 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// DaCMS Content Management System +// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.4 2005-01-03 19:38:03 dankert +// Neue Methode outputLn +// +// Revision 1.3 2004/12/19 21:49:02 dankert +// Methode pathToObject() +// +// Revision 1.2 2004/12/19 15:25:12 dankert +// Anpassung Session-Funktionen +// +// Revision 1.1 2004/12/15 23:14:21 dankert +// *** empty log message *** +// +// Revision 1.5 2004/11/10 22:50:10 dankert +// Neue Methode execute() +// +// Revision 1.4 2004/10/06 09:53:39 dankert +// Benutzung auch nicht-statisch +// +// Revision 1.3 2004/05/03 20:21:34 dankert +// neu: setObjectId() +// +// Revision 1.2 2004/05/02 15:04:16 dankert +// Einf?gen package-name (@package) +// +// Revision 1.1 2004/04/24 17:03:29 dankert +// Initiale Version +// +// --------------------------------------------------------------------------- + +/** + * Service-Klasse fuer allgemeine Interface-Methoden. Insbesondere + * in Code-Elementen kann und soll auf diese Methoden zurueckgegriffen + * werden. + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Dynamic +{ + var $project; + var $output = ''; + var $objectid = 0; + var $page; + var $parameters = array(); + var $description = ''; + + + function db() + { + return db_connection(); + } + + function getObjectId() + { + return $this->objectid; + } + + function &getObject() + { + return Session::getObject(); + } + + function setObjectId( $objectid ) + { + $this->objectid = $objectid; + } + + function getRootObjectId() + { + $project = Session::getProject(); + return $project->getRootObjectId(); + } + + function folderid() + { + global $SESS; + return $SESS['folderid']; + } + + + function execute() + { + // overwrite this in subclasses + } + + function delOutput() + { + $this->output = ''; + } + + function output( $text ) + { + $this->output .= $text; + } + + function outputLn( $text ) + { + $this->output .= $text."\n"; + } + + + function getOutput() + { + return $this->output; + } + + function setSessionVar( $var,$value ) + { + Session::set( $var,$value ); + } + + + function getSessionVar( $var ) + { + return Session::get( $var ); + } + + + function pathToObject( $obj ) + { + if ( is_object($obj) ) + return $this->page->path_to_object($obj->objectid); + else + return $this->page->path_to_object($obj); + } + +}+ \ No newline at end of file diff --git a/util/FileUtils.class.php b/util/FileUtils.class.php @@ -0,0 +1,75 @@ +<?php + +/** + * Werkzeugklasse f�r Datei-Operationen. + * + */ +class FileUtils +{ + /** + * Fuegt einen Slash ("/") an das Ende an, sofern nicht bereits vorhanden. + * + * @param String $pfad + * @return Pfad mit angeh�ngtem Slash. + */ + function slashify($pfad) + { + if ( substr($pfad,-1,1) == '/') + return $pfad; + else + return $pfad.'/'; + } + + + /** + * Ermittelt das tempor�re Verzeichnis. + * + * @return String + */ + function getTempDir() + { + $tmpFilename = tempnam(ini_get('upload_tmp_dir'),"bla"); + @unlink($tmpFilename); + return FileUtils::slashify( dirname($tmpFilename) ); + } + + + + /** + * Liest die Dateien aus dem angegebenen Ordner in ein Array. + * + * @param $dir Verzeichnis, welches gelesen werden soll + * @return Array Liste der Dateien im Ordner + */ + function readDir($dir) + { + $dir = FileUtils::slashify($dir); + $dateien = array(); + + if ( !is_dir($dir) ) + { + return false; + } + + if ( $dh = opendir($dir) ) + { + while( ($verzEintrag = readdir($dh)) !== false ) + { + if ( substr($verzEintrag,0,1) != '.' ) + { + $dateien[] = $verzEintrag; + } + } + closedir($dh); + + return $dateien; + } + else + { + die('unable to open directory: '.$dir); + } + + } +} + +?>+ \ No newline at end of file diff --git a/util/Ftp.class.php b/util/Ftp.class.php @@ -0,0 +1,245 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Darstellen einer FTP-Verbindung, das beinhaltet + * das Login, das Kopieren von Dateien sowie praktische + * FTP-Funktionen + * + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Ftp +{ + var $verb; + var $url; + var $log = array(); + + var $passive = false; + + var $ok = true; + + + // Konstruktor + function Ftp( $url ) + { + $this->connect( $url ); + } + + + // Aufbauen der Verbindung + function connect( $url ) + { + $this->url = $url; + + global $conf; + + $conf_ftp = $conf['publish']['ftp']; + $ftp = parse_url( $this->url ); + + // Die projektspezifischen Werte gewinnen bei �berschneidungen mit den Default-Werten + $ftp = array_merge($conf_ftp,$ftp); + + // Nur FTP und FTPS (seit PHP 4.3) erlaubt + if ( !ereg('^ftps?$',$ftp['scheme']) ) + { + $this->log[] = 'Unknown scheme in FTP Url: '.$ftp['scheme']; + $this->log[] = 'Only FTP (and FTPS, if compiled in) are supported'; + $this->ok = false; + return; + } + + if ( function_exists('ftp_ssl_connect') && $ftp['scheme'] == 'ftps' ) + $this->verb = @ftp_ssl_connect( $ftp['host'],$ftp['port'] ); + else + $this->verb = @ftp_connect( $ftp['host'],$ftp['port'] ); + + if ( !$this->verb ) + { + $this->log[] = 'Cannot connect to '.$ftp['scheme'].'-server: '.$ftp['host'].':'.$ftp['port']; + $this->ok = false; + + Logger::error('Cannot connect to '.$ftp['host'].':'.$ftp['port']); + return; + } + + $this->log[] = 'Connected to FTP server '.$ftp['host'].':'.$ftp['port']; + + if ( empty($ftp['user']) ) + { + $ftp['user'] = 'anonymous'; + $ftp['pass'] = 'openrat@openrat.de'; + } + + if ( ! ftp_login( $this->verb,$ftp['user'],$ftp['pass'] ) ) + { + $this->log[] = 'Unable to login as user '.$ftp['user']; + $this->ok = false; + return; + } + + $this->log[] = 'Logged in as user '.$ftp['user']; + + $pasv = (!empty($ftp['fragment']) && $ftp['fragment'] == 'passive' ); + + $this->log[] = 'entering passive mode '.($pasv?'on':'off'); + if ( ! ftp_pasv($this->verb,true) ) + { + $this->log[] = 'cannot switch PASV mode'; + $this->ok = false; + return; + } + + if ( !empty($ftp['query']) ) + { + parse_str( $ftp['query'],$ftp_var ); + + if ( isset( $ftp_var['site'] ) ) + { + $site_commands = explode( ',',$ftp_var['site'] ); + foreach( $site_commands as $cmd ) + { + $this->log .= 'executing SITE command: '.$cmd; + + if ( ! @ftp_site( $this->verb,$cmd ) ) + { + $this->log[] = 'unable to do SITE command: '.$cmd; + $this->ok = false; + return; + } + } + } + } + + $this->path = ereg_replace( '\/$','',$ftp['path']); + + $this->log[] = 'Changing directory to '.$this->path; + + if ( ! @ftp_chdir( $this->verb,$this->path ) ) + { + $this->log[] = 'unable CHDIR to directory: '.$this->path; + $this->ok = false; + return; + } + } + + + /** + * Kopieren einer Datei vom lokalen System auf den FTP-Server. + * + * @param String Quelle + * @param String Ziel + * @param int FTP-Mode (BINARY oder ASCII) + */ + function put( $source,$dest ) + { + if ( ! $this->ok ) + return; + + $ftp = parse_url( $this->url ); + + $dest = $this->path.'/'.$dest; + + $this->log .= "Copying file: $source -&gt; $dest ...\n"; + + $mode = FTP_BINARY; + $p = strrpos( basename($dest),'.' ); // Letzten Punkt suchen + + if ($p!==false) // Wennn letzten Punkt gefunden, dann dort aufteilen + { + $extension = substr( basename($dest),$p+1 ); + $type = config('mime-types',$extension); + if ( substr($type,0,5) == 'text/') + $mode = FTP_ASCII; + } + + Logger::debug("FTP PUT target:$dest mode:".(($mode==FTP_ASCII)?'ascii':'binary')); + + if ( !@ftp_put( $this->verb,$dest,$source,$mode ) ) + { + if ( !$this->mkdirs( dirname($dest) ) ) + return; // Fehler. + + ftp_chdir( $this->verb,$this->path ); + + if ( ! @ftp_put( $this->verb,$dest,$source,$mode ) ) + { + $this->ok = false; + $this->log[] = 'FTP PUT failed...'; + $this->log[] = 'source : '.$source; + $this->log[] = 'destination: '.$dest; + return; + } + + } + } + + + + /** + * Private Methode zum rekursiven Anlegen von Verzeichnissen. + * + * @param String Pfad + * @return boolean true, wenn ok + */ + function mkdirs( $strPath ) + { + if ( @ftp_chdir($this->verb,$strPath) ) + return true; // Verzeichnis existiert schon :) + + $pStrPath = dirname($strPath); + + if ( !$this->mkdirs($pStrPath) ) + return false; + + if ( ! @ftp_mkdir($this->verb,$strPath) ) + { + $this->ok = false; + $this->log[] = "failed to create remote directory: $strPath"; + } + + return $this->ok; + } + + + + /** + * Schlie�en der FTP-Verbindung.<br> + * Sollte unbedingt aufgerufen werden, damit keine unn�tigen Sockets aufbleiben. + */ + function close() + { + if ( !$this->ok ) // Noch alles ok? + return; + + if ( ! @ftp_quit( $this->verb ) ) + { + // Das Schlie�en der Verbindung hat nicht funktioniert. + // Eigentlich k�nnten wir das ignorieren, aber wir sind anst�ndig und melden eine Fehler. + $this->log[] = 'failed to close connection'; + $this->ok = false; + return; + } + } +} + + +?>+ \ No newline at end of file diff --git a/util/GlobalFunctions.class.php b/util/GlobalFunctions.class.php @@ -0,0 +1,71 @@ +<?php + +/** + * Bereitstellen von globalen Funktionen + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class GlobalFunctions +{ + function getIsoCodes() + { + global $conf_php; + + $iso = parse_ini_file( './language/lang.ini.'.$conf_php ); + asort( $iso ); + return $iso; + } + + + function lang( $text ) + { + global $SESS; + $text = strtoupper($text); + + if ( isset( $SESS['lang'][$text] ) ) + { + return $SESS['lang'][$text]; + } + else + { + return( '?'.$text.'?' ); + } + } + + + # Spracheinstellungen laden + + function language_from_http() + { + global $SESS, + $HTTP_SERVER_VARS, + $conf_php, + $conf; + + $languages = $HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE']; + $languages = explode(',',$languages); + foreach( $languages as $l ) + { + $l = substr($l,0,2); + if ( file_exists("./language/$l.ini.$conf_php") ) + return( $l ); + } + + // Keine passende Sprache im HTTP-Header gefunden + return $conf['global']['default_language']; + } + + + function language_read( $l='' ) + { + global $SESS, + $HTTP_SERVER_VARS, + $conf_php; + + $l = language_from_http(); + $SESS['lang'] = parse_ini_file( "./language/$l.ini.$conf_php" ); + } +} + +?>+ \ No newline at end of file diff --git a/util/Html.class.php b/util/Html.class.php @@ -0,0 +1,146 @@ +<?php + +/** + * Bereitstellen von Methoden fuer die Darstellung von HTML-Elementen + * + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Html +{ + function error( $field ) + { + global $inputErrors; + + if ( isset($inputErrors[$field]) ) + return '<span class="error">'.lang($inputErrors[$field]).'</span'; + } + + + + /** + * Ausgabe eines Variablenwertes.<br> + */ + function debug( $wert, $text='' ) + { + echo "<strong>DEBUG: $text (".gettype($wert).")</strong><br/>"; + echo "<pre>"; + print_r($wert); + echo "</pre>"; + } + + + /** + * Erzeugt eine relative Url innerhalb von Openrat + * + * @param Aktion, die aufgerufen werden soll + * @param Unteraktion, die innerhalb der Aktion aufgerufen werden soll + * @param Id fuer diesen Aufruf + * @param Weitere beliebige Parameter + */ + function url( $action,$subaction='',$id='',$params=array() ) + { + if ( intval($id)==0 ) + $id='-'; + + global $conf; + + if ( is_array($action) ) + { + $params = $action; + + if ( isset($params['callAction']) ) + { + $params['subaction'] = $params['callAction']; + unset( $params['callAction'] ); + unset( $params['callSubaction'] ); + } + + + if ( !isset($params['action' ])) $params['action' ] = ''; + if ( !isset($params['subaction'])) $params['subaction'] = ''; + if ( !isset($params['id' ])) $params['id' ] = ''; + $action = $params['action' ]; + $subaction = $params['subaction']; + $id = $params['id' ]; + unset( $params['action' ] ); + unset( $params['subaction'] ); + unset( $params['id' ] ); + $params['old']='true'; + } + + // Session-Id ergaenzen + if ( $conf['interface']['url']['add_sessionid'] ) + $params[ session_name() ] = session_id(); + + $fake_urls = $conf['interface']['url']['fake_url' ]; + $url_format = $conf['interface']['url']['url_format']; + + if ( isset($params['objectid']) && !isset($params['id']) ) + $params['id'] = $params['objectid']; + + if ( $fake_urls ) + { +// if ( $id != '' ) +// $id = '.'.$id; + } + else + { + global $view; + $params[REQ_PARAM_ACTION ] = $action; + $params[REQ_PARAM_SUBACTION] = $subaction; + $params[REQ_PARAM_ID ] = $id; + + if ( !isset($params[REQ_PARAM_TARGET])) + $params[REQ_PARAM_TARGET ] = $view; + } + + if ( count($params) > 0 ) + { + $urlParameterList = array(); + foreach( $params as $var=>$value ) + { + $urlParameterList[] = urlencode($var).'='.urlencode($value); + } + $urlParameter = '?'.implode('&amp;',$urlParameterList); + } + else + { + $urlParameter = ''; + } + + if ( @$conf['interface']['url']['index'] ) + $controller_file_name = ''; + else + $controller_file_name = OR_CONTROLLER_FILE.'.'.PHP_EXT; + + $prefix = './'; + + if ( $fake_urls ) + $src = sprintf( $url_format,$action,$subaction,$id,session_id() ).$urlParameter; + else + $src = $prefix.$controller_file_name.$urlParameter; + + return $src; + } + + + + function open_tag($tagname,$attributes) + { + $text = '<'.$tagname; + foreach( $attributes as $attribute_name=>$attribute_value ) + if ( !empty($attribute_value) ) + $text .= ' '.$attribute_name.'="'.$attribute_value.'"'; + $text .= '>'; + return $text; + } + + + function close_tag($tagname) + { + return '</'.$tagname.'>'; + } +} +?>+ \ No newline at end of file diff --git a/util/Http.class.php b/util/Http.class.php @@ -0,0 +1,498 @@ +<?php + +/** + * Kapselung einer HTTP-Anfrage.<br> + * Unter Beruecksichtigung von RFC 1945.<br> + * + * @author Jan Dankert + * @package openrat.services + */ +class Http +{ + var $url = array(); + var $header = array(); + var $responseHeader = array(); + var $requestParameter = array(); + var $urlParameter = array(); + + /** + * HTTP-Request-Typ.<br> + * Muss entweder "GET" oder "POST" sein.<br> + * Default: "GET". + * + * @var String Request-Typ + */ + var $method = 'GET'; + var $error = ''; + var $status = ''; + var $body = ''; + + var $httpCmd = ''; + + + + /** + * Erzeugt eine HTTP-Anfrage. + * + * @param String URL + * @return Http + */ + function Http( $url = '' ) + { + $this->setURL( $url ); + $this->header['User-Agent'] = 'Mozilla/5.0 (OpenRat CMS)'; + $this->header['Connection'] = 'close'; + } + + + + /** + * Setzt die URL. + * + * @param String URL + */ + function setURL( $url ) + { + $this->url = parse_url($url); + + if ( empty($this->url['host']) && !empty($this->url['path']) ) + { + $this->url['host'] = basename($this->url['path']); + $this->url['path'] = '/'; + } + + if ( empty($this->url['path']) ) + $this->url['path'] = '/'; + + if ( !isset($this->url['port']) ) + if ( !isset($this->url['scheme']) ) + { + $this->url['scheme'] = 'http'; // Standard-Port. + $this->url['port'] = 80; // Standard-Port. + } + elseif ( $this->url['scheme'] == 'https' ) + $this->url['port'] = 443; // SSL-Port. + else + $this->url['port'] = 80; // Standard-Port. + + if ( !empty($this->url['query']) ) + parse_str( $this->url['query'],$this->urlParameter ); + + } + + + + /** + * Setzt Authentisierungsinformationen in den HTTP-Request.<br> + * + * @param String Benutzername + * @param String Kennwort + */ + function setBasicAuthentication( $user, $password ) + { + $this->header['Authorization'] = 'Basic '.base64_encode($user.':'.$password); + } + + + + /** + * Erzeugt eine Zeichenkette mit allen Parametern. + * @param withPraefixQuestionMark Praefix mit Fragezeichen (f�r GET-Anfragen) + * @return String URL-Parameter + */ + function getParameterString( $withPraefixQuestionMark=false ) + { + $parameterString = ''; + $parameter = $this->urlParameter + $this->requestParameter; + + if ( ! empty($parameter) ) + { + foreach( $this->requestParameter as $paramName => $paramValue ) + { + if ( strlen($parameterString) > 0) + $parameterString .= '&'; + elseif ( $withPraefixQuestionMark ) + $parameterString .= '?'; + + $parameterString .= urlencode($paramName) . '=' .urlencode($paramValue); + } + } + + return $parameterString; + } + + + /** + * Sendet eine Redirect-Anweisung an den Browser. + * @return String URL + */ + function getUrl() + { + $location = $this->url['scheme']; + $location .= '://'; + $location .= $this->url['host']; + if ( $this->url['scheme'] == 'http' && $this->url['port'] != 80 || + $this->url['scheme'] == 'https' && $this->url['port'] != 443 ) + $location .= ':'.$this->url['port']; + $location .= $this->url['path']; + + $location .= $this->getParameterString(true); + + if ( isset($this->url['fragment']) ) + $location .= '#'.$this->url['fragment']; + + return $location; + } + + + /** + * Sendet eine Redirect-Anweisung mit der aktuellen URL an den Browser. + */ + function sendRedirect() + { + $location = $this->getUrl(); + + header('Location: '.$location); + exit; + } + + + /** + * Erzeugt den HTTP-Request + * + * @return boolean Erfolg der Anfrage. + */ + function request() + { + $this->error = ''; + $this->status = ''; + + $errno = 0; + $errstr = ''; + + if ( empty($this->url['host']) ) + { + $this->error = "No hostname specified"; + return false; + } + + foreach( $this->header as $header_key=>$header_value ) + { + if ( is_numeric( $header_key ) ) + { + $dp = strpos($header_value,':'); + if ( $dp!==FALSE) + $this->header[substr($header_value,0,$dp)] = substr($header_value,$dp+1); + unset($this->header[$header_key]); + } + } + + $parameterString = $this->getParameterString(); + + if ( $this->method == 'POST' ) + { + $this->header['Content-Type' ] = 'application/x-www-form-urlencoded'; + $this->header['Content-Length'] = strlen($parameterString); + } + + // Accept-Header setzen, falls noch nicht vorhanden. + if ( !array_key_exists('Accept',$this->header) ) + $this->header['Accept'] = '*/*'; + + $this->responseHeader = array(); + + // RFC 1945 (Section 9.3) says: + // A user agent should never automatically redirect a request + // more than 5 times, since such redirections usually indicate an infinite loop. + for( $r=1; $r<=5; $r++ ) + { + $this->header['Host'] = $this->url['host']; + + // Die Funktion fsockopen() erwartet eine Protokollangabe (bei TCP optional, bei SSL notwendig). + if ( $this->url['scheme'] == 'https' || $this->url['port'] == '443' ) + $prx_proto = 'ssl://'; // SSL + else + $prx_proto = 'tcp://'; // Default + + $fp = @fsockopen ($prx_proto.$this->url['host'],$this->url['port'], $errno, $errstr, 30); + + if ( !$fp || !is_resource($fp) ) + { + // Keine Verbindung zum Host moeglich. + $this->error = "Connection refused: '".$prx_proto.$this->url['host'].':'.$this->url['port']." - $errstr ($errno)"; + return false; + } + else + { + + $lb = "\r\n"; + $http_get = $this->url['path']; + + $request_header = array( $this->method.' '.$http_get.' HTTP/1.0'); + + foreach($this->header as $header_key=>$header_value) + $request_header[] = $header_key.': '.$header_value; + + $http_request = implode($lb,$request_header).$lb.$lb; + + if ( $this->method == 'GET') + if ( !empty($parameterString) ) + $http_get .= '?'.$parameterString; + + if ( $this->method == 'POST' ) + $http_request .= $parameterString; + + if (!is_resource($fp)) { + $this->error = 'Connection lost after connect: '.$prx_proto.$this->url['host'].':'.$this->url['port']; + return false; + } + fputs($fp, $http_request); // Die HTTP-Anfrage zum Server senden. + + // Jetzt erfolgt das Auslesen der HTTP-Antwort. + $isHeader = true; + + // RFC 1945 (Section 6.1) schreibt als Statuszeile folgendes Format vor + // "HTTP/" 1*DIGIT "." 1*DIGIT SP 3DIGIT SP + if (!is_resource($fp)) { + $this->error = 'Connection lost during transfer: '.$this->url['host'].':'.$this->url['port']; + return false; + } + elseif (!feof($fp)) { + $line = fgets($fp,1028); + $this->status = substr($line,9,3); + } + else + { + $this->error = 'Unexpected EOF while reading HTTP-Response'; + return false; + } + + $this->body = ''; + while (!feof($fp)) { + $line = fgets($fp,1028); + if ( $isHeader && trim($line)=='' ) // Leerzeile nach Header. + { + $isHeader = false; + } + elseif( $isHeader ) + { + list($headerName,$headerValue) = explode(': ',$line) + array(1=>''); + $this->responseHeader[$headerName] = trim($headerValue); + } + else + { + $this->body .= $line; + } + } + fclose($fp); // Verbindung brav schlie�en. + + + // RFC 1945 (Section 6.1.1) schreibt + // "[...] However, applications must understand the class of any status code, as + // indicated by the first digit" + // Daher interessiert uns nur die erste Stelle des 3-stelligen HTTP-Status. + + // 301 Moved Permanently + // 302 Moved Temporarily + if ( $this->status == '301' || + $this->status == '302' ) + { + $location = @$this->responseHeader['Location']; + if ( empty($location) ) + { + $this->error = '301/302 Response without Location-header'; + return false; + } + + //Html::debug($this->url,"alte URL"); + //Html::debug($location,"NEUES REDIRECT AUF"); + $this->setURL($location); + continue; // Naechster Versuch mit umgeleiteter Adresse. + } + + // RFC 1945 (Section 6.1.1) schreibt + // "2xx: Success - The action was successfully received, understood, and accepted." + elseif ( substr($this->status,0,1) == '2' ) + { + return true; + } + elseif ( substr($this->status,0,1) == '4' ) + { + $this->error = 'Client Error: '.$this->status; + return false; + } + elseif ( substr($this->status,0,1) == '5' ) + { + $this->error = 'Server Error: '.$this->status; + return false; + } + else + { + $this->error = 'Unexpected HTTP-Status: '.$this->status. '; this is mostly a client error, sorry.'; + return false; + } + } + + $this->error = 'Too much redirects, infinite loop assumed. Exiting. Last URL: '.$http_get; + return false; + + } + + } + + + /** + * Aus dem HTTP-Header werden die vom Browser angeforderten Sprachen + * gelesen.<br> + * Es wird eine Liste von Sprachen erzeugt.<br> + * Beispiel: 'de_DE','de','en_GB','en' ... usw.<br> + * Wenn der Browser 'de_DE' anfordert, wird hier auch 'de' (als Fallback) ermittelt. + * + * @static + * @return Array + */ + function getLanguages() + { + global $HTTP_SERVER_VARS; + + $languages = array(); + $http_languages = @$HTTP_SERVER_VARS['HTTP_ACCEPT_LANGUAGE']; + foreach( explode(',',$http_languages) as $l ) + { + list($part) = explode(';',$l); // Priorit�ten ignorieren. + $languages[] = trim($part); + + // Aus "de_DE" das "de" extrahieren. + $languages[] = current(explode('_',str_replace('-','_',trim($part)))); + } + + return array_unique( $languages ); + } + + + /** + * Ermittelt die aktuelle URL des Requests (ohne Datei). + * + * @static + * @return String URL + */ + function getServer() + { + $https = getenv('HTTPS'); + + if ( $https ) + $server = 'https://'; + else + $server = 'http://'; + + $server .= getenv('SERVER_NAME').dirname(getenv('REQUEST_URI')); + + return $server; + } + + + + /** + * Server-Fehlermeldung anzeigen.<br> + * + * Erzeugt einen "HTTP 501 Internal Server Error". Zu�tzlich + * wird ein 'rollback' auf der Datenbank ausgef�hrt. + * + * @param String $message Eigener Hinweistext + */ + function serverError($message,$reason='') + { + $db = db_connection(); + if ( is_object( $db ) ) + $db->rollback(); + + Http::sendStatus(501,'Internal Server Error',$message,$reason); + } + + + + /** + * Der Benutzer ist nicht autorisiert, eine Aktion auszufuehren. + * Diese Funktion erzeugt einen "HTTP 403 Not Authorized" und das + * Skript wird beendet. + * + * @param String $message Eigener Hinweistext + */ + function notAuthorized($message) + { + + Http::sendStatus(403,'Not Authorized',$message); + } + + + + /** + * Schickt einen HTTP-Status zum Client und beendet das Skript. + * + * @param Integer $status HTTP-Status + * @param String $text HTTP-Meldung + * @param String $message Eigener Hinweistext + */ + function sendStatus( $status=501,$text='Internal Server Error',$message='',$reason='' ) + { + if ( headers_sent() ) + { + echo "$status $text\n$message"; + exit; + } + + header('HTTP/1.0 '.intval($status).' '.$text); + + + $types = Http::getAccept(); + + if ( sizeof($types)==1 && in_array('application/json',$types) ) + { + header('Content-Type: application/json'); + require_once( OR_SERVICECLASSES_DIR."JSON.class.".PHP_EXT ); + $json = new JSON(); + echo $json->encode( array('status'=>$status,'error'=>$text,'description'=>$message) ); + } + elseif ( sizeof($types)==1 && in_array('application/xml',$types) ) + { + header('Content-Type: application/xml'); + require_once( OR_SERVICECLASSES_DIR."XML.class.".PHP_EXT ); + $xml = new XML(); + $xml->root='error'; + echo $xml->encode( array('status'=>$status,'error'=>$text,'description'=>$message) ); + } + else + { + header('Content-Type: text/html'); + $message = htmlentities($message); + $reason = htmlentities($reason ); + $signature = OR_TITLE.' '.OR_VERSION.' '.getenv('SERVER_SOFTWARE'); + echo <<<HTML +<html> +<head><title>$status $text - OpenRat</title></head> +<body> +<h1>$text</h1> +<p>$message</p> +<pre>$reason</pre> +<hr> +<address>$signature</adddress> +</body> +</html> +HTML; + } + exit; + } + + + /** + * + * @return Array Mime-Typen, welche vom User-Agent akzeptiert werden. + */ + function getAccept() + { + $httpAccept = getenv('HTTP_ACCEPT'); + return $types = explode(',',$httpAccept); + } +} + +?>+ \ No newline at end of file diff --git a/util/JSON.class.php b/util/JSON.class.php @@ -0,0 +1,809 @@ +<?php +/** + * Converts to and from JSON format. + * + * JSON (JavaScript Object Notation) is a lightweight data-interchange + * format. It is easy for humans to read and write. It is easy for machines + * to parse and generate. It is based on a subset of the JavaScript + * Programming Language, Standard ECMA-262 3rd Edition - December 1999. + * This feature can also be found in Python. JSON is a text format that is + * completely language independent but uses conventions that are familiar + * to programmers of the C-family of languages, including C, C++, C#, Java, + * JavaScript, Perl, TCL, and many others. These properties make JSON an + * ideal data-interchange language. + * + * This package provides a simple encoder and decoder for JSON notation. It + * is intended for use with client-side Javascript applications that make + * use of HTTPRequest to perform server communication functions - data can + * be encoded into JSON notation for use in a client-side javascript, or + * decoded from incoming Javascript requests. JSON format is native to + * Javascript, and can be directly eval()'ed with no further parsing + * overhead + * + * All strings should be in ASCII or UTF-8 format! + * + * LICENSE: 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. + * + * THIS SOFTWARE IS PROVIDED ``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 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. + * + * @category + * @package Services_JSON + * @author Michal Migurski <mike-json@teczno.com> + * @author Matt Knapp <mdknapp[at]gmail[dot]com> + * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> + * @author Jan Dankert + * @copyright 2005 Michal Migurski + * @version CVS: $Id$ + * @license http://www.opensource.org/licenses/bsd-license.php + * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 + */ + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_INDENT', "\t"); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_SLICE', 1); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_STR', 2); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_ARR', 3); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_OBJ', 4); + +/** + * Marker constant for Services_JSON::decode(), used to flag stack state + */ +define('SERVICES_JSON_IN_CMT', 5); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_LOOSE_TYPE', 16); + +/** + * Behavior switch for Services_JSON::decode() + */ +define('SERVICES_JSON_SUPPRESS_ERRORS', 32); + +/** + * Converts to and from JSON format. + * + * Brief example of use: + * + * <code> + * // create a new instance of Services_JSON + * $json = new Services_JSON(); + * + * // convert a complexe value to JSON notation, and send it to the browser + * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); + * $output = $json->encode($value); + * + * print($output); + * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] + * + * // accept incoming POST data, assumed to be in JSON notation + * $input = file_get_contents('php://input', 1000000); + * $value = $json->decode($input); + * </code> + */ +class JSON +{ + /** + * constructs a new JSON instance + * + * @param int $use object behavior flags; combine with boolean-OR + * + * possible values: + * - SERVICES_JSON_LOOSE_TYPE: loose typing. + * "{...}" syntax creates associative arrays + * instead of objects in decode(). + * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. + * Values which can't be encoded (e.g. resources) + * appear as NULL instead of throwing errors. + * By default, a deeply-nested resource will + * bubble up with an error, so all return values + * from encode() should be checked with isError() + */ + function Services_JSON() + { + $this->use = SERVICES_JSON_LOOSE_TYPE; + } + + /** + * convert a string from one UTF-16 char to one UTF-8 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf16 UTF-16 character + * @return string UTF-8 character + * @access private + */ + function utf162utf8($utf16) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); + } + + $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); + + switch(true) { + case ((0x7F & $bytes) == $bytes): + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x7F & $bytes); + + case (0x07FF & $bytes) == $bytes: + // return a 2-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xC0 | (($bytes >> 6) & 0x1F)) + . chr(0x80 | ($bytes & 0x3F)); + + case (0xFFFF & $bytes) == $bytes: + // return a 3-byte UTF-8 character + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0xE0 | (($bytes >> 12) & 0x0F)) + . chr(0x80 | (($bytes >> 6) & 0x3F)) + . chr(0x80 | ($bytes & 0x3F)); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * convert a string from one UTF-8 char to one UTF-16 char + * + * Normally should be handled by mb_convert_encoding, but + * provides a slower PHP-only method for installations + * that lack the multibye string extension. + * + * @param string $utf8 UTF-8 character + * @return string UTF-16 character + * @access private + */ + function utf82utf16($utf8) + { + // oh please oh please oh please oh please oh please + if(function_exists('mb_convert_encoding')) { + return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); + } + + switch(strlen($utf8)) { + case 1: + // this case should never be reached, because we are in ASCII range + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return $utf8; + + case 2: + // return a UTF-16 character from a 2-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr(0x07 & (ord($utf8{0}) >> 2)) + . chr((0xC0 & (ord($utf8{0}) << 6)) + | (0x3F & ord($utf8{1}))); + + case 3: + // return a UTF-16 character from a 3-byte UTF-8 char + // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + return chr((0xF0 & (ord($utf8{0}) << 4)) + | (0x0F & (ord($utf8{1}) >> 2))) + . chr((0xC0 & (ord($utf8{1}) << 6)) + | (0x7F & ord($utf8{2}))); + } + + // ignoring UTF-32 for now, sorry + return ''; + } + + /** + * encodes an arbitrary variable into JSON format + * + * @param mixed $var any number, boolean, string, array, or object to be encoded. + * see argument 1 to Services_JSON() above for array-parsing behavior. + * if var is a strng, note that encode() always expects it + * to be in ASCII or UTF-8 format! + * + * @return mixed JSON string representation of input var or an error if a problem occurs + * @access public + */ + function encode($var) + { + static $indentNr = 0; + + $indent = str_repeat(SERVICES_JSON_INDENT,$indentNr); + + switch (gettype($var)) { + case 'boolean': + return $var ? 'true' : 'false'; + + case 'NULL': + return 'null'; + + case 'integer': + return (int) $var; + + case 'double': + case 'float': + return (float) $var; + + case 'string': + // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT + $ascii = ''; + $strlen_var = strlen($var); + + /* + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ + for ($c = 0; $c < $strlen_var; ++$c) { + + $ord_var_c = ord($var{$c}); + + switch (true) { + case $ord_var_c == 0x08: + $ascii .= '\b'; + break; + case $ord_var_c == 0x09: + $ascii .= '\t'; + break; + case $ord_var_c == 0x0A: + $ascii .= '\n'; + break; + case $ord_var_c == 0x0C: + $ascii .= '\f'; + break; + case $ord_var_c == 0x0D: + $ascii .= '\r'; + break; + + case $ord_var_c == 0x22: + case $ord_var_c == 0x2F: + case $ord_var_c == 0x5C: + // double quote, slash, slosh + $ascii .= '\\'.$var{$c}; + break; + + case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): + // characters U-00000000 - U-0000007F (same as ASCII) + $ascii .= $var{$c}; + break; + + case (($ord_var_c & 0xE0) == 0xC0): + // characters U-00000080 - U-000007FF, mask 110XXXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, ord($var{$c + 1})); + $c += 1; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF0) == 0xE0): + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2})); + $c += 2; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xF8) == 0xF0): + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3})); + $c += 3; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFC) == 0xF8): + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4})); + $c += 4; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + + case (($ord_var_c & 0xFE) == 0xFC): + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $char = pack('C*', $ord_var_c, + ord($var{$c + 1}), + ord($var{$c + 2}), + ord($var{$c + 3}), + ord($var{$c + 4}), + ord($var{$c + 5})); + $c += 5; + $utf16 = $this->utf82utf16($char); + $ascii .= sprintf('\u%04s', bin2hex($utf16)); + break; + } + } + + return '"'.$ascii.'"'; + + case 'array': + /* + * As per JSON spec if any array key is not an integer + * we must treat the the whole array as an object. We + * also try to catch a sparsely populated associative + * array with numeric keys here because some JS engines + * will create an array with empty indexes up to + * max_index which can cause memory issues and because + * the keys, which may be relevant, will be remapped + * otherwise. + * + * As per the ECMA and JSON specification an object may + * have any string as a property. Unfortunately due to + * a hole in the ECMA specification if the key is a + * ECMA reserved word or starts with a digit the + * parameter is only accessible using ECMAScript's + * bracket notation. + */ + + // treat as a JSON object + if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { + $indentNr++; + $properties = array_map(array($this, 'name_value'), + array_keys($var), + array_values($var)); + $indentNr--; + + foreach($properties as $property) { + if(JSON::isError($property)) { + return $property; + } + } + + return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) ."\n$indent".'}'."\n$indent"; + } + + // treat it like a regular array + $indentNr++; + $elements = array_map(array($this, 'encode'), $var); + $indentNr--; + + foreach($elements as $element) { + if(JSON::isError($element)) { + return $element; + } + } + + return "\n$indent".'['."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $elements) . "\n$indent".']'."\n$indent"; + + case 'object': + $vars = get_object_vars($var); + + $indentNr++; + $properties = array_map(array($this, 'name_value'), + array_keys($vars), + array_values($vars)); + $indentNr--; + + foreach($properties as $property) { + if(JSON::isError($property)) { + return $property; + } + } + + return "\n$indent".'{' ."\n$indent".SERVICES_JSON_INDENT. join(','."\n$indent".SERVICES_JSON_INDENT, $properties) . "\n$indent".'}'."\n$indent"; + + default: + return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) + ? 'null' + : new JSON_Error(gettype($var)." can not be encoded as JSON string"); + } + } + + + + /** + * array-walking function for use in generating JSON-formatted name-value pairs + * + * @param string $name name of key to use + * @param mixed $value reference to an array element to be encoded + * + * @return string JSON-formatted name-value pair, like '"name":value' + * @access private + */ + function name_value($name, $value ) + { + $encoded_value = $this->encode($value); + + if(JSON::isError($encoded_value)) { + return $encoded_value; + } + + return $this->encode(strval($name)) . ':' . $encoded_value; + } + + /** + * reduce a string by removing leading and trailing comments and whitespace + * + * @param $str string string value to strip of comments and whitespace + * + * @return string string value stripped of comments and whitespace + * @access private + */ + function reduce_string($str) + { + $str = preg_replace(array( + + // eliminate single line comments in '// ...' form + '#^\s*//(.+)$#m', + + // eliminate multi-line comments in '/* ... */' form, at start of string + '#^\s*/\*(.+)\*/#Us', + + // eliminate multi-line comments in '/* ... */' form, at end of string + '#/\*(.+)\*/\s*$#Us' + + ), '', $str); + + // eliminate extraneous space + return trim($str); + } + + /** + * decodes a JSON string into appropriate variable + * + * @param string $str JSON-formatted string + * + * @return mixed number, boolean, string, array, or object + * corresponding to given JSON input string. + * See argument 1 to Services_JSON() above for object-output behavior. + * Note that decode() always returns strings + * in ASCII or UTF-8 format! + * @access public + */ + function decode($str) + { + $str = $this->reduce_string($str); + + switch (strtolower($str)) { + case 'true': + return true; + + case 'false': + return false; + + case 'null': + return null; + + default: + $m = array(); + + if (is_numeric($str)) { + // Lookie-loo, it's a number + + // This would work on its own, but I'm trying to be + // good about returning integers where appropriate: + // return (float)$str; + + // Return float or int, as appropriate + return ((float)$str == (integer)$str) + ? (integer)$str + : (float)$str; + + } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { + // STRINGS RETURNED IN UTF-8 FORMAT + $delim = substr($str, 0, 1); + $chrs = substr($str, 1, -1); + $utf8 = ''; + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c < $strlen_chrs; ++$c) { + + $substr_chrs_c_2 = substr($chrs, $c, 2); + $ord_chrs_c = ord($chrs{$c}); + + switch (true) { + case $substr_chrs_c_2 == '\b': + $utf8 .= chr(0x08); + ++$c; + break; + case $substr_chrs_c_2 == '\t': + $utf8 .= chr(0x09); + ++$c; + break; + case $substr_chrs_c_2 == '\n': + $utf8 .= chr(0x0A); + ++$c; + break; + case $substr_chrs_c_2 == '\f': + $utf8 .= chr(0x0C); + ++$c; + break; + case $substr_chrs_c_2 == '\r': + $utf8 .= chr(0x0D); + ++$c; + break; + + case $substr_chrs_c_2 == '\\"': + case $substr_chrs_c_2 == '\\\'': + case $substr_chrs_c_2 == '\\\\': + case $substr_chrs_c_2 == '\\/': + if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || + ($delim == "'" && $substr_chrs_c_2 != '\\"')) { + $utf8 .= $chrs{++$c}; + } + break; + + case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): + // single, escaped unicode character + $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) + . chr(hexdec(substr($chrs, ($c + 4), 2))); + $utf8 .= $this->utf162utf8($utf16); + $c += 5; + break; + + case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): + $utf8 .= $chrs{$c}; + break; + + case ($ord_chrs_c & 0xE0) == 0xC0: + // characters U-00000080 - U-000007FF, mask 110XXXXX + //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 2); + ++$c; + break; + + case ($ord_chrs_c & 0xF0) == 0xE0: + // characters U-00000800 - U-0000FFFF, mask 1110XXXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 3); + $c += 2; + break; + + case ($ord_chrs_c & 0xF8) == 0xF0: + // characters U-00010000 - U-001FFFFF, mask 11110XXX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 4); + $c += 3; + break; + + case ($ord_chrs_c & 0xFC) == 0xF8: + // characters U-00200000 - U-03FFFFFF, mask 111110XX + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 5); + $c += 4; + break; + + case ($ord_chrs_c & 0xFE) == 0xFC: + // characters U-04000000 - U-7FFFFFFF, mask 1111110X + // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 + $utf8 .= substr($chrs, $c, 6); + $c += 5; + break; + + } + + } + + return $utf8; + + } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { + // array, or object notation + + if ($str{0} == '[') { + $stk = array(SERVICES_JSON_IN_ARR); + $arr = array(); + } else { + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = array(); + } else { + $stk = array(SERVICES_JSON_IN_OBJ); + $obj = new stdClass(); + } + } + + array_push($stk, array('what' => SERVICES_JSON_SLICE, + 'where' => 0, + 'delim' => false)); + + $chrs = substr($str, 1, -1); + $chrs = $this->reduce_string($chrs); + + if ($chrs == '') { + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } else { + return $obj; + + } + } + + //print("\nparsing {$chrs}\n"); + + $strlen_chrs = strlen($chrs); + + for ($c = 0; $c <= $strlen_chrs; ++$c) { + + $top = end($stk); + $substr_chrs_c_2 = substr($chrs, $c, 2); + + if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { + // found a comma that is not inside a string, array, etc., + // OR we've reached the end of the character list + $slice = substr($chrs, $top['where'], ($c - $top['where'])); + array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); + //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + // we are in an array, so just push an element onto the stack + array_push($arr, $this->decode($slice)); + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + // we are in an object, so figure + // out the property name and set an + // element in an associative array, + // for now + $parts = array(); + + if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // "name":value pair + $key = $this->decode($parts[1]); + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { + // name:value pair, where name is unquoted + $key = $parts[1]; + $val = $this->decode($parts[2]); + + if ($this->use & SERVICES_JSON_LOOSE_TYPE) { + $obj[$key] = $val; + } else { + $obj->$key = $val; + } + } + + } + + } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { + // found a quote, and we are not inside a string + array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); + //print("Found start of string at {$c}\n"); + + } elseif (($chrs{$c} == $top['delim']) && + ($top['what'] == SERVICES_JSON_IN_STR) && + ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { + // found a quote, we're in a string, and it's not escaped + // we know that it's not escaped becase there is _not_ an + // odd number of backslashes at the end of the string so far + array_pop($stk); + //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '[') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-bracket, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); + //print("Found start of array at {$c}\n"); + + } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { + // found a right-bracket, and we're in an array + array_pop($stk); + //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($chrs{$c} == '{') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a left-brace, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); + //print("Found start of object at {$c}\n"); + + } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { + // found a right-brace, and we're in an object + array_pop($stk); + //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } elseif (($substr_chrs_c_2 == '/*') && + in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { + // found a comment start, and we are in an array, object, or slice + array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); + $c++; + //print("Found start of comment at {$c}\n"); + + } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { + // found a comment end, and we're in one now + array_pop($stk); + $c++; + + for ($i = $top['where']; $i <= $c; ++$i) + $chrs = substr_replace($chrs, ' ', $i, 1); + + //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); + + } + + } + + if (reset($stk) == SERVICES_JSON_IN_ARR) { + return $arr; + + } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { + return $obj; + + } + + } + } + } + + /** + * @todo Ultimately, this should just call PEAR::isError() + */ + function isError($data, $code = null) + { + if (class_exists('pear')) { + return PEAR::isError($data, $code); + } elseif (is_object($data) && (get_class($data) == 'json_error' || + is_subclass_of($data, 'json_error'))) { + return true; + } + + return false; + } +} + + + /** + * @todo Ultimately, this class shall be descended from PEAR_Error + */ + class JSON_Error + { + function JSON_Error($message = 'unknown error', $code = null, + $mode = null, $options = null, $userinfo = null) + { + + } + } + + +?> diff --git a/util/Ldap.class.php b/util/Ldap.class.php @@ -0,0 +1,184 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Bereitstellen von LDAP-Funktionen. + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Ldap +{ + var $connection; + var $timeout; + var $aliases; + + + /** + * + */ + function Ldap() + { + global $conf; + + $this->timeout = intval($conf['ldap']['search']['timeout']); + + if ( $conf['ldap']['search']['aliases'] ) + $this->aliases = LDAP_DEREF_ALWAYS; + else + $this->aliases = LDAP_DEREF_NEVER; + } + + + + /** + * Verbindung �ffnen. + */ + function connect() + { + global $conf; + + $ldapHost = $conf['ldap']['host']; + $ldapPort = $conf['ldap']['port']; + + // Verbindung zum LDAP-Server herstellen + $this->connection = @ldap_connect( $ldapHost,$ldapPort ); + + // siehe http://bugs.php.net/bug.php?id=15637 + // Unter bestimmten Bedingungen wird trotz nicht erreichbarem LDAP-Server eine PHP-Resource + // zurueck gegeben. Dann erscheint zwar keine Fehlermeldung, aber zumindestens misslingt + // der nachfolgende Bind-Befehl. + if ( !is_resource($this->connection) || $this->connection === false ) + { + Logger::error( "connect to ldap server '$ldapHost:$ldapPort' failed" ); + // Abbruch, wenn LDAP-Server nicht erreichbar + die( "Connection failed to $ldapHost:$ldapPort (".ldap_errno().'/'.ldap_error().'). Please contact your administrator.' ); + } + + // Protokollversion setzen. + $j = ldap_set_option( $this->connection, LDAP_OPT_PROTOCOL_VERSION,intval($conf['ldap']['protocol']) ); + if ( ! $j ) + die( 'LDAP error while setting protocol version'.ldap_errno().'/'.ldap_error().')' ); + + } + + + + /** + * Ein Binding auf den LDAP-Server durchf�hren. + */ + function bind( $user,$pw ) + { + return @ldap_bind( $this->connection,$user,$pw); + } + + + + /** + * Ein Binding auf den LDAP-Server durchf�hren. + */ + function bindAnonymous() + { + return @ldap_bind( $this->connection ); + } + + + + /** + * Das Bindung wird entfernt. + */ + function unbind() + { + ldap_unbind( $this->connection ); + } + + + + /** + * Eine Suche auf den LDAP-Server durchf�hren. + */ + function searchUser( $username ) + { + global $conf; + + $techUser = $conf['ldap']['search']['user']; + $techPass = $conf['ldap']['search']['password']; + + if ( $conf['ldap']['search']['anonymous'] ) + $this->bindAnonymous(); + else + $this->bind( $techUser, $techPass ); + + $dn = $conf['ldap']['search']['basedn']; + $filter = $conf['ldap']['search']['filter']; + $filter = str_replace('{user}', $username, $filter); + + $s = @ldap_search( $this->connection,$dn,$filter,array(),0,1,$this->timeout,$this->aliases ); + + if ( ! is_resource($s) ) + return null; + + $dn = @ldap_get_dn($this->connection, ldap_first_entry($this->connection,$s) ); + + return $dn; + } + + + + /** + * Ein Binding auf den LDAP-Server durchf�hren. + */ + function searchAttribute( $filter,$attr ) + { + global $conf; + + $timeout = intval($conf['ldap']['search']['timeout']); + + if ( $conf['ldap']['search']['aliases'] ) + $aliases = LDAP_DEREF_ALWAYS; + else + $aliases = LDAP_DEREF_NEVER; + + + $base_dn = $conf['ldap']['search']['basedn']; + $s = ldap_search( $this->connection,$base_dn,$filter,array(),0,0,$this->timeout,$this->aliases ); + $ergebnisse = ldap_get_entries($this->connection,$s); + + $liste = array(); +// Html::debug($ergebnisse); + for( $i=0; $i<=$ergebnisse['count']-1; $i++ ) + $liste[] = $ergebnisse[$i][$attr][0]; + + return $liste; + } + + + + /** + * Verbindung schlie�en. + */ + function close() + { + // Verbindung zum LDAP-Server brav beenden + ldap_close( $this->connection ); + } +} + +?>+ \ No newline at end of file diff --git a/util/Line.class.php b/util/Line.class.php @@ -0,0 +1,152 @@ +<?php + +/** + * Darstellung einer Zeile in einem Freitext.<br> + * <br> + * Im Konstruktor wird die Zeile analysiert und es wird festgestellt, was + * die Zeile für einen Inhalt hat (z.B. ein Listenelement, eine Überschrift, usw.)<br> + * + * @author Jan Dankert + * @version $Revision$ + * @package openrat.services + */ +class Line +{ + var $source; // Der ursprüngliche Inhalt + var $value; // Der textuelle Inhalt (sofern vorhanden) + + var $isDefinition = false; // Definitionseintrag + var $isList = false; // nicht-numerierte Liste + var $isNumberedList = false; // numerierte Liste + var $indent = 0; // Einschubtiefe der Liste + + var $isHeadline = false; // Überschrift + var $isHeadlineUnderline = false; // unterstrichene Überschrift + var $headlineLevel = 0; // Grad der Überschrift (1,2,3...) + + + var $isTableOfContent = false; // Inhaltsverzeichnis + var $isTable = false; // Tabelle + var $isCode = false; // Code + var $isQuote = false; // Zitat + var $isQuotePraefix = false; // Zitatbeginn/-ende + + var $isUnparsed = false; + + var $isEmpty = false; // Zeile ist leer + var $isNormal = false; // Zeile ist ohne besonderen Inhalt, d.h. keine Tabelle, kein Zitat, usw. + + + + /** + * Erzeugt einen Zeilenobjekt, der Text im Parameter wird dabei geparst. + */ + function Line( $s ) + { + global $conf; + $text_markup = $conf['editor']['text-markup']; +// Html::debug($text_markup); + + $list_numbered = $text_markup['list-numbered' ]; + $list_unnumbered = $text_markup['list-unnumbered']; + $headline = $text_markup['headline' ]; + + $this->source = $s; + $this->value = $s; + + $this->isList = $this->isAnErsterStelle(ltrim($s),$list_unnumbered); + $this->isNumberedList = $this->isAnErsterStelle(ltrim($s),$list_numbered ); + $this->indent = strlen($s) - strlen(ltrim($s)) + 1; + + if ( $this->isList || $this->isNumberedList ) + $this->value = ltrim(substr($s,$this->indent)); + + $this->level = strspn( $s,$headline ); + $this->isHeadline = $this->level >= 1; + + if ( $this->isHeadline ) + $this->value = ltrim(substr($s,$this->level)); + + + $hl = array( 1 => $text_markup['headline_level1_underline'], + 2 => $text_markup['headline_level2_underline'], + 3 => $text_markup['headline_level3_underline'] ); + + foreach($hl as $lev=>$char ) + { + if ( substr($s,0,3*strlen($char))==str_repeat($char,3*strlen($char)) ) + { + $this->isHeadlineUnderline = true; + $this->isNormal = true; + $this->level = intval($lev); + } + } + + if ( $this->isAnErsterStelle($s,$text_markup['table-of-content']) ) + { + $this->isTableOfContent = true; + $this->isNumberedList = false; + $this->isList = false; + $this->value = ''; + } + elseif + ( $this->isHeadline || + $this->isHeadlineUnderline || + $this->isList || + $this->isNumberedList ) + { + ; + } + elseif ( $this->isAnErsterStelle($s,$text_markup['table-cell-sep']) ) + { + $this->isTable = true; + $this->value = ''; + } + elseif ( $this->isAnErsterStelle($s,$text_markup['pre-begin']) && !$this->isHeadlineUnderline ) + { + $this->isCode = true; + $this->value = substr($s,strlen($text_markup['pre-begin'])); + } + elseif ( strpos($s, $text_markup['definition-sep'])!== false ) + { + $this->isDefinition = true; + } + elseif ( trim($s)==$text_markup['quote-line-begin'] ) + { + $this->isQuote = true; + } + elseif ( $this->isAnErsterStelle($s,$text_markup['quote']) && strlen(trim($s))>1 ) + { + $this->isQuotePraefix = true; + $this->value = ltrim(substr($s,strlen($text_markup['quote']))); + $this->level = strspn( str_replace(' ','',$s),$text_markup['quote'] ); + } + elseif ( $this->isAnErsterStelle($s,'`') ) + { + $this->isUnparsed = true; + $this->value = substr($this->value,1); + } + elseif ( $s == '' ) + { + $this->isEmpty = true; + } + else + { + $this->isNormal = true; + } + } + + + /** + * Stellt fest, ob $wort am Anfang von $text steht. + */ + function isAnErsterStelle( $text,$wort ) + { +// Html::debug($text,"Text"); +// Html::debug($wort,"Wort"); +// Html::debug(substr($text,0,strlen($wort))==$wort,'Ergebnis'); + return substr($text,0,strlen($wort))==$wort; + } +} + +?>+ \ No newline at end of file diff --git a/util/Logger.class.php b/util/Logger.class.php @@ -0,0 +1,194 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// OpenRat Content Management System +// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.5 2007-11-08 21:32:06 dankert +// Aktion-Name mitloggen. +// +// Revision 1.4 2004/11/10 22:50:37 dankert +// Benutzen von Konstanten zur Performancesteigerung +// +// Revision 1.3 2004/10/04 19:57:17 dankert +// Bugfix und trace() +// +// Revision 1.2 2004/05/02 15:04:16 dankert +// Einf?gen package-name (@package) +// +// Revision 1.1 2004/04/24 17:03:28 dankert +// Initiale Version +// +// --------------------------------------------------------------------------- + + +switch( strtolower($conf['log']['level']) ) +{ + case 'trace': + define('OR_LOG_LEVEL_TRACE',true ); + + case 'debug': + define('OR_LOG_LEVEL_DEBUG',true ); + + case 'info': + define('OR_LOG_LEVEL_INFO' ,true ); + + case 'warn': + define('OR_LOG_LEVEL_WARN' ,true ); + + case 'error': + define('OR_LOG_LEVEL_ERROR',true ); +} + +if ( !defined('OR_LOG_LEVEL_TRACE') ) define('OR_LOG_LEVEL_TRACE',false ); +if ( !defined('OR_LOG_LEVEL_DEBUG') ) define('OR_LOG_LEVEL_DEBUG',false ); +if ( !defined('OR_LOG_LEVEL_INFO' ) ) define('OR_LOG_LEVEL_INFO' ,false ); +if ( !defined('OR_LOG_LEVEL_WARN' ) ) define('OR_LOG_LEVEL_WARN' ,false ); +if ( !defined('OR_LOG_LEVEL_ERROR') ) define('OR_LOG_LEVEL_ERROR',false ); + + + +/** + * Schreiben eines Eintrages in die Logdatei + * + * @author $Author$ + * @version $Rev: $ + * @package openrat.services + */ +class Logger +{ + /** + * Schreiben einer Trace-Meldung in die Logdatei + * + * @param message Log-Text + */ + function trace( $message ) + { + if ( OR_LOG_LEVEL_TRACE ) + Logger::doLog( 'trace',$message ); + } + + + /** + * Schreiben einer Debug-Meldung in die Logdatei + * + * @param message Log-Text + */ + function debug( $message ) + { + if ( OR_LOG_LEVEL_DEBUG ) + Logger::doLog( 'debug',$message ); + } + + + /** + * Schreiben einer Information in die Logdatei + * + * @param message Log-Text + */ + function info( $message ) + { + if ( OR_LOG_LEVEL_INFO ) + Logger::doLog( 'info',$message ); + } + + + /** + * Schreiben einer Warnung in die Logdatei + * + * @param message Log-Text + */ + function warn( $message ) + { + if ( OR_LOG_LEVEL_WARN ) + Logger::doLog( 'warn',$message ); + } + + + /** + * Schreiben einer normalen Fehlermeldung in die Logdatei + * + * @param message Log-Text + */ + function error( $message ) + { + if ( OR_LOG_LEVEL_ERROR ) + Logger::doLog( 'error',$message ); + } + + + /** + * Schreiben der Meldung in die Logdatei + * + * @author $Author$ + * @param facility Schwere dieses Logdatei-Eintrages (z.B. warning) + * @param message Log-Text + * @access private + */ + function doLog( $facility,$message ) + { + global $conf; + global $SESS; + + $filename = $conf['log']['file']; + + if ( $filename == '' ) + return; + + if ( ! is_writable($filename) ) + Http::serverError( "logfile $filename is not writable by the server" ); + + $thisLevel = strtoupper($facility); + + $user = Session::getUser(); + if ( is_object($user) ) + $username = $user->name; + else + $username = '-'; + + $text = $conf['log']['format']; // Format der Logdatei lesen + + // Ersetzen von Variablen + if ( $conf['log']['dns_lookup'] ) + $text = str_replace( '%host',gethostbyaddr(getenv('REMOTE_ADDR')),$text ); + else + $text = str_replace( '%host',getenv('REMOTE_ADDR'),$text ); + + $action = Session::get('action'); + if ( empty($action) ) + $action = '-'; + + $action = Session::get('action'); + if ( empty($action) ) + $action = '-'; + + $text = str_replace( '%user' ,str_pad($username ,8),$text ); + $text = str_replace( '%level' ,str_pad($thisLevel,5),$text ); + $text = str_replace( '%agent' ,getenv('HTTP_USER_AGENT'),$text ); + $text = str_replace( '%action',str_pad($action,12),$text ); + $text = str_replace( '%text' ,$message,$text ); + $text = str_replace( '%time' ,date($conf['log']['date_format']),$text ); + $text = str_replace( "\n" ,"\n ",$text ); + + // Schreiben in Logdatei + error_log( $text."\n",3,$filename ); + } +} + +?>+ \ No newline at end of file diff --git a/util/Mail.class.php b/util/Mail.class.php @@ -0,0 +1,572 @@ +<?php +/* +OpenRat Content Management System +Copyright (C) Jan Dankert + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +or 3 of the License. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see <http://www.gnu.org/licenses/>. +*/ + +/** + * Erzeugen und Versender einer E-Mail gemaess RFC 822.<br> + * <br> + * Die E-Mail kann entweder �ber + * - die interne PHP-Funktion "mail()" versendet werden oder + * - direkt per SMTP-Protokoll an einen SMTP-Server.<br> + * Welcher Weg gew�hlt wird, kann konfiguriert werden.<br> + * <br> + * Prinzipiell spricht nichts gegen die interne PHP-Funktion mail(), wenn diese + * aber nicht zu Verf�gung steht oder PHP ungeeignet konfiguriert ist, so kann + * SMTP direkt verwendet werden. Hierbei sollte wenn m�glich ein Relay-Host + * eingesetzt werden. Die Mail kann zwar auch direkt an Mail-Exchanger (MX) des + * Empf�ngers geschickt werden, falls dieser aber Greylisting einsetzt ist eine + * Zustellung nicht m�glich.<br> + * <br> + * + * @author Jan Dankert + * @version $Id$ + * @package serviceClasses + */ +class Mail +{ + var $from = ''; + var $to = ''; + var $bcc = ''; + var $cc = ''; + var $subject = ''; + var $text = ''; + var $header = array(); + var $nl = ''; + + /** + * Falls beim Versendern der E-Mail etwas schiefgeht, steht hier drin + * die technische Fehlermeldung. + * + * @var String Fehler + */ + var $error = array(); + + /** + * Set to true for debugging. + * If true, All SMTP-Commands are written to error log. + * + * @var unknown_type + */ + var $debug = true; + + + /** + * Konstruktor. + * Es werden folgende Parameter erwartet + * @param String $to Empf�nger + * @param String der Textschl�ssel + * @param String unbenutzt. + * @return Mail + */ + function Mail( $to,$text,$xy='' ) + { + global $conf; + + // Zeilenumbruch CR/LF gem. RFC 822. + $this->nl = chr(13).chr(10); + + if ( !empty($conf['mail']['from']) ) + $this->from = $this->header_encode($conf['mail']['from']); + + // Priorit�t definieren (sofern konfiguriert) + if ( !empty($conf['mail']['priority']) ) + $this->header[] = 'X-Priority: '.$conf['mail']['priority']; + + $this->header[] = 'X-Mailer: '.$this->header_encode(OR_TITLE.' '.OR_VERSION); + $this->header[] = 'Content-Type: text/plain; charset='.lang( 'CHARSET' ); + $this->subject = $this->header_encode(lang( 'mail_subject_'.$text )); + $this->to = $this->header_encode($to); + + $this->text = $this->nl.wordwrap(str_replace(';',$this->nl,lang('mail_text_'.$text)),70,$this->nl).$this->nl; + + // Signatur anhaengen (sofern konfiguriert) + if ( !empty($conf['mail']['signature']) ) + { + $this->text .= $this->nl.'-- '.$this->nl; + $this->text .= str_replace(';',$this->nl,$conf['mail']['signature']); + $this->text .= $this->nl; + } + + // Kopie-Empf�nger + if ( !empty($conf['mail']['cc']) ) + $this->cc = $this->header_encode($conf['mail']['cc']); + + // Blindkopie-Empf�nger + if ( !empty($conf['mail']['bcc']) ) + $this->bcc = $this->header_encode($conf['mail']['bcc']); + } + + + + /** + * Kodiert einen Text in das Format "Quoted-printable".<br> + * See RFC 2045. + * @param String $text Eingabe + * @return Text im quoted-printable-Format + */ + function quoted_printable_encode( $text ) + { + $text = str_replace(' ','=20',$text); + + for( $i=128; $i<=255; $i++ ) + { + $text = str_replace( chr($i),'='.dechex($i),$text ); + } + + return $text; + } + + + + /** + * Setzen einer Variablen in den Mail-Inhalt. + */ + function setVar( $varName,$varInhalt) + { + $this->text = str_replace( '{'.$varName.'}', $varInhalt, $this->text ); + } + + + /** + * Mail absenden. + * Die E-Mail wird versendet. + * + * @return boolean Erfolg + */ + function send() + { + global $conf; + + $to_domain = array_pop( explode('@',$this->to) ); + + // Prüfen gegen die Whitelist + $white = @$conf['mail']['whitelist']; + + if ( !empty($white) ) + { + if ( ! $this->containsDomain($to_domain,$white) ) + { + // Wenn Domain nicht in Whitelist gefunden, dann Mail nicht verschicken. + $this->error[] = 'Mail-Domain is not whitelisted'; + return false; + } + } + + // Prüfen gegen die Blacklist + $black = @$conf['mail']['blacklist']; + + if ( !empty($black) ) + { + if ( $this->containsDomain($to_domain,$black) ) + { + // Wenn Domain in Blacklist gefunden, dann Mail nicht verschicken. + $this->error[] = 'Mail-Domain is blacklisted'; + return false; + } + } + + // Header um Adressangaben erg�nzen. + if ( !empty($this->from ) ) + $this->header[] = 'From: '.$this->from; + + if ( !empty($this->cc ) ) + $this->header[] = 'Cc: '.$this->cc; + + if ( !empty($this->bcc ) ) + $this->header[] = 'Bcc: '.$this->bcc; + + // Mail versenden + if ( strtolower(@$conf['mail']['client']) == 'php' ) + { + // PHP-interne Mailfunktion verwenden. + $result = @mail( $this->to, // Empf�nger + $this->subject, // Betreff + $this->text, // Inhalt + // Lt. RFC822 müssen Header mit CRLF enden. + // ABER: Der Parameter "additional headers" verlangt offenbar \n am Zeilenende. + implode("\n",$this->header) ); + if ( !$result ) + // Die E-Mail wurde nicht akzeptiert. + // Genauer geht es leider nicht, da mail() nur einen boolean-Wert + // zur�ck liefert. + $this->error[] = 'Mail was NOT accepted by mail()'; + + return $result; + } + else + { + // eigenen SMTP-Dialog verwenden. + $smtpConf = $conf['mail']['smtp']; + + if ( !empty($smtpConf['host'])) + { + // Eigenen Relay-Host verwenden. + $mxHost = $smtpConf['host']; + $mxPort = intval($smtpConf['port']); + } + else + { + // Mail direkt zustellen. + $mxHost = $this->getMxHost($this->to); + + if ( empty($mxHost) ) + { + $this->error[] = "No MX-Entry found. Mail could not be sent."; + return false; + } + + if ($smtpConf['ssl']) + $mxPort = 465; + else + $mxPort = 25; + } + + + if ( !empty($smtpConf['localhost'])) + { + $myHost = $smtpConf['localhost']; + } + else + { + $myHost = gethostbyaddr(getenv('REMOTE_ADDR')); + } + + if ( $smtpConf['ssl']) + $proto = 'ssl'; + else + $proto = 'tcp'; + + //connect to the host and port + $smtpSocket = fsockopen($proto.'://'.$mxHost,$mxPort, $errno, $errstr, intval($smtpConf['timeout'])); + + if ( !is_resource($smtpSocket) ) + { + $this->error[] = 'Connection failed to: '.$proto.'://'.$mxHost.':'.$mxPort.' ('.$errstr.'/'.$errno.')'; + return false; + } + + $smtpResponse = fgets($smtpSocket, 4096); + if ( $this->debug) + $this->error[] = trim($smtpResponse); + + if ( substr($smtpResponse,0,3) != '220' ) + { + $this->error[] = 'No 220: '.trim($smtpResponse); + return false; + } + + if ( !is_resource($smtpSocket) ) + { + $this->error[] = 'Connection failed to: '.$smtpConf['host'].':'.$smtpConf['port'].' ('.$smtpResponse.')'; + return false; + } + + //you have to say HELO again after TLS is started + $smtpResponse = $this->sendSmtpCommand($smtpSocket,'HELO '.$myHost); + + if ( substr($smtpResponse,0,3) != '250' ) + { + $this->error[] = "No 2xx after HELO, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + if ( $smtpConf['tls'] ) + { + $smtpResponse = $this->sendSmtpCommand($smtpSocket,'STARTTLS'); + if ( substr($smtpResponse,0,3) == '220' ) + { + // STARTTLS ist gelungen. + //you have to say HELO again after TLS is started + $smtpResponse = $this->sendSmtpCommand($smtpSocket,'HELO '.$myHost); + + if ( substr($smtpResponse,0,3) != '250' ) + { + $this->error[] = "No 2xx after HELO, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + } + else + { + // STARTTLS ging in die Hose. Einfach weitermachen. + } + } + + // request for auth login + if ( isset($smtpConf['auth_username']) && !empty($smtpConf['host']) && !empty($smtpConf['auth_username'])) + { + $smtpResponse = $this->sendSmtpCommand($smtpSocket,"AUTH LOGIN"); + if ( substr($smtpResponse,0,3) != '334' ) + { + $this->error[] = "No 334 after AUTH_LOGIN, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + if ( $this->debug) + $this->error[] = 'Login for '.$smtpConf['auth_username']; + + //send the username + $smtpResponse = $this->sendSmtpCommand($smtpSocket, base64_encode($smtpConf['auth_username'])); + if ( substr($smtpResponse,0,3) != '334' ) + { + $this->error[] = "No 3xx after setting username, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + //send the password + $smtpResponse = $this->sendSmtpCommand($smtpSocket, base64_encode($smtpConf['auth_password'])); + if ( substr($smtpResponse,0,3) != '235' ) + { + $this->error[] = "No 235 after sending password, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + } + + //email from + $smtpResponse = $this->sendSmtpCommand($smtpSocket, 'MAIL FROM: <'.$conf['mail']['from'].'>'); + if ( substr($smtpResponse,0,3) != '250' ) + { + $this->error[] = "No 2xx after MAIL_FROM, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + //email to + $smtpResponse = $this->sendSmtpCommand($smtpSocket, 'RCPT TO: <'.$this->to.'>'); + if ( substr($smtpResponse,0,3) != '250' ) + { + $this->error[] = "No 2xx after RCPT_TO, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + //the email + $smtpResponse = $this->sendSmtpCommand($smtpSocket, "DATA"); + if ( substr($smtpResponse,0,3) != '354' ) + { + $this->error[] = "No 354 after DATA, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + $this->header[] = 'To: '.$this->to; + $this->header[] = 'Subject: '.$this->subject; + $this->header[] = 'Date: '.date('r'); + $this->header[] = 'Message-Id: '.'<'.getenv('REMOTE_ADDR').'.'.time().'.openrat@'.getenv('SERVER_NAME').'.'.getenv('HOSTNAME').'>'; + + //observe the . after the newline, it signals the end of message + $smtpResponse = $this->sendSmtpCommand($smtpSocket, implode($this->nl,$this->header).$this->nl.$this->nl.$this->text.$this->nl.'.'); + if ( substr($smtpResponse,0,3) != '250' ) + { + $this->error[] = "No 2xx after putting DATA, server says: ".$smtpResponse; + $this->sendSmtpQuit($smtpSocket); + return false; + } + + // say goodbye + $this->sendSmtpQuit($smtpSocket); + return true; + } + } + + + /** + * Sendet ein SMTP-Kommando zum SMTP-Server. + * + * @access private + * @param Resource $socket TCP/IP-Socket zum SMTP-Server + * @param unknown_type $cmd SMTP-Kommando + * @return Server-Antwort + */ + function sendSmtpCommand( $socket,$cmd ) + { + if ( $this->debug ) + $this->error[] = 'CLIENT: >>> '.trim($cmd); + if ( !is_resource($socket) ) + { + // Die Verbindung ist geschlossen. Dies kann bei dieser + // Implementierung eigentlich nur dann passieren, wenn + // der Server die Verbindung schlie�t. + // Dieser Client trennt die Verbindung nur nach einem "QUIT". + $this->error[] = "Connection lost"; + return; + } + + fputs($socket,$cmd.$this->nl); + $response = trim(fgets($socket, 4096)); + if ( $this->debug ) + $this->error[] = 'SERVER: <<< '.$response; + return $response; + } + + + + /** + * Sendet ein QUIT zum SMTP-Server, wartet die Antwort ab und + * schlie�t danach die Verbindung. + * + * @param Resource Socket + */ + function sendSmtpQuit( $socket ) + { + + if ( $this->debug ) + $this->error[] = "CLIENT: >>> QUIT"; + if ( !is_resource($socket) ) + return; + // Wenn die Verbindung nicht mehr da ist, brauchen wir + // auch kein QUIT mehr :) + + + fputs($socket,'QUIT'.$this->nl); + $response = trim(fgets($socket, 4096)); + if ( $this->debug ) + $this->error[] = 'SERVER: <<< '.$response; + + if ( substr($response,0,3) != '221' ) + $this->error[] = 'QUIT FAILED: '.$response; + + fclose($socket); + } + + + + /** + * Umwandlung von 8-bit-Zeichen in MIME-Header gemaess RFC 2047.<br> + * Header d�rfen nur 7-bit-Zeichen enthalten. 8-bit-Zeichen m�ssen kodiert werden. + * + * @param String $text + * @return String + */ + function header_encode( $text ) + { + global $conf; + + if ( empty($conf['mail']['header_encoding']) ) + return $text; + + $woerter = explode(' ',$text); + $neu = array(); + + + foreach( $woerter as $wort ) + { + $type = strtolower(substr($conf['mail']['header_encoding'],0,1)); + $neu_wort = ''; + + if ( $type == 'b' ) + $neu_wort = base64_encode($wort); + elseif ( $type == 'q' ) + $neu_wort = $this->quoted_printable_encode($wort); + else + Logger::error( 'Mail-Configuratin broken: UNKNOWN Header-Encoding type: '.$type); + + if ( strlen($wort)==strlen($neu_wort) ) + $neu[] = $wort; + else + $neu[] = '=?'.lang('CHARSET').'?'.$type.'?'.$neu_wort.'?='; + } + + return implode(' ',$neu); + } + + + /** + * Ermittelt den MX-Eintrag zu einer E-Mail-Adresse.<br> + * Es wird der Eintrag mit der h�chsten Priorit�t ermittelt. + * + * @param String E-Mail-Adresse des Empf�ngers. + * @return MX-Eintrag + */ + function getMxHost( $to ) + { + list($user,$host) = explode('@',$to.'@'); + + if ( empty($host) ) + { + $this->error[] = 'Illegal mail address - No hostname found.'; + return ""; + } + + list($host) = explode('>',$host); + + $mxHostsName = array(); + $mxHostsPrio = array(); + getmxrr($host,$mxHostsName,$mxHostsPrio); + + $mxList = array(); + foreach( $mxHostsName as $id=>$mxHostName ) + { + $mxList[$mxHostName] = $mxHostsPrio[$id]; + } + asort($mxList); + return key($mxList); + } + + + + /** + * Stellt fest, ob die E-Mail-Adresse eine gueltige Syntax besitzt. + * + * Es wird nur die Syntax geprüft. Ob die Adresse wirklich existiert, steht dadurch noch lange + * nicht fest. Dazu müsste man die MX-Records auflösen und einen Zustellversuch unternehmen. + * + * @param $email_address Adresse + * @return true, falls Adresse OK, sonst false + */ + function checkAddress( $email_address ) + { + // Source: de.php.net/ereg + return ereg("^[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[@]{1}[-A-Za-z0-9_]+[-A-Za-z0-9_.]*[.]{1}[A-Za-z]{2,5}$", $email_address); + } + + + + /** + * Prüft, ob eine Domain in einer List von Domains enthalten ist. + * + * @param $checkDomain zu prüfende Domain + * @param $domain_list Liste von Domains als kommaseparierte Liste + * @return true, falls vorhanden, sonst false + */ + function containsDomain($checkDomain, $domain_list) + { + $domains = explode(',',$domain_list); + + foreach( $domains as $domain ) + { + $domain = trim($domain); + + if (empty($domain)) + continue; + + if ($domain == substr($checkDomain,-strlen($domain))) + { + return true; + } + } + return false; + } +} + + +?> diff --git a/util/OpenId.class.php b/util/OpenId.class.php @@ -0,0 +1,467 @@ +<?php + + +/** + * Open-Id Authentisierung gem�� OpenId-Spezifikation 1.0. + * + */ +class OpenId +{ + /** + * Open-Id Server, an den die Authentisierungsanfrage gestellt wird. + * + * @var String + */ + var $server; + + + /** + * Informationen zum Benutzer. + * + * @var Array + */ + var $info; + + /** + * Open-Id Identity. + * + * @var String + */ + var $identity; + + /** + * Fehlermeldung (falls vorhanden). + * + * @var String + */ + var $error; + + /** + * OpenId-Benutzername. + * + * @var String + */ + var $user; + + /** + * OpenId-Provider. + * + * @var String + */ + var $provider; + + + var $supportAX; + var $supportSREG; + var $supportOpenId1_1; + var $supportOpenId2_0; + + + /** + * Neue Open-Id Anfrage. + * + * @param String $user + * @return OpenId + */ + function OpenId( $provider='',$user='' ) + { + $this->provider = $provider; + $this->user = $user; + } + + + /** + * Stellt fest, ob der Server vertrauensw�rdig ist. + * + * @return true, wenn vertrauensw�rdig. + */ + function serverOk() + { + global $conf; + $servers = $conf['security']['openid']['trusted_server']; + + if ( empty($servers) ) + { + return true; + } + else + { + $serverList = explode(',',$servers); + + $http = new Http($this->server); + if ( !in_array($http->url['host'],$serverList) ) + { + $this->error = 'Server '.$this->server.' is not trusted'; + return false; + } + else + return true; + } + + } + + + + /** + * Authentisierung Schritt 1.<br> + * Ermitteln der Identity. + * + * @return boolean TRUE, wenn Identity ermittelt wurde. + */ + function login() + { + if ( $this->provider != 'identity' ) + { + $this->user = config('security','openid','provider.'.$this->provider.'.xrds_uri'); + $this->identity = 'http://specs.openid.net/auth/2.0/identifier_select'; + } + $this->supportSREG = config('security','openid','provider.'.$this->provider.'.sreg_1_0'); + $this->supportAX = config('security','openid','provider.'.$this->provider.'.ax_1_0' ); + + // Schritt 1: Identity aus Yadis-Dokument laden. + $this->getIdentityFromYadis(); + + // Schritt 2: Fallback auf HTML-Dokument. + if ( empty($this->server) ) + { + $this->getIdentityFromHtmlMetaData(); + } + + // Falls immer noch kein Servername gefunden wurde, dann Abbruch. + if ( empty($this->server) ) + { + if ( empty($this->error) ) + $this->error = 'Unable to locate OpenId-Server in URL'; + return false; + } + + if ( !$this->serverOk() ) + return false; // Server nicht vertrauenswuerdig. + + if ( empty($this->identity) ) + // Falls die Identity bis hierher nicht deligiert wurde... + // Lt. Spezifikation mit Prefix "http://". + $this->identity = 'http://'.$this->user; + + return true; + } + + + + /** + * Erzeugt einen HTTP-Redirect auf den OpenId-Provider. + */ + function redirect() + { + global $conf; + + $this->handle = md5(microtime().session_id()); + + $redirHttp = new Http($this->server); + + if ( $this->supportOpenId2_0 ) + $redirHttp->requestParameter['openid.ns' ] = 'http://specs.openid.net/auth/2.0'; + + $redirHttp->requestParameter['openid.mode' ] = 'checkid_setup'; + $redirHttp->requestParameter['openid.identity' ] = $this->identity; + + if ( $this->supportOpenId2_0 ) + $redirHttp->requestParameter['openid.claimed_id'] = $this->identity; + + + // Profilangaben anfordern. E-Mail wird ben�tigt, Name und Sprache sind optional. + + if ( $this->supportAX ) + { + Logger::info("OpenId-Server is using OpenID Attribute Exchange 1.0"); + $redirHttp->requestParameter['openid.ns.ax' ] = 'http://openid.net/srv/ax/1.0'; + $redirHttp->requestParameter['openid.ax.mode' ] = 'fetch_request'; + $redirHttp->requestParameter['openid.ax.type.email' ] = 'http://axschema.org/contact/email'; + $redirHttp->requestParameter['openid.ax.type.username' ] = 'http://axschema.org/namePerson/friendly'; + $redirHttp->requestParameter['openid.ax.type.fullname' ] = 'http://axschema.org/namePerson'; + $redirHttp->requestParameter['openid.ax.type.language' ] = 'http://axschema.org/pref/language'; + $redirHttp->requestParameter['openid.ax.required' ] = 'username,email'; + $redirHttp->requestParameter['openid.ax.if_available' ] = 'language,fullname'; + } + + if ( $this->supportSREG ) + { + Logger::info("OpenId-Server is using OpenID Simple Registration Extension 1.0"); + $redirHttp->requestParameter['openid.ns.sreg' ] = 'http://openid.net/sreg/1.0'; + $redirHttp->requestParameter['openid.sreg.required'] = 'email,nickname'; + $redirHttp->requestParameter['openid.sreg.optional'] = 'fullname,language'; + } + + $trustRoot = @$conf['security']['openid']['trust_root']; + $server = Http::getServer(); + if ( empty($trustRoot) ) + $trustRoot = $server; + + $redirHttp->requestParameter['openid.trust_root' ] = slashify($trustRoot); + $redirHttp->requestParameter['openid.return_to' ] = slashify($server).'openid.'.PHP_EXT; + //$redirHttp->requestParameter['openid.realm' ] = slashify($server).'openid.'.PHP_EXT; + $redirHttp->requestParameter['openid.assoc_handle' ] = $this->handle; + + $redirHttp->sendRedirect(); // Browser umleiten. + exit; // Ende. + } + + + + /** + * Ermittelt OpenId-Server und OpenId-Identity aus Yadis-Dokument.<br> + * + * @return unknown + */ + function getIdentityFromYadis() + { + $http = new Http($this->user); +// $http->url['host'] = $this->user; + + $http->header[] = 'Accept: application/xrds+xml'; + if ( ! $http->request() ) + { + $this->error = 'Unable to get XML delegate information'; + return false; + } + + Logger::debug("OpenId: Found YADIS-document for ".$http->getUrl()); + //die(); + $p = xml_parser_create(); + $ok = xml_parse_into_struct($p, $http->body, $vals, $index); + xml_parser_free($p); + + foreach( $vals as $tag ) + { + if ( strtolower($tag['tag']) == 'type' ) + { + if ( $tag['value'] == 'http://openid.net/srv/ax/1.0' ) + $this->supportAX = true; + + if ( $tag['value'] == 'http://openid.net/sreg/1.0' ) + $this->supportSREG = true; + + if ( $tag['value'] == 'http://openid.net/signon/1.1' ) + $this->supportOpenId1_1 = true; + + if ( $tag['value'] == 'http://specs.openid.net/auth/2.0/server' ) + $this->supportOpenId2_0 = true; + } + + if ( strtolower($tag['tag']) == 'uri' ) + { + $this->server = $tag['value']; + } + + if ( strtolower($tag['tag']) == 'openid:delegate' ) + { + $this->identity = $tag['value']; + } + } + + if ( !$this->supportOpenId1_1 && !$this->supportOpenId2_0 ) + { + $this->error = 'Only OpenId 1.1 and 2.0 is supported but this identity-provider does not seem to support any of these.'; + return false; + } + if ( !$this->supportAX && !$this->supportSREG ) + { + $this->error = 'The identity-provider must support either Attribute-Exchange (AX) oder Simple-Registration (SREG), but it does not seem to support any of these.'; + return false; + } + } + + + /** + * Ermittelt OpenId-Server und OpenId-Identity aus HTML Meta-Tags.<br> + */ + function getIdentityFromHtmlMetaData() + { + $http = new Http($this->user); +// $http = new Http(); +// $http->url['host'] = $this->user; + $http->header[] = 'Accept: text/html'; + + if ( ! $http->request() ) + { + $this->error = 'Unable to get HTML delegate information'; + return false; + } + + $seite = $http->body; + + // Die Meta-Tags mit regulaerem Ausdruck auslesen. + $treffer = array(); + preg_match('/rel="openid.server"\s+href="(\S+)"/',$seite,$treffer); + if ( count($treffer) >= 1 ) + { + $this->server = $treffer[1]; + $this->supportOpenId1_1 = true; + } + + $treffer = array(); + preg_match('/rel="openid2.provider"\s+href="(\S+)"/',$seite,$treffer); + if ( count($treffer) >= 1 ) + { + $this->supportOpenId2_0 = true; + $this->server = $treffer[1]; + } + + $treffer = array(); + preg_match('/rel="openid.delegate"\s+href="(\S+)"/',$seite,$treffer); + if ( count($treffer) >= 1 ) + $this->identity = $treffer[1]; + } + + + /** + * Ermittelt den Hostnamen aus der Identity. + * + * @return String + */ + function getUserFromIdentiy() + { + if ( $this->provider == 'identity' ) + { + $http = new Http($this->identity); + return $http->url['host']; + } + else + { + $attribute_name = config('security','openid','provider.'.$this->provider.'.map_attribute'); + return $this->info[$attribute_name]; + } + } + + + /** + * Open-Id Login, �berpr�fen der Anmeldung.<br> + * Spezifikation: http://openid.net/specs/openid-authentication-1_1.html<br> + * Kapitel "4.4. check_authentication"<br> + * <br> + * Im 2. Schritt (Mode "id_res") erfolgte ein Redirect vom Open-Id Provider an OpenRat zur�ck.<br> + * Wir befinden uns nun im darauf folgenden Request des Browsers.<br> + * <br> + * Es muss noch beim OpenId-Provider die Best�tigung eingeholt werden, danach ist der + * Benutzer angemeldet.<br> + */ + function checkAuthentication() + { + $queryVars = $this->getQueryParamList(); + + if ( $queryVars['openid.invalidate_handle'] != $this->handle ) + { + $this->error = 'Association-Handle mismatch.'; + return false; + } + + if ( $queryVars['openid.mode'] != 'id_res' ) + { + $this->error ='Open-Id: Unknown mode:'.$queryVars['openid.mode']; + return false; + } + + if ( $this->provider=='identity' && $queryVars['openid.identity'] != $this->identity ) + { + $this->error ='Open-Id: Identity mismatch. Wrong identity:'.$queryVars['openid.identity']; + return false; + } + + + $params = array(); + + if ( $this->supportAX ) + // Den Namespace-Prefix für AX (attribute exchange) herausfinden. + // Leider kann das ein anderer Prefix sein, als wir im Request verwendet haben. + foreach( $queryVars as $request_key=>$request_value ) + if ( substr($request_key,0,10)=='openid.ns.' && $request_value == 'http://openid.net/srv/ax/1.0' ) + $axPrefix = substr($request_key,10); + + foreach( $queryVars as $request_key=>$request_value ) + { + // Benutzer-Attribute ermitteln. + // Benutzer-Attribute über SREG ermitteln. + if ( $this->supportSREG && substr($request_key,0,12)=='openid.sreg.' ) + $this->info[ substr($request_key,12) ] = $request_value; + // Benutzer-Attribute über AX ermitteln. + elseif ( $this->supportAX && substr($request_key,0,14+strlen($axPrefix))=='openid.'.$axPrefix.'.value.' ) + $this->info[ substr($request_key,14+strlen($axPrefix)) ] = $request_value; + + // Alle OpenId-Parameter in den Check-Authentication-Request übertragen. + if ( substr($request_key,0,7)=='openid.' ) + $params['openid.'.substr($request_key,7) ] = $request_value; + } + $params['openid.mode'] = 'check_authentication'; + + $checkRequest = new Http($this->server); + + $checkRequest->method = 'POST'; // Spezifikation verlangt POST. + $checkRequest->header['Accept'] = 'text/plain'; + $checkRequest->requestParameter = $params; + + if ( ! $checkRequest->request() ) + { + // Der HTTP-Request ging in die Hose. + $this->error = $checkRequest->error; + return false; + } + //Html::debug($checkRequest); + + // Analyse der HTTP-Antwort, Parsen des BODYs. + // Die Anmeldung ist best�tigt, wenn im BODY die Zeile "is_valid:true" vorhanden ist. + // Siehe Spezifikation Kapitel 4.4.2 + $result = array(); + foreach( explode("\n",$checkRequest->body) as $line ) + { + $pair = explode(':',trim($line)); + if (count($pair)==2) + $result[strtolower($pair[0])] = strtolower($pair[1]); + } + + if ( !array_key_exists('is_valid',$result) ) + { + // Zeile nicht gefunden. + $this->error = 'Undefined Open-Id response: "is_valid" expected, but not found'; + return false; + } + elseif ( $result['is_valid'] == 'true' ) + { + // Anmeldung wurde mit "is_valid:true" best�tigt. + return true; + } + else + { + // Bestaetigung wurde durch den OpenId-Provider abgelehnt. + $this->error = 'Server refused login.'; + return false; + } + } + + + /** + * Liefert die Query-Parameter aus der aktuellen URL.<br> + * <br> + * PHP hat leider die sehr bescheuerte Angewohnheit, Punkte und Leerzeichen in Request-Variablen + * durch Unterstriche zu ersetzen. Diese Funktion liefert die GET-Parameter ohne diese Ersetzung. + * + * @return Parameter der aktuellen URL + */ + function getQueryParamList() + { + // Quelle: php.net + $str = $_SERVER['QUERY_STRING']; + $op = array(); + $pairs = explode("&", $str); + foreach ($pairs as $pair) + { + list($k, $v) = array_map("urldecode", explode("=", $pair)); + $op[$k] = $v; + } + + return $op; + } + + +} + +?>+ \ No newline at end of file diff --git a/util/Preferences.class.php b/util/Preferences.class.php @@ -0,0 +1,59 @@ +<?php + +/** + * Bereitstellen von Methoden fuer das Lesen von Einstellungen + * + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Preferences +{ + /** + * Liest die Konfigurationsdateien im angegebenen Ordner. + * + * @param $dir Verzeichnis, welche gelesen wird. Optional. Falls nicht gesetzt, wird + * das Standard-Konfigurationsverzeichnis verwendet. + * @return Array + */ + function load( $dir='' ) + { + if ( !defined('QUOTE') ) + define('QUOTE','"'); + + $values = array(); + + // Bei erstem (nicht-rekursiven) Aufruf der Methoden das Konfigurationsverzeichnis voreinstellen + if ( empty($dir) ) + { + if ( isset($_GET['config']) ) + $dir = basename( $_GET['config'] ).'/'; + else + $dir = OR_PREFERENCES_DIR; + } + + if ( !is_dir($dir) ) + { + Http::sendStatus(501,'Internal Server Error','not a directory: '.$dir); + exit; + } + + $dateien = FileUtils::readDir($dir); + + foreach( $dateien as $datei ) + { + $filename = $dir.$datei; + + if ( is_file($filename) && eregi('\.(ini.*|conf)$',$datei) ) + { + $nameBestandteile = explode('.',$datei); + $values[$nameBestandteile[0]] = parse_ini_file( $filename,true ); + } + } + + ksort($values); + + return $values; + } +} +?>+ \ No newline at end of file diff --git a/util/ProjectTree.class.php b/util/ProjectTree.class.php @@ -0,0 +1,476 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Darstellen der Projektstruktur + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class ProjectTree extends AbstractTree +{ + var $projectId; + var $userIsProjectAdmin = false; + + function root() + { + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_PROJECT'); + $treeElement->description = lang('GLOBAL_PROJECT'); + $treeElement->type = 'project'; + $treeElement->icon = 'project'; + + $this->addTreeElement( $treeElement ); + } + + + + function pageelements( $id ) + { + $page = new Page( $id ); + $page->load(); + + $template = new Template( $page->templateid ); + + foreach( $template->getElementIds() as $elementid ) + { + $element = new Element( $elementid ); + $element->load(); + + if ( $element->isWritable() ) + { + $treeElement = new TreeElement(); + $treeElement->text = $element->name; + $treeElement->url = Html::url('pageelement','edit', + $id, + array('elementid'=>$elementid, + REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'el_'.$element->type; + + $treeElement->description = lang('EL_'.$element->type); + if ( $element->desc != '' ) + $treeElement->description .= ' - '.Text::maxLaenge( 25,$element->desc ); + else + $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + $treeElement->target = 'content'; + + if ( in_array($element->type,array('link','list','include') ) ) + { + $treeElement->type = 'value'; + $value = new Value(); + $value->pageid = $page->pageid; + $value->element = $element; + $value->load(); + $treeElement->internalId = $value->valueid; + } + + $this->addTreeElement( $treeElement ); + } + } + } + + + function value( $id ) + { + //echo "id: $id"; + if ( $id != 0 ) + { + $value = new Value(); + $value->loadWithId( $id ); + + $objectid = intval($value->linkToObjectId); + if ( $objectid != 0 ) + { + $object = new Object( $objectid ); + $object->load(); + + $treeElement = new TreeElement(); + $treeElement->text = $object->name; + if ( in_array($object->getType(),array('page','folder'))) + { + $treeElement->type = $object->getType(); + $treeElement->internalId = $object->objectid; + } + $treeElement->url = Html::url($object->getType(),'',$objectid); + $treeElement->icon = $object->getType(); + + $treeElement->description = lang('GLOBAL_'.$object->getType()); + if ( $object->desc != '' ) + $treeElement->description .= ' - '.Text::maxLaenge( 25,$object->desc ); + else + $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + $treeElement->target = 'content'; + + $this->addTreeElement( $treeElement ); + } + } + } + + + function link( $id ) + { + $link = new Link( $id ); + $link->load(); + + if ( $link->isLinkToObject ) + { + $o = new Object( $link->linkedObjectId ); + $o->load(); + + $treeElement = new TreeElement(); + $treeElement->internalId = $o->objectid; + $treeElement->target = 'content'; + $treeElement->text = $o->name; + $treeElement->description= lang( 'GLOBAL_'.$o->getType() ).' '.$id; + + if ( $o->desc != '' ) + $treeElement->description .= ': '.$o->desc; + else + $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + + $treeElement->url = Html::url($o->getType(),'',$o->objectid,array(REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = $o->getType(); + + // Besonderheiten fuer bestimmte Objekttypen + + if ( $o->isPage ) + { + // Nur wenn die Seite beschreibbar ist, werden die + // Elemente im Baum angezeigt + if ( $o->hasRight( ACL_WRITE ) ) + $treeElement->type='pageelements'; + } + $this->addTreeElement( $treeElement ); + } + } + + + /** + * Laedt Elemente zu einem Ordner + * @return Array + */ + function folder( $id ) + { + global + $SESS, + $projectid; + + $f = new Folder( $id ); + $t = time(); + + foreach( $f->getObjects() as $o ) + { + // Wenn keine Leseberechtigung + if ( !$o->hasRight( ACL_READ ) ) + continue; + + $treeElement = new TreeElement(); + $treeElement->internalId = $o->objectid; + $treeElement->target = 'content'; + $treeElement->text = $o->name; + $treeElement->description= lang( 'GLOBAL_'.$o->getType() ).' '.$o->objectid; + + if ( $o->desc != '' ) + $treeElement->description .= ': '.$o->desc; + else + $treeElement->description .= ' - '.lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + + $treeElement->url = Html::url( $o->getType(),'',$o->objectid,array('readit'=>'__OID__'.$o->objectid.'__',REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = $o->getType(); + + // Besonderheiten fuer bestimmte Objekttypen + + if ( $o->isLink ) + { + $treeElement->type='link'; + } + + if ( $o->isPage ) + { + // Nur wenn die Seite beschreibbar ist, werden die + // Elemente im Baum angezeigt + if ( $o->hasRight( ACL_WRITE ) ) + $treeElement->type='pageelements'; + } + + if ( $o->isFile ) + { + $file = new File( $o->objectid ); + $file->load(); + + if ( substr($file->mimeType(),0,6) == 'image/' ) + $treeElement->icon = 'image'; + else $treeElement->icon = 'file'; + } + + if ( $o->isFolder ) + { + $treeElement->type = 'folder'; + } + + + $this->addTreeElement( $treeElement ); + } + } + + + function project() + { + $language = Session::getProjectLanguage(); + $model = Session::getProjectModel(); + $user = Session::getUser(); + + $project = Session::getProject(); + $this->projectid = $project->projectid; + + // Hoechster Ordner der Projektstruktur + $folder = new Folder( $project->getRootObjectId() ); + $folder->load(); + + + // Ermitteln, ob der Benutzer Projektadministrator ist + // Projektadministratoren haben das Recht, im Root-Ordner die Eigenschaften zu aendern. + if ( $folder->hasRight( ACL_PROP ) ) + $this->userIsProjectAdmin = true; + + if ( $folder->hasRight( ACL_READ ) ) + { + $treeElement = new TreeElement(); +// $treeElement->text = $folder->name; + $treeElement->text = lang('FOLDER_ROOT'); + $treeElement->description = lang('FOLDER_ROOT_DESC'); + $treeElement->icon = 'folder'; + $treeElement->url = Html::url( 'folder','',$folder->objectid,array(REQ_PARAM_TARGET=>'content') ); + $treeElement->target = 'content'; + $treeElement->type = 'folder'; + $treeElement->internalId = $folder->objectid; + $this->addTreeElement( $treeElement ); + } + + + if ( $this->userIsProjectAdmin ) + { + // Templates + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_TEMPLATES'); + $treeElement->url = Html::url('template','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); + $treeElement->description= lang('GLOBAL_TEMPLATES_DESC'); + $treeElement->icon = 'template_list'; + $treeElement->target = 'content'; + $treeElement->type = 'templates'; + $this->addTreeElement( $treeElement ); + } + + + // Sprachen + $treeElement = new TreeElement(); + $treeElement->description= ''; + $treeElement->text = lang('GLOBAL_LANGUAGES'); + $treeElement->url = Html::url('language','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'language_list'; + $treeElement->description= lang('GLOBAL_LANGUAGES_DESC'); + $treeElement->target = 'content'; + + // Nur fuer Projekt-Administratoren aufklappbar + if ( $this->userIsProjectAdmin ) + $treeElement->type = 'languages'; + + $this->addTreeElement( $treeElement ); + + + // Projektmodelle + $treeElement = new TreeElement(); + $treeElement->description= ''; + + // Nur fuer Projekt-Administratoren aufklappbar + if ( $this->userIsProjectAdmin ) + $treeElement->type = 'models'; + + $treeElement->description= lang('GLOBAL_MODELS_DESC'); + $treeElement->text = lang('GLOBAL_MODELS'); + $treeElement->url = Html::url('model','listing',0,array(REQ_PARAM_TARGETSUBACTION=>'listing',REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'model_list'; + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + + + // Sonstiges +// $treeElement = new TreeElement(); +// $treeElement->text = lang('GLOBAL_OTHER'); +// $treeElement->description= lang('GLOBAL_OTHER_DESC'); +// $treeElement->icon = 'other'; +// $treeElement->type = 'other'; +// $this->addTreeElement( $treeElement ); + + // Suche + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_SEARCH'); + $treeElement->url = Html::url('search','',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'search'; + $treeElement->description = lang('GLOBAL_SEARCH_DESC'); + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + + } + + + function templates() + { + foreach( Template::getAll() as $id=>$name ) + { + $treeElement = new TreeElement(); + + $t = new Template( $id ); + $t->load(); + $treeElement->text = $t->name; + $treeElement->url = Html::url('template','src',$id,array(REQ_PARAM_TARGETSUBACTION=>'src',REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'template'; + $treeElement->target = 'content'; + $treeElement->internalId = $id; + $treeElement->type = 'template'; + $treeElement->description = $t->name.' ('.lang('GLOBAL_TEMPLATE').' '.$id.'): '.htmlentities(Text::maxLaenge( 40,$t->src )); + $this->addTreeElement( $treeElement ); + } + } + + + function template( $id ) + { + + $t = new Template( $id ); + $t->load(); + + // Anzeigen der Template-Elemente + // + foreach( $t->getElementIds() as $elementid ) + { + $e = new Element( $elementid ); + $e->load(); + + // "Code"-Element nur fuer Administratoren + if ( $e->type == 'code' && !$this->userIsAdmin ) + continue; + + $treeElement = new TreeElement(); + $treeElement->text = $e->name; + $treeElement->url = Html::url('element','',$elementid,array(REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = 'el_'.$e->type; + + if ( $e->desc == '' ) + $desc = lang('GLOBAL_NO_DESCRIPTION_AVAILABLE'); + else + $desc = $e->desc; + $treeElement->description = $e->name.' ('.lang('EL_'.$e->type).'): '.Text::maxLaenge( 40,$desc ); + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + } + } + + + /** + * Sprachen + */ + function languages() + { + // Sprachvarianten + // + $l = Session::getProjectLanguage(); + $languages = $l->getAll(); + + foreach( $languages as $languageid=>$name ) + { + $treeElement = new TreeElement(); + $treeElement->text = $name; + $treeElement->url = Html::url('language','edit',$languageid, + array(REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content') ); + $treeElement->icon = 'language'; + $treeElement->description = ''; + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + } + } + + + // Projektvarianten + // + function models() + { + $m = Session::getProjectModel(); + $models = $m->getAll(); + + foreach( $models as $id=>$name ) + { + $treeElement = new TreeElement(); + $treeElement->text = $name; + $treeElement->url = Html::url('model','edit',$id, + array(REQ_PARAM_TARGETSUBACTION=>'edit',REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'model'; + $treeElement->description = ''; + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + } + } + + + function other() + { +// Deaktiviert, da +// - Dateien auf den Server laden unverst�ndlich/undurchsichtig erscheint +// - M�glichkeit zum Entpacken von ZIP/TAR online besteht. +// if ( $this->userIsProjectAdmin ) +// { +// $treeElement = new TreeElement(); +// $treeElement->text = lang('GLOBAL_FILE_TRANSFER'); +// $treeElement->description = lang('GLOBAL_FILE_TRANSFER_DESC'); +// $treeElement->url = Html::url('main','transfer'); +// $treeElement->icon = 'transfer'; +// $treeElement->target = 'content'; +// $this->addTreeElement( $treeElement ); +// } + + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_SEARCH'); + $treeElement->url = Html::url('search'); + $treeElement->icon = 'search'; + $treeElement->description = lang('GLOBAL_SEARCH_DESC'); + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + + + $treeElement = new TreeElement(); + $treeElement->text = lang('USER_YOURPROFILE'); + $treeElement->url = Html::url('profile','edit',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'user'; + $treeElement->description = lang('USER_PROFILE_DESC'); + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + + + $treeElement = new TreeElement(); + $treeElement->text = lang('GLOBAL_PROJECTS'); + $treeElement->url = Html::url('index','projectmenu',0,array(REQ_PARAM_TARGET=>'content')); + $treeElement->icon = 'project'; + $treeElement->description = lang('GLOBAL_PROJECTS'); + $treeElement->target = 'content'; + $this->addTreeElement( $treeElement ); + } +} + +?>+ \ No newline at end of file diff --git a/util/Publish.class.php b/util/Publish.class.php @@ -0,0 +1,364 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Diese Klasse kapselt das Veroeffentlichen von Dateien.<br> + * <br> + * Hier werden<br> + * - Dateien in das Zielverzeichnis kopiert<br> + * - Dateien per FTP veroeffentlicht<br> + * - Zielverzeichnisse aufgeraeumt<br> + * - Systembefehle ausgefuehrt. + * + * @author Jan Dankert + * @package openrat.services + */ +class Publish +{ + /** + * Enthaelt bei Bedarf das FTP-Objekt. N�mlich dann, wenn + * zu einem FTP-Server veroeffentlicht werden soll. + * @var Object + */ + var $ftp; + + /** + * Flag, ob in das lokale Dateisystem veroeffentlicht werden soll. + * @var boolean + */ + var $with_local = false; + + /** + * Flag, ob zu einem FTP-Server ver�ffentlicht werden soll. + * @var boolean + */ + var $with_ftp = false; + + var $local_destdir = ''; + + /** + * Enthaelt die gleichnamige Einstellung aus dem Projekt. + * @var boolean + */ + var $content_negotiation = false; + + /** + * Enthaelt die gleichnamige Einstellung aus dem Projekt. + * @var boolean + */ + var $cut_index = false; + + /** + * Enthaelt die gleichnamige Einstellung aus dem Projekt. + * @var String + */ + var $cmd_after_publish = ''; + + /** + * Enthaelt am Ende der Ver�ffentlichung ein Array mit den ver�ffentlichten Objekten. + * @var Array + */ + var $publishedObjects = array(); + + /** + * Enthaelt im Fehlerfall (wenn 'ok' auf 'false' steht) eine + * Fehlermeldung. + * + * @var String + */ + var $log = array(); + + /** + * Stellt nach der Ver�ffentlichung fest, ob der Vorgang erfolgreich ist. + * Falls nicht, enth�lt die Variable 'log' eine Fehlermeldung. + * @var boolean + */ + var $ok = true; + + /** + * Konstruktor.<br> + * <br> + * Oeffnet ggf. Verbindungen. + * + * @return Publish + */ + function Publish() + { + global $conf; + $conf_project = $conf['publish']['project']; + + if ( $conf['security']['nopublish'] ) + { + $this->ok = false; + $this->log[] = 'publishing is disabled.'; + return; + } + + $project = Session::getProject(); + + // Feststellen, ob FTP benutzt wird. + // Dazu muss FTP aktiviert sein (enable=true) und eine URL vorhanden sein. + if ( @$conf['publish']['ftp']['enable'] && + ( !empty($project->ftp_url) || + isset($conf['publish']['ftp']['host']) ) ) + { + $this->with_ftp = true; + $this->ftp = new Ftp( $project->ftp_url ); // Aufbauen einer FTP-Verbindung + + if ( ! $this->ftp->ok ) // FTP-Verbindung ok? + { + $this->ok = false; + $this->log = $this->ftp->log; + return; // Ende. Ohne FTP brauchen wir nicht weitermachen. + } + + $this->ftp->passive = ( $project->ftp_passive == '1' ); + } + + $localDir = ereg_replace( '\/$','',$project->target_dir); + if ( empty( $localDir)) + $localDir = $project->name; + + if ( $conf_project['override_publish_dir'] && $localDir != basename($localDir) ) + $this->local_destdir = $localDir; + else + $this->local_destdir = $conf_project['publish_dir'].$localDir; + + + // Sofort pruefen, ob das Zielverzeichnis ueberhaupt beschreibbar ist. + if ( $this->local_destdir != '' ) + { + if ( !is_writeable( $this->local_destdir ) ) + { + $this->ok = false; + $this->log[] = 'directory not writable: '.$this->local_destdir; + $this->log[] = 'please correct the file permissions.'; + return; + } + + $this->with_local = true; + } + + $this->content_negotiation = ( $project->content_negotiation == '1' ); + $this->cut_index = ( $project->cut_index == '1' ); + + if ( $conf_project['override_system_command'] && !empty($project->cmd_after_publish) ) + $this->cmd_after_publish = $project->cmd_after_publish; + else + $this->cmd_after_publish = @$conf_project['system_command']; + + // Im Systemkommando Variablen ersetzen + $this->cmd_after_publish = str_replace('{name}' ,$project->name ,$this->cmd_after_publish); + $this->cmd_after_publish = str_replace('{dir}' ,$this->local_destdir ,$this->cmd_after_publish); + $this->cmd_after_publish = str_replace('{dirbase}',basename($this->local_destdir),$this->cmd_after_publish); + } + + + + /** + * Kopieren einer Datei aus dem tempor�ren Verzeichnis in das Zielverzeichnis.<br> + * Falls notwenig, wird ein Hochladen per FTP ausgef�hrt. + * + * @param String $tmp_filename + * @param String $dest_filename + */ + function copy( $tmp_filename,$dest_filename,$lastChangeDate=null ) + { + if ( !$this->ok) + return; + + global $conf; + $source = $tmp_filename; + + if ( $this->with_local ) + { + $dest = $this->local_destdir.'/'.$dest_filename; + + if (!@copy( $source,$dest )); + { + if ( ! $this->mkdirs( dirname($dest) ) ) + return; // Fehler bei Verzeichniserstellung, also abbrechen. + + if (!@copy( $source,$dest )) + { + $this->ok = false; + $this->log[] = 'failed copying local file:'; + $this->log[] = 'source : '.$source; + $this->log[] = 'destination: '.$dest; + return; // Fehler beim Kopieren, also abbrechen. + } + if ( ! is_null($lastChangeDate) ) + touch( $dest,$lastChangeDate ); + } + + if (!empty($conf['security']['chmod'])) + { + // CHMOD auf der Datei ausfuehren. + if ( ! @chmod($dest,octdec($conf['security']['chmod'])) ) + { + $this->ok = false; + $this->log[] = 'Unable to CHMOD file '.$dest; + return; + } + } + } + + if ( $this->with_ftp ) // Falls FTP aktiviert + { + $dest = $dest_filename; + $this->ftp->put( $source,$dest ); + + if ( ! $this->ftp->ok ) + { + $this->ok = false; + $this->log[] = $this->ftp->log; + } + } + } + + + + /** + * Rekursives Anlagen von Verzeichnisse + * Nett gemacht. + * Quelle: http://de3.php.net/manual/de/function.mkdir.php + * Thx to acroyear at io dot com + * + * @param String Verzeichnis + * @return boolean + */ + function mkdirs( $strPath ) + { + global $conf; + + if ( is_dir($strPath) ) + return true; + + $pStrPath = dirname($strPath); + if ( !$this->mkdirs($pStrPath) ) + return false; + + if ( ! @mkdir($strPath,0777) ) + { + $this->ok = false; + $this->log[] = 'Cannot create directory: '.$strPath; + return false; + } + + // CHMOD auf dem Verzeichnis ausgef�hren. + if (!empty($conf['security']['chmod_dir'])) + { + if ( ! @chmod($strPath,octdec($conf['security']['chmod_dir'])) ) + { + $this->ok = false; + $this->log[] = 'Unable to CHMOD directory: '.$strPath; + return false; + } + } + + + return $this->ok; + } + + + + /** + * Beenden des Ver�ffentlichungs-Vorganges.<br> + * Eine vorhandene FTP-Verbindung wird geschlossen.<br> + * Falls entsprechend konfiguriert, wird ein Systemkommando ausgef�hrt. + */ + function close() + { + if ( $this->with_ftp ) + { + $this->ftp->close(); + } + + // Ausf�hren des Systemkommandos. + if ( !empty($this->cmd_after_publish) && $this->ok ) + { + $ausgabe = array(); + $rc = false; + exec( $this->cmd_after_publish,$ausgabe,$rc ); + + if ( $rc != 0 ) // Wenn Returncode ungleich 0, dann Ausgabe ins Log schreiben und Fehler melden. + { + $this->log = $ausgabe; + $this->log[] = 'OpenRat: System command failed - returncode is '.$rc; + $this->ok = false; + } + } + } + + + + /** + * Aufraeumen des Zielverzeichnisses.<br><br> + * Es wird der komplette Zielordner samt Unterverzeichnissen durchsucht. Jede + * Datei, die laenger existiert als der aktuelle Request alt ist, wird geloescht.<br> + * Natuerlich darf diese Funktion nur nach einem Gesamt-Veroeffentlichen ausgefuehrt werden. + */ + function clean() + { + if ( $this->ok ) + return; + + if ( !empty($this->local_destdir) ) + $this->cleanFolder($this->local_destdir); + } + + + + /** + * Aufr�umen eines Verzeichnisses.<br><br> + * Dateien, die l�nger existieren als der aktuelle Request alt ist, werden gel�scht.<br> + * + * @param String Verzeichnis + */ + function cleanFolder( $folderName ) + { + $dh = opendir( $folderName ); + + while( $file = readdir($dh) ) + { + if ( $file != '.' && $file != '..') + { + $fullpath = $folderName.'/'.$file; + + // Wenn eine Datei beschreibbar und entsprechend alt + // ist, dann entfernen + if ( is_file($fullpath) && + is_writable($fullpath) && + filemtime($fullpath) < START_TIME ) + unlink($fullpath); + + // Bei Ordnern rekursiv absteigen + if ( is_dir( $fullpath) ) + { + $this->cleanFolder($fullpath); + @rmdir($fullpath); + } + } + } + } + +} + +?>+ \ No newline at end of file diff --git a/util/Session.class.php b/util/Session.class.php @@ -0,0 +1,225 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// OpenRat Content Management System +// Copyright (C) 2002-2004 Jan Dankert, cms@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + +// PHP-Versionsunabhaengiges Array fuer die Session-Variablen ermitteln +if (isset($_SESSION)) + $SESS = &$_SESSION; +else $SESS = &$HTTP_SESSION_VARS; + +if ( isset($_FILES) ) + $FILES = &$_FILES; +else $FILES = &$HTTP_POST_FILES; + + +/** + * Session-Funktionen zum Lesen/Schreiben in/von HTTP-Session + * In der Session werden folgende Daten abgelegt + * - Ausgewaehltes Projekt + * - Ausgewaehlte Projectsprache + * - Ausgewaehlte Projektvariante + * - Angemeldeter Benutzer + * - Auswahlbaum + * - Geladene Sprachelemente + * - Ausgewaehlter Ordner + * - Ausgewaehltes Objekt + * - Datenbankobjekt + * Die Methoden dieser Klassen koennen statisch aufgerufen werden + * + * @author $Author$ + * @version $Revision$ + * @package openrat.service + */ + +class Session +{ + function get( $var ) + { + global $SESS; + if ( isset($SESS['ors_'.$var]) ) + return $SESS['ors_'.$var]; + else + return ''; + } + + function set( $var,$value ) + { + global $SESS; + $SESS[ 'ors_'.$var ] = $value; + } + + + + function getConfig() + { + return Session::get('config'); + } + + function setConfig( $var ) + { + Session::set('config',$var); + } + + + + function getProjectModel() + { + return Session::get('project_model'); + } + + function setProjectModel( $var ) + { + Session::set('project_model',$var); + } + + + + function getProjectLanguage() + { + return Session::get('project_language'); + } + + function setProjectLanguage( $var ) + { + Session::set('project_language',$var); + } + + + + function getObject() + { + return Session::get('object'); + } + + function setObject( $var ) + { + Session::set('object',$var); + } + + + + function getFolder() + { + return Session::get('folder'); + } + + function setFolder( $var ) + { + Session::set('folder',$var); + } + + + + function getTree() + { + return Session::get('tree'); + } + + function setTree( $var ) + { + Session::set('tree',$var); + } + + + + function getElement() + { + return Session::get('element'); + } + + function setElement( $var ) + { + Session::set('element',$var); + } + + + + function getProject() + { + return Session::get('project'); + } + + function setProject( $var ) + { + Session::set('project',$var); + } + + + + function getUser() + { + return Session::get('userObject'); + } + + function setUser( $var ) + { + Session::set('userObject',$var); + } + + + function getDatabase() + { + return Session::get('database'); + } + + function setDatabase( $var ) + { + Session::set('database',$var); + } + + + function getSubaction() + { + return Session::get('subaction'); + } + + function setSubaction( $var ) + { + Session::set('subaction',$var); + } + + + function getClipboard() + { + return Session::get('clipboard'); + } + + function setClipboard( $var ) + { + Session::set('clipboard',$var); + } + + + /** + * Schliesst die aktuelle Session + * + * Diese Funktion sollte so schnell wie moeglich aufgerufen werden, da vorher + * keine andere Seite (im Frameset!) geladen werden kann + * Nach Aufruf dieser Methode sind keine Session-Zugriffe ueber diese Klasse mehr + * moeglich. + */ + function close() + { + session_write_close(); + } +} + +?>+ \ No newline at end of file diff --git a/util/Sql.class.php b/util/Sql.class.php @@ -0,0 +1,334 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// OpenRat Content Management System +// Copyright (C) 2002-2006 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- + + + +/** + * SQL-Anweisung.<br> + * <br> + * Darstellen eines SQL-Statements incl. Methoden zum Fuellen von + * Platzhaltern im SQL-Befehl.<br> + * <br> + * Beispiel<br> + * <pre> + * // Neues Objekt erzeugen mit SQL-Anweisung + * $sql = new Sql('SELECT * FROM xy WHERE id={uid} AND name={name}'); + * + * // Parameter f�llen + * $sql->setInt ('uid' ,1 ); + * $sql->setString('name','peter'); + * + * // Fertige SQL-Anweisung verwenden + * $xy->execute( $sql->query ); + * </pre> + * <br> + * Ziele dieser Klasse sind:<br> + * - Schreiben einfacher SQL-Anweisungen ohne Stringverarbeitung<br> + * - Verhindern von SQL-Injection.<br> + * <br> + * + * @author Jan Dankert, $Author$ + * @version $Revision$ + * @package openrat.services + */ + +class Sql +{ + /** + * Urspr�ngliche SQL-Anweisung. + */ + var $src = ''; + + /** + * Auszuf�hrende Abfrage. + */ + var $query = ''; + + var $raw = ''; + + + /** + * Zwischenspeicher f�r Parameterwerte. + */ + var $data = Array(); + + /** + * Ein 2-dimensionales Array mit den Positionen der Parameter.<br> + * <br> + * Beispiel:<br> + * <pre> + * + * Array + * ( + * [lid] => Array + * ( + * [0] => 65 + * [1] => 81 + * ) + * [oid] => Array + * ( + * [0] => 123 + * ) + * ) + * </pre> + * In der ersten Dimension sind die Parameter vorhanden, jeder Parameter hat eine Liste von Positionen, an denen er steht.<br> + * Ein Parameter kann n�mlich mehrfach vorkommen! + */ + var $param = array(); + + + var $dbid = ''; + + + /** + * Erzeugt ein SQL-Objekt und analysiert die SQL-Anfrage. + */ + function Sql( $query = '', $dbid='' ) + { + $this->dbid = $dbid; + $this->parseSourceQuery( $query ); + + $this->data = array(); + } + + + + /** + * Die SQL-Anfrage wird auf Parameter untersucht. + */ + function parseSourceQuery( $query ) + { + $this->src = $query; // Wir merken uns die Ur-Abfrage, evtl. f�r Fehlermeldungen interessant. + + while( true ) // Schleife wird solange durchlaufen, solange Parameter gefunden werden. + { + $posKlLinks = strpos($query,'{'); + $posKlRechts = strpos($query,'}'); + + if ( $posKlLinks === false ) + break; // Schleife abbrechen, wenn kein Parameter mehr gefunden wird. + + $nameParam = substr($query,$posKlLinks+1,$posKlRechts-$posKlLinks-1); // Name Parameter + + if ( !isset($this->param[$nameParam ])) + $this->param [$nameParam ] = array(); + + $this->param[$nameParam ][] = $posKlLinks; + + $query = substr($query,0,$posKlLinks).substr($query,$posKlRechts+1); + } + + $this->query = $query; +// $merkeParam = $this->param; + + // Tabellennamen in die Platzhalter setzen. + // Dies ist noch OpenRat-spezifisch und sollte bei einer sauberen Abstraktion woanders gemacht werden. Aber wo? + foreach( table_names($this->dbid) as $t=>$name ) + { + $this->setParam($t,$name,false ); + + unset( $this->param[$t] ); + + } + + $this->raw = $this->query; + //$this->param = $merkeParam; + + } + + + + /** + * Setzt eine neue SQL-Abfrage.<br> + * Bereits vorhandene Parameter werden automatisch wieder gesetzt. + */ + function setQuery( $query = '' ) + { + $this->parseSourceQuery( $query ); + + // Bereits vorhande Parameter setzen. + foreach( $this->data as $name=>$data ) + { + if ( $data['type']=='string' ) $this->setString ($name,$data['value'] ); + if ( $data['type']=='int' ) $this->setInt ($name,$data['value'] ); + if ( $data['type']=='null' ) $this->setNull ($name ); + } + } + + + + /** + * Setzt einen Parameter.<br> + * Diese Methode sollte nur intern aufgerufen werden!<br> + * + * @param name Name des Parameters + * @param value Inhalt + * @param dieIfUnknown wenn <code>true</code> und Parameter unbekannt, dann Abbruch. + * @access private + */ + function setParam( $name,$value,$dieIfUnknown=true) + { + + // Nett gemeint, f�hrt aber aktuell zu Fehlern, weil an vielen Stellen zu viele Parameter gef�llt werden. + // Daher erstmal deaktiviert. + // if ( !isset($this->param[$name]) ) + // { + // if ( $dieIfUnknown ) + // die("parameter '$name' unknown. SQL=".$this->src); + // else + // return; + // } + + if ( !isset($this->param[$name]) ) + return; // Parameter nicht vorhanden. + + if ( is_array($this->param[$name]) ) + { + foreach( $this->param[$name] as $idx=>$xyz ) + { + $pos = $this->param[$name][$idx]; + + $this->query = substr( $this->query,0,$pos ).$value.substr( $this->query,$pos ); + + foreach( $this->param as $pn=>$par) + { + foreach( $par as $i=>$p ) + { + if ( $p > $pos ) + $this->param[$pn][$i]=$p+strlen($value); + } + } + + } + } + } + + + + /** + * Setzt einen Parameter.<br> + * Der Typ des Parameters wird automatisch ermittelt.<br> + * + * @param name Name des Parameters + * @param value Inhalt + */ + function setVar( $name,$value ) + { + if ( is_string($value) ) + $this->setString( $name,$value ); + + if ( is_null($value) ) + $this->setNull( $name ); + + if ( is_int($value) ) + $this->setInt( $name,$value ); + } + + + + /** + * Setzt eine Ganzzahl als Parameter.<br> + * + * @param name Name des Parameters + * @param value Inhalt + */ + function setInt( $name,$value ) + { + $this->data[ $name ] = array( 'type'=>'int','value'=>(int)$value ); + } + + + + /** + * Setzt eine Zeichenkette als Parameter.<br> + * + * @param name Name des Parameters + * @param value Inhalt + */ + function setString( $name,$value ) + { + $this->data[ $name ] = array( 'type'=>'string','value'=>$value ); + } + + + + /** + * Setzt einen bool'schen Wert als Parameter.<br> + * Ist der Parameterwert wahr, dann wird eine 1 gesetzt. Sonst 0.<br> + * + * @param name Name des Parameters + * @param value Inhalt + */ + function setBoolean( $name,$value ) + { + if ( $value ) + $this->setInt( $name,1 ); + else $this->setInt( $name,0 ); + } + + + + /** + * Setzt einen Parameter auf den Wert <code>null</code>.<br> + * + * @param name Name des Parameters + */ + function setNull( $name ) + { + $this->data[ $name ] = array( 'type'=>'null' ); + } + + + + /** + * Ermittelt die fertige SQL-Anfrage.<br> + * Alias zu #getQuery() + */ + function &query() + { + return $this->getQuery(); + } + + + + /** + * Ermittelt die fertige SQL-Anfrage. + * @param Name einer Funktion, die eine Zeichenkette für die + * Datenbank schuetzt. Dies kann je nach verwendetem RDBMS + * unterschiedlich sein, daher diese Funktionsreferenz. + */ + function &getQuery( $escape_function ) + { + // Bereits gesetzte Parameter setzen. + foreach( $this->data as $name=>$data ) + { + if ( $data['type']=='string' ) $this->setParam($name,"'".$escape_function($data['value'])."'" ); + elseif ( $data['type']=='int' ) $this->setParam($name,(int)$data['value'] ); + elseif ( $data['type']=='null' ) $this->setParam($name,'NULL' ); + } + + return $this->query; + } +} + + +?>+ \ No newline at end of file diff --git a/util/TemplateEngine.class.php b/util/TemplateEngine.class.php @@ -0,0 +1,507 @@ +<?php +# +# OpenRat Content Management System +# Copyright (C) 2002-2009 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Wandelt eine Vorlage in ein PHP-Skript um. + * + * Die Vorlage wird gesparst, Elemente werden geladen und in die Zieldatei kopiert. + * + * @author Jan Dankert + * @package openrat.services + */ +class TemplateEngine +{ + var $actualTagName = ''; + + /** + * Name Template. + * + * @var String + */ + var $tplName; + + /** + * Erzeugt einen Templateparser. + * + * @param String $tplName Name des Templates, das umgewandelt werden soll. + */ + function TemplateEngine( $tplName='' ) + { + $this->tplName = $tplName; + } + + + /** + * Wandelt eine Vorlage um + * @param filename Dateiname der Datei, die erstellt werden soll. + */ + function compile( $tplName = '') + { + if ( empty($tplName) ) + $tplName = $this->tplName; + + global $conf; + $srcOrmlFilename = 'themes/default/templates/'.$tplName.'.tpl.src.'.PHP_EXT; + $srcXmlFilename = 'themes/default/templates/'.$tplName.'.tpl.src.xml'; + + if ( is_file($srcOrmlFilename) ) + $srcFilename = $srcOrmlFilename; + elseif ( is_file($srcXmlFilename) ) + $srcFilename = $srcXmlFilename; + else + // Wenn Vorlage (noch) nicht existiert + die( get_class($this).': Template not found: "'.$tplName.'"' ); + + $filename = 'themes/default/pages/html/'.$tplName.'.tpl.'.PHP_EXT; + + // Wenn Vorlage gaendert wurde, dann Umwandlung erneut ausf�hren. + if ( $conf['theme']['compiler']['cache'] && is_file($filename) && filemtime($srcFilename) <= filemtime($filename)) + return; + + if ( is_file($filename) && !is_writable($filename) ) + die( get_class($this).': File is read-only: '.$filename); + + Logger::debug("Compile template: ".$srcFilename.' to '.$filename); + + // Vorlage und Zieldatei oeffnen + $document = $this->loadDocument( $srcFilename ); + + // Prüfen, ob Zielverzeichnis existiert, falls nicht: Anlegen. + if ( ! is_dir(dirname($filename)) ) + { + $rc = mkdir( dirname($filename) ); + if ( ! $rc ) + Http::serverError('Unable to create directory: '.dirname($filename)); + } + + $outFile = @fopen($filename,'w'); + + if ( !is_resource($outFile) ) + Http::serverError( get_class($this).': Unable to open file for writing: '.$filename); + + $openCmd = array(); + $depth = 0; + + foreach( $document as $line ) + { + // Initialisieren der m�glichen Element-Inhalte + $type = ''; + $attributes = array(); + $value = ''; + $tag = ''; + + + // Setzt: $tag, $attributes, $value, $type + extract( $line ); + + $this->actualTagName = $tag; + + if ($type == 'complete' || $type == 'open') + $attributes = $this->checkAttributes($tag,$attributes); + + if ( $type == 'open' ) + $this->copyFileContents( $tag,$outFile,$attributes,++$depth ); + elseif ( $type == 'complete' ) + { + $this->copyFileContents( $tag ,$outFile,$attributes,$depth+1 ); + $this->copyFileContents( $tag.'-end',$outFile,array() ,$depth+1 ); + } + elseif ( $type == 'close' ) + $this->copyFileContents( $tag.'-end',$outFile,array(),--$depth ); + } + + fclose($outFile); + + // CHMOD ausf�hren. + if ( !empty($conf['theme']['compiler']['chmod'])) + if ( !@chmod($filename,octdec($conf['theme']['compiler']['chmod'])) ) + die( "CHMOD failed on file ".$filename ); + } + + + + function getElementValue( $elFilename,$attributes ) + { + extract($attributes); + require($elFilename); + return $value; + } + + + + function attributeValueOpenPHP($value) + { + $erg = $this->attributeValue($value); + + // Für statische Texte muss kein PHP-Abschnitt geoeffnet werden. + if (substr($erg,0,1) == "'" && strpos($erg,'$')===FALSE ) + return substr($erg,1,-1); + else + return '<'.'?php echo '.$erg.' ?>'; + } + + + + function attributeValue( $value ) + { + $parts = explode( ':', $value, 2 ); + + if ( count($parts) < 2 ) + $parts = array('',$value); + + list( $type,$value ) = $parts; + + $invert = ''; + if ( substr($type,0,1)=='!' ) + { + $type = substr($type,1); + $invert = '! '; + } + + switch( $type ) + { + case 'var': + return $invert.'$'.$value; + case 'text': + case '': + // Sonderf�lle f�r die Attributwerte "true" und "false". + // Hinweis: Die Zeichenkette "false" entspricht in PHP true. + // Siehe http://de.php.net/manual/de/language.types.boolean.php + if ( $value == 'true' || $value == 'false' ) + return $value; + else + // macht aus "text1{var}text2" => "text1".$var."text2" + return "'".preg_replace('/{(\w+)\}/','\'.$\\1.\'',$value)."'"; + case 'method': + return $invert.'$this->'.$value.'()'; + case 'size': + return '@count($'.$value.')'; + case 'property': + return $invert.'$this->'.$value; + case 'message': +// return 'lang('."'".$value."'".')'; + // macht aus "text1{var}text2" => "text1".$var."text2" + return 'lang('."'".preg_replace('/{(\w+)\}/','\'.$\\1.\'',$value)."'".')'; + case 'messagevar': + return 'lang($'.$value.')'; + case 'mode': + return $invert.'$mode=="'.$value.'"'; + case 'arrayvar': + list($arr,$key) = explode(':',$value.':none'); + return $invert.'@$'.$arr.'['.$key.']'; + case 'config': + $config_parts = explode('/',$value); + return $invert.'@$conf['."'".implode("'".']'.'['."'",$config_parts)."'".']'; + + default: + Http::serverError( get_class($this).': Unknown type "'.$type.'" in attribute. Allowed: var|method|property|message|messagevar|config or none'); + } + } + + + + /** + * Ein Baustein wird in die neue Vorlagedatei kopiert. + */ + function copyFileContents( $infile,$outFileHandler,$attr,$depth ) + { + global $conf; + $hash = $depth; + + $inFileName = OR_THEMES_DIR.$conf['interface']['theme'].'/include/html/'.$infile.'.inc.'.PHP_EXT; + $elFileName = OR_THEMES_DIR.$conf['interface']['theme'].'/include/html/'.$infile.'.el.' .PHP_EXT; + if ( !is_file($inFileName) ) + if ( count($attr)==0 ) + return; + else + // Baustein nicht vorhanden, Abbbruch. + die( get_class($this).': Compile failed, file not found: '.$inFileName ); + + $values = array(); + foreach( $attr as $attrName=>$attrValue ) + { + $values[] = "'".$attrName."'=>".$this->attributeValue($attrValue); + } + + // Variablen $attr_* setzen + if ( count($attr) > 0 ) + { + fwrite( $outFileHandler,'<?php '); + foreach( $attr as $attrName=>$attrValue ) + fwrite( $outFileHandler,'$a'.$hash.'_'.$attrName."=".$this->attributeValue($attrValue).';'); + fwrite( $outFileHandler,' ?>'); + } + + $file = file( $inFileName ); + $ignore = false; + $linebreaks = true; + + foreach( $file as $line ) + { + // Ignoriere Zeilen, die fuer ein nicht vorhandenes Attribut gelten. + if ( strpos($line,'#IF-ATTR')!==FALSE ) + { + $found = false; + foreach( $attr as $attrName=>$attrValue ) + { + if ( strpos($line,'#IF-ATTR '.$attrName.'#')!==FALSE ) + $found = true; + if ( strpos($line,'#IF-ATTR-VALUE '.$attrName.':'.$attrValue.'#')!==FALSE ) + $found = true; + } + if ( ! $found ) + $ignore = true; + } + // Nach einem IF-Block ertmal alles wieder anzeigen. + if ( strpos($line,'#END-IF')!==FALSE ) + { + $ignore = false; + } + + if ( strpos($line,'#ELSE')!==FALSE ) + { + $ignore = !$ignore; + } + + // Zeilenumbr�che nicht setzen. + if ( strpos($line,'#SET-LINEBREAK-OFF')!==FALSE ) + $linebreaks = false; + + // Zeilenumbr�che setzen. + if ( strpos($line,'#SET-LINEBREAK-ON')!==FALSE ) + $linebreaks = true; + + // Ignoriere Zeilen, die zu ignorieren sind (logisch). + // Dies sind Blöcke, die nur fuer ein Attribut gueltig sind, welches + // aber nicht gesetzt ist. + if ( $ignore ) + continue; + + // Ignoriere Leerzeilen + if ( strlen(trim($line)) == 0) + continue; + // Ignoriere Kommentarzeilen + if ( in_array(substr(ltrim($line),0,2),array('//','/*','<!') ) || substr(ltrim($line),0,1) == '#') + continue; + // Ignoriere Kommentarzeilen + if ( in_array(substr(rtrim($line),-3),array('-->',' */') ) ) + continue; + + if ( !$linebreaks ) + $line = rtrim($line); + + // Die Variablen "$attr_*" muessen pro Ebene eindeutig sein, daher wird an den + // Variablennamen die Tiefe angehangen. + $line = str_replace('$attr_','$a'.$hash.'_',$line); + + foreach( $attr as $attrName=>$attrValue ) + $line = str_replace('%'.$attrName.'%',$this->attributeValueOpenPHP($attrValue),$line); + + + fwrite( $outFileHandler,$line ); + } + + // Variablen $attr_* entfernen. + $unset_attr = array(); + foreach( $attr as $attrName=>$attrValue ) + $unset_attr[] = '$a'.$hash.'_'.$attrName; + + if ( count($unset_attr) > 0 ) + fwrite( $outFileHandler,'<?php unset('.implode(',',$unset_attr).') ?>'); + + if ( is_file($elFileName) ) + { + fwrite( $outFileHandler, $this->getElementValue( $elFileName,$attr) ); + } + } + + + + /** + * Diese Funktion pr�ft, ob die Attribute zu einem Element g�ltig sind.<br> + * Falls ein ung�ltiges Attribut oder ein ung�ltiger Wert entdeckt wird, + * so wird das Skript abgebrochen. + * @return �berpr�fte und mit Default-Werten angereicherte Attribute + */ + function checkAttributes( $cmd,$attr ) + { + global $conf; + $elements = parse_ini_file( OR_THEMES_DIR.$conf['interface']['theme'].'/include/elements.ini.'.PHP_EXT); + + if ( !isset($elements[$cmd]) ) + Http::serverError( get_class($this).': Parser error, unknown element "'.$cmd.'". Allowed: '.implode(',',array_keys($elements)) ); + + $checkedAttr = array(); + + // Schleife �ber alle Attribute. + foreach( explode(',',$elements[$cmd]) as $al ) + { + $al=trim($al); + if ( $al=='') + continue; // Leeres Attribut... nicht zu gebrauchen. + + + $pair = explode(':',$al,2); + if ( count($pair) == 1 ) $pair[] = null; + list($a,$default) = $pair; + + if ( is_string($default)) + $default = str_replace('COMMA',',',$default); // Komma in Default-Werten ersetzen. + + if ( isset($attr[$a])) + $checkedAttr[$a]=$attr[$a]; // Attribut ist bereits vorhanden, alles ok. + elseif ( $default=='*') // Pflichtfeld! + die( get_class($this).': Element "'.$cmd.'" needs the required attribute "'.$a.'"' ); + elseif ( !is_null($default) ) + $checkedAttr[$a]=$default; + else + ; + + unset( $attr[$a] ); // Damit am Ende das Urprungsarray leer wird. + } + + if ( count($attr) > 0 ) + { + foreach($attr as $name=>$value) + Http::serverError( get_class($this).': Unknown attribute "'.$name.'" in element "'.$cmd.'". Allowed: '.$elements[$cmd]."\n" ); + } + + return $checkedAttr; + + } + + + /** + * Diese Funktion l�dt die passende Vorlagedatei. + */ + function loadDocument( $filename ) + { + if ( substr($filename,-4)=='.xml') + return $this->loadXmlDocument( $filename ); + else + return $this->loadOrmlDocument( $filename ); + } + + + /** + * Laden und Parsen eines XML-Dokumentes. + */ + function loadXmlDocument( $filename ) + { + $index = array(); + $vals = array(); + $p = xml_parser_create(); + xml_parser_set_option ( $p, XML_OPTION_CASE_FOLDING,false ); + xml_parser_set_option ( $p, XML_OPTION_SKIP_WHITE,false ); + xml_parse_into_struct($p, implode('',file($filename)), $vals, $index); + xml_parser_free($p); + + return $vals; + } + + + /** + * Laden und Parsen eines Dokumentes im Openrat-eigenem Format.<br> + * ("ORML"=Openrat Meta Language) + */ + function loadOrmlDocument( $filename ) + { + $vals = array(); + + $openCmd = array(); + + foreach( file($filename) as $line ) + { + $indent = strlen($line)-strlen(ltrim($line)); // Einzugstiefe + $line = trim($line); // Inhalt der Zeile ohne Einzug + + if ( empty($line) ) // Leerzeilen in Vorlage + { + continue; + } + + if ( substr($line,0,1)=='#' || substr($line,0,2)=='//') + continue; + + $openCmdCopy = $openCmd; + krsort($openCmdCopy); + foreach($openCmdCopy as $idx=>$ccmd) + { + if ( $idx >= $indent ) + { + $vals[] = array( 'tag' =>$ccmd, + 'type' =>'close', + 'value' =>'', + 'attributes' => array(), + 'level' => $indent ); + unset($openCmd[$idx]); + } + } + + // Zeile parsen + $li = explode(' ',$line); + $attr = array(); + foreach( $li as $nr=>$part ) + { + if ($nr==0) + $cmd = $part; + else + { + $el = explode(':',$part,2); + if ( count($el) < 2 ) + die( 'parser error in line: '.$line ); + + list($a,$b) = $el; + $attr[$a]=$b; + } + + } + // $cmd => enthaelt das Kommando + // $attr => enthaelt die Attribute + + $openCmd[$indent]=$cmd; + + $vals[] = array( 'tag'=>$cmd, + 'type'=>'open', + 'value'=>'', + 'attributes'=>$attr, + 'level'=>$indent ); + } + + // Am Ende der Datei alle offenen Tags schlie�en + $openCmdCopy = $openCmd; + krsort($openCmdCopy); + foreach($openCmdCopy as $idx=>$ccmd) + { + $vals[] = array( 'tag'=>$ccmd, + 'type'=>'close', + 'value'=>'', + 'attributes'=>array(), + 'level'=>$indent ); + + unset($openCmd[$idx]); + } + + + return $vals; + } +} + +?>+ \ No newline at end of file diff --git a/util/Text.class.php b/util/Text.class.php @@ -0,0 +1,415 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// DaCMS Content Management System +// Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.10 2009-04-18 00:56:14 dankert +// Beim Verarbeiten von if-empty-Bereichen der Seitenvorlage keine regulären Ausdrücke mehr verwenden (da Binärausgaben wie PDF-Dokumente dabei beschädigt werden). +// +// Revision 1.9 2007-11-27 21:16:33 dankert +// Bugfix in "encodeHtmlSpecialChars()" +// +// Revision 1.8 2007-11-27 21:10:35 dankert +// Verschieben von "replaceHtmlChars()" nach Klasse Text. +// +// Revision 1.7 2007-11-24 13:22:04 dankert +// Neue Methode "encodeHtmlSpecialChars()" +// +// Revision 1.6 2007-11-17 13:36:06 dankert +// Methode "textdiff()" in Text-Klasse verschoben. +// +// Revision 1.5 2006/12/09 16:56:40 dankert +// Methode "encodeHtml()" ersetzt nun auch Umlaute gem. Konfiguration. +// +// Revision 1.4 2005/04/16 22:26:15 dankert +// Erweiterung Methode maxLength() +// +// Revision 1.3 2005/02/17 21:22:22 dankert +// Weitere Funktionen f?r HTML und BB-Code +// +// Revision 1.2 2004/05/02 15:04:16 dankert +// Einf�gen package-name (@package) +// +// Revision 1.1 2004/04/24 17:03:28 dankert +// Initiale Version +// +// --------------------------------------------------------------------------- + + +/** + * Nuetzliche Funktionen fuer das Bearbeiten von Texten/Zeichenketten + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Text +{ + /** + * Alias fuer Methode maxLength() + * + * @deprecated use maxlength() ! + */ + function maxLaenge( $laenge,$text ) + { + return Text::maxLength($text,$laenge); + } + + + /** + * Einen Text auf eine bestimmte Laenge begrenzen. + * + * Ist der Text zu lang, so wird abgeschnitten und + * eine Zeichenkette angehaengt. + * + * @param String Text, der zu begrenzen ist + * @param Integer maximale Laenge des Textes (optional) + * @param Text, der an gekuerzten Text angehangen wird (optional) + */ + function maxLength( $text,$laenge=20,$append='...',$where=STR_PAD_RIGHT ) + { + if ( strlen($text) > $laenge ) + { + if ( $where == STR_PAD_RIGHT ) + $text = substr($text,0,$laenge).$append; + elseif ( $where == STR_PAD_BOTH ) + $text = substr($text,0,$laenge/2).$append.substr($text,strlen($text)-($laenge/2)); + } + + return $text; + } + + + /** + * Umwandeln von BB-Code in Wiki-Textauszeichnungen + * + * @param text zu bearbeitender Text + * + * @return String Ausgabe + */ + function bbCode2Wiki( $inhalt ) + { + $inhalt = eregi_replace('\[b\]([^\[]*)\[\/b\]' , '*\\1*' ,$inhalt); + $inhalt = eregi_replace('\[i\]([^\[]*)\[\/i\]' , '_\\1_' ,$inhalt); + $inhalt = eregi_replace('\[code\]([^\[]*)\[\/code\]' , '=\\1=' ,$inhalt); + + $inhalt = eregi_replace('\[url\]([^\[]*)[\/url\]' ,'"\\1"->"\\1"' ,$inhalt); + $inhalt = eregi_replace('\[url=([^\[]*)\]([^\[]*)\[\/url\]','"\\2"->"\\1"' ,$inhalt); + + return $inhalt; + } + + + /** + * Umwandeln von einfachen HTML-Befehlen in Wiki-Textauszeichnungen + * + * @param text zu bearbeitender Text + * + * @return String Ausgabe + */ + function Html2Wiki( $inhalt ) + { + $inhalt = eregi_replace('<b(.*)>(.*)</b>','*\\2*' ,$inhalt); + $inhalt = eregi_replace('<i(.*)>(.*)</i>','_\\2_' ,$inhalt); + $inhalt = eregi_replace('<a(.*)href="(.*)">(.*)</a>','"\\3"->"\\2"' ,$inhalt); + + return $inhalt; + } + + + /** + * HTML-Entitaeten fuer HTML-Tags verwenden + * + * @param String Text, in dem HTML-Tags umgewandelt werden sollen + * @return String Ausgabe + */ + function encodeHtml( $inhalt ) + { + $inhalt = str_replace('&','&amp;',$inhalt); + $inhalt = str_replace('"','&quot;',$inhalt); + $inhalt = str_replace('<','&lt;' ,$inhalt); + $inhalt = str_replace('>','&gt;' ,$inhalt); + + return $inhalt; + } + + + + /** + * Ersetzt Sonderzeichen durch HTML-�quivalente.<br> + * Z.B. Ersetzt "(c)" durch "&copy;". + */ + function replaceHtmlChars( $text ) + { + global $conf; + + foreach( explode(' ',$conf['editor']['html']['replace']) as $repl ) + { + list( $ersetze, $mit ) = explode(':',$repl.':'); + $text = str_replace($ersetze, $mit, $text); + } + + return $text; + } + + + + /** + * HTML-Entitaeten fuer HTML-Tags verwenden + * + * @param String Text, in dem HTML-Tags umgewandelt werden sollen + * @return String Ausgabe + */ + function encodeHtmlSpecialChars( $inhalt ) + { + return Text::replaceHtmlChars( $inhalt ); + } + + + + /** + * Vergleicht 2 Text-Arrays und ermittelt eine Darstellung der Unterschiede + * + */ + function diff( $from_text,$to_text ) + { + // Zaehler pro Textarray + $pos_from = -1; + $pos_to = -1; + + // Ergebnis-Arrays + $from_out = array(); + $to_out = array(); + + while( true ) + { + $pos_from++; + $pos_to ++; + + if ( !isset($from_text[$pos_from]) && + !isset($to_text [$pos_to ]) ) + { + // Text in ist 'neu' und 'alt' zuende. Ende der Schleife. + break; + } + elseif + ( isset($from_text[$pos_from]) && + !isset($to_text [$pos_to]) ) + { + // Text in 'neu' ist zuende, die Restzeilen von 'alt' werden ausgegeben + while( isset($from_text[$pos_from]) ) + { + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'old'); + $to_out [] = array(); + $pos_from++; + } + break; + } + elseif + ( !isset($from_text[$pos_from]) && + isset($to_text [$pos_to]) ) + { + // Umgekehrter Fall: Text in 'alt' ist zuende, Restzeilen aus 'neu' werden ausgegeben + while( isset($to_text[$pos_to]) ) + { + $from_out[] = array(); + $to_out [] = array('text'=>$to_text[$pos_to],'line'=>$pos_to+1,'type'=>'new'); + $pos_to++; + } + break; + } + elseif + ( rtrim($from_text[$pos_from]) != rtrim($to_text[$pos_to]) ) + { + // Zeilen sind vorhanden, aber ungleich + // Wir suchen jetzt die naechsten beiden Zeilen, die gleich sind. + $max_entf = min(count($from_text)-$pos_from-1,count($to_text)-$pos_to-1); + + #echo "suche start, max_entf=$max_entf, pos_from=$pos_from, pos_to=$pos_to<br/>"; + + for ( $a=0; $a<=$max_entf; $a++ ) + { + #echo "a ist $a<br/>"; + for ( $b=0; $b<=$max_entf; $b++ ) + { + #echo "b ist $b<br/>"; + if ( trim($from_text[$pos_from+$b]) != '' && + $from_text[$pos_from+$b] == $to_text[$pos_to+$a] ) + { + $pos_gef_from = $pos_from+$b; + $pos_gef_to = $pos_to +$a; + break; + } + + if ( trim($from_text[$pos_from+$a]) != '' && + $from_text[$pos_from+$a] == $to_text[$pos_to+$b] ) + { + $pos_gef_from = $pos_from+$a; + $pos_gef_to = $pos_to +$b; + break; + } + } + + if ( $b <=$max_entf) + { + break; + } + } + + if ( $a<=$max_entf ) + { + // Gleiche Zeile gefunden + #echo "gefunden, pos_gef_from=$pos_gef_from, pos_gef_to=$pos_gef_to<br/>"; + + if ( $pos_gef_from - $pos_from == 0 ) + $type = 'new'; + elseif + ( $pos_gef_to - $pos_to == 0 ) + $type = 'old'; + else + $type = 'notequal'; + + while( $pos_gef_from - $pos_from > 0 && + $pos_gef_to - $pos_to > 0 ) + { + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>$type); + $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>$type); + + $pos_from++; + $pos_to++; + } + + while( $pos_gef_from - $pos_from > 0 ) + { + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>$type); + $to_out [] = array(); + $pos_from++; + } + + while( $pos_gef_to - $pos_to > 0 ) + { + $from_out[] = array(); + $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>$type); + $pos_to++; + } + $pos_from--; + $pos_to--; + } + else + { + // Keine gleichen Zeilen gefunden + #echo "nicht gefunden, i=$i, j=$j, pos_from war $pos_from, pos_to war $pos_to<br/>"; + + while( true ) + { + if ( !isset($from_text[$pos_from]) && + !isset($to_text [$pos_to ]) ) + { + break; + } + elseif + ( isset($from_text[$pos_from]) && + !isset($to_text [$pos_to ]) ) + { + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'notequal'); + $to_out [] = array(); + } + elseif + ( !isset($from_text[$pos_from]) && + isset($to_text [$pos_to ]) ) + { + $from_out[] = array(); + $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'notequal'); + } + else + { + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'notequal'); + $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'notequal'); + } + $pos_from++; + $pos_to++; + } + } + } + else + { + // Zeilen sind gleich + $from_out[] = array('text'=>$from_text[$pos_from],'line'=>$pos_from+1,'type'=>'equal'); + $to_out [] = array('text'=>$to_text [$pos_to ],'line'=>$pos_to+1 ,'type'=>'equal'); + } + } + + return( array($from_out,$to_out) ); + } + + + /** + * Entfernt einen Text-Bereich aus einer Zeichenkette.<br> + * Es wird angegeben, von wo bis wo entfernt werden soll. + * + * @param $text Text, aus dem entfernt wird + * @param $von der Text, AB dem entfernt wird + * @param $bis der Text, BIS ZU DEM entfernt wird + * @return String Text + */ + function entferneVonBis($text,$von,$bis) + { + $beg = strpos($text,$von); + $end = strpos($text,$bis); + if ( $beg!==false && $end !==false ) + $text = substr($text,0,$beg).substr($text,$end+strlen($bis)); + return $text; + } + + + /** + * Saeubert eine Zeichenkette. + * + * Es werden ungueltige Zeichen aus einer Zeichenkette entfernt. Es wird mit einer Whitelist + * gearbeitet, d.h. die erlaubten Zeichen werden angegeben. + * + * @param $eingabe Die Eingabe-Zeichenkette, aus der ungueltige Zeichen entfernt werden sollen. + * @param $erlaubt Die erlaubten Zeichen (eine "White-List") + * @return String die aufgeräumte Zeichenkette + */ + function clean( $eingabe, $erlaubt ) + { + $first = strtr( $eingabe, $erlaubt, str_repeat("\x01", strlen($erlaubt)) ); + $second = strtr( $eingabe, $first , str_repeat("\x00", strlen($first )) ); + return str_replace("\x00",'',$second); + } + + + + function parseOID( $text ) + { + $oids = array(); + $treffer = array(); + + preg_match_all('/\"([^\"]*)__OID__([0-9]+)__([^\"]*)\"/', $text, $treffer,PREG_SET_ORDER); + + foreach( $treffer as $t ) + $oids[$t[2]] = $t[0]; + + return $oids; + } +} + + +?>+ \ No newline at end of file diff --git a/util/Transformer.class.php b/util/Transformer.class.php @@ -0,0 +1,94 @@ +<?php + +/** + * Transformieren eines Textes.<br> + * Ein Text wird geparst und neu gerendert. + * + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Transformer +{ + var $text = ''; + var $doc; + var $page; + var $element; + + function transform() + { + $this->parseDocument(); + $this->renderDocument(); + + $this->text = $this->renderedText; + } + + + + /** + * Parsen eines Textes.<br> + * Der Text muss in der Eigenschaft 'text' bereits zur Verf�gung stehen.<br> + * Der Text wird geparst und als DOM (Document object model) intern gespeichert. + */ + + function parseDocument() + { + // Den Text zeilenweise aufteilen. + $zeilen = explode("\n",$this->text); + + // Dokument erzeugen und den Text parsen. + $parser = new WikiParser(); + $this->doc = new DocumentElement(); + $this->doc->element = $this->element; + $this->doc->parse( $zeilen ); + $this->doc->page = $this->page; + } + + + + /** + * Das interne Dokumente wird gerendet.<br> + * Die fertige Ausgabe steht anschliessend in der Eigenschaft "renderedText" zur Verf�gung. + */ + function renderDocument() + { + $this->doc->encodeHtml = !$this->element->html; + + $text = $this->doc->render( $this->page->mimeType() ); + + // Liste der verlinkten Objekt-Ids. + // Die Objekt-Ids werden absteigend sortiert, damit z.B. '33' vor '3' ersetzt wird. + $linkedObjectIds = $this->doc->linkedObjectIds; + rsort( $linkedObjectIds,SORT_NUMERIC ); + + // Links object:nnn ersetzen + // + // Das Dokument-Objekt hat keine Information ueber die aktuelle Seite, + // daher werden die Links auf Objekte hier gesetzt. + foreach( $linkedObjectIds as $objectId ) + { + $targetPath = $this->page->path_to_object( $objectId ); + + // Hack: Sonderzeichen muessen in URLs maskiert werden, aber nur bei URLs die aus Link-Objekten kommen, bei allem + // anderen (insbesondere Preview-Links zu andereen Seiten) darf die Umsetzung nicht erfolgen. + // Der Renderer kann dies nicht tun, denn der erzeugt nur "object://..."-URLs. + // Beispiel: "...?a=1&b=2" wird zu "...?a=1&amp;b=2" + $o = new Object($objectId); + $o->load(); + if ( $o->isLink ) + { + $l = new Link($objectId); + $l->load(); + if ( $l->isLinkToUrl && $this->page->mimeType() == 'text/html' ) + $targetPath = htmlspecialchars($targetPath); + } + + $text = str_replace( 'object:' .$objectId, $targetPath, $text ); + $text = str_replace( 'object://'.$objectId, $targetPath, $text ); + } + + $this->renderedText = $text; + } +} + +?>+ \ No newline at end of file diff --git a/util/TreeElement.class.php b/util/TreeElement.class.php @@ -0,0 +1,73 @@ +<?php +# +# DaCMS Content Management System +# Copyright (C) 2002 Jan Dankert, jandankert@jandankert.de +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +# + +/** + * Darstellen eines Elementes in einer Baumstruktur + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class TreeElement +{ + /** + * @type Integer + */ + var $id; + + var $internalId = 0; + + /** + * Text des Baumelementes + * @type String + */ + var $text = ""; + + /** + * Beschreibung + * @type String + */ + var $description = ""; + var $url = ""; + var $icon = ""; + var $target = ""; + + /** + * Unterelemente + * Ein Array von Ids + * @type Array + */ + var $subElementIds = array(); + + /** + * Typ des Elementes + * In der Tree-Klasse muss es eine Methode mit diesem Namen geben, die das + * Element laedt. + * @type String + */ + var $type = ""; + + + // Konstruktor + function TreeElement() + { + } +} + +?>+ \ No newline at end of file diff --git a/util/Upload.class.php b/util/Upload.class.php @@ -0,0 +1,109 @@ +<?php +// --------------------------------------------------------------------------- +// $Id$ +// --------------------------------------------------------------------------- +// OpenRat Content Management System +// Copyright (C) 2002-2004 Jan Dankert, jandankert@jandankert.de +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// --------------------------------------------------------------------------- +// $Log$ +// Revision 1.5 2007-11-22 21:20:21 dankert +// Fehlerhandling, wenn Upload misslingt. +// +// Revision 1.4 2007-10-25 22:28:18 dankert +// Filemanager f?r den FCK-Editor mit Zugriff auf OpenRat-Verzeichnis. +// +// Revision 1.3 2007-10-02 21:13:44 dankert +// Men?punkt "Neu" mit direktem Hinzuf?gen von Objekten. +// +// Revision 1.2 2004/05/02 15:04:16 dankert +// Einfügen package-name (@package) +// +// Revision 1.1 2004/04/24 17:03:28 dankert +// Initiale Version +// +// Revision 1.1 2003/10/27 23:21:55 dankert +// Methode(n) hinzugefügt: savevalue(), save() +// +// --------------------------------------------------------------------------- + +/** + * Methoden fuer den Upload einer Datei + * + * @author $Author$ + * @version $Revision$ + * @package openrat.services + */ +class Upload +{ + var $filename; + var $extension; + var $value; + var $size; + var $error = ''; + + + /** + * Stellt fest, ob der Upload geklappt hat. + * + * @return boolean + */ + function isValid() + { + return empty($this->error); + } + + + + /** + * Bearbeitet den Upload einer Datei.<br> + * Bei der Objekterzeugung wird die Datei bereits geladen.<br> + * + * @return Upload + */ + function Upload( $name='file' ) // Konstruktor + { + global $FILES; + + if ( !isset($FILES[$name]) || + !isset($FILES[$name]['tmp_name']) || + !is_file($FILES[$name]['tmp_name']) ) + { + $this->error = 'No file received.'; + return; + } + + $this->size = filesize($FILES[$name]['tmp_name']); + + $fh = fopen( $FILES[$name]['tmp_name'],'r' ); + + $this->value = fread($fh,$this->size); + fclose( $fh ); + + $this->filename = $FILES[$name]['name']; + $this->extension = ''; + + $p = strrpos( $this->filename,'.' ); // Letzten Punkt suchen + + if ($p!==false) // Wennn letzten Punkt gefunden, dann dort aufteilen + { + $this->extension = substr( $this->filename,$p+1 ); + $this->filename = substr( $this->filename,0,$p ); + } + } +} + +?>+ \ No newline at end of file diff --git a/util/XML.class.php b/util/XML.class.php @@ -0,0 +1,169 @@ +<?php +/** + * Multidimensional Array-to-XML. + * + * Example: + * $xml = new XML(); + * header('Content-Type: application/xml'); + * echo $xml->encode( $yourBigArray ); + * exit; + * + * Author: Honor� Vasconcelos, Jan Dankert + * + * Original from: + * Clean XML To Array: http://www.phpclasses.org/browse/package/3598.html + * + * License of this class: BSD-Licence. + * + * 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 Author(s) 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 COPYRIGHT OWNER 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. + */ +class XML +{ + /** + * Parse multidimentional array to XML. + * + * @param array $array + * @return String + */ + var $xmlText = ''; + + + /** + * Name of the root element. + * + * @var String + */ + var $root = 'xml'; + + /* + * Char to indent with. + * + * @var String + */ + var $indentChar = "\t"; + + + /** + * Newline-Char + * @var String + */ + var $nl = "\n"; + + /** + * Encode a array to XML. + * + * @param Array $array + * @return String (serialized XML) + */ + function encode($array) + { + //star and end the XML document + $this->xmlText = '<?xml version="1.0" encoding="utf-8"?>'.$this->nl; + $this->xmlText .= '<'.$this->root.'>'.$this->nl; + $this->array_transform($array,1); + $this->xmlText .='</'.$this->root.'>'; + + return $this->xmlText; + } + + + /** + * @access private + */ + function array_transform($array,$depth){ + + foreach($array as $key => $value) + { + $attr = array(); + if ( is_numeric($key) ) + { + // Array-Einträge mit numerischen Index können nicht direkt in ein XML-Element + // umgewandelt werden, da nur-numerische Element-Namen nicht erlaubt sind. + // Daher verwenden wir dann 'entry' als Elementnamen. + $attr['id'] = $key; + $key = 'entry'; + } + + $indent = str_repeat($this->indentChar,$depth); + + if ( empty($value) ) + { + $this->xmlText .= $indent.$this->shortTag($key,$attr).$this->nl; + } + elseif ( is_object($value) ) + { + // Der Inhalt ist ein Array, daher rekursiv verzweigen. + $this->xmlText .= $indent.$this->openTag($key,$attr).$this->nl; + $prop = get_object_vars($value); + $this->array_transform($prop,$depth+1); // Rekursiver Aufruf + $this->xmlText .= $indent.$this->closeTag($key).$this->nl; + } + elseif ( is_array($value) ) + { + // Der Inhalt ist ein Array, daher rekursiv verzweigen. + $this->xmlText .= $indent.$this->openTag($key,$attr).$this->nl; + $this->array_transform($value,$depth+1); // Rekursiver Aufruf + $this->xmlText .= $indent.$this->closeTag($key).$this->nl; + } + else + { + // Der Inhalt ist ein einfacher Inhalt (kein Array). + $this->xmlText .= $indent.$this->openTag($key,$attr); + $this->xmlText .= $value; + $this->xmlText .= $this->closeTag($key).$this->nl; + } + } + } + + + function openTag($key,$attr) + { + $tag = '<'.$key; + foreach( $attr as $attr_name=>$attr_value ) + $tag .= ' '.$attr_name.'="'.$attr_value.'"'; + $tag .= '>'; + return $tag; + } + + + + function shortTag($key,$attr) + { + $tag = '<'.$key; + foreach( $attr as $attr_name=>$attr_value ) + $tag .= ' '.$attr_name.'="'.$attr_value.'"'; + $tag .= ' />'; + return $tag; + } + + + + function closeTag($key) + { + return '</'.$key.'>'; + } +} + +?>+ \ No newline at end of file diff --git a/util/include.inc.php b/util/include.inc.php @@ -0,0 +1,64 @@ +<?php + +require_once( OR_SERVICECLASSES_DIR."GlobalFunctions.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Http.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Html.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Text.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Mail.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Ldap.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."TemplateEngine.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."Preferences.class.".PHP_EXT ); +require_once( OR_SERVICECLASSES_DIR."FileUtils.class.".PHP_EXT ); + +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('tree')) ) +{ + require_once( OR_SERVICECLASSES_DIR."TreeElement.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."AbstractTree.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."AdministrationTree.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."ProjectTree.class.".PHP_EXT ); +} + +// Login +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('index')) ) +{ + require_once( OR_SERVICECLASSES_DIR."OpenId.class.".PHP_EXT ); +} + +// Veroeffentlichung +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','page','pageelement','folder')) ) +{ + require_once( OR_SERVICECLASSES_DIR."Publish.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."Ftp.class.".PHP_EXT ); +} + +// Nur bei der Erzeugung von Seiten notwendig. +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('pageelement','page','folder','element')) ) +{ + require_once( OR_SERVICECLASSES_DIR."Dynamic.class.".PHP_EXT ); +} + +// Nur bei der Erzeugung von Seiten notwendig. +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('pageelement','page','folder')) ) +{ + require_once( OR_SERVICECLASSES_DIR."Api.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."Code.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."Transformer.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."Line.class.".PHP_EXT ); +} + + +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','folder','filebrowser')) ) +{ + require_once( OR_SERVICECLASSES_DIR."Upload.class.".PHP_EXT ); +} + + +//if ( !empty($REQ[REQ_PARAM_ACTION]) && in_array($REQ[REQ_PARAM_ACTION],array('file','folder')) ) +{ + require_once( OR_SERVICECLASSES_DIR."Upload.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."ArchiveTar.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."ArchiveUnzip.class.".PHP_EXT ); + require_once( OR_SERVICECLASSES_DIR."ArchiveZip.class.".PHP_EXT ); +} + +?>+ \ No newline at end of file