also
1. Datei class.module.php
Code: Alles auswählen
<?php
/*****************************************
* File : $RCSfile: class.module.php,v $
* Project : Contenido
* Descr : Module access classes
*
* Author : Timo A. Hummel
*
* Created : 26.02.2003
* Modified : $Date: 2006/10/05 23:43:48 $
*
* © four for business AG, www.4fb.de
*
* $Id: class.module.php,v 1.13 2006/10/05 23:43:48 bjoern.behrens Exp $
******************************************/
cInclude("classes", "class.genericdb.php");
class cApiModuleCollection extends ItemCollection {
/**
* Constructor Function
* @param none
*/
function cApiModuleCollection()
{
global $cfg;
parent::ItemCollection($cfg["tab"]["mod"], "idmod");
$this->_setItemClass("cApiModule");
}
/**
* Creates a new communication item
*/
function create ($name)
{
global $auth, $client;
$item = parent::create();
$item->set("idclient", $client);
$item->set("name", $name);
$item->set("author", $auth->auth["uid"]);
$item->set("created", date("Y-m-d H:i:s"),false);
$item->store();
return $item;
}
}
/**
* Module access class
*/
class cApiModule extends Item {
var $_error;
/**
* Constructor Function
* @param $loaditem Item to load
*/
function cApiModule($loaditem = false) {
global $cfg;
parent::Item($cfg["tab"]["mod"], "idmod");
// Using no filters is just for compatibility reasons.
// That's why you don't have to stripslashes values if you store them
// using ->set. You have to add slashes, if you store data directly
// (data not from a form field)
$this->setFilters(array(), array());
if ($loaditem !== false)
{
$this->loadByPrimaryKey($loaditem);
}
} // end function
function loadByPrimaryKey ($id)
{
parent::loadByPrimaryKey($id);
if ($this->_shouldLoadFromFiles())
{
global $cfg;
$sRootPath = $cfg['path']['contenido'] . $cfg['path']['modules'] . $this->get("idclient")."/" . $this->get("idmod").".xml";
if (file_exists($sRootPath))
{
$this->import($sRootPath);
}
}
}
/**
* getTranslatedName
* Returns the translated name of the module if
* a translation exists.
*
* @param none
* @return string Translated module name or original
*/
function getTranslatedName ()
{
global $lang;
/* If we're not loaded, return */
if ($this->virgin == true)
{
return false;
}
$modname = $this->getProperty("translated-name", $lang);
if ($modname === false)
{
return $this->get("name");
} else {
return $modname;
}
}
/**
* setTranslatedName
* Sets the translated name of the module
*
* @param $name string Translated name of the module
* @return none
*/
function setTranslatedName ($name)
{
global $lang;
$this->setProperty("translated-name", $lang, $name);
}
/**
* parseModuleForStrings
* Parses the module for mi18n strings and returns
* them in an array
*
* @return array Found strings for this module
*/
function parseModuleForStrings ()
{
if ($this->virgin == true)
{
return false;
}
/* Fetch the code, append input to output */
$code = $this->get("output");
$code .= $this->get("input");
/* Initialize array */
$strings = array();
/* Split the code into mi18n chunks */
$varr = preg_split('/mi18n([\s]*)\(([\s]*)"/', $code, -1);
if (count($varr) > 1)
{
foreach ($varr as $key => $value)
{
/* Search first closing */
$closing = strpos($value,'")');
if ($closing === false)
{
$closing = strpos($value,'" )');
}
if ($closing !== false)
{
$value = substr($value,0, $closing).'")';
}
/* Append mi18n again */
$varr[$key] = 'mi18n("'.$value;
/* Parse for the mi18n stuff */
preg_match_all('/mi18n([\s]*)\("(.*)"\)/', $varr[$key], $results);
/* Append to strings array if there are any results */
if (is_array($results[1]) && count($results[2]) > 0)
{
$strings = array_merge($strings, $results[2]);
}
/* Unset the results for the next run */
unset($results);
}
}
/* Make the strings unique */
return array_unique($strings);
}
/**
* moduleInUse()
* Checks if the module is in use
* @return bool Specifies if the module is in use
*/
function moduleInUse( $module ) {
global $cfg;
$db = new DB_Contenido;
$sql = "SELECT
idmod
FROM
". $cfg["tab"]["container"] ."
WHERE
idmod = '".$module."'";
$db->query($sql);
if ($db->nf() == 0)
{
return false;
} else {
return true;
}
} // end function
/**
* isOldModule()
* Checks if the module is a pre-4.3 module
* @return boolean true if this module is an old one
*/
function isOldModule ()
{
/* Keywords to scan */
$scanKeywords = array('$cfgTab', 'idside', 'idsidelang');
$input = $this->get("input");
$output = $this->get("output");
foreach ($scanKeywords as $keyword)
{
if (strstr($input, $keyword))
{
return true;
}
if (strstr($output, $keyword))
{
return true;
}
}
}
function getField ($field)
{
$value = parent::getField($field);
switch ($field)
{
case "name":
if ($value == "")
{
$value = i18n("- Unnamed Module -");
}
}
return ($value);
}
function import ($file)
{
global $_mImport;
cInclude("classes", "class.xmlparser.php");
$parser = new XmlParser("ISO-8859-1");
$parser->setEventHandlers(array("/module/name"=> "cModule_in_Handler",
"/module/description"=> "cModule_in_Handler",
"/module/type"=> "cModule_in_Handler",
"/module/input" => "cModule_in_Handler",
"/module/output" => "cModule_in_Handler"));
if ($parser->parseFile($file))
{
$bStore = false;
foreach ($_mImport as $key => $value)
{
if ($this->get($key) != $value)
{
$this->set($key, addslashes($value));
$bStore = true;
}
}
if ($bStore == true)
{
$this->store();
}
return true;
} else {
$this->_error = $parser->error;
return false;
}
}
function store ()
{
global $cfg;
if (getEffectiveSetting("modules", "disable-history", "false") !== "true")
{
$modarchives = new cApiModuleHistoryCollection;
$modarchives->create($this->get("idmod"));
}
parent::store();
conGenerateCodeForAllArtsUsingMod($this->get("idmod"));
if ($this->_shouldStoreToFile())
{
if ($this->_makeFileDirectoryStructure())
{
$sRootPath = $cfg['path']['contenido'] . $cfg['path']['modules'] . $this->get("idclient")."/";
file_put_contents($sRootPath . $this->get("idmod").".xml", $this->export($this->get("idmod").".xml", true));
}
}
}
function _makeFileDirectoryStructure ()
{
global $cfg;
$sRootPath = $cfg['path']['contenido'] . $cfg['path']['modules'];
if (!is_dir($sRootPath))
{
@mkdir($sRootPath);
}
$sRootPath = $cfg['path']['contenido'] . $cfg['path']['modules'] . $this->get("idclient")."/";
if (!is_dir($sRootPath))
{
@mkdir($sRootPath);
}
if (is_dir($sRootPath))
{
return true;
} else {
return false;
}
}
function _shouldStoreToFile ()
{
if (getSystemProperty("modules", "storeasfiles") == "true")
{
return true;
} else {
return false;
}
}
function _shouldLoadFromFiles ()
{
if (getSystemProperty("modules", "loadfromfiles") == "true")
{
return true;
} else {
return false;
}
}
/**
* export
* Exports the specified module strings to a file
*
* @param $idmod int Module ID
* @param $idlang int Language ID
* @param $filename string Filename to return
* @param $return boolean if false, the result is immediately sent to the browser
*/
function export ($filename, $return = false)
{
cInclude("classes", "class.xmltree.php");
$tree = new XmlTree('1.0', 'ISO-8859-1');
$root =& $tree->addRoot('module');
$root->appendChild("name", htmlspecialchars($this->get("name")));
$root->appendChild("description", htmlspecialchars($this->get("description")));
$root->appendChild("type", htmlspecialchars($this->get("type")));
$root->appendChild("input", htmlspecialchars($this->get("input")));
$root->appendChild("output", htmlspecialchars($this->get("output")));
if ($return == false)
{
header("Content-Type: text/xml");
header("Etag: ".md5(mt_rand()));
header("Content-Disposition: attachment;filename=\"$filename\"");
$tree->dump(false);
} else {
return stripslashes($tree->dump(true));
}
}
} // end class
class cApiModuleTranslationCollection extends ItemCollection
{
var $_error;
/**
* Constructor Function
* @param none
*/
function cApiModuleTranslationCollection()
{
global $cfg;
parent::ItemCollection($cfg["tab"]["mod_translations"], "idmodtranslation");
$this->_setItemClass("cApiModuleTranslation");
}
/**
* Creates a new module translation item
*/
function create ($idmod, $idlang, $original, $translation = false)
{
/* Check if the original already exists. If it does,
update the translation if passed */
$mod = new cApiModuleTranslation;
$sorg = $mod->_inFilter($original);
$this->select("idmod = '$idmod' AND idlang = '$idlang' AND original = '$sorg'");
if ($item = $this->next())
{
if ($translation !== false)
{
$item->set("translation", $translation);
$item->store();
}
return $item;
} else {
$item = parent::create();
$item->set("idmod", $idmod);
$item->set("idlang", $idlang);
$item->set("original", $original);
$item->set("translation", $translation);
$item->store();
return $item;
}
}
/**
* fetchTranslation
* Fetches a translation
*
* @param $module int Module ID
* @param $lang int Language ID
* @param $string string String to lookup
*/
function fetchTranslation ($module, $lang, $string)
{
/* If the f_obj does not exist, create one */
if (!is_object($this->f_obj))
{
$this->f_obj = new cApiModuleTranslation;
}
/* Create original string */
$sorg = $this->f_obj->_inFilter($string);
/* Look up */
$this->select("idmod = '$module' AND idlang='$lang' AND original = '$sorg'");
if ($t = $this->next())
{
$translation = $t->get("translation");
if ($translation != "")
{
return $translation;
} else {
return $string;
}
} else {
return $string;
}
}
function import ($idmod, $idlang, $file)
{
global $_mImport;
cInclude("classes", "class.xmlparser.php");
$parser = new XmlParser("ISO-8859-1");
$parser->setEventHandlers(array("/module/translation/string/original"=> "cModule_in_moduleHandlerOriginal",
"/module/translation/string/translation"=> "cModule_in_moduleHandlerTranslated"));
if ($parser->parseFile($file))
{
foreach ($_mImport["items"] as $key => $value)
{
$this->create ($idmod, $idlang, $key, $value);
}
return true;
} else {
$this->_error = $parser->error;
return false;
}
}
/**
* export
* Exports the specified module strings to a file
*
* @param $idmod int Module ID
* @param $idlang int Language ID
* @param $filename string Filename to return
* @param $return boolean if false, the result is immediately sent to the browser
*/
function export ($idmod, $idlang, $filename, $return = false)
{
$langobj = new Language;
$langobj->loadByPrimaryKey($idlang);
$langstring = $langobj->get("name") . ' ('.$idlang.')';
$translations = new cApiModuleTranslationCollection;
$translations->select("idmod = '$idmod' AND idlang='$idlang'");
cInclude("classes", "class.xmltree.php");
$tree = new XmlTree('1.0', 'ISO-8859-1');
$root =& $tree->addRoot('module');
$translation =& $root->appendChild('translation');
$translation->setNodeAttribs(array("origin-language-id" => $idlang,
"origin-language-name" => $langobj->get("name")));
while ($otranslation = $translations->next())
{
$string =&$translation->appendChild("string");
$string->appendChild("original", htmlspecialchars($otranslation->get("original")));
$string->appendChild("translation", htmlspecialchars($otranslation->get("translation")));
}
if ($return == false)
{
header("Content-Type: text/xml");
header("Etag: ".md5(mt_rand()));
header("Content-Disposition: attachment;filename=\"$filename\"");
$tree->dump(false);
} else {
return $tree->dump(true);
}
}
}
/**
* Module access class
*/
class cApiModuleTranslation extends Item {
/**
* Constructor Function
* @param $loaditem Item to load
*/
function cApiModuleTranslation($loaditem = false)
{
global $cfg;
parent::Item($cfg["tab"]["mod_translations"], "idmodtranslation");
if ($loaditem !== false)
{
$this->loadByPrimaryKey($loaditem);
}
} // end function
} // end class
function cModule_in_Handler($name, $attribs, $content)
{
global $_mImport;
$_mImport[$name] = $content;
}
function cModule_in_moduleHandlerOriginal($name, $attribs, $content)
{
global $_mImport;
$_mImport["currentItem"] = $content;
}
function cModule_in_moduleHandlerTranslated($name, $attribs, $content)
{
global $_mImport;
$_mImport["items"][$_mImport["currentItem"]] = $content;
}
?>
2. Datei class.xmlparser.php
Code: Alles auswählen
<?php
/*****************************************
*
* $Id: class.xmlparser.php,v 1.7 2006/04/28 09:20:55 timo.hummel Exp $
*
* File : $RCSfile: class.xmlparser.php,v $
* Project :
* Descr :
*
* Author : Jan Lengowski
* Modified : $Date: 2006/04/28 09:20:55 $
*
* © four for business AG, www.4fb.de
******************************************/
/**
* Class for parsing XML documents using SAX
*
* This class is a abstraction class for the PHP Expat XML functions.
*
* You can define handler functions/objects for start, end, PI and data sections (1.) or
* your can define path which will trigger the defined event when encountered (2.)
*
* Example:
*
* 1.) $parser->setEvents(array("startElement"=> "myFunction",
* "endElement"=> "myFunction",
* "characterData"=> "myFunction",
* "processingInstruction" => "myFunction");
*
* The value can also be an array with the object reference and the method to call.
* i.e. "startElement"=>array(&$myObj, "myMethod") instead of "startelement"=>"myFunction"
*
* 2.) $parser->setEvents(array("/root/foo/bar"=>"myFunction"));
*
* Valid array keys are: 'startElement', 'endElement', 'characterData', 'processingInstruction' and paths
* folowing the scheme '/root/element'. The path MUST begin from the root element and MUST start with '/'.
*
* The value can also be an array with the object reference and the method to call.
* i.e. "/foo/bar"=>array(&$myObj, "myMethod") instead of "/foo/bar"=>"myFunction"
*
* It has 3 public methods:
*
* setEventHandlers - Set specific handlers for the xml parser
* parseFile - Used to parse a XML file
* parse - Used to parse a XML string
*
* A small example:
*
* include ("class.xmlparser.php");
*
* // The XML String
* $xml = '
* <?xml version="1.0"?>
* <foo>
* <bar>some text</bar>
* <bar>another text</bar>
* </foo>';
*
* function myHandler($name, $attribs, $content)
* {
* echo "<b style='color:red'>HIT</b>: [ <b>$name</b> ] [ $content ]<br/>";
* }
*
* $parser = new XmlParser; // Parser instance
* $parser->setEventHandlers(array("/foo/bar"=>"myHandler")); // Define our handler
* $parser->parse($xml); // Parse the XML string
*
* Report bugs to: jan.lengowski@4fb.de
*
* @author Jan Lengowski <Jan.Lengowski@4fb.de>
* @copyright four for business AG <www.4fb.de>
* @version 1.0
* @package 4fb_XML
*/
class XmlParser
{
/**
* XML Parser autofree
*
* @var bool
*/
var $autofree = true;
/**
* XML Parser object
*
* @var object
* @access private
*/
var $parser;
/**
* Error message
*
* @var string
* @access private
*/
var $error = '';
/**
* Element depth
* @var int
* @access private
*/
var $depth = -1;
/**
* Element counter
* @var int
* @access private
*/
var $count = 0;
/**
* Path counter
* @var int
* @access private
*/
var $pcount = 0;
/**
* Array for creating the path
* @var array
* @access private
*/
var $paths = array();
/**
* Data storage container for the path data
* @var array
* @access private
*/
var $pathdata = array();
/**
* String storing the active path
* @var string
* @access private
*/
var $activepath = '';
/**
* The active node
* @var string
* @access private
*/
var $activenode = '';
/**
* The defined events
* @var array
* @access private
*/
var $events = array();
/**
* Construtor function
*
* @access private
* @return void
*/
/* function XmlParser()
{
$this->_init();
}*/
function XmlParser($encoding = false)
{
if (!$encoding) {
$encoding = "UTF-8";
}
$this->_init($encoding);
}
/**
* Initialize the XML Parser object and sets all options
*
* @return void
* @access private
*/
function _init($encoding = false)
{
if (!$encoding) {
$encoding = "UTF-8";
}
// Create parser instance
$this->parser = xml_parser_create($encoding);
// Set parser options
xml_set_object($this->parser, $this);
xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $encoding);
xml_set_element_handler($this->parser, '_startElement', '_endElement');
xml_set_character_data_handler($this->parser, '_characterData');
xml_set_processing_instruction_handler($this->parser, '_processingInstruction');
// Misc stuff
$this->events['paths'] = array(NULL);
}
/**
* Returns the XML error message
*
* @return string XML Error message
* @access private
*/
function _error()
{
$this->error = "XML error: ".xml_error_string(xml_get_error_code($this->parser))." at line ".xml_get_current_line_number($this->parser);
return $this->error;
}
/**
* Define events for the XML parser
*
* You can define handler functions/objects for start, end, PI and data sections (1.) or
* your can define path which will trigger the defined event when encountered (2.)
*
* Example:
*
* 1.) $parser->setEvents(array("startElement" => "myFunction",
* "endElement" => "myFunction",
* "characterData" => "myFunction",
* "processingInstruction" => "myFunction");
*
* The value can also be an array with the object reference and the method to call.
* i.e. "startElement"=>array(&$myObj, "myMethod") instead of "startelement"=>"myFunction"
*
* 2.) $parser->setEvents(array("/root/foo/bar"=>"myFunction"));
*
* Valid array keys are: 'startElement', 'endElement', 'characterData', 'processingInstruction' and paths
* folowing the scheme '/root/element'. The path MUST begin from the root element and MUST start with '/'.
*
* The value can also be an array with the object reference and the method to call.
* i.e. "/foo/bar"=>array(&$myObj, "myMethod") instead of "/foo/bar"=>"myFunction"
*
* @param array Options array, valid keys are 'startElement', 'endElement', 'characterData', 'processingInstruction', or a path
*
* @access public
* @return void
*/
function setEventHandlers($options = array(NULL))
{
$options = $this->_changeKeyCase($options);
if (array_key_exists('startelement', $options))
{
$this->events['startelement'] = $options['startelement'];
}
if (array_key_exists('endelement', $options))
{
$this->events['endelement'] = $options['endelement'];
}
if (array_key_exists('characterdata', $options))
{
$this->events['characterdata'] = $options['characterdata'];
}
if (array_key_exists('processinginstruction', $options))
{
$this->events['processinginstruction'] = $options['processinginstruction'];
}
$paths = $this->_getDefinedPaths($options);
$this->events['paths'] = $paths;
}
/**
* Set the processing instruction handler
*
* @param string Processing instruction handler
*
* @return void
* @access private
*/
function _processingInstruction($parser, $target, $data)
{
$handler = $this->_getEventHandler('processinginstruction');
if ($handler)
{
if (is_array($handler))
{
$handler[0]->$handler[1]($target, $data);
} else
{
$handler($target, $data);
}
}
}
/**
* Change all array keys to lowercase
* (PHP function change_key_case is available at PHP 4.2 +)
*
* @param array Source array
*
* @return array Array with lowercased keys
* @access private
*/
function _changeKeyCase($options = array())
{
$tmp = array();
foreach ($options as $key => $value)
{
$tmp[strtolower($key)] = $value;
}
return $tmp;
}
/**
* Returns events handlers if set
*
* @param string Event type
*
* @return sring Event handler name
* @access private
*/
function _getEventHandler($event)
{
// Standard events
if (array_key_exists($event, $this->events))
{
return $this->events[$event];
}
// Paths events
if (array_key_exists($event, $this->events['paths']))
{
return $this->events['paths'][$event];
}
// No events found
return false;
}
/**
* Return all defined paths from the options
* array and returns a new array containing
* only the paths to function bindings
*
* @param array Options array
*
* @return array Paths array
* @access private
*/
function _getDefinedPaths($options)
{
$tmp = array();
foreach ($options as $key => $value)
{
if (strstr($key, '/'))
{
$tmp[$key] = $value;
}
}
return $tmp;
}
/**
* Add a path to the stack
*
* @param string Element node name
* @access private
* @return void
*/
function _addPath($depth, $name)
{
$this->paths[$depth] = $name;
}
/**
* Returns the current active path
*
* @access private
*/
function _getActivePath()
{
$tmp = array();
for ($i=0; $i<=$this->depth; $i++)
{
$tmp[] = $this->paths[$i];
}
$path = '/' . join('/', $tmp);
return $path;
}
/**
* XML start element handler
*
* @param resource XML Parser resource
* @param string XML Element node name
* @param array XML Element node attributes
*
* @return void
* @access private
*/
function _startElement($parser, $name, $attribs)
{
// Increase depth
$this->depth ++;
// Set active node
$this->activenode = $name;
// Increase element counter
if ($this->activenode == $this->pathdata[$this->activepath][$this->count]['name'])
{
$this->count ++;
} else
{
$this->count = 0;
}
// Entering element context, add subpath
$this->_addPath($this->depth, $name);
// Get the handler for this event
$handler = $this->_getEventHandler('startelement');
// If a handler is defined call it
if ($handler)
{
if (is_array($handler))
{
$handler[0]->$handler[1]($name, $attribs);
} else
{
$handler($name, $attribs);
}
}
// Check for defined path handlers
$this->activepath = $this->_getActivePath();
// Save path data
$this->pathdata[$this->activepath][$this->count] = array('name'=>$name, 'attribs'=>$attribs);
}
/**
* XML character data handler
*
* @param resource XML Parser resource
* @param string XML node data
*
* @return void
* @access private
*/
function _characterData($parser, $data)
{
// Reset node count
if ($this->activenode != $this->pathdata[$this->activepath][$this->count]['name'])
{
$this->count = 0;
}
// Save path data
$this->pathdata[$this->activepath][$this->count]['content'] .= $data;
// Get the handler for this event
$handler = $this->_getEventHandler('characterdata');
// If a handler is defined call it
if ($handler)
{
if (is_array($handler))
{
$handler[0]->$handler[1]($data);
} else
{
$handler($data);
}
}
}
/**
* XML end element handler
*
* @param resource XML Parser resource
* @param string XML Element node name
*
* @return void
* @access private
*/
function _endElement($parser, $name)
{
// Get the handler for this event
$handler = $this->_getEventHandler('endelement');
// Call Element handler
if ($handler)
{
if (is_array($handler))
{
$handler[0]->$handler[1]($name);
} else
{
$handler($name);
}
}
// Reset the active path
$this->activepath = $this->_getActivePath();
// Get handler for the active path
$handler = $this->_getEventHandler($this->activepath);
// Call path handler
if ($handler)
{
if (is_array($handler))
{ // Handler is an object method
$handler[0]->$handler[1]($this->pathdata[$this->activepath][$this->count]['name'],
$this->pathdata[$this->activepath][$this->count]['attribs'],
$this->pathdata[$this->activepath][$this->count]['content']);
} else
{ // Handler is a function
$handler($this->pathdata[$this->activepath][$this->count]['name'],
$this->pathdata[$this->activepath][$this->count]['attribs'],
$this->pathdata[$this->activepath][$this->count]['content']);
}
}
// Decrease depth
$this->depth --;
}
/**
* Parse a XML string
*
* @param string XML data
*
* @return bool
* @access public
*/
function parse($data, $final = false)
{
$success = xml_parse($this->parser, trim($data), $final);
if ($final && $this->autofree)
{
xml_parser_free($this->parser);
}
if (!$success)
{
return $this->_error();
}
return $success;
}
/**
* Parse a XML file
*
* @param string File location
*
* @return bool
* @access public
*/
function parseFile($file)
{
if (!($fp = fopen($file, "rb")))
{
}
while ($sData = fread($fp, 4096))
{
if (!xml_parse($this->parser, $sData, feof($fp)))
{
$this->_error();
return false;
}
}
if ($this->autofree)
{
xml_parser_free($this->parser);
}
return true;
}
} // XML_Parser
?>