Beispiel #1
0
 public function render(Register $ParameterOutput)
 {
     $doc = new XMLDocument();
     $root = $doc->createElement($this->parameters()->{'root-element'});
     try {
         $static = new XMLDocument();
         $node = $static->loadXML($this->parameters()->xml);
         $root->appendChild($doc->importNode($static->documentElement, true));
     } catch (FrontendPageNotFoundException $error) {
         FrontendPageNotFoundExceptionHandler::render($error);
     } catch (Exception $error) {
         $root->appendChild($doc->createElement('error', General::sanitize($error->getMessage())));
     }
     $doc->appendChild($root);
     return $doc;
 }
Beispiel #2
0
 public function render(Register $Parameters, XMLDocument &$Document = NULL, DocumentHeaders &$Headers = NULL)
 {
     $ParameterOutput = new Register();
     if (!is_null($Headers)) {
         $Headers->append('Content-Type', $this->{'content-type'});
     } else {
         header('Content-Type: ' . $this->{'content-type'});
     }
     if (is_null($Document)) {
         $Document = new XMLDocument();
         $Document->appendChild($Document->createElement('data'));
     }
     $root = $Document->documentElement;
     $datasources = $events = array();
     $events_wrapper = $Document->createElement('events');
     $root->appendChild($events_wrapper);
     if (is_array($this->about()->{'events'}) && !empty($this->about()->{'events'})) {
         $events = $this->about()->{'events'};
     }
     if (is_array($this->about()->{'data-sources'}) && !empty($this->about()->{'data-sources'})) {
         $datasources = $this->about()->{'data-sources'};
     }
     ####
     # Delegate: FrontendEventsAppend
     # Description: Append additional Events.
     # Global: Yes
     Extension::notify('FrontendEventsAppend', '/frontend/', array('events' => &$events));
     if (!empty($events)) {
         $postdata = General::getPostData();
         $events_ordered = array();
         foreach ($events as $handle) {
             $events_ordered[] = Event::loadFromHandle($handle);
         }
         uasort($events_ordered, array($this, '__cbSortEventsByPriority'));
         foreach ($events_ordered as $e) {
             if (!$e->canTrigger($postdata)) {
                 continue;
             }
             $fragment = $e->trigger($ParameterOutput, $postdata);
             if ($fragment instanceof DOMDocument && !is_null($fragment->documentElement)) {
                 $node = $Document->importNode($fragment->documentElement, true);
                 $events_wrapper->appendChild($node);
             }
         }
     }
     ####
     # Delegate: FrontendDataSourceAppend
     # Description: Append additional DataSources.
     # Global: Yes
     Extension::notify('FrontendDataSourcesAppend', '/frontend/', array('datasources' => &$datasources));
     //	Find dependancies and order accordingly
     $datasource_pool = array();
     $dependency_list = array();
     $datasources_ordered = array();
     $all_dependencies = array();
     foreach ($datasources as $handle) {
         $datasource_pool[$handle] = Datasource::loadFromHandle($handle);
         $dependency_list[$handle] = $datasource_pool[$handle]->parameters()->dependencies;
     }
     $datasources_ordered = $this->__sortByDependencies($dependency_list);
     if (!empty($datasources_ordered)) {
         foreach ($datasources_ordered as $handle) {
             $ds = $datasource_pool[$handle];
             try {
                 $fragment = $ds->render($ParameterOutput);
             } catch (FrontendPageNotFoundException $e) {
                 FrontendPageNotFoundExceptionHandler::render($e);
             }
             if ($fragment instanceof DOMDocument && !is_null($fragment->documentElement)) {
                 $node = $Document->importNode($fragment->documentElement, true);
                 $root->appendChild($node);
             }
         }
     }
     if ($ParameterOutput->length() > 0) {
         foreach ($ParameterOutput as $p) {
             $Parameters->{$p->key} = $p->value;
         }
     }
     ####
     # Delegate: FrontendParamsPostResolve
     # Description: Access to the resolved param pool, including additional parameters provided by Data Source outputs
     # Global: Yes
     Extension::notify('FrontendParamsPostResolve', '/frontend/', array('params' => $Parameters));
     $element = $Document->createElement('parameters');
     $root->appendChild($element);
     foreach ($Parameters as $key => $parameter) {
         if (is_array($parameter->value) && count($parameter->value) > 1) {
             $p = $Document->createElement($key);
             $p->setAttribute('value', (string) $parameter);
             foreach ($parameter->value as $v) {
                 $p->appendChild($Document->createElement('item', (string) $v));
             }
             $element->appendChild($p);
         } else {
             $element->appendChild($Document->createElement($key, (string) $parameter));
         }
     }
     $template = $this->template;
     ####
     # Delegate: FrontendTemplatePreRender
     # Description: Access to the template source, before it is rendered.
     # Global: Yes
     Extension::notify('FrontendTemplatePreRender', '/frontend/', array('document' => $Document, 'template' => &$template));
     $this->template = $template;
     // When the XSLT executes, it uses the CWD as set here
     $cwd = getcwd();
     chdir(WORKSPACE);
     $output = XSLProc::transform($Document, $this->template, XSLProc::XML, $Parameters->toArray(), array());
     chdir($cwd);
     if (XSLProc::hasErrors()) {
         throw new XSLProcException('Transformation Failed');
     }
     /*
     header('Content-Type: text/plain; charset=utf-8');
     $Document->formatOutput = true;
     print $Document->saveXML();
     die();
     */
     return $output;
 }
Beispiel #3
0
 public function toDoc()
 {
     $doc = new XMLDocument();
     $root = $doc->createElement('field');
     $root->setAttribute('guid', $this->guid);
     foreach ($this->properties as $name => $value) {
         if ($name == 'guid') {
             continue;
         }
         $element = $doc->createElement($name);
         $element->setValue($value);
         $root->appendChild($element);
     }
     $doc->appendChild($root);
     return $doc;
 }
 public function trigger(Register $parameter_output, array $data)
 {
     $errors = new MessageStack();
     $result = new XMLDocument();
     $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
     $result->formatOutput = true;
     $root = $result->documentElement;
     try {
         $this->root = $root;
         $status = $this->login($errors, $parameter_output, $data);
         $root->setAttribute('result', 'success');
     } catch (Exception $error) {
         $root->setAttribute('result', 'error');
         $root->appendChild($result->createElement('message', $error->getMessage()));
         if ($errors->valid()) {
             $element = $result->createElement('errors');
             $this->appendMessages($element, $errors);
             $root->appendChild($element);
         }
         //echo '<pre>', htmlentities($result->saveXML()), '</pre>'; exit;
     }
     return $result;
 }
Beispiel #5
0
    public function render(Register $ParameterOutput, $joins = NULL, array $where = array(), $filter_operation_type = self::FILTER_AND)
    {
        $execute = true;
        $result = new XMLDocument();
        $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
        $root = $result->documentElement;
        //	Conditions
        //	If any one condtion returns true (that is, do not execute), the DS will not execute at all
        if (is_array($this->parameters()->conditions)) {
            foreach ($this->parameters()->conditions as $condition) {
                if (preg_match('/:/', $condition['parameter'])) {
                    $c = Datasource::replaceParametersInString($condition['parameter'], $ParameterOutput);
                } else {
                    $c = Datasource::resolveParameter($condition['parameter'], $ParameterOutput);
                }
                // Is Empty
                if ($condition['logic'] == 'empty' && (is_null($c) || strlen($c) == 0)) {
                    $execute = false;
                } elseif ($condition['logic'] == 'set' && !is_null($c)) {
                    $execute = false;
                }
                if ($execute !== true) {
                    return NULL;
                }
            }
        }
        // Grab the section
        try {
            $section = Section::loadFromHandle($this->parameters()->section);
        } catch (SectionException $e) {
        } catch (Exception $e) {
        }
        $pagination = (object) array('total-entries' => NULL, 'entries-per-page' => max(1, (int) self::replaceParametersInString($this->parameters()->limit, $ParameterOutput)), 'total-pages' => NULL, 'current-page' => max(1, (int) self::replaceParametersInString($this->parameters()->page, $ParameterOutput)));
        $pagination->{'record-start'} = max(0, ($pagination->{'current-page'} - 1) * $pagination->{'entries-per-page'});
        $order = $sort = NULL;
        //	Apply the Sorting & Direction
        if ($this->parameters()->{'sort-order'} == 'random') {
            $order = 'RAND()';
        } else {
            $sort = strtolower($this->parameters()->{'sort-order'}) == 'asc' ? 'ASC' : 'DESC';
            // System Field
            if (preg_match('/^system:/i', $this->parameters()->{'sort-field'})) {
                switch (preg_replace('/^system:/i', NULL, $this->parameters()->{'sort-field'})) {
                    case 'id':
                        $order = "e.id {$sort}";
                        break;
                    case 'creation-date':
                        $order = "e.creation_date {$sort}";
                        break;
                    case 'modification-date':
                        $order = "e.modification_date {$sort}";
                        break;
                }
            } else {
                $join = NULL;
                $sort_field = $section->fetchFieldByHandle($this->parameters()->{'sort-field'});
                if ($sort_field instanceof Field && $sort_field->isSortable() && method_exists($sort_field, "buildSortingQuery")) {
                    $sort_field->buildSortingQuery($join, $order);
                    $joins .= sprintf($join, $sort_field->section, $sort_field->{'element-name'});
                    $order = sprintf($order, $sort);
                }
            }
        }
        //	Process Datasource Filters for each of the Fields
        if (is_array($this->parameters()->filters) && !empty($this->parameters()->filters)) {
            foreach ($this->parameters()->filters as $k => $filter) {
                if ($filter['element-name'] == 'system:id') {
                    $filter_value = $this->prepareFilterValue($filter['value'], $ParameterOutput);
                    if (!is_array($filter_value)) {
                        continue;
                    }
                    $filter_value = array_map('intval', $filter_value);
                    if (empty($filter_value)) {
                        continue;
                    }
                    $where[] = sprintf("(e.id %s IN (%s))", $filter['type'] == 'is-not' ? 'NOT' : NULL, implode(',', $filter_value));
                } else {
                    $field = $section->fetchFieldByHandle($filter['element-name']);
                    if ($field instanceof Field) {
                        $field->buildFilterQuery($filter, $joins, $where, $ParameterOutput);
                    }
                }
            }
        }
        // Escape percent symbold:
        $where = array_map(create_function('$string', 'return str_replace(\'%\', \'%%\', $string);'), $where);
        $query = sprintf('SELECT DISTINCT SQL_CALC_FOUND_ROWS e.*
				FROM `tbl_entries` AS `e`
				%1$s
				WHERE `section` = "%2$s"
				%3$s
				ORDER BY %4$s
				LIMIT %5$d, %6$d', $joins, $section->handle, is_array($where) && !empty($where) ? 'AND (' . implode($filter_operation_type == self::FILTER_AND ? ' AND ' : ' OR ', $where) . ')' : NULL, $order, $pagination->{'record-start'}, $pagination->{'entries-per-page'});
        try {
            $entries = Symphony::Database()->query($query, array($section->handle, $section->{'publish-order-handle'}), 'EntryResult');
            if (isset($this->parameters()->{'append-pagination'}) && $this->parameters()->{'append-pagination'} === true) {
                $pagination->{'total-entries'} = (int) Symphony::Database()->query("SELECT FOUND_ROWS() AS `total`")->current()->total;
                $pagination->{'total-pages'} = (int) ceil($pagination->{'total-entries'} * (1 / $pagination->{'entries-per-page'}));
                // Pagination Element
                $root->appendChild(General::buildPaginationElement($result, $pagination->{'total-entries'}, $pagination->{'total-pages'}, $pagination->{'entries-per-page'}, $pagination->{'current-page'}));
            }
            if (isset($this->parameters()->{'append-sorting'}) && $this->parameters()->{'append-sorting'} === true) {
                $sorting = $result->createElement('sorting');
                $sorting->setAttribute('field', $this->parameters()->{'sort-field'});
                $sorting->setAttribute('order', $this->parameters()->{'sort-order'});
                $root->appendChild($sorting);
            }
            $schema = array();
            // Build Entry Records
            if ($entries->valid()) {
                // Do some pre-processing on the include-elements.
                if (is_array($this->parameters()->{'included-elements'}) && !empty($this->parameters()->{'included-elements'})) {
                    $included_elements = (object) array('system' => array(), 'fields' => array());
                    foreach ($this->parameters()->{'included-elements'} as $element) {
                        $element_name = $mode = NULL;
                        if (preg_match_all('/^([^:]+):\\s*(.+)$/', $element, $matches, PREG_SET_ORDER)) {
                            $element_name = $matches[0][1];
                            $mode = $matches[0][2];
                        } else {
                            $element_name = $element;
                        }
                        if ($element_name == 'system') {
                            $included_elements->system[] = $mode;
                        } else {
                            $field = $section->fetchFieldByHandle($element_name);
                            if (!$field instanceof Field) {
                                continue;
                            }
                            $schema[] = $element_name;
                            $included_elements->fields[] = array('element-name' => $element_name, 'instance' => $field, 'mode' => !is_null($mode) > 0 ? trim($mode) : NULL);
                        }
                    }
                }
                // Do some pre-processing on the param output array
                if (is_array($this->parameters()->{'parameter-output'}) && !empty($this->parameters()->{'parameter-output'})) {
                    $parameter_output = (object) array('system' => array(), 'fields' => array());
                    foreach ($this->parameters()->{'parameter-output'} as $element) {
                        if (preg_match('/^system:/i', $element)) {
                            $parameter_output->system[preg_replace('/^system:/i', NULL, $element)] = array();
                        } else {
                            $schema[] = $element;
                            $parameter_output->fields[$element] = array();
                        }
                    }
                }
                $entries->setSchema($schema);
                foreach ($entries as $e) {
                    // If there are included elements, need an entry element.
                    if (is_array($this->parameters()->{'included-elements'}) && !empty($this->parameters()->{'included-elements'})) {
                        $entry = $result->createElement('entry');
                        $entry->setAttribute('id', $e->id);
                        $root->appendChild($entry);
                        foreach ($included_elements->system as $field) {
                            switch ($field) {
                                case 'creation-date':
                                    $entry->appendChild(General::createXMLDateObject($result, DateTimeObj::fromGMT($e->creation_date), 'creation-date'));
                                    break;
                                case 'modification-date':
                                    $entry->appendChild(General::createXMLDateObject($result, DateTimeObj::fromGMT($e->modification_date), 'modification-date'));
                                    break;
                                case 'user':
                                    $obj = User::load($e->user_id);
                                    $user = $result->createElement('user', $obj->getFullName());
                                    $user->setAttribute('id', $e->user_id);
                                    $user->setAttribute('username', $obj->username);
                                    $user->setAttribute('email-address', $obj->email);
                                    $entry->appendChild($user);
                                    break;
                            }
                        }
                        foreach ($included_elements->fields as $field) {
                            $field['instance']->appendFormattedElement($entry, $e->data()->{$field['element-name']}, false, $field['mode'], $e);
                        }
                    }
                    if (is_array($this->parameters()->{'parameter-output'}) && !empty($this->parameters()->{'parameter-output'})) {
                        foreach ($parameter_output->system as $field => $existing_values) {
                            switch ($field) {
                                case 'id':
                                    $parameter_output->system[$field][] = $e->id;
                                    break;
                                case 'creation-date':
                                    $parameter_output->system[$field][] = DateTimeObj::get('Y-m-d H:i:s', DateTimeObj::fromGMT($e->creation_date));
                                    break;
                                case 'modification-date':
                                    $parameter_output->system[$field][] = DateTimeObj::get('Y-m-d H:i:s', DateTimeObj::fromGMT($e->modification_date));
                                    break;
                                case 'user':
                                    $parameter_output->system[$field][] = $e->user_id;
                                    break;
                            }
                        }
                        foreach ($parameter_output->fields as $field => $existing_values) {
                            if (!isset($e->data()->{$field}) or is_null($e->data()->{$field})) {
                                continue;
                            }
                            $o = $section->fetchFieldByHandle($field)->getParameterOutputValue($e->data()->{$field}, $e);
                            if (is_array($o)) {
                                $parameter_output->fields[$field] = array_merge($o, $parameter_output->fields[$field]);
                            } else {
                                $parameter_output->fields[$field][] = $o;
                            }
                        }
                    }
                }
                // Add in the param output values to the ParameterOutput object
                if (is_array($this->parameters()->{'parameter-output'}) && !empty($this->parameters()->{'parameter-output'})) {
                    foreach ($parameter_output->system as $field => $values) {
                        $key = sprintf('ds-%s.system.%s', $this->parameters()->{'root-element'}, $field);
                        $values = array_filter($values);
                        if (is_array($values) && !empty($values)) {
                            $ParameterOutput->{$key} = array_unique($values);
                        }
                    }
                    foreach ($parameter_output->fields as $field => $values) {
                        $key = sprintf('ds-%s.%s', $this->parameters()->{'root-element'}, $field);
                        $values = array_filter($values);
                        if (is_array($values) && !empty($values)) {
                            $ParameterOutput->{$key} = array_unique($values);
                        }
                    }
                }
            } elseif ($this->parameters()->{'redirect-404-on-empty'} === true) {
                throw new FrontendPageNotFoundException();
            } else {
                $this->emptyXMLSet($root);
            }
        } catch (DatabaseException $e) {
            $root->appendChild($result->createElement('error', $e->getMessage()));
        }
        return $result;
    }
Beispiel #6
0
 public function __buildPageXML($view, View $parent = null)
 {
     $result = new XMLDocument();
     $xView = $result->createElement('view');
     $xView->setAttribute('handle', $view->handle);
     $xView->appendChild($result->createElement('title', $view->title));
     ##	Types
     if (is_array($view->types) && count($view->types) > 0) {
         $types = $result->createElement('types');
         foreach ($view->types as $t) {
             $types->appendChild($result->createElement('item', General::sanitize($t)));
         }
         $xView->appendChild($types);
     }
     ##	Children
     foreach ($view->children() as $child) {
         $node = $this->__buildPageXML($child, $view);
         if (!is_null($node)) {
             $xView->appendChild($result->importNode($node, true));
         }
     }
     return $xView;
 }
Beispiel #7
0
 public function trigger(Register $ParameterOutput, array $postdata)
 {
     $result = new XMLDocument();
     $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
     $root = $result->documentElement;
     // Apply default values:
     foreach ($this->parameters()->{'defaults'} as $name => $value) {
         if (!isset($postdata['fields'][$name])) {
             $postdata['fields'][$name] = $value;
         } else {
             if (is_string($postdata['fields'][$name]) and $postdata['fields'][$name] == '') {
                 $postdata['fields'][$name] = $value;
             } else {
                 if (is_array($postdata['fields'][$name]) and empty($postdata['fields'][$name])) {
                     $postdata['fields'][$name] = array($value);
                 }
             }
         }
     }
     // Apply override values:
     foreach ($this->parameters()->{'overrides'} as $name => $value) {
         if (is_array($postdata['fields'][$name])) {
             $postdata['fields'][$name] = array($value);
         } else {
             $postdata['fields'][$name] = $value;
         }
     }
     if (isset($postdata['id'])) {
         $entry = Entry::loadFromID($postdata['id']);
         $type = 'edit';
     } else {
         $entry = new Entry();
         $entry->section = $this->parameters()->{'section'};
         if (isset(Frontend::instance()->User) && Frontend::instance()->User instanceof User) {
             $entry->user_id = Frontend::instance()->User->id;
         } else {
             $entry->user_id = (int) Symphony::Database()->query("SELECT `id` FROM `tbl_users` ORDER BY `id` ASC LIMIT 1")->current()->id;
         }
         $type = 'create';
     }
     if (isset($postdata['fields']) && is_array($postdata['fields']) && !empty($postdata['fields'])) {
         $entry->setFieldDataFromFormArray($postdata['fields']);
     }
     $root->setAttribute('type', $type);
     ###
     # Delegate: EntryPreCreate
     # Description: Just prior to creation of an Entry. Entry object provided
     Extension::notify('EntryPreCreate', '/frontend/', array('entry' => &$entry));
     $errors = new MessageStack();
     $status = Entry::save($entry, $errors);
     if ($status == Entry::STATUS_OK) {
         ###
         # Delegate: EntryPostCreate
         # Description: Creation of an Entry. New Entry object is provided.
         Extension::notify('EntryPostCreate', '/frontend/', array('entry' => $entry));
         if ($this->parameters()->{'output-id-on-save'} == true) {
             $ParameterOutput->{sprintf('event-%s-id', $this->parameters()->{'root-element'})} = $entry->id;
         }
         $root->setAttribute('result', 'success');
         $root->setAttribute('id', $entry->id);
         $root->appendChild($result->createElement('message', __("Entry %s successfully.", array($type == 'edit' ? __('edited') : __('created')))));
     } else {
         $root->setAttribute('result', 'error');
         $root->appendChild($result->createElement('message', __('Entry encountered errors when saving.')));
         if (!isset($postdata['fields']) || !is_array($postdata['fields'])) {
             $postdata['fields'] = array();
         }
         $element = $result->createElement('errors');
         $this->appendMessages($element, $errors);
         $root->appendChild($element);
     }
     $messages = new MessageStack();
     ###
     # Delegate: EventPostSaveFilter
     # Description: After saving entry from the front-end. This delegate will not force the Events to terminate if it populates the error
     #              array reference. Provided with the event, message stack, postdata and entry object.
     Extension::notify('EventPostSaveFilter', '/frontend/', array('event' => $this, 'messages' => $messages, 'fields' => $postdata, 'entry' => $entry));
     if ($messages->valid()) {
         $filter = $result->createElement('filters');
         $this->appendMessages($filter, $messages);
         $root->appendChild($filter);
     }
     $element = $result->createElement('values');
     $this->appendValues($element, is_array($postdata['fields']) ? $postdata['fields'] : array());
     $root->appendChild($element);
     return $result;
 }
Beispiel #8
0
 public function trigger(Register $ParameterOutput, array $postdata)
 {
     $result = new XMLDocument();
     $result->appendChild($result->createElement($this->parameters()->{'root-element'}));
     $root = $result->documentElement;
     if (isset($postdata['id'])) {
         $entry = Entry::loadFromID($postdata['id']);
         $type = 'edit';
     } else {
         $entry = new Entry();
         $entry->section = $this->parameters()->{'section'};
         if (isset(Frontend::instance()->User) && Frontend::instance()->User instanceof User) {
             $entry->user_id = Frontend::instance()->User->id;
         } else {
             $entry->user_id = (int) Symphony::Database()->query("SELECT `id` FROM `tbl_users` ORDER BY `id` ASC LIMIT 1")->current()->id;
         }
         $type = 'create';
     }
     if (isset($postdata['fields']) && is_array($postdata['fields']) && !empty($postdata['fields'])) {
         $entry->setFieldDataFromFormArray($postdata['fields']);
     }
     $root->setAttribute('type', $type);
     ###
     # Delegate: EntryPreCreate
     # Description: Just prior to creation of an Entry. Entry object provided
     Extension::notify('EntryPreCreate', '/frontend/', array('entry' => &$entry));
     $errors = new MessageStack();
     $status = Entry::save($entry, $errors);
     if ($status == Entry::STATUS_OK) {
         ###
         # Delegate: EntryPostCreate
         # Description: Creation of an Entry. New Entry object is provided.
         Extension::notify('EntryPostCreate', '/frontend/', array('entry' => $entry));
         if ($this->parameters()->{'output-id-on-save'} == true) {
             $ParameterOutput->{sprintf('event-%s-id', $this->parameters()->{'root-element'})} = $entry->id;
         }
         $root->setAttribute('result', 'success');
         $root->appendChild($result->createElement('message', __("Entry %s successfully.", array($type == 'edit' ? __('edited') : __('created')))));
     } else {
         $root->setAttribute('result', 'error');
         $root->appendChild($result->createElement('message', __('Entry encountered errors when saving.')));
         if (!isset($postdata['fields']) || !is_array($postdata['fields'])) {
             $postdata['fields'] = array();
         }
         $element = $result->createElement('values');
         $this->appendValues($element, $postdata['fields']);
         $root->appendChild($element);
         $element = $result->createElement('errors');
         $this->appendMessages($element, $errors);
         $root->appendChild($element);
     }
     return $result;
 }
Beispiel #9
0
 public function render(Register $ParameterOutput)
 {
     $result = null;
     $doc = new XMLDocument();
     if (isset($this->parameters()->url)) {
         $this->parameters()->url = self::replaceParametersInString($this->parameters()->url, $ParameterOutput);
     }
     if (isset($this->parameters()->xpath)) {
         $this->parameters()->xpath = self::replaceParametersInString($this->parameters()->xpath, $ParameterOutput);
     }
     $cache_id = md5($this->parameters()->url . serialize($this->parameters()->namespaces) . $this->parameters()->xpath);
     $cache = Cache::instance();
     $cachedData = $cache->read($cache_id);
     $writeToCache = false;
     $force_empty_result = false;
     $valid = true;
     $result = NULL;
     $creation = DateTimeObj::get('c');
     if (isset($this->parameters()->timeout)) {
         $timeout = (int) max(1, $this->parameters()->timeout);
     }
     if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->parameters()->{'cache-timeout'} * 60) {
         if (Mutex::acquire($cache_id, $timeout, TMP)) {
             $start = precision_timer();
             $ch = new Gateway();
             $ch->init();
             $ch->setopt('URL', $this->parameters()->url);
             $ch->setopt('TIMEOUT', $this->parameters()->timeout);
             $xml = $ch->exec();
             $writeToCache = true;
             $end = precision_timer('STOP', $start);
             $info = $ch->getInfoLast();
             Mutex::release($cache_id, TMP);
             $xml = trim($xml);
             if ((int) $info['http_code'] != 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) {
                 $writeToCache = false;
                 if (is_array($cachedData) && !empty($cachedData)) {
                     $xml = trim($cachedData['data']);
                     $valid = false;
                     $creation = DateTimeObj::get('c', $cachedData['creation']);
                 } else {
                     $result = $doc->createElement($this->parameters()->{'root-element'});
                     $result->setAttribute('valid', 'false');
                     if ($end > $timeout) {
                         $result->appendChild($doc->createElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                     } else {
                         $result->appendChild($doc->createElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                     }
                     return $result;
                 }
             } elseif (strlen($xml) > 0 && !General::validateXML($xml, $errors)) {
                 $writeToCache = false;
                 if (is_array($cachedData) && !empty($cachedData)) {
                     $xml = trim($cachedData['data']);
                     $valid = false;
                     $creation = DateTimeObj::get('c', $cachedData['creation']);
                 } else {
                     $result = $doc->createElement($this->parameters()->{'root-element'}, $doc->createElement('error', __('XML returned is invalid.')), array('valid' => 'false'));
                     return $result;
                 }
             } elseif (strlen($xml) == 0) {
                 $force_empty_result = true;
             }
         } elseif (is_array($cachedData) && !empty($cachedData)) {
             $xml = trim($cachedData['data']);
             $valid = false;
             $creation = DateTimeObj::get('c', $cachedData['creation']);
             if (empty($xml)) {
                 $force_empty_result = true;
             }
         } else {
             $force_empty_result = true;
         }
     } else {
         $xml = trim($cachedData['data']);
         $creation = DateTimeObj::get('c', $cachedData['creation']);
     }
     if (!$force_empty_result) {
         $result = new XMLDocument();
         $root = $result->createElement($this->parameters()->{'root-element'});
         //XPath Approach, saves Transforming the Document.
         $xDom = new XMLDocument();
         $xDom->loadXML($xml);
         if ($xDom->hasErrors()) {
             $root->setAttribute('valid', 'false');
             $root->appendChild($result->createElement('error', __('XML returned is invalid.')));
             $messages = $result->createElement('messages');
             foreach ($xDom->getErrors() as $e) {
                 if (strlen(trim($e->message)) == 0) {
                     continue;
                 }
                 $messages->appendChild($result->createElement('item', General::sanitize($e->message)));
             }
             $root->appendChild($messages);
         } else {
             if ($writeToCache) {
                 $cache->write($cache_id, $xml);
             }
             $xpath = new DOMXPath($xDom);
             ## Namespaces
             if (is_array($this->parameters()->namespaces) && !empty($this->parameters()->namespaces)) {
                 foreach ($this->parameters()->namespaces as $index => $namespace) {
                     $xpath->registerNamespace($namespace['name'], $namespace['uri']);
                 }
             }
             $xpath_list = $xpath->query($this->parameters()->xpath);
             foreach ($xpath_list as $node) {
                 if ($node instanceof XMLDocument) {
                     $root->appendChild($result->importNode($node->documentElement, true));
                 } else {
                     $root->appendChild($result->importNode($node, true));
                 }
             }
             $root->setAttribute('status', $valid === true ? 'fresh' : 'stale');
             $root->setAttribute('creation', $creation);
         }
     }
     if (!$root->hasChildNodes() || $force_empty_result) {
         $this->emptyXMLSet($root);
     }
     $result->appendChild($root);
     return $result;
 }
Beispiel #10
0
 public function render(Register $parameter_output)
 {
     $document = new XMLDocument();
     $root = $document->createElement($this->parameters()->{'root-element'});
     $addresses = DataSource::replaceParametersInString(trim($this->parameters()->{'addresses'}), $parameter_output);
     $addresses = preg_split('%,\\s*%', $addresses);
     $params = array('s' => $this->parameters()->{'size'}, 'r' => $this->parameters()->{'rating'}, 'd' => $this->parameters()->{'default'});
     foreach ($params as $key => $value) {
         $value = DataSource::replaceParametersInString($value, $parameter_output);
         if ($key == 's') {
             $value = (int) $value;
         }
         $params[$key] = $value;
     }
     if ($params['s'] < 1 or $params['s'] > 512) {
         unset($params['s']);
     }
     if (!in_array($params['r'], array('g', 'pg', 'r', 'x'))) {
         unset($params['r']);
     }
     if (is_null($params['d'])) {
         unset($params['d']);
     }
     foreach ($addresses as $address) {
         $address = trim($address);
         if (empty($address)) {
             continue;
         }
         $hash = md5($address);
         $url = new URLWriter('http://www.gravatar.com/avatar/' . $hash, $params);
         $element = $document->createElement('avatar');
         $element->setAttribute('email', $address);
         $element->setAttribute('url', (string) $url);
         $root->appendChild($element);
     }
     $document->appendChild($root);
     return $document;
 }
Beispiel #11
0
 public function render(Register $ParameterOutput)
 {
     $result = new XMLDocument();
     $root = $result->createElement($this->parameters()->{'root-element'});
     try {
         ##	User Filtering
         if (is_array($this->parameters()->filters) && !empty($this->parameters()->filters)) {
             $user_ids = NULL;
             $where_clauses = array();
             $query = "SELECT * FROM `tbl_users` WHERE 1 %s ORDER BY `id` ASC";
             foreach ($this->parameters()->filters as $field => $value) {
                 if (!is_array($value) && trim($value) == '') {
                     continue;
                 }
                 $value = self::replaceParametersInString($value, $ParameterOutput);
                 if (!is_array($value)) {
                     $value = preg_split('/,\\s*/', $value, -1, PREG_SPLIT_NO_EMPTY);
                     $value = array_map('trim', $value);
                 }
                 $where_clauses[] = sprintf("`%s` IN ('%s')", str_replace('-', '_', $field), implode(',', $value));
             }
             // Should the $where_clauses array be empty, it means there were no valid filters. I.E. they were all empty strings.
             // If that is the case, we still want Users to get returned, hence the "WHERE 1" part of the SQL to avoid errors.
             if (!empty($where_clauses)) {
                 $where_clauses = 'AND' . implode(' AND ', $where_clauses);
             } else {
                 $where_clauses = NULL;
             }
             $users = Symphony::Database()->query(sprintf($query, $where_clauses), array(), 'UserResult');
         } else {
             $users = new UserIterator();
         }
         if ($users->length() > 0) {
             $included_fields = $this->parameters()->{'included-elements'};
             foreach ($users as $user) {
                 $xUser = $result->createElement('user', null);
                 $xUser->setAttribute('id', $user->id);
                 foreach ($included_fields as $element) {
                     switch ($element) {
                         case 'name':
                             $xUser->appendChild($result->createElement('name', $user->getFullName()));
                             break;
                         case 'email-address':
                             $xUser->appendChild($result->createElement('email-address', $user->email));
                             break;
                         case 'username':
                             $xUser->appendChild($result->createElement('username', $user->username));
                             break;
                         case 'language':
                             if (!is_null($user->language)) {
                                 $xUser->appendChild($result->createElement('language', $user->language));
                             }
                             break;
                         case 'authentication-token':
                             if ($user->isTokenActive()) {
                                 $xUser->appendChild($result->createElement('authentication-token', $user->createAuthToken()));
                             }
                             break;
                         case 'default-section':
                             try {
                                 $section = Section::loadFromHandle($user->default_section);
                                 $default_section = $result->createElement('default-section', $section->name);
                                 $default_section->setAttribute('handle', $section->handle);
                                 $xUser->appendChild($default_section);
                             } catch (SectionException $error) {
                                 // Do nothing, section doesn't exist, but no need to error out about it..
                             }
                             break;
                         default:
                             break;
                     }
                 }
                 $root->appendChild($xUser);
             }
         } else {
             throw new DataSourceException("No records found.");
         }
     } catch (Exception $error) {
         $root->appendChild($result->createElement('error', General::sanitize($error->getMessage())));
     }
     $result->appendChild($root);
     return $result;
 }