/**
  * Runs the phpOpenTracker API call.
  *
  * @param  array $parameters
  * @return mixed
  * @access public
  */
 function run($parameters)
 {
     $visitors = array();
     $this->db->query(sprintf("SELECT visitors.accesslog_id AS accesslog_id,\r\n                visitors.visitor_id   AS visitor_id,\r\n                visitors.timestamp    AS timestamp\r\n           FROM %s accesslog,\r\n                %s visitors\r\n          WHERE visitors.client_id    = '%d'\r\n            AND visitors.accesslog_id = accesslog.accesslog_id\r\n                %s\r\n                %s\r\n          ORDER BY visitors.visitor_id,\r\n                   visitors.timestamp", $this->config['accesslog_table'], $this->config['visitors_table'], $parameters['client_id'], $this->_constraint($parameters['constraints']), $this->_whereTimerange($parameters['start'], $parameters['end'])));
     while ($row = $this->db->fetchRow()) {
         $visitors[$row['visitor_id']]['accesslog_ids'][] = $row['accesslog_id'];
         $visitors[$row['visitor_id']]['timestamps'][] = $row['timestamp'];
     }
     if (!empty($visitors)) {
         $keys = array_keys($visitors);
         $numKeys = sizeof($keys);
         for ($i = 0; $i < $numKeys; $i++) {
             $visitors[$keys[$i]]['num_visits'] = sizeof($visitors[$keys[$i]]['accesslog_ids']);
             $visitors[$keys[$i]]['visitor_id'] = $keys[$i];
             if ($visitors[$keys[$i]]['num_visits'] > 1) {
                 $time = 0;
                 for ($j = 0; $j < $visitors[$keys[$i]]['num_visits'] - 1; $j++) {
                     $time += $visitors[$keys[$i]]['timestamps'][$j + 1] - $visitors[$keys[$i]]['timestamps'][$j];
                 }
                 $visitors[$keys[$i]]['average_time_between_visits'] = floor($time / ($visitors[$keys[$i]]['num_visits'] - 1));
             } else {
                 unset($visitors[$keys[$i]]);
             }
         }
         if (!empty($visitors)) {
             foreach ($visitors as $visitor) {
                 $tmp[] = $visitor['num_visits'];
             }
             array_multisort($tmp, SORT_DESC, $visitors);
         }
     }
     switch ($parameters['result_format']) {
         case 'xml':
         case 'xml_object':
             $tree = new XML_Tree();
             $root =& $tree->addRoot('returningVisitors');
             $numVisitors = sizeof($visitors);
             for ($i = 0; $i < $numVisitors; $i++) {
                 $visitorChild =& $root->addChild('visitor');
                 $visitsChild =& $visitorChild->addChild('visits');
                 $numVisits = sizeof($visitors[$i]['accesslog_ids']);
                 for ($j = 0; $j < $numVisits; $j++) {
                     $visitChild =& $visitsChild->addChild('visit');
                     $visitChild->addChild('accesslogID', $visitors[$i]['accesslog_ids'][$j]);
                     $visitChild->addChild('timestamp', $visitors[$i]['timestamps'][$j]);
                 }
                 $visitorChild->addChild('numVisits', $visitors[$i]['num_visits']);
                 $visitorChild->addChild('visitorID', $visitors[$i]['visitor_id']);
             }
             if ($parameters['result_format'] == 'xml') {
                 return $root->get();
             } else {
                 return $root;
             }
             break;
         default:
             return $visitors;
     }
 }
Example #2
0
function load_svg($filename)
{
    $tree = new XML_Tree($filename);
    $root = $tree->getTreeFromFile();
    if (!$root) {
        die("Couldn't parse svg data.");
    }
    return $root;
}
<?php

require_once 'XML/Tree.php';
$xmlfile = 'presentations/slides/sdphp/data/sdphp_talk2.xml';
$tree = new XML_Tree($xmlfile);
$root = $tree->getTreeFromFile();
echo "<pre>\n";
print_r($root);
echo "</pre>\n";
Example #4
0
 /**
  * Downloads XML file or returns it from cache
  *
  * @param string URL of XML file
  * @param int Length of time to cache
  * @return object XML_Tree object
  */
 function retrieveXML($url, $cacheLength, $cacheDir)
 {
     include_once 'XML/Tree.php';
     if ($data = $this->retrieveFile($url, $cacheLength, $cacheDir)) {
         $tree = new XML_Tree();
         $root =& $tree->getTreeFromString($data);
         return $root;
     }
     return false;
 }
Example #5
0
 /**
  * Constructor
  *
  * @param  string    name            Node name
  * @param  string    content         Node content (text)
  * @param  array     attributes      Attribute-hash for the node
  */
 function XML_Tree_Node($name, $content = '', $attributes = array(), $lineno = null, $use_cdata_section = null)
 {
     $check_name = XML_Tree::isValidName($name, 'element');
     if (PEAR::isError($check_name)) {
         $this->error =& $check_name;
         return;
     }
     if (!is_array($attributes)) {
         $attributes = array();
     }
     foreach ($attributes as $attribute_name => $value) {
         $error = XML_Tree::isValidName($attribute_name, 'Attribute');
         if (PEAR::isError($error)) {
             $this->error =& $error;
             return;
         }
     }
     $this->name = $name;
     $this->setContent($content, $use_cdata_section);
     $this->attributes = $attributes;
     $this->children = array();
     $this->lineno = $lineno;
 }
Example #6
0
 /**
  * @param  optional string $file
  * @access public
  */
 public function __construct($file = 'phpunit-log.xml')
 {
     $this->file = $file;
     $this->tree = new XML_Tree();
     $this->root = $this->tree->addRoot('run');
 }
/**
 * Récupérer toutes les informations dans un fichier DocBook.
 * @param string $filename nom du fichier à analyser
 * @return object DocInfos objet contenant les infos de l'article, ou un tableau de chaînes contenant des messages d'erreurs
 * @todo Relire le code, il ne vérifie parfois pas assez les données d'entrées/les erreurs qui peuvent survenir pendant le traitement.
 */
function docbookGetArticleInfoFromFile($filename)
{
    $doc = new DocInfos();
    /* Extrait du XML toutes les informations pour remplir la classe Article */
    /* Obtenir un arbre à partir du fichier XML */
    $xmltree = new XML_Tree($filename);
    /* lecture du fichier qui récupère la balise <article> */
    $article = $xmltree->getTreeFromFile();
    if ($xmltree->isError($article)) {
        $erreur = $article->getUserInfo();
        if ($erreur == '') {
            $erreur = 'probablement un document mal formé';
        }
        return array('Impossible de parser le fichier XML (' . $erreur . ')');
    }
    preg_match('/^\\s*<\\?xml(.*?)encoding="(.+?)"/', file_get_contents($filename), $charset);
    $charset = $charset[2];
    $doc->repertoire = _toUtf8($charset, trim($article->getAttribute("id")));
    $doc->type = _toUtf8($charset, array_key_exists("role", $article->attributes) ? $article->getAttribute("role") : "article");
    $doc->lang = _toUtf8($charset, array_key_exists("lang", $article->attributes) ? $article->getAttribute("lang") : "fr");
    $artinfonode = getElementsByTagName($article, "articleinfo");
    if (count($artinfonode) == 0) {
        return array('Impossible de continuer à parser le fichier XML : il manque la section articleinfo du docbook');
    }
    /* Traitement particulier pour les balises <author> */
    $auteurs = array();
    foreach (getElementsByTagName($artinfonode[0], "author") as $author) {
        $firstnames = getElementsByTagName($author, "firstname");
        $surnames = getElementsByTagName($author, "surname");
        $auteurs[] = (count($firstnames) ? ucfirst(trim(tree2text($firstnames[0]))) : "") . ' ' . (count($surnames) ? ucfirst(trim(tree2text($surnames[0]))) : "");
    }
    $doc->auteurs = _toUtf8($charset, implode(', ', $auteurs));
    $doc->classement = array();
    foreach ($artinfonode[0]->children as $child) {
        /* Récupération des balises <title>, <pubdate> et <date> */
        if (!strcmp($child->name, "title")) {
            $doc->titre = _toUtf8($charset, tree2text($child));
        }
        if (!strcmp($child->name, "titleabbrev")) {
            $doc->titremini = _toUtf8($charset, tree2text($child));
        }
        if (!strcmp($child->name, "pubdate")) {
            $doc->pubdate = _toUtf8($charset, tree2text($child));
        }
        if (!strcmp($child->name, "date")) {
            $doc->update = _toUtf8($charset, tree2text($child));
        }
        if (!strcmp($child->name, "subjectset")) {
            foreach (getElementsByTagName($child, "subject") as $subjnode) {
                $attribute = _toUtf8($charset, $subjnode->getAttribute("role"));
                $doc->classement[$attribute] = array();
                foreach (getElementsByTagName($subjnode, "subjectterm") as $entry) {
                    $doc->classement[$attribute][] = _toUtf8($charset, tree2text($entry));
                }
            }
        }
        if (!strcmp($child->name, "abstract")) {
            $doc->accroche = _toUtf8($charset, tree2text($child));
        }
    }
    return $doc;
}
Example #8
0
 /**
  * Returns XML markup for the graph.
  *
  * @param  boolean $returnObject
  * @return mixed
  * @access public
  */
 function toXML($returnObject = false)
 {
     if (!@(include_once 'XML/Tree.php')) {
         phpOpenTracker::handleError('Could not find PEAR XML_Tree package, exiting.', E_USER_ERROR);
     }
     $tree = new XML_Tree();
     $root =& $tree->addRoot('clickpath');
     for ($i = 0; $i < $this->length; $i++) {
         $root->addChild('length', $this->length);
         $node =& $root->addChild('node');
         $node->addChild('document', $this->documents[$i]);
         if (!isset($this->statistics[$i]['count'])) {
             $node->addChild('timespent', $this->statistics[$i]);
         }
     }
     if (!$returnObject) {
         return $root->get();
     } else {
         return $root;
     }
 }
 /**
  * Récupérer toutes les informations dans un fichier DocBook.
  * @param string $filename nom du fichier à analyser
  * @return boolean booléen indiquant si le document XML a pu être lu
  * @throws PEAR_ErrorStack
  */
 function setFromDocbook($filename)
 {
     $xmltree = new XML_Tree($filename);
     $xmltree->setErrorHandling(PEAR_ERROR_CALLBACK, array(&$this, '_XMLTreeErrorHandler'));
     $article = $xmltree->getTreeFromFile();
     if ($this->errors->hasErrors('error')) {
         return false;
     }
     $this->charset = xml_parser_get_option($xmltree->parser, XML_OPTION_TARGET_ENCODING);
     $this->repertoire = $this->stringValue(@$article->getAttribute("id"));
     $this->type = $this->stringValue(@$article->getAttribute("role"));
     $this->lang = $this->stringValue(@$article->getAttribute("lang"));
     $artinfonode = $this->getElementsByTagName($article, "articleinfo");
     if (count($artinfonode) == 0) {
         $this->errors->push(OW_MISSING_NODE, 'error', array('file' => $filename, 'node' => 'articleinfo'));
         return false;
     }
     /* Traitement particulier pour les balises <author> */
     $auteurs = array();
     foreach ($this->getElementsByTagName($artinfonode[0], "author") as $author) {
         $firstnames = $this->getElementsByTagName($author, "firstname");
         $surnames = $this->getElementsByTagName($author, "surname");
         $nom = $this->stringValue(ucfirst(implode(' ', $firstnames)) . ' ' . ucfirst(implode(' ', $surnames)));
         if (preg_match('/^\\s*$/', $nom) != 0) {
             $auteurs[] = $nom;
         }
     }
     $this->auteurs = implode(', ', $auteurs);
     /* Traitement des autres méta-données */
     $this->classement = array();
     /**
      * Tableau des balises que l'on récupère sans traitement particulier
      */
     $autotags = array('title', 'titleabbrev', 'pubdate', 'date', 'abstract');
     foreach ($artinfonode[0]->children as $child) {
         $name = $child->name;
         if (in_array($name, $autotags)) {
             $this->{$name} = $this->stringValue($child);
         }
         if ($name == 'subjectset') {
             foreach ($this->getElementsByTagName($child, 'subject') as $subjnode) {
                 $attribute = $this->stringValue($subjnode->getAttribute('role'));
                 if (empty($attribute)) {
                     continue;
                 }
                 $this->classement[$attribute] = array();
                 foreach ($this->getElementsByTagName($subjnode, 'subjectterm') as $entry) {
                     $this->classement[$attribute][] = $this->stringValue($entry);
                 }
             }
         }
     }
     return true;
 }
Example #10
0
 
require_once('XML/Tree.php');
require_once('Image/Transform.php');

if (@$_POST || @$_GET) {
    echo "No hacking please";
    exit;
}


$f=  $_SERVER['argv'][1];
 
$exec = "tidy -asxml $f";
$data = `$exec`;
/* for debugging - just show it ! */ 
 $tree = new XML_Tree;
   $tree->getTreeFromString($data);
   $tree->dump();

class SDX_Parser {
    var $outputDir = '';

    function start($data) {
        $this->transform($data);
        // make the subdirectories?
        
            
        
        $fh = fopen ('slides.xml','w');
        fwrite($fh,'<?xml version="1.0" encoding="ISO-8859-1"?>'."\n");
        fwrite($fh,"<presentation {$this->presentation}>\n");
Example #11
0
    /**
     * Initialize the storage container
     *
     * @param array Array with the storage configuration
     * @return bool true on success, false on failure.
     *
     * @access public
     */
    function init(&$storageConf)
    {
        parent::init($storageConf);

        if (!is_file($this->file)) {
            if (!is_file(getenv('DOCUMENT_ROOT') . $this->file)) {
                $this->stack->push(LIVEUSER_ERROR_MISSING_DEPS, 'exception', array(),
                    "Perm initialisation failed. Can't find xml file.");
                return false;
            }
            $this->file = getenv('DOCUMENT_ROOT') . $this->file;
        }

        $tree = new XML_Tree($this->file);
        $err =& $tree->getTreeFromFile();
        if (PEAR::isError($err)) {
            $this->stack->push(LIVEUSER_ERROR, 'exception', array(),
                "Perm initialisation failed. Can't get tree from file");
            return false;
        }
        $this->tree =& $tree;

        if (!is_a($this->tree, 'xml_tree')) {
            $this->stack->push(LIVEUSER_ERROR_INIT_ERROR, 'error',
                array('container' => 'storage layer configuration missing'));
            return false;
        }

        return true;
    }
Example #12
0
<?php

require_once 'XML/Tree.php';
$tree = new XML_Tree();
$root =& $tree->addRoot('_#:A');
/* Check for error on the Root node */
if (PEAR::isError($root->error)) {
    var_dump($root->error);
}
$child =& $root->addChild('abc:def', 'bar');
if (PEAR::isError($child)) {
    var_dump($child);
}
$root->registerName('abc', 'http://some_name_space');
$child->registerName('abc', 'http://some_other_name_space');
echo $tree->getNodeNamespace($child);
if (PEAR::isError($child)) {
    var_dump($child);
}
echo $tree->get();
<?php

require_once 'XML/Tree.php';
$tree = new XML_Tree();
$root =& $tree->addRoot('slide', '', array('title' => 'A simple slide'));
$root->addChild('blurb', 'A blurb element', array('align' => 'center'));
$root->addChild('example', '', array('type' => 'xml', 'filename' => 'data/sdphp_talks.xml'));
$list =& $root->addChild('list', '', array('type' => 'arrow'));
$list->addChild('bullet', 'first bullet');
$list->addChild('bullet', 'second bullet');
$out = $tree->get();
echo nl2br(htmlspecialchars($out));
Example #14
0
 /**
  * Import XML text to driver data
  *
  * @param string $xml       The XML text
  * 
  * @return object           The XML_Tree content
  * @access public
  */
 function importXML($xml)
 {
     $tree = new XML_Tree();
     $tree->getTreeFromString($xml);
     return $tree->root;
 }
/**
*
* @param string	$file	the file to run through
*
* @return boolean
* @access public
*/
function process_errors_file($path, $file)
{
    bam('ERRORS ' . $file);
    $xml_object = new XML_Tree($file);
    $root = $xml_object->getTreeFromFile();
    assert_equals($root->name, 'files');
    echo $locale = $root->attributes['locale'];
    for (reset($root->children); null !== ($file_index = key($root->children)); next($root->children)) {
        $file_tag =& $root->children[$file_index];
        $file_name = $path . '/' . $file_tag->attributes['source'] . '/' . $locale . '/lang_errors.xml';
        // now create the file (and directory if required)
        create_directory($path . '/' . $file_tag->attributes['source'] . '/' . $locale);
        string_to_file($file_tag->children[0]->get(), $file_name);
    }
    return true;
}
Example #16
0
 /**
  * Runs the phpOpenTracker API call.
  *
  * @param  array $parameters
  * @return mixed
  * @access public
  */
 function run($parameters)
 {
     if (!isset($parameters['what'])) {
         return phpOpenTracker::handleError('Required parameter "what" missing.');
     }
     list($constraint, $selfJoin) = $this->_constraint($parameters['constraints'], true);
     if ($selfJoin) {
         $selfJoinConstraint = 'AND accesslog.accesslog_id = accesslog2.accesslog_id';
         $selfJoinTable = sprintf('%s accesslog2,', $this->config['accesslog_table']);
     } else {
         $selfJoinConstraint = '';
         $selfJoinTable = '';
     }
     $timerange = $this->_whereTimerange($parameters['start'], $parameters['end']);
     switch ($parameters['result_format']) {
         case 'csv':
             $csv = "Rank;Item;Count;Percent\n";
             break;
         case 'xml':
         case 'xml_object':
             $tree = new XML_Tree();
             $root =& $tree->addRoot('top');
             break;
         case 'separate_result_arrays':
             $names = array();
             $values = array();
             $percent = array();
             break;
         default:
             $topItems = array();
     }
     switch ($parameters['what']) {
         case 'document':
         case 'exit_target':
         case 'host':
         case 'operating_system':
         case 'referer':
         case 'user_agent':
         case 'entry_document':
         case 'exit_document':
             $dataConstraint = '';
             switch ($parameters['what']) {
                 case 'document':
                     $column = 'accesslog.document_id';
                     $dataTable = $this->config['documents_table'];
                     break;
                 case 'entry_document':
                     $column = 'accesslog.document_id';
                     $dataConstraint = "AND accesslog.entry_document = '1'";
                     $dataTable = $this->config['documents_table'];
                     break;
                 case 'exit_document':
                     $column = 'accesslog.document_id';
                     $dataConstraint = "AND accesslog.exit_target_id <> '0'";
                     $dataTable = $this->config['documents_table'];
                     break;
                 case 'exit_target':
                     $column = 'accesslog.exit_target_id';
                     $dataConstraint = "AND accesslog.exit_target_id <> '0'";
                     $dataTable = $this->config['exit_targets_table'];
                     break;
                 case 'host':
                     $column = 'visitors.host_id';
                     $dataTable = $this->config['hostnames_table'];
                     break;
                 case 'operating_system':
                     $column = 'visitors.operating_system_id';
                     $dataTable = $this->config['operating_systems_table'];
                     break;
                 case 'referer':
                     $column = 'visitors.referer_id';
                     $dataTable = $this->config['referers_table'];
                     break;
                 case 'user_agent':
                     $column = 'visitors.user_agent_id';
                     $dataTable = $this->config['user_agents_table'];
                     break;
             }
             $nestedQuery = sprintf("SELECT data_table.string AS item\n             FROM %s accesslog,\n                  %s\n                  %s visitors,\n                  %s data_table\n            WHERE visitors.client_id    = '%d'\n              AND visitors.accesslog_id = accesslog.accesslog_id\n              AND data_table.data_id    = %s\n                  %s\n                  %s\n                  %s\n                  %s\n            GROUP BY visitors.accesslog_id,\n                     data_table.string", $this->config['accesslog_table'], $selfJoinTable, $this->config['visitors_table'], $dataTable, $parameters['client_id'], $column, $selfJoinConstraint, $dataConstraint, $constraint, $timerange);
             break;
         default:
             $nestedQuery = sprintf("SELECT add_data.data_value AS item\n             FROM %s accesslog,\n                  %s\n                  %s visitors,\n                  %s add_data\n            WHERE visitors.client_id     = '%d'\n              AND visitors.accesslog_id  = accesslog.accesslog_id\n              AND accesslog.accesslog_id = add_data.accesslog_id\n              AND add_data.data_field    = '%s'\n                  %s\n                  %s\n                  %s\n            GROUP BY visitors.accesslog_id,\n                     add_data.data_value", $this->config['accesslog_table'], $selfJoinTable, $this->config['visitors_table'], $this->config['additional_data_table'], $parameters['client_id'], $parameters['what'], $selfJoinConstraint, $constraint, $timerange);
     }
     if ($this->db->supportsNestedQueries()) {
         $queryTotalUnique = sprintf('SELECT COUNT(item)           AS total_items,
             COUNT(DISTINCT(item)) AS unique_items
        FROM (%s) items', $nestedQuery);
         $queryItems = sprintf('SELECT COUNT(item) AS item_count,
             item
        FROM (%s) items
       GROUP BY item
       ORDER BY item_count %s,
                item', $nestedQuery, $parameters['order']);
         if ($parameters['result_format'] == 'sql') {
             return $queryItems;
         }
     } else {
         if ($this->config['db_type'] == 'mysql' || $this->config['db_type'] == 'mysql_merge') {
             $queryCreateTemporaryTable = sprintf('CREATE TEMPORARY TABLE pot_temporary_table %s', $nestedQuery);
             $queryTotalUnique = sprintf('SELECT COUNT(item)           AS total_items,
               COUNT(DISTINCT(item)) AS unique_items
          FROM pot_temporary_table', $nestedQuery);
             $queryItems = sprintf('SELECT COUNT(item) AS item_count,
               item
          FROM pot_temporary_table
         GROUP BY item
         ORDER BY item_count %s,
                  item', $parameters['order']);
             if ($parameters['result_format'] != 'sql') {
                 $dropTemporaryTable = true;
                 $this->db->query($queryCreateTemporaryTable);
             } else {
                 return $queryCreateTemporaryTable . ';' . $queryItems;
             }
         } else {
             return phpOpenTracker::handleError('You need a database system capable of nested queries.', E_USER_ERROR);
         }
     }
     $this->db->query($queryTotalUnique);
     if ($row = $this->db->fetchRow()) {
         $totalItems = intval($row['total_items']);
         $uniqueItems = intval($row['unique_items']);
     } else {
         return phpOpenTracker::handleError('Database query failed.');
     }
     if ($totalItems > 0) {
         $this->db->query($queryItems, $parameters['limit']);
         $i = 0;
         while ($row = $this->db->fetchRow()) {
             $percentValue = doubleval(number_format(100 * $row['item_count'] / $totalItems, 2));
             switch ($parameters['result_format']) {
                 case 'csv':
                     $csv .= sprintf("%d;%s;%d;%d\n", $i + 1, $row['item'], intval($row['item_count']), $percentValue);
                     break;
                 case 'xml':
                 case 'xml_object':
                     $itemChild =& $root->addChild('item');
                     $itemChild->addChild('rank', $i + 1);
                     $itemChild->addChild('string', $row['item']);
                     $itemChild->addChild('count', intval($row['item_count']));
                     $itemChild->addChild('percent', $percentValue);
                     if (isset($row['document_url'])) {
                         $itemChild->addChild('url', $row['document_url']);
                     }
                     break;
                 case 'separate_result_arrays':
                     $names[$i] = $row['item'];
                     $values[$i] = intval($row['item_count']);
                     $percent[$i] = $percentValue;
                     break;
                 default:
                     $topItems[$i]['count'] = intval($row['item_count']);
                     $topItems[$i]['string'] = $row['item'];
                     $topItems[$i]['percent'] = $percentValue;
                     if (isset($row['document_url'])) {
                         $topItems[$i]['url'] = $row['document_url'];
                     }
             }
             $i++;
         }
     }
     if (isset($dropTemporaryTable)) {
         $this->db->query('DROP TABLE pot_temporary_table');
     }
     switch ($parameters['result_format']) {
         case 'csv':
             return $csv;
             break;
         case 'xml':
         case 'xml_object':
             $root->addChild('total', $totalItems);
             $root->addChild('unique', $uniqueItems);
             switch ($parameters['result_format']) {
                 case 'xml':
                     return $root->get();
                     break;
                 case 'xml_object':
                     return $root;
                     break;
             }
             break;
         case 'separate_result_arrays':
             return array($names, $values, $percent, $uniqueItems);
             break;
         default:
             return array('top_items' => $topItems, 'unique_items' => $uniqueItems);
     }
 }
Example #17
0
 /**
  * Check if the XML respect the DTD.
  * Require the XML_DTD package
  *
  * @param string $xml   The XML text to check
  *
  * @return boolean      Return true if valid
  * @access public
  */
 function isValid(&$xml)
 {
     $validator = new XML_DTD_XmlValidator();
     $tree = new XML_Tree();
     $nodes = $tree->getTreeFromString($xml);
     if (PEAR::isError($nodes)) {
         return $nodes;
     }
     $parser =& new XML_DTD_Parser();
     $validator->dtd = $parser->parse($this->_dtd);
     $validator->_runTree($nodes);
     if ($validator->_errors) {
         $errors = $validator->getMessage();
         return PEAR::raiseError($errors, XML_FASTCREATE_ERROR_DTD);
     }
     return true;
 }
Example #18
0
include_once "objects/class.poi.php";
include_once "xml/Tree.php";
date_default_timezone_set('America/Chicago');
// figure out what the user is requesting
$x = $_REQUEST["x"];
$y = $_REQUEST["y"];
$format = $_REQUEST["format"];
if ($format == "") {
    $format = "xml";
}
if ($format != "xml") {
    echo "Only XML format is supported right now.";
    die;
}
// instantiate object
$tree = new XML_Tree();
// add the root element
$root =& $tree->addRoot("POICollection");
$root->setAttribute("x", $x);
$root->setAttribute("y", $y);
$root->setAttribute("timestamp", time());
// fetch poi child elements
$terms = array(array("quadrant_x", "=", $x), array("quadrant_y", "=", $y));
$handle = new POI();
$pois = $handle->GetList($terms, '', true, 1000);
foreach ($pois as $poi) {
    $node =& $root->addChild("POI");
    $node->setAttribute("name", $poi->title);
    $node->setAttribute("lat", $poi->lat);
    $node->setAttribute("lon", $poi->lon);
    $node->addChild("description", $poi->description);
Example #19
0
 /**
  * Constructor
  *
  * 
  * 
  * 
  * @param   string               Filename
  * @param   array $options
  *                   valid options:
  *               debug = 0/1
  *               filter => array(
  *                   tagname => callback
  *   
  *           where callback can be
  *               - toObject|toArary = built in converters
  *               - 'function', array($object,'method') or
  *                 array('class','staticMethod');
  * 
  *
  * @access   public
  */
 function XML_Tree_Morph($filename, $options)
 {
     XML_Tree::XML_Tree($filename, '1.0');
     $this->_morphOptions = $options;
 }
Example #20
0
require ELMAR_PATH . 'elmar.inc.php';
if (headers_sent($filename, $linenum)) {
    ob_end_flush();
    exit('HTTP-Header wurden bereits gesendet von der Datei ' . $filename . ' Zeile ' . $linenum . ".\nEs muss ein Fehler aufgetreten sein, der erst zu beheben ist, bevor dieses Affiliate-Skript ordnungsgemaess laeuft.\n" . '(Abbruch in Datei ' . __FILE__ . ' Zeile ' . __LINE__ . '.)');
}
if (defined('POWEREDBY')) {
    header('X-Powered-By: ' . POWEREDBY, FALSE);
}
header('Content-Type: text/xml');
// Alle Includes hier, wegen der Pfadangabe. Reihenfolge ist relevant!
require ELMAR_PATH . 'tools/pear.php';
require ELMAR_PATH . 'tools/node.php';
require ELMAR_PATH . 'tools/parser.php';
require ELMAR_PATH . 'tools/tree.php';
$attributes = '1.0" encoding="ISO-8859-1';
$tree = new XML_Tree(NULL, $attributes);
$XMLarray = array('xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'xmlns' => 'http://elektronischer-markt.de/schema/affiliate-1.0', 'xsi:schemaLocation' => 'http://elektronischer-markt.de/schema/affiliate-1.0 ' . ELMAR_SCHEMA_BASE_URL . 'affiliate-1.0.xsd', 'version' => '1.0');
$root =& $tree->addRoot("affiliate", NULL, $XMLarray);
if (!isset($_REQUEST['name']) || trim($_REQUEST['name']) == '') {
    $xml_error =& $root->addChild('error', '100');
    if (defined('AFFILIATES_CONTACT_EMAIL')) {
        $email =& $root->addChild('email', AFFILIATES_CONTACT_EMAIL);
    }
    if (defined('AFFILIATES_CONTACT_URL')) {
        $url =& $root->addChild('url', htmlentities(AFFILIATES_CONTACT_URL));
    }
    $description_de =& $root->addChild('description', 'Der Parameter name fehlt oder ist leer. Bitte geben Sie Ihren Domainnamen an.', array('lang' => 'de'));
    $description_en =& $root->addChild('description', 'Parameter name is missing or empty. Please specify your domain name.', array('lang' => 'en'));
} else {
    $name = $_REQUEST['name'];
    // Partner-ID zum Namen bestimmen
Example #21
0
 /**
  * @brief Build a DiGIR search query.
  *
  * Given an institutional code (such as a museum abbreviation) and a specimen 
  * number we construct a DiGIR query to retrieve the corresponding record.
  * 
  * This is a bit of an undertaking as there is not an easy means to discover the
  * DiGIR provider corresponding to a given specimen code, and the DiGIR providers
  * themselves vary in what version of the DarwinCore schema they support. 
  * See The Big Dig (http://bigdig.ecoforge.net/wiki) for details.
  * Here I use the value of  <b>Revision</b> in the &lt;version&gt; tag in the header field of
  * the DiGIR provider response as a flag to use different code to make the query.
  *
  * By default I assume we have an original specimen code such as <b>FMNH 14734</b>,
  * and this has been parsed into the institution code (FMNH), a namespace (where needed),
  * and the specimen number
  * (14734). Namespaces are needed for two reasons:
  *    - Different taxon collections may have different providers (e.g., FMNH)
  *    - The same institution and specimen code may occur in different collections
  *      served by the same provider (e.g., MVZ)
  *
  * An example of an identifier is <b>FMNH:Mammals:14734</b>. 
  * In some cases, we need some further fussing. For example, the KU and Calacademy DiGIR
  * providers expects specimen numbers to include the institutional or collection prefix.
  *
  * I hard code the mapping between museum codes and DiGIR providers. 
  * If I was clever we'd do this via GBIF's UDDI interface, but that 
  * looks like a world of pain. Typically the DiGIR provider's URL is found by browsing
  * GBIF's web site. 
  *
  * The DiGIR query is a XML tree, which is then encoded as a URL. The tree varies depending
  * on whether the provider is serving schema 1.2 or 1.4.
  *
  * @param institution Institutional code
  * @param id Specimen number
  */
 function buildDIGIRQuery($institution, $id)
 {
     //echo $institution, "<br/>";
     // Kansas expects specimen codes to have KU at the start
     //		if (strcasecmp($institution,'KU-Herps') == 0) { $id = 'KU' . $id; }
     // Calacademy is similar to KU
     if (strcasecmp($institution, 'CASENT') == 0) {
         $id = strtolower($institution) . $id;
         $institution = 'CASENT';
     }
     if (strcasecmp($institution, 'inbiocri') == 0) {
         $id = strtolower($institution) . $id;
         $institution = 'CASENT';
     }
     if (strcasecmp($institution, 'lacment') == 0) {
         $id = 'lacm ent ' . $id;
         $institution = 'CASENT';
     }
     if (strcasecmp($institution, 'jtlc') == 0) {
         $id = strtolower($institution) . $id;
         $institution = 'CASENT';
     }
     $server = $this->serverURL[$institution];
     $resource = $this->resourceCode[$institution];
     // Build request message
     $tree = new XML_Tree();
     $root =& $tree->addRoot("request", '', array("xmlns" => 'http://digir.net/schema/protocol/2003/1.0', "xmlns:xsd" => 'http://www.w3.org/2001/XMLSchema', "xmlns:xsi" => 'http://www.w3.org/2001/XMLSchema-instance', "xmlns:digir" => 'http://digir.net/schema/protocol/2003/1.0', "xmlns:dwc" => 'http://digir.net/schema/conceptual/darwin/2003/1.0', "xmlns:darwin" => 'http://digir.net/schema/conceptual/darwin/2003/1.0', "xsi:schemaLocation" => 'http://digir.net/schema/protocol/2003/1.0', "xsi:schemaLocation" => 'http://digir.net/schema/protocol/2003/1.0 http://digir.sourceforge.net/schema/protocol/2003/1.0/digir.xsd http://digir.net/schema/conceptual/darwin/2003/1.0 http://digir.sourceforge.net/schema/conceptual/darwin/2003/1.0/darwin2.xsd'));
     $header =& $root->addChild("header");
     $header->addChild("version", "1.0.0");
     $header->addChild("sendTime", date("Ymd \\TG:i:s"));
     $header->addChild("source", $_SERVER['SERVER_ADDR']);
     $header->addChild("destination", $server, array("resource" => $resource));
     $header->addChild("type", "search");
     $search =& $root->addChild("search");
     $filter =& $search->addChild("filter");
     // Australian stuff served by Ozcam may have more than one provider
     switch ($institution) {
         case 'SAMA':
         case 'ANWC':
         case 'AMS':
         case 'WAM':
         case 'NT':
             $and =& $filter->addChild("and");
             $equals =& $and->addChild("equals");
             $equals->addChild("darwin:CatalogNumberText", $id);
             $equals2 =& $and->addChild("equals");
             $equals2->addChild("darwin:InstitutionCode", $institution);
             break;
         default:
             if (preg_match('/^MVZ/', $institution)) {
                 //echo $institution;
                 list($inst, $coll) = explode("-", $institution);
                 //echo $coll;
                 $and =& $filter->addChild("and");
                 $equals =& $and->addChild("equals");
                 $equals->addChild("darwin:CatalogNumberText", $id);
                 $equals2 =& $and->addChild("equals");
                 switch ($coll) {
                     case 'Herps':
                         $equals2->addChild("darwin:CollectionCode", 'Herp');
                         break;
                     case 'Mammals':
                         $equals2->addChild("darwin:CollectionCode", 'Mamm');
                         break;
                     case 'Birds':
                         $equals2->addChild("darwin:CollectionCode", 'Bird');
                         break;
                     default:
                         $equals2->addChild("darwin:CollectionCode", $coll);
                         break;
                 }
             } else {
                 $equals =& $filter->addChild("equals");
                 switch ($this->schema[$institution]) {
                     case "1.14":
                         $equals->addChild("darwin:CatalogNumber", $id);
                         break;
                     default:
                         $equals->addChild("darwin:CatalogNumberText", $id);
                         break;
                 }
             }
             break;
     }
     $records =& $search->addChild("records", "", array("limit" => 10, "start" => 0));
     if ($this->schema[$institution] == '1.12') {
         $records->addChild("structure", "", array("schemaLocation" => "http://digir.sourceforge.net/schema/conceptual/darwin/result/full/2003/darwin2resultfull.xsd"));
     } else {
         $structure =& $records->addChild("structure", "");
         $element =& $structure->addChild("xsd:element", "", array("name" => "record"));
         $complexType =& $element->addChild("xsd:complexType", "");
         $sequence =& $complexType->addChild("xsd:sequence", "");
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:InstitutionCode"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:CollectionCode"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:CatalogNumber"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:ScientificName"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:VerbatimCollectingDate"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:DateLastModified"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:YearCollected"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:MonthCollected"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:DayCollected"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:TimeCollected"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Kingdom"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Phylum"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Class"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Order"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Family"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Genus"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Species"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Subspecies"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Country"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:StateProvince"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:County"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Island"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:IslandGroup"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:ContinentOcean"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Locality"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:HorizontalDatum"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Collector"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Remarks"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:TypeStatus"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:OtherCatalogNumbers"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:CollectorNumber"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:FieldNumber"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:GenBankNum"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Latitude"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Longitude"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Sex"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:Notes"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:IdentifiedBy"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:YearIdentified"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:MonthIdentified"));
         $sequence->addChild("xsd:element", "", array("ref" => "darwin:DayIdentified"));
     }
     $xml = $tree->get();
     //echo $xml;
     // Strip XML header
     $xml = str_replace('<?xml version="1.0"?>', '', $xml);
     // Remove line breaks
     $xml = str_replace("\n", '', $xml);
     // Replace spaces with HEX code
     $xml = str_replace(" ", '%20', $xml);
     //echo $xml;
     $url = "http://{$server}?doc=";
     $url .= $xml;
     //echo $url;
     /*	$url = "http://$server?doc=<request%20xmlns='http://digir.net/schema/protocol/2003/1.0'%20xmlns:xsd='http://www.w3.org/2001/XMLSchema'%20xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'%20xmlns:digir='http://digir.net/schema/protocol/2003/1.0'%20xmlns:dwc='http://digir.net/schema/conceptual/darwin/2003/1.0'%20xmlns:darwin='http://digir.net/schema/conceptual/darwin/2003/1.0'%20xsi:schemaLocation='http://digir.net/schema/protocol/2003/1.0%20http://digir.sourceforge.net/schema/protocol/2003/1.0/digir.xsd%20http://digir.net/schema/conceptual/darwin/2003/1.0%20http://digir.sourceforge.net/schema/conceptual/darwin/2003/1.0/darwin2.xsd'><header><version>1.0.0</version><sendTime>20040324T094003+0100</sendTime><source>192.168.1.101</source><destination%20resource='$resource'>$server</destination><type>search</type></header><search><filter><equals><darwin:CatalogNumberText>$id</darwin:CatalogNumberText></equals></filter><records%20limit=\"10\"%20start=\"0\"><structure%20schemaLocation=\"http://bnhm.berkeley.museum/manis/DwC/darwin2resultfull.xsd\"%20/></records></search></request>";
      */
     return $url;
 }
Example #22
0
<?php

require_once 'XML/Tree.php';
$tree = new XML_Tree();
$root =& $tree->addRoot('root');
//$tree->useCdataSections();
$root->addChild('foo', 'bar');
$baz =& $root->addChild('baz');
$baz->addChild('bat', 'qux', array(), null, true);
$baz->addChild('bat', 'quux', array(), null, false);
$tree->dump();
Example #23
0
 /**
  * Creates a treeMenu from XML. The structure of your XML should be
  * like so:
  *
  * <treemenu>
  *     <node text="First node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
  *     <node text="Second node" icon="folder.gif" expandedIcon="folder-expanded.gif">
  *         <node text="Sub node" icon="folder.gif" expandedIcon="folder-expanded.gif" />
  *     </node>
  *     <node text="Third node" icon="folder.gif" expandedIcon="folder-expanded.gif">
  * </treemenu>
  *
  * Any of the options you can supply to the HTML_TreeNode constructor can be supplied as
  * attributes to the <node> tag. If there are no subnodes for a particular node, you can
  * use the XML shortcut <node ... /> instead of <node ... ></node>. The $xml argument can
  * be either the XML as a string, or an pre-created XML_Tree object. Also, this method
  * REQUIRES my own Tree class to work (http://phpguru.org/tree.html). If this has not
  * been include()ed or require()ed this method will die().
  *
  * @param  mixed  $xml  This can be either a string containing the XML, or an XML_Tree object
  *                      (the PEAR::XML_Tree package).
  * @return object       The HTML_TreeMenu object
  */
 function createFromXML($xml)
 {
     if (!class_exists('Tree')) {
         die('Could not find Tree class');
     }
     // Supplied $xml is a string
     if (is_string($xml)) {
         require_once 'XML/Tree.php';
         $xmlTree = new XML_Tree();
         $xmlTree->getTreeFromString($xml);
         // Supplied $xml is an XML_Tree object
     } else {
         $xmlTree = $xml;
     }
     // Now process the XML_Tree object, setting the XML attributes
     // to be the tag data (with out the XML tag name or contents).
     $treeStructure = Tree::createFromXMLTree($xmlTree, true);
     $treeStructure->nodes->traverse(create_function('&$node', '$tagData = $node->getTag(); $node->setTag($tagData["attributes"]);'));
     return HTML_TreeMenu::createFromStructure(array('structure' => $treeStructure));
 }
 /**
  * Runs the phpOpenTracker API call.
  *
  * @param  array $parameters
  * @return mixed
  * @access public
  */
 function run($parameters)
 {
     $parameters['session_lifetime'] = isset($parameters['session_lifetime']) ? $parameters['session_lifetime'] : 3;
     switch ($parameters['result_format']) {
         case 'xml':
         case 'xml_object':
             $tree = new XML_Tree();
             $root =& $tree->addRoot('visitorsonline');
             $children = array();
             break;
         default:
             $result = array();
     }
     $accesslogIDs = array();
     $this->db->query(sprintf("SELECT DISTINCT(accesslog.accesslog_id) AS accesslog_id\r\n           FROM %s accesslog,\r\n                %s visitors\r\n          WHERE visitors.client_id    = '%d'\r\n            AND visitors.accesslog_id = accesslog.accesslog_id\r\n            AND accesslog.timestamp  >= '%d'", $this->config['accesslog_table'], $this->config['visitors_table'], $parameters['client_id'], time() - $parameters['session_lifetime'] * 60));
     while ($row = $this->db->fetchRow()) {
         $accesslogIDs[] = $row['accesslog_id'];
     }
     for ($i = 0, $max = sizeof($accesslogIDs); $i < $max; $i++) {
         switch ($parameters['result_format']) {
             case 'xml':
             case 'xml_object':
                 $visitorNode =& $root->addChild('visitor');
                 $visitorNode->addChild(phpOpenTracker::get(array('client_id' => $parameters['client_id'], 'api_call' => 'individual_clickpath', 'accesslog_id' => $accesslogIDs[$i], 'result_format' => 'xml_object')));
                 break;
             default:
                 $result[$i]['clickpath'] = phpOpenTracker::get(array('client_id' => $parameters['client_id'], 'api_call' => 'individual_clickpath', 'accesslog_id' => $accesslogIDs[$i]));
         }
         $this->db->query(sprintf("SELECT MAX(timestamp) as last_access\r\n             FROM %s\r\n            WHERE accesslog_id = '%s'", $this->config['accesslog_table'], $accesslogIDs[$i]));
         if ($row = $this->db->fetchRow()) {
             switch ($parameters['result_format']) {
                 case 'xml':
                 case 'xml_object':
                     $visitorNode->addChild('last_access', $row['last_access']);
                     break;
                 default:
                     $result[$i]['last_access'] = $row['last_access'];
             }
         } else {
             return phpOpenTracker::handleError('Database query failed.');
         }
         $this->db->query(sprintf("SELECT hosts.string       AS host,\r\n                  user_agents.string AS user_agent\r\n             FROM %s visitors,\r\n                  %s hosts,\r\n                  %s user_agents\r\n            WHERE visitors.accesslog_id  = '%d'\r\n              AND visitors.host_id       = hosts.data_id\r\n              AND visitors.user_agent_id = user_agents.data_id", $this->config['visitors_table'], $this->config['hostnames_table'], $this->config['user_agents_table'], $accesslogIDs[$i]));
         if ($row = $this->db->fetchRow()) {
             switch ($parameters['result_format']) {
                 case 'xml':
                 case 'xml_object':
                     $visitorNode->addChild('host', $row['host']);
                     $visitorNode->addChild('user_agent', $row['user_agent']);
                     break;
                 default:
                     $result[$i]['host'] = $row['host'];
                     $result[$i]['user_agent'] = $row['user_agent'];
             }
         } else {
             return phpOpenTracker::handleError('Database query failed.');
         }
         $this->db->query(sprintf("SELECT referers.string AS referer\r\n             FROM %s visitors,\r\n                  %s referers\r\n            WHERE visitors.accesslog_id = '%d'\r\n              AND visitors.referer_id   = referers.data_id", $this->config['visitors_table'], $this->config['referers_table'], $accesslogIDs[$i]));
         if ($row = $this->db->fetchRow()) {
             $referer = $row['referer'];
         } else {
             $referer = '';
         }
         switch ($parameters['result_format']) {
             case 'xml':
             case 'xml_object':
                 $visitorNode->addChild('referer', $referer);
                 break;
             default:
                 $result[$i]['referer'] = $referer;
         }
     }
     switch ($parameters['result_format']) {
         case 'xml':
             return $root->get();
             break;
         case 'xml_object':
             return $root;
             break;
         default:
             return $result;
     }
 }
Example #25
0
function update_shopinfo_xml()
{
    global $spalten;
    if (!file_exists(DIR_FS_SHOPINFO_XML) || filesize(DIR_FS_SHOPINFO_XML) == 0) {
        echo '<p class="ok">OK, die Shopdatei wurde noch nicht angelegt und muss folglich auch nicht angepasst werden.</p>' . "\n";
        return true;
    }
    echo '<p>Lade Shopdatei: <code>' . DIR_FS_SHOPINFO_XML . '</code>' . "\n";
    $tree = new XML_Tree(DIR_FS_SHOPINFO_XML, '1.0" encoding="ISO-8859-1');
    #$tree->useCdataSections();
    $root =& $tree->getTreeFromFile();
    if (PEAR::isError($root)) {
        echo '<p class="error">Fehler beim Parsen der Shopdatei:<br>' . "\n";
        echo $root->toString() . "</p>\n";
        return false;
    }
    $name_parts = explode(':', $root->name);
    if (sizeof($name_parts) > 1) {
        $namespace = $name_parts[0] . ':';
    } else {
        $namespace = '';
    }
    $requests =& $tree->getNodeAt($namespace . 'Shop/Requests');
    if (PEAR::isError($requests)) {
        #echo '<p>Warnung: Zugriff auf Produktdaten in der Shopdatei nicht gefunden.</p>'."\n";
        // Request-Tag nach dem Url-Tag einfügen
        $pos = -1;
        for ($i = 0; $i < count($root->children); ++$i) {
            if ($root->children[$i]->name == 'Url') {
                $pos = $i + 1;
            }
        }
        $requests = new XML_Tree_Node('Requests');
        $res =& $root->insertChild(null, $pos, $requests);
        if (PEAR::isError($res)) {
            echo '<p class="error">Das Requests-Tag konnte nicht in die shopinfo.xml eingef&uuml;gt werden:<br>' . "\n";
            echo $res->toString() . "</p>\n";
            return false;
        }
    }
    $offlineRequest =& $tree->getNodeAt($namespace . 'Shop/Requests/OfflineRequest');
    if (PEAR::isError($offlineRequest)) {
        #echo '<p>Warnung: Produktdatei-Angaben in der Shopdatei nicht gefunden.</p>'."\n";
        $offlineRequest =& offlineRequest($requests);
        echo '<p class="ok">OK, Produktdatei-Angaben erg&auml;nzt.</p>' . "\n";
    } else {
        $header =& $tree->getNodeAt($namespace . 'Shop/Requests/OfflineRequest/Format/Tabular/CSV/Header');
        if (PEAR::isError($header)) {
            echo '<p class="error">Das Kopfzeilen-Tag in der Shopdatei nicht gefunden:<br>' . "\n";
            echo $header->toString() . "</p>\n";
            return false;
        }
        $old_titel = $header->content;
        // Funktion getContent gibt es nicht.
        #echo 'old_titel: '.htmlspecialchars($old_titel)."\n\n";
        $corrected = false;
        if ($header->getAttribute('columns') != count($spalten)) {
            $header->setAttribute('columns', count($spalten));
            $corrected = true;
        }
        $mappings =& $tree->getNodeAt($namespace . 'Shop/Requests/OfflineRequest/Format/Tabular/Mappings');
        if (PEAR::isError($mappings)) {
            echo '<p class="error">Das Mappings-Tag in der Shopdatei nicht gefunden:<br>' . "\n";
            echo $mappings->toString() . "</p>\n";
            return false;
        }
        foreach ($mappings->children as $idx => $child) {
            if (count($child->attributes) > 0) {
                if ($child->getAttribute('columnName') != $spalten[$child->getAttribute('column') - 1]) {
                    #echo $idx.': '.$child->getAttribute('columnName').' =&gt; ';
                    $mappings->children[$idx]->setAttribute('columnName', $spalten[$child->getAttribute('column') - 1]);
                    #echo $mappings->children[$idx]->getAttribute('columnName')."<br>\n";
                    $corrected = true;
                }
            }
        }
        if (defined('DEFAULT_QUOTE')) {
            $titel = DEFAULT_QUOTE . implode(DEFAULT_QUOTE . DEFAULT_DELIMITER . DEFAULT_QUOTE, $spalten) . DEFAULT_QUOTE;
        } else {
            $titel = implode(DEFAULT_DELIMITER, $spalten);
        }
        #echo 'titel: '.htmlspecialchars($titel)."\n\n";
        if ($old_titel != $titel) {
            $header->setContent($titel);
        }
        $special =& $tree->getNodeAt($namespace . 'Shop/Requests/OfflineRequest/Format/Tabular/CSV/SpecialCharacters');
        if (PEAR::isError($special)) {
            echo '<p class="error">Das Sonderzeichen-Tag in der Shopdatei nicht gefunden:<br>' . "\n";
            echo $special->toString() . "</p>\n";
            return false;
        }
        $old_escape = $special->getAttribute('escaped');
        $old_quote = $special->getAttribute('quoted');
        $old_lineend = $special->getAttribute('lineend');
        $old_delimiter = $special->getAttribute('delimiter');
        if (defined('DEFAULT_ESCAPE')) {
            $special->setAttribute('escaped', DEFAULT_ESCAPE);
        } else {
            $special->unsetAttribute('escaped');
        }
        if (defined('DEFAULT_QUOTE')) {
            $special->setAttribute('quoted', DEFAULT_QUOTE);
        } else {
            $special->unsetAttribute('quoted');
        }
        if (defined('DEFAULT_LINEEND')) {
            $special->setAttribute('lineend', DEFAULT_LINEEND == "\n" ? '\\n' : (DEFAULT_LINEEND == "\r" ? '\\r' : '\\r\\n'));
        } else {
            $special->unsetAttribute('lineend');
        }
        if (defined('DEFAULT_DELIMITER')) {
            $special->setAttribute('delimiter', DEFAULT_DELIMITER == "\t" ? '[tab]' : DEFAULT_DELIMITER);
        } else {
            $special->unsetAttribute('delimiter');
        }
        $new_escape = $special->getAttribute('escaped');
        $new_quote = $special->getAttribute('quoted');
        $new_lineend = $special->getAttribute('lineend');
        $new_delimiter = $special->getAttribute('delimiter');
        if (!$corrected && $old_titel == $titel && $new_escape == $old_escape && $new_quote == $old_quote && $new_lineend == $old_lineend && $new_delimiter == $old_delimiter) {
            echo '<p class="ok">OK, die Shopdatei wurde bereits aktualisiert.</p>' . "\n";
            return true;
        }
        if ($old_titel != $titel) {
            echo '<p class="ok">OK, Kopfzeile aktualisiert.</p>' . "\n";
        }
        if ($corrected) {
            echo '<p class="ok">OK, Spaltennamen aktualisiert.</p>' . "\n";
        }
        if ($new_escape != $old_escape) {
            echo '<p class="ok">OK, Escape-Zeichen aktualisiert.</p>' . "\n";
        }
        if ($new_quote != $old_quote) {
            echo '<p class="ok">OK, Zeichenkettenbegrenzer aktualisiert.</p>' . "\n";
        }
        if ($new_lineend != $old_lineend) {
            echo '<p class="ok">OK, Zeilenendezeichen aktualisiert.</p>' . "\n";
        }
        if ($new_delimiter != $old_delimiter) {
            echo '<p class="ok">OK, Trennzeichenzeichen aktualisiert.</p>' . "\n";
        }
    }
    #echo '<pre>'.(htmlspecialchars($tree->get())).'</pre>'."\n";
    if (!is_writable(DIR_FS_SHOPINFO_XML)) {
        echo '<p class="error">Die Shopdatei kann nicht geschrieben werden:<br>' . DIR_FS_SHOPINFO_XML . "</p>\n";
        return false;
    }
    if (!($handle = @fopen(DIR_FS_SHOPINFO_XML, 'wb'))) {
        echo '<p class="error">Die Shopdatei kann nicht zum Schreiben ge&ouml;ffnet werden:<br>' . DIR_FS_SHOPINFO_XML . "</p>\n";
        return false;
    }
    flock($handle, LOCK_EX);
    if (!@fwrite($handle, $tree->get())) {
        echo '<p class="error">Fehler beim Schreiben der Shopdatei:<br>' . DIR_FS_SHOPINFO_XML . "</p>\n";
        return false;
    }
    flock($handle, LOCK_UN);
    @fclose($handle);
    // wenn hier etwas schief geht, ignorieren
    #$tree->free();
    echo '<p class="ok">OK, die Shopdatei wurde aktualisiert.<br>' . DIR_FS_SHOPINFO_XML . '</p>' . "\n";
    return true;
}
 function _nxvisitors($parameters)
 {
     $parameters['interval'] = isset($parameters['interval']) ? $parameters['interval'] : false;
     $intervalStrings = array();
     $timestamps = array();
     $values = array();
     switch ($parameters['result_format']) {
         case 'csv':
             if ($parameters['api_call'] == 'page_impressions') {
                 $csv = "Interval;Page Impressions\n";
             } else {
                 $csv = "Interval;Visitors\n";
             }
             break;
         case 'xml':
         case 'xml_object':
             $tree = new XML_Tree();
             if ($parameters['api_call'] == 'page_impressions') {
                 $root =& $tree->addRoot('pageimpressions');
             } else {
                 $root =& $tree->addRoot('visitors');
             }
             break;
         default:
             $result = array();
     }
     if ($parameters['interval'] != false) {
         $start = $parameters['start'] ? $parameters['start'] : 0;
         $end = $parameters['end'] ? $parameters['end'] : time();
         for ($i = $parameters['start']; $i < $parameters['end']; $i += $parameters['interval']) {
             $correct = (mktime(0, 0, 0, date('m', $i), date('d', $i) + 1, date('Y', $i)) - mktime(0, 0, 0, date('m', $i), date('d', $i), date('Y', $i))) * ($parameters['interval'] / 86400) - $parameters['interval'];
             // Correct weeks
             $j = $i;
             if ($parameters['interval'] == 604800) {
                 $j = $i + 86400;
             }
             $intervalStrings[] = sprintf('%s - %s', date('d-m-Y', $j), date('d-m-Y', $j + $parameters['interval'] + $correct));
             $values[] = phpOpenTracker::get(array('client_id' => $parameters['client_id'], 'api_call' => $parameters['api_call'], 'start' => $j, 'end' => $j + $parameters['interval'] + $correct, 'constraints' => $parameters['constraints']));
             $timestamps[] = $i;
             $i += $correct;
         }
     } else {
         $this->db->query(sprintf("SELECT %s AS result\r\n             FROM %s accesslog,\r\n                  %s visitors\r\n            WHERE visitors.client_id    = '%d'\r\n              AND visitors.accesslog_id = accesslog.accesslog_id\r\n                  %s\r\n                  %s", $parameters['api_call'] == 'page_impressions' ? 'COUNT(*)' : 'COUNT(DISTINCT(visitors.accesslog_id))', $this->config['accesslog_table'], $this->config['visitors_table'], $parameters['client_id'], $this->_constraint($parameters['constraints']), $this->_whereTimerange($parameters['start'], $parameters['end'], 'accesslog')));
         if ($row = $this->db->fetchRow()) {
             $values = array(intval($row['result']));
         } else {
             $values = array(0);
         }
         if ($parameters['start'] != false && $parameters['end'] != false) {
             $intervalStrings = array(sprintf('%s - %s', date('d-m-Y', $parameters['start']), date('d-m-Y', $parameters['end'])));
         } else {
             $intervalStrings = array('');
         }
     }
     switch ($parameters['result_format']) {
         case 'csv':
             for ($i = 0; $i < sizeof($values); $i++) {
                 $csv .= sprintf("%s;%d\n", $intervalStrings[$i], $values[$i]);
             }
             return $csv;
             break;
         case 'xml':
         case 'xml_object':
             for ($i = 0; $i < sizeof($values); $i++) {
                 $intervalChild =& $root->addChild('interval');
                 $intervalChild->addChild('interval', $intervalStrings[$i]);
                 $intervalChild->addChild('value', $values[$i]);
             }
             if ($parameters['result_format'] == 'xml') {
                 return $root->get();
             } else {
                 return $root;
             }
             break;
         default:
             if (sizeof($values) == 1) {
                 return $values[0];
             } else {
                 $result = array();
                 for ($i = 0; $i < sizeof($values); $i++) {
                     $result[] = array('timestamp' => $timestamps[$i], 'value' => $values[$i]);
                 }
             }
             return $result;
     }
 }
 /**
  * @param  array $parameters
  * @return mixed
  * @access public
  */
 function run($parameters)
 {
     if (!isset($parameters['what'])) {
         return phpOpenTracker::handleError('Required parameter "what" missing.');
     }
     $constraint = $this->_constraint($parameters['constraints']);
     $timerange = $this->_whereTimerange($parameters['start'], $parameters['end']);
     switch ($parameters['what']) {
         case 'combined_statistics':
             $_parameters = $parameters;
             $_parameters['what'] = 'top_search_engines';
             $searchEngines = phpOpenTracker::get($_parameters);
             $_parameters['what'] = 'top_search_keywords';
             for ($i = 0; $i < sizeof($searchEngines['top_items']); $i++) {
                 $_parameters['search_engine'] = $searchEngines['top_items'][$i]['string'];
                 $searchKeywords = phpOpenTracker::get($_parameters);
                 $searchEngines['top_items'][$i]['search_keywords'] = $searchKeywords['top_items'];
             }
             return $searchEngines['top_items'];
             break;
         case 'top_search_engines':
         case 'top_search_keywords':
             switch ($parameters['result_format']) {
                 case 'csv':
                     $csv = "Rank;Item;Count;Percent\n";
                     break;
                 case 'xml':
                 case 'xml_object':
                     $tree = new XML_Tree();
                     $root = $tree->addRoot('top');
                     break;
                 case 'separate_result_arrays':
                     $names = array();
                     $values = array();
                     $percent = array();
                     break;
                 default:
                     $topItems = array();
             }
             if (isset($parameters['search_engine'])) {
                 $searchEngineConstraint = sprintf("AND search_engines.search_engine = '%s'", $parameters['search_engine']);
             } else {
                 $searchEngineConstraint = '';
             }
             $field = $parameters['what'] == 'top_search_engines' ? 'search_engine' : 'keywords';
             $nestedQuery = sprintf("SELECT search_engines.%s AS item\r\n             FROM %s accesslog,\r\n                  %s visitors,\r\n                  %s search_engines\r\n            WHERE visitors.client_id    = '%d'\r\n              AND visitors.accesslog_id = accesslog.accesslog_id\r\n              AND visitors.accesslog_id = search_engines.accesslog_id\r\n                  %s\r\n                  %s\r\n                  %s\r\n            GROUP BY visitors.accesslog_id,\r\n                     search_engines.%s", $field, $this->config['accesslog_table'], $this->config['visitors_table'], $this->config['plugins']['search_engines']['table'], $parameters['client_id'], $searchEngineConstraint, $constraint, $timerange, $field);
             if ($this->db->supportsNestedQueries()) {
                 $queryTotalUnique = sprintf('SELECT COUNT(item)           AS total_items,
                 COUNT(DISTINCT(item)) AS unique_items
            FROM (%s) items', $nestedQuery);
                 $queryItems = sprintf('SELECT COUNT(item) AS item_count,
                 item
            FROM (%s) items
           GROUP BY item
           ORDER BY item_count %s,
                    item', $nestedQuery, $parameters['order']);
             } else {
                 if ($this->config['db_type'] == 'mysql' || $this->config['db_type'] == 'mysql_merge') {
                     $dropTemporaryTable = true;
                     $this->db->query(sprintf('CREATE TEMPORARY TABLE pot_temporary_table %s', $nestedQuery));
                     $queryTotalUnique = sprintf('SELECT COUNT(item)           AS total_items,
                   COUNT(DISTINCT(item)) AS unique_items
              FROM pot_temporary_table', $nestedQuery);
                     $queryItems = sprintf('SELECT COUNT(item) AS item_count,
                   item
              FROM pot_temporary_table
             GROUP BY item
             ORDER BY item_count %s,
                      item', $parameters['order']);
                 } else {
                     return phpOpenTracker::handleError('You need a database system capable of nested ' . 'queries to use the "search_engines" API calls.', E_USER_ERROR);
                 }
             }
             $this->db->query($queryTotalUnique);
             if ($row = $this->db->fetchRow()) {
                 $totalItems = intval($row['total_items']);
                 $uniqueItems = intval($row['unique_items']);
             } else {
                 return phpOpenTracker::handleError('Database query failed.');
             }
             if ($totalItems > 0) {
                 $this->db->query($queryItems, $parameters['limit']);
                 $i = 0;
                 while ($row = $this->db->fetchRow()) {
                     $percentValue = doubleval(number_format(100 * $row['item_count'] / $totalItems, 2));
                     switch ($parameters['result_format']) {
                         case 'csv':
                             $csv = sprintf("%d;%s;%d;%d\n", $i + 1, $row['item'], intval($row['item_count']), $percentValue);
                             break;
                         case 'xml':
                         case 'xml_object':
                             $itemChild =& $root->addChild('item');
                             $itemChild->addChild('rank', $i + 1);
                             $itemChild->addChild('string', $row['item']);
                             $itemChild->addChild('count', intval($row['item_count']));
                             $itemChild->addChild('percent', $percentValue);
                             break;
                         case 'separate_result_arrays':
                             $names[$i] = $row['item'];
                             $values[$i] = intval($row['item_count']);
                             $percent[$i] = $percentValue;
                             break;
                         default:
                             $topItems[$i]['count'] = intval($row['item_count']);
                             $topItems[$i]['string'] = $row['item'];
                             $topItems[$i]['percent'] = $percentValue;
                     }
                     $i++;
                 }
             }
             if (isset($dropTemporaryTable)) {
                 $this->db->query('DROP TABLE pot_temporary_table');
             }
             switch ($parameters['result_format']) {
                 case 'csv':
                     return $csv;
                     break;
                 case 'xml':
                 case 'xml_object':
                     $root->addChild('total', $totalItems);
                     $root->addChild('unique', $uniqueItems);
                     switch ($parameters['result_format']) {
                         case 'xml':
                             return $root->get();
                             break;
                         case 'xml_object':
                             return $root;
                             break;
                     }
                     break;
                 case 'separate_result_arrays':
                     return array($names, $values, $percent, $uniqueItems);
                     break;
                 default:
                     return array('top_items' => $topItems, 'unique_items' => $uniqueItems);
             }
             break;
     }
 }
Example #28
0
 /**
  * Returns information for the returning visitors.
  *
  * @param  array $parameters
  * @return array
  * @access private
  */
 function _returningVisitors($parameters)
 {
     $visitors = $this->_queryReturningVisitors($parameters);
     if (!empty($visitors)) {
         $keys = array_keys($visitors);
         $numKeys = sizeof($keys);
         for ($i = 0; $i < $numKeys; $i++) {
             $visitors[$keys[$i]]['num_visits'] = sizeof($visitors[$keys[$i]]['accesslog_ids']);
             $visitors[$keys[$i]]['visitor_id'] = $keys[$i];
             if ($visitors[$keys[$i]]['num_visits'] > 1) {
                 $time = 0;
                 for ($j = 0; $j < $visitors[$keys[$i]]['num_visits'] - 1; $j++) {
                     $time += $visitors[$keys[$i]]['timestamps'][$j + 1] - $visitors[$keys[$i]]['timestamps'][$j];
                 }
                 $visitors[$keys[$i]]['average_time_between_visits'] = floor($time / ($visitors[$keys[$i]]['num_visits'] - 1));
             } else {
                 unset($visitors[$keys[$i]]);
             }
         }
         if (!empty($visitors)) {
             foreach ($visitors as $visitor) {
                 $tmp[] = $visitor['num_visits'];
             }
             array_multisort($tmp, SORT_DESC, $visitors);
         }
     }
     switch ($parameters['result_format']) {
         case 'xml':
         case 'xml_object':
             $tree = new XML_Tree();
             $root =& $tree->addRoot('returningVisitors');
             $numVisitors = sizeof($visitors);
             for ($i = 0; $i < $numVisitors; $i++) {
                 $visitorChild =& $root->addChild('visitor');
                 $visitsChild =& $visitorChild->addChild('visits');
                 $numVisits = sizeof($visitors[$i]['accesslog_ids']);
                 for ($j = 0; $j < $numVisits; $j++) {
                     $visitChild =& $visitsChild->addChild('visit');
                     $visitChild->addChild('accesslogID', $visitors[$i]['accesslog_ids'][$j]);
                     $visitChild->addChild('timestamp', $visitors[$i]['timestamps'][$j]);
                 }
                 $visitorChild->addChild('numVisits', $visitors[$i]['num_visits']);
                 $visitorChild->addChild('visitorID', $visitors[$i]['visitor_id']);
             }
             if ($parameters['result_format'] == 'xml') {
                 return $root->get();
             } else {
                 return $root;
             }
             break;
         default:
             return $visitors;
     }
 }
Example #29
0
 /**
  * Writes current values for user back to the database.
  *
  * @return bool true on success or false on failure
  *
  * @access private
  */
 function _updateUserData()
 {
     if (!array_key_exists('lastlogin', $this->tables['users']['fields'])) {
         return true;
     }
     $index = 0;
     foreach ($this->userObj->children as $value) {
         if ($value->name == $this->alias['lastlogin']) {
             $el =& $this->userObj->getElement(array($index));
             $el->setContent($this->currentLogin);
         }
         $index++;
     }
     $success = false;
     do {
         if (!is_writable($this->file)) {
             $errorMsg = 'Auth freeze failure. Cannot write to the xml file';
             break;
         }
         $fp = fopen($this->file, 'wb');
         if (!$fp) {
             $errorMsg = "Auth freeze failure. Failed to open the xml file.";
             break;
         }
         if (!flock($fp, LOCK_EX)) {
             $errorMsg = "Auth freeze failure. Couldn't get an exclusive lock on the file.";
             break;
         }
         if (!fwrite($fp, $this->tree->get())) {
             $errorMsg = "Auth freeze failure. Write error when writing back the file.";
             break;
         }
         @fflush($fp);
         $success = true;
     } while (false);
     @flock($fp, LOCK_UN);
     @fclose($fp);
     if (!$success) {
         $this->stack->push(LIVEUSER_ERROR, 'exception', array(), 'Cannot read XML Auth file: ' . $errorMsg);
     }
     return $success;
 }
Example #30
0
 /**
  *
  *
  *
  * @param array &$storageConf Array with the storage configuration
  * @return boolean true on success, false on failure.
  *
  * @access public
  */
 function init(&$storageConf)
 {
     if (!parent::init($storageConf)) {
         return false;
     }
     if (!is_file($this->file)) {
         if (!is_file(getenv('DOCUMENT_ROOT') . $this->file)) {
             $this->_stack->push(LIVEUSER_ERROR_MISSING_DEPS, 'exception', array(), "Perm initialisation failed. Can't find xml file.");
             return false;
         }
         $this->file = getenv('DOCUMENT_ROOT') . $this->file;
     }
     if (!class_exists('XML_Tree')) {
         $this->_stack->push(LIVEUSER_ERROR_MISSING_DEPS, 'exception', array(), "Perm initialisation failed. Can't find XML_Tree class");
         return false;
     }
     $tree = new XML_Tree($this->file);
     $err =& $tree->getTreeFromFile();
     if (PEAR::isError($err)) {
         $this->_stack->push(LIVEUSER_ERROR, 'exception', array(), "Perm initialisation failed. Can't get tree from file");
         return false;
     }
     $this->tree = $tree;
     return true;
 }