Esempio n. 1
0
 public function __viewIndex()
 {
     $this->setTitle(__('Symphony') . ' – ' . __('Users'));
     $this->appendSubheading(__('Users'), Widget::Anchor(__('Add a User'), Administration::instance()->getCurrentPageURL() . '/new/', array('title' => __('Add a new User'), 'class' => 'create button')));
     $users = new UserIterator();
     $aTableHead = array(array(__('Name'), 'col'), array(__('Email Address'), 'col'), array(__('Last Seen'), 'col'));
     $aTableBody = array();
     $colspan = count($aTableHead);
     if ($users->length() == 0) {
         $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('None found.'), array('class' => 'inactive', 'colspan' => $colspan))), array('class' => 'odd')));
     } else {
         foreach ($users as $u) {
             ## Setup each cell
             $td1 = Widget::TableData(Widget::Anchor($u->getFullName(), Administration::instance()->getCurrentPageURL() . '/edit/' . $u->id . '/', array('title' => $u->username)));
             $td2 = Widget::TableData(Widget::Anchor($u->email, 'mailto:' . $u->email, array('title' => 'Email this user')));
             if ($u->last_seen != NULL) {
                 $td3 = Widget::TableData(DateTimeObj::get(__SYM_DATETIME_FORMAT__, strtotime($u->last_seen)));
             } else {
                 $td3 = Widget::TableData('Unknown', array('class' => 'inactive'));
             }
             $td3->appendChild(Widget::Input('items[' . $u->id . ']', NULL, 'checkbox'));
             ## Add a row to the body array, assigning each cell to the row
             $aTableBody[] = Widget::TableRow(array($td1, $td2, $td3));
         }
     }
     $table = Widget::Table(Widget::TableHead($aTableHead), NULL, Widget::TableBody($aTableBody));
     $this->Form->appendChild($table);
     $tableActions = $this->createElement('div');
     $tableActions->setAttribute('class', 'actions');
     $options = array(array(NULL, false, 'With Selected...'), array('delete', false, 'Delete'));
     $tableActions->appendChild(Widget::Select('with-selected', $options));
     $tableActions->appendChild(Widget::Input('action[apply]', 'Apply', 'submit'));
     $this->Form->appendChild($tableActions);
 }
 public function processDependencies(array $params = array())
 {
     $datasources = $this->getDependencies();
     if (!is_array($datasources) || empty($datasources)) {
         return;
     }
     $datasources = array_map(create_function('$a', "return str_replace('\$ds-', '', \$a);"), $datasources);
     $datasources = array_map(create_function('$a', "return str_replace('-', '_', \$a);"), $datasources);
     $env = array('today' => DateTimeObj::get('Y-m-d'), 'current-time' => DateTimeObj::get('H:i'), 'this-year' => DateTimeObj::get('Y'), 'this-month' => DateTimeObj::get('m'), 'this-day' => DateTimeObj::get('d'), 'timezone' => DateTimeObj::get('P'), 'enm-newsletter-id' => $this->newsletter_id);
     $this->_env['param'] = $env;
     $this->_env['env']['pool'] = $params;
     $dependencies = array();
     foreach ($datasources as $handle) {
         $profiler = Symphony::Profiler();
         $profiler->seed();
         $pool[$handle] =& DatasourceManager::create($handle, NULL, false);
         $dependencies[$handle] = $pool[$handle]->getDependencies();
     }
     $dsOrder = $this->__findDatasourceOrder($dependencies);
     foreach ($dsOrder as $handle) {
         $ds = $pool[$handle];
         $ds->processParameters($this->_env);
         $ds->grab($this->_env['env']['pool']);
         unset($ds);
     }
     $this->processParameters($this->_env);
 }
Esempio n. 3
0
 /**
  * Given an array or string as `$needle` and an existing `$member_id`
  * this function will return the `$member_id` if the given
  * password matches this `$member_id`, otherwise null.
  *
  * @param array|string $needle
  * @param integer $member_id
  * @return Entry|null
  */
 public function fetchMemberIDBy($needle, $member_id)
 {
     if (is_array($needle)) {
         extract($needle);
     } else {
         $password = $needle;
     }
     if (empty($password)) {
         extension_Members::$_errors[$this->get('element_name')] = array('message' => __('\'%s\' is a required field.', array($this->get('label'))), 'type' => 'missing', 'label' => $this->get('label'));
         return null;
     }
     $data = Symphony::Database()->fetchRow(0, sprintf("\n\t\t\t\t\tSELECT `entry_id`, `reset`\n\t\t\t\t\tFROM `tbl_entries_data_%d`\n\t\t\t\t\tWHERE `password` = '%s'\n\t\t\t\t\tAND `entry_id` = %d\n\t\t\t\t\tLIMIT 1\n\t\t\t\t", $this->get('id'), $password, Symphony::Database()->cleanValue($member_id)));
     // Check that if the password has been reset that it is still valid
     if (!empty($data) && $data['reset'] == 'yes') {
         $valid_id = Symphony::Database()->fetchVar('entry_id', 0, sprintf("\n\t\t\t\t\t\tSELECT `entry_id`\n\t\t\t\t\t\tFROM `tbl_entries_data_%d`\n\t\t\t\t\t\tWHERE `entry_id` = %d\n\t\t\t\t\t\tAND DATE_FORMAT(expires, '%%Y-%%m-%%d %%H:%%i:%%s') > '%s'\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t", $this->get('id'), $data['entry_id'], DateTimeObj::get('Y-m-d H:i:s', strtotime('now - ' . $this->get('code_expiry')))));
         // If we didn't get an entry_id back, then it's because it was expired
         if (is_null($valid_id)) {
             extension_Members::$_errors[$this->get('element_name')] = array('message' => __('Recovery code has expired.'), 'type' => 'invalid', 'label' => $this->get('label'));
         } else {
             $fields = array('reset' => 'no', 'expires' => null);
             Symphony::Database()->update($fields, 'tbl_entries_data_' . $this->get('id'), ' `entry_id` = ' . $valid_id);
         }
     }
     if (!empty($data)) {
         return $member_id;
     }
     extension_Members::$_errors[$this->get('element_name')] = array('message' => __('Invalid %s.', array($this->get('label'))), 'type' => 'invalid', 'label' => $this->get('label'));
     return null;
 }
function handleShutdown()
{
    $error = error_get_last();
    if ($error !== NULL && $error['type'] <= 1) {
        file_put_contents(DOCROOT . '/manifest/newsletter-log.txt', '[' . DateTimeObj::get('Y/m/d H:i:s') . '] pid: ' . getmypid() . ' - ' . $error['message'] . ' in file: ' . $error['file'] . ' on line ' . $error['line'] . "\r\n", FILE_APPEND);
    }
}
 /**
  * Initialize contextual XML (formerly params)
  */
 public function initializeContext()
 {
     $this->View->context->register(array('system' => array('site-name' => Symphony::Configuration()->core()->symphony->sitename, 'site-url' => URL, 'admin-url' => URL . '/symphony', 'symphony-version' => Symphony::Configuration()->core()->symphony->version), 'date' => array('today' => DateTimeObj::get('Y-m-d'), 'current-time' => DateTimeObj::get('H:i'), 'this-year' => DateTimeObj::get('Y'), 'this-month' => DateTimeObj::get('m'), 'this-day' => DateTimeObj::get('d'), 'timezone' => date_default_timezone_get())));
     if ($this->User) {
         $this->View->context->register(array('session' => self::instance()->User->fields()));
     }
 }
Esempio n. 6
0
 public static function lastUpdateFilterList()
 {
     if (!file_exists(WORKSPACE . self::$file)) {
         return false;
     }
     return DateTimeObj::get(DateTimeObj::getSetting('datetime_format'), filemtime(WORKSPACE . self::$file));
 }
Esempio n. 7
0
 function __switchboard($type)
 {
     $this->_page = isset($this->_context[0]) ? $this->_context[0] : 'view';
     $this->_id = !empty($this->_context[1]) && is_numeric($this->_context[1]) ? $this->_context[1] : 0;
     $this->_flag = $this->_context[2];
     // Notices
     if (isset($this->_flag)) {
         $result = null;
         switch ($this->_flag) {
             case 'edited':
                 $result = __('Category updated at %1$s.');
                 break;
             case 'deleted':
                 $result = __('Category deleted');
                 break;
             case 'created':
                 $result = __('Category created at %1$s. <a href="%2$s">Create another?</a>');
                 break;
         }
         if ($result) {
             $this->pageAlert(__($result, array(DateTimeObj::get(__SYM_TIME_FORMAT__), BASE_URL . '/list/new/' . $this->_id)), Alert::SUCCESS);
         }
     }
     $function = ($type == 'action' ? '__action' : '__view') . ($this->_page == 'view' ? 'Index' : ucfirst($this->_page));
     if (!method_exists($this, $function)) {
         if ($type == 'action') {
             return;
         }
         $this->_Parent->errorPageNotFound();
     }
     return $this->{$function}();
 }
 function processRecordGroup(&$wrapper, $element, $group, $ds, &$Parent, &$entryManager, &$fieldPool, &$param_pool, $param_output_only = false)
 {
     $xGroup = new XMLElement($element, NULL, $group['attr']);
     $key = 'ds-' . $ds->dsParamROOTELEMENT;
     if (is_array($group['records']) && !empty($group['records'])) {
         foreach ($group['records'] as $entry) {
             $data = $entry->getData();
             $fields = array();
             $xEntry = new XMLElement('entry');
             $xEntry->setAttribute('id', $entry->get('id'));
             $associated_entry_counts = $entry->fetchAllAssociatedEntryCounts();
             if (is_array($associated_entry_counts) && !empty($associated_entry_counts)) {
                 foreach ($associated_entry_counts as $section_id => $count) {
                     $section_handle = $Parent->Database->fetchVar('handle', 0, "SELECT `handle` FROM `tbl_sections` WHERE `id` = '{$section_id}' LIMIT 1");
                     $xEntry->setAttribute($section_handle, '' . $count . '');
                 }
             }
             if (isset($ds->dsParamPARAMOUTPUT)) {
                 if ($ds->dsParamPARAMOUTPUT == 'system:id') {
                     $param_pool[$key][] = $entry->get('id');
                 } elseif ($ds->dsParamPARAMOUTPUT == 'system:date') {
                     $param_pool[$key][] = DateTimeObj::get('c', strtotime($entry->creationDate));
                 } elseif ($ds->dsParamPARAMOUTPUT == 'system:author') {
                     $param_pool[$key][] = $entry->get('author_id');
                 }
             }
             foreach ($data as $field_id => $values) {
                 if (!isset($fieldPool[$field_id]) || !is_object($fieldPool[$field_id])) {
                     $fieldPool[$field_id] =& $entryManager->fieldManager->fetch($field_id);
                 }
                 if (isset($ds->dsParamPARAMOUTPUT) && $ds->dsParamPARAMOUTPUT == $fieldPool[$field_id]->get('element_name')) {
                     $param_pool[$key][] = $fieldPool[$field_id]->getParameterPoolValue($values);
                 }
                 if (!$param_output_only) {
                     foreach ($ds->dsParamINCLUDEDELEMENTS as $handle) {
                         list($handle, $mode) = preg_split('/\\s*:\\s*/', $handle, 2);
                         if ($fieldPool[$field_id]->get('element_name') == $handle) {
                             $fieldPool[$field_id]->appendFormattedElement($xEntry, $values, $ds->dsParamHTMLENCODE ? true : false, $mode);
                         }
                     }
                 }
             }
             if (!$param_output_only) {
                 $xGroup->appendChild($xEntry);
             }
         }
     }
     if (is_array($group['groups']) && !empty($group['groups'])) {
         foreach ($group['groups'] as $element => $group) {
             foreach ($group as $g) {
                 processRecordGroup($xGroup, $element, $g, $ds, $Parent, $entryManager, $fieldPool, $param_pool, $param_output_only);
             }
         }
     }
     if (!$param_output_only) {
         $wrapper->appendChild($xGroup);
     }
     return;
 }
 function getValuesFromXML()
 {
     $xml_location = $this->get('xml_location');
     if (General::validateURL($xml_location) != '') {
         // is a URL, check cache
         $cache_id = md5($xml_location);
         $cache = new Cacheable($this->_Parent->_Parent->Database);
         $cachedData = $cache->check($cache_id);
         $creation = DateTimeObj::get('c');
         if (!$cachedData || time() - $cachedData['creation'] > 5 * 60) {
             if (Mutex::acquire($cache_id, 6, TMP)) {
                 $ch = new Gateway();
                 $ch->init();
                 $ch->setopt('URL', $xml_location);
                 $ch->setopt('TIMEOUT', 6);
                 $xml = $ch->exec();
                 $writeToCache = true;
                 Mutex::release($cache_id, TMP);
                 $xml = trim($xml);
                 if (empty($xml) && $cachedData) {
                     $xml = $cachedData['data'];
                 }
             } elseif ($cachedData) {
                 $xml = $cachedData['data'];
             }
         } else {
             $xml = $cachedData['data'];
         }
         $xml = simplexml_load_string($xml);
     } elseif (substr($xml_location, 0, 1) == '/') {
         // relative to DOCROOT
         $xml = simplexml_load_file(DOCROOT . $this->get('xml_location'));
     } else {
         // in extension's /xml folder
         $xml = simplexml_load_file(EXTENSIONS . '/xml_selectbox/xml/' . $this->get('xml_location'));
     }
     if (!$xml) {
         return;
     }
     $items = $xml->xpath($this->get('item_xpath'));
     $options = array();
     foreach ($items as $item) {
         $option = array();
         $text_xpath = $item->xpath($this->get('text_xpath'));
         $option['text'] = General::sanitize((string) $text_xpath[0]);
         if ($this->get('value_xpath') != '') {
             $value_xpath = $item->xpath($this->get('value_xpath'));
             $option['value'] = General::sanitize((string) $value_xpath[0]);
         }
         if ((string) $option['value'] == '') {
             $option['value'] = $option['text'];
         }
         $options[] = $option;
     }
     return $options;
 }
Esempio n. 10
0
 function __viewIndex()
 {
     $this->setPageType('table');
     $this->setTitle(__('%1$s &ndash; %2$s', array(__('Symphony'), __('Authors'))));
     if (Administration::instance()->Author->isDeveloper()) {
         $this->appendSubheading(__('Authors'), Widget::Anchor(__('Add an Author'), $this->_Parent->getCurrentPageURL() . 'new/', __('Add a new author'), 'create button'));
     } else {
         $this->appendSubheading(__('Authors'));
     }
     $authors = AuthorManager::fetch();
     $aTableHead = array(array(__('Name'), 'col'), array(__('Email Address'), 'col'), array(__('Last Seen'), 'col'));
     $aTableBody = array();
     if (!is_array($authors) || empty($authors)) {
         $aTableBody = array(Widget::TableRow(array(Widget::TableData(__('None found.'), 'inactive', NULL, count($aTableHead))), 'odd'));
     } else {
         $bOdd = true;
         foreach ($authors as $a) {
             if (intval($a->get('superuser')) == 1) {
                 $group = 'admin';
             } else {
                 $group = 'author';
             }
             ## Setup each cell
             if (Administration::instance()->Author->isDeveloper() || Administration::instance()->Author->get('id') == $a->get('id')) {
                 $td1 = Widget::TableData(Widget::Anchor($a->getFullName(), $this->_Parent->getCurrentPageURL() . 'edit/' . $a->get('id') . '/', $a->get('username'), $group));
             } else {
                 $td1 = Widget::TableData($a->getFullName(), 'inactive');
             }
             $td2 = Widget::TableData(Widget::Anchor($a->get('email'), 'mailto:' . $a->get('email'), 'Email this author'));
             if ($a->get('last_seen') != NULL) {
                 $td3 = Widget::TableData(DateTimeObj::get(__SYM_DATETIME_FORMAT__, strtotime($a->get('last_seen'))));
             } else {
                 $td3 = Widget::TableData('Unknown', 'inactive');
             }
             if (Administration::instance()->Author->isDeveloper()) {
                 if ($a->get('id') != Administration::instance()->Author->get('id')) {
                     $td3->appendChild(Widget::Input('items[' . $a->get('id') . ']', NULL, 'checkbox'));
                 }
             }
             ## Add a row to the body array, assigning each cell to the row
             $aTableBody[] = Widget::TableRow(array($td1, $td2, $td3), $bOdd ? 'odd' : NULL);
             $bOdd = !$bOdd;
         }
     }
     $table = Widget::Table(Widget::TableHead($aTableHead), NULL, Widget::TableBody($aTableBody));
     $this->Form->appendChild($table);
     if (Administration::instance()->Author->isDeveloper()) {
         $tableActions = new XMLElement('div');
         $tableActions->setAttribute('class', 'actions');
         $options = array(array(NULL, false, __('With Selected...')), array('delete', false, __('Delete')));
         $tableActions->appendChild(Widget::Select('with-selected', $options));
         $tableActions->appendChild(Widget::Input('action[apply]', __('Apply'), 'submit'));
         $this->Form->appendChild($tableActions);
     }
 }
Esempio n. 11
0
 public function write()
 {
     $section = $this->section->get('object');
     $entry = null;
     $entry_data = array();
     //	If it's an existing entry we want to load that entry object
     foreach ($this->writes as $write) {
         $field = $write->get('object');
         $field_data = $write->get('data');
         if ($field == SymQuery::SYSTEM_ID) {
             $existing = SymQuery::$em->fetch($field_data, $section->get('id'));
             if (is_array($existing) && !empty($existing)) {
                 $entry = current($existing);
                 break;
             }
         }
     }
     //	If $entry is null, then it's a new entry, so fill it with some default metadata
     if (is_null($entry)) {
         $entry = SymQuery::$em->create();
         $author = SymQuery::$symphony->Author;
         // Build default entry data:
         $entry->set('section_id', $section->get('id'));
         if (is_object($author)) {
             $entry->set('author_id', $author->get('id'));
         }
         $entry->set('creation_date', DateTimeObj::get('Y-m-d H:i:s'));
         $entry->set('creation_date_gmt', DateTimeObj::getGMT('Y-m-d H:i:s'));
     }
     foreach ($this->writes as $write) {
         $field = $write->get('object');
         $field_data = $write->get('data');
         if ($field instanceof Field) {
             $field_handle = $field->get('element_name');
             $entry_data[$field_handle] = $field_data;
         }
     }
     if (__ENTRY_FIELD_ERROR__ == $entry->checkPostData($entry_data, $errors, $entry->get('id') ? true : false)) {
         $validation_errors = array();
         foreach ($errors as $field_id => $message) {
             if (!in_array($field_id, SymQuery::$field_cache)) {
                 SymQuery::$field_cache[$field_id] = SymQuery::$fm->fetch($field_id, $section->get('id'));
             }
             $validation_errors[$field_id] = array('field' => SymQuery::$field_cache[$field_id], 'error' => $message);
         }
         $error = new SymWriteException('Unable to validate entry.');
         $error->setValidationErrors($validation_errors);
         throw $error;
     }
     if (__ENTRY_OK__ != $entry->setDataFromPost($entry_data, $error, false, $entry->get('id') ? true : false)) {
         throw new SymQueryException(sprintf('Unable to save entry: %s', $error));
     }
     $entry->commit();
     return $entry;
 }
Esempio n. 12
0
 public static function getMetaInfo($file, $type)
 {
     $meta = array();
     if (!file_exists($file) || !is_readable($file)) {
         return $meta;
     }
     $meta['creation'] = DateTimeObj::get('c', filemtime($file));
     if (General::in_iarray($type, fieldUpload::$imageMimeTypes) && ($array = @getimagesize($file))) {
         $meta['width'] = $array[0];
         $meta['height'] = $array[1];
     }
     return $meta;
 }
Esempio n. 13
0
 public function view()
 {
     $this->setPageType('table');
     $this->setTitle('Symphony &ndash; Cron');
     $this->appendSubheading('Cron Tasks', [Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL() . 'new/', __('Create a cron task'), 'create button', null, ['accesskey' => 'c'])]);
     Extension_Cron::init();
     $iterator = new Lib\CronTaskIterator(realpath(MANIFEST . '/cron'), Symphony::Database());
     $aTableHead = [['Name', 'col'], ['Description', 'col'], ['Enabled', 'col'], ['Last Executed', 'col'], ['Next Execution', 'col'], ['Last Output', 'col']];
     $aTableBody = [];
     if ($iterator->count() == 0) {
         $aTableBody = [Widget::TableRow([Widget::TableData(__('None found.'), 'inactive', null, count($aTableHead))], 'odd')];
     } else {
         foreach ($iterator as $ii => $task) {
             $td1 = Widget::TableData(Widget::Anchor($task->name, sprintf('%sedit/%s/', Administration::instance()->getCurrentPageURL(), $task->filename)));
             $td1->appendChild(Widget::Label(__('Select Task %s', [$task->filename]), null, 'accessible', null, array('for' => 'task-' . $ii)));
             $td1->appendChild(Widget::Input('items[' . $task->filename . ']', 'on', 'checkbox', array('id' => 'task-' . $ii)));
             $td2 = Widget::TableData(is_null($task->description) ? 'None' : $task->description);
             if (is_null($task->description)) {
                 $td2->setAttribute('class', 'inactive');
             }
             $td3 = Widget::TableData($task->enabledReal() == true ? 'Yes' : 'No');
             if ($task->enabled == false) {
                 $td3->setAttribute('class', 'inactive');
             }
             $td4 = Widget::TableData(!is_null($task->getLastExecutionTimestamp()) ? DateTimeObj::get(__SYM_DATETIME_FORMAT__, $task->getLastExecutionTimestamp()) : 'Unknown');
             if (is_null($task->getLastExecutionTimestamp())) {
                 $td4->setAttribute('class', 'inactive');
             }
             $td5 = Widget::TableData(!is_null($task->nextExecution()) ? self::__minutesToHumanReadable(ceil($task->nextExecution() * (1 / 60))) : 'Unknown');
             if (is_null($task->nextExecution()) || $task->enabledReal() == false) {
                 $td5->setAttribute('class', 'inactive');
             }
             if (is_null($task->getLog())) {
                 $td6 = Widget::TableData('None', 'inactive');
             } else {
                 $td6 = Widget::TableData(Widget::Anchor('view', sprintf('%slog/%s/', Administration::instance()->getCurrentPageURL(), $task->filename)));
             }
             $aTableBody[] = Widget::TableRow(array($td1, $td2, $td3, $td4, $td5, $td6));
         }
     }
     $table = Widget::Table(Widget::TableHead($aTableHead), null, Widget::TableBody($aTableBody), 'selectable', null, array('role' => 'directory', 'aria-labelledby' => 'symphony-subheading', 'data-interactive' => 'data-interactive'));
     $this->Form->appendChild($table);
     $tableActions = new XMLElement('div');
     $tableActions->setAttribute('class', 'actions');
     $options = [[null, false, __('With Selected...')], ['enable', false, __('Enable')], ['disable', false, __('Disable')], ['delete', false, __('Delete'), 'confirm', null, ['data-message' => __('Are you sure you want to delete the selected tasks?')]]];
     $tableActions->appendChild(Widget::Apply($options));
     $this->Form->appendChild($tableActions);
 }
Esempio n. 14
0
 /**
  * Overload the Symphony::login function to bypass some code that
  * forces use of the Administration class (which of course is not
  * available in Shell). Hopefully this is fixed in the core Symphony code
  *
  */
 public static function login($username, $password, $isHash = false)
 {
     $username = self::Database()->cleanValue($username);
     $password = self::Database()->cleanValue($password);
     if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0) {
         $author = \AuthorManager::fetch('id', 'ASC', 1, null, sprintf("\n                `username` = '%s'\n                ", $username));
         if (!empty($author) && \Cryptography::compare($password, current($author)->get('password'), $isHash)) {
             self::$Author = current($author);
             // Only migrate hashes if there is no update available as the update might change the tbl_authors table.
             if (\Cryptography::requiresMigration(self::$Author->get('password'))) {
                 throw new ShellException('User details require updating. Please login to the admin interface.');
             }
             self::$Cookie->set('username', $username);
             self::$Cookie->set('pass', self::$Author->get('password'));
             self::Database()->update(array('last_seen' => \DateTimeObj::get('Y-m-d H:i:s')), 'tbl_authors', sprintf(" `id` = %d", self::$Author->get('id')));
             return true;
         }
     }
     return false;
 }
 function grab(&$param_pool)
 {
     $result = NULL;
     $Forum = $this->_Parent->ExtensionManager->create('forum');
     $members = $this->_Parent->ExtensionManager->create('members');
     $members->initialiseCookie();
     if (!$members->isLoggedIn() || !isset($param_pool['ds-forum-discussions']) || empty($param_pool['ds-forum-discussions'])) {
         $result = $this->emptyXMLSet();
     } else {
         if (!$members->Member) {
             $members->initialiseMemberObject();
         }
         $member_id = $members->Member->get('id');
         $member_read_cutoff_date = Symphony::Database()->fetchVar('local', 0, sprintf("SELECT `local` FROM `tbl_entries_data_%d` WHERE `entry_id` = %d LIMIT 1", Discussion::getUnreadCutoffField(), $member_id));
         if (is_null($member_read_cutoff_date)) {
             $member_read_cutoff_date = strtotime(Symphony::Database()->fetchVar('creation_date', 0, "SELECT `creation_date` FROM `tbl_entries` WHERE `id` = {$member_id} LIMIT 1"));
         }
         $discussion_last_active_field = Symphony::Configuration()->get('discussion-last-active-field', 'forum');
         $pre_dated_discussions = Symphony::Database()->fetchCol('entry_id', sprintf("SELECT `entry_id` \n\t\t\t\t\t\tFROM `tbl_entries_data_%d` \n\t\t\t\t\t\tWHERE `entry_id` IN (" . @implode(',', $param_pool['ds-forum-discussions']) . ") \n\t\t\t\t\t\tAND `local` <= '%s'", $discussion_last_active_field, $member_read_cutoff_date));
         $read_discussions = @implode(',', array_diff($param_pool['ds-forum-discussions'], $pre_dated_discussions));
         if (empty($read_discussions)) {
             $read_discussions = 0;
         }
         $read = $this->_Parent->Database->fetch(sprintf("SELECT * FROM `tbl_forum_read_discussions` \n\t\t\t\t\t\tWHERE `member_id` = {$member_id} \n\t\t\t\t\t\tAND `discussion_id` IN (%s)", $read_discussions));
         if (empty($read) && empty($pre_dated_discussions)) {
             $result = $this->emptyXMLSet();
         } else {
             $result = new XMLElement($this->dsParamROOTELEMENT);
             foreach ($read as $r) {
                 $result->appendChild(new XMLElement('discussion', NULL, array('id' => $r['discussion_id'], 'comments' => $r['comments'], 'last-viewed' => DateTimeObj::get('c', $r['last_viewed']))));
                 if (isset($pre_dated_discussions[$r['discussion_id']])) {
                     unset($pre_dated_discussions[$r['discussion_id']]);
                 }
             }
             foreach ($pre_dated_discussions as $id) {
                 $result->appendChild(new XMLElement('discussion', NULL, array('id' => $id, 'comments' => '100000', 'last-viewed' => DateTimeObj::get('c', strtotime($member_registration_date)))));
             }
         }
     }
     return $result;
 }
Esempio n. 16
0
 public function grab(&$param_pool = NULL)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     $param_output = array();
     $filters = array();
     if (!empty($this->dsParamSECTIONS)) {
         $filters['item_type'] = $this->dsParamSECTIONS;
     } else {
         $filters['item_type'] = 'REGEXP "[[:digit:]]+"';
     }
     if (!empty($this->dsParamACTIONS)) {
         $filters['action_type'] = $this->dsParamACTIONS;
     }
     // Fetch the activity
     $activities = Tracker::fetchActivities($filters, $this->dsParamLIMIT, 0, $this->dsParamSORT, $this->dsParamORDER);
     // Build the XML
     foreach ($activities as $activity) {
         // Capture the section and entry ID for output params
         $param_output[$activity['item_type']][] = $activity['item_id'];
         // Break the fallback description into useful bits
         $activity['fallback_description'] = explode(':::', $activity['fallback_description']);
         // Build the <activity> element
         $item = new XMLElement('activity', NULL, array('type' => $activity['action_type'], 'entry-id' => $activity['item_id']));
         // Append Section info
         $item->appendChild(new XMLElement('section', $activity['fallback_description'][1], array('id' => $activity['item_type'])));
         // Append Author info
         $item->appendChild(new XMLElement('author', $activity['fallback_username'], array('id' => $activity['user_id'])));
         // Append Date info
         $item->appendChild(new XMLElement('date', DateTimeObj::get('Y-m-d', strtotime($activity['timestamp'] . ' GMT')), array('time' => DateTimeObj::get('H:i', strtotime($activity['timestamp'] . ' GMT')), 'weekday' => DateTimeObj::get('N', strtotime($activity['timestamp'] . ' GMT')))));
         $result->appendChild($item);
     }
     // Build output params
     foreach ($param_output as $section => $ids) {
         $param_pool['ds-' . $this->dsParamROOTELEMENT . '-' . $section] = implode(', ', $ids);
     }
     return $result;
 }
 public function generate()
 {
     if ($this->_useTemplate !== false) {
         $template = $this->viewDir . '/' . (empty($this->_useTemplate) ? $this->_getTemplate($this->_type, $this->_function) : $this->_useTemplate . '.xsl');
         if (file_exists($template)) {
             $current_path = explode(dirname($_SERVER['SCRIPT_NAME']), $_SERVER['REQUEST_URI'], 2);
             $current_path = '/' . ltrim(end($current_path), '/');
             $params = array('today' => DateTimeObj::get('Y-m-d'), 'current-time' => DateTimeObj::get('H:i'), 'this-year' => DateTimeObj::get('Y'), 'this-month' => DateTimeObj::get('m'), 'this-day' => DateTimeObj::get('d'), 'timezone' => DateTimeObj::get('P'), 'website-name' => Symphony::Configuration()->get('sitename', 'general'), 'root' => URL, 'symphony-url' => SYMPHONY_URL, 'workspace' => URL . '/workspace', 'current-page' => strtolower($this->_type) . ucfirst($this->_function), 'current-path' => $current_path, 'current-url' => URL . $current_path, 'upload-limit' => min($upload_size_php, $upload_size_sym), 'symphony-version' => Symphony::Configuration()->get('version', 'symphony'));
             $html = $this->_XSLTProc->process($this->_XML->generate(), file_get_contents($template), $params);
             if ($this->_XSLTProc->isErrors()) {
                 $errstr = NULL;
                 while (list($key, $val) = $this->_XSLTProc->getError()) {
                     $errstr .= 'Line: ' . $val['line'] . ' - ' . $val['message'] . self::CRLF;
                 }
                 throw new SymphonyErrorPage(trim($errstr), NULL, 'xslt-error', array('proc' => clone $this->_XSLTProc));
             }
         } else {
             Administration::instance()->errorPageNotFound();
         }
         $this->Form = NULL;
         $this->Contents->setValue($html);
     }
     return parent::generate();
 }
 public function login($username, $password, $isHash = false)
 {
     if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0) {
         if (!$isHash) {
             $password = md5($password);
         }
         $result = Symphony::Database()->query("\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tu.id\n\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\ttbl_users AS u\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tu.username = '******'\n\t\t\t\t\t\t\tAND u.password = '******'\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t", array($username, $password));
         if ($result->valid()) {
             $this->_user_id = $result->current()->id;
             $this->User = User::load($this->_user_id);
             $this->Cookie->set('username', $username);
             $this->Cookie->set('pass', $password);
             Symphony::Database()->update('tbl_users', array('last_seen' => DateTimeObj::get('Y-m-d H:i:s')), array($this->_user_id), "`id` = '%d'");
             $this->reloadLangFromUserPreference();
             return true;
         }
     }
     return false;
 }
 public function execute(array &$param_pool = null)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     $this->dsParamURL = $this->parseParamURL($this->dsParamURL);
     if (isset($this->dsParamXPATH)) {
         $this->dsParamXPATH = $this->__processParametersInString($this->dsParamXPATH, $this->_env);
     }
     $stylesheet = new XMLElement('xsl:stylesheet');
     $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform'));
     $output = new XMLElement('xsl:output');
     $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes'));
     $stylesheet->appendChild($output);
     $template = new XMLElement('xsl:template');
     $template->setAttribute('match', '/');
     $instruction = new XMLElement('xsl:copy-of');
     // Namespaces
     if (isset($this->dsParamFILTERS) && is_array($this->dsParamFILTERS)) {
         foreach ($this->dsParamFILTERS as $name => $uri) {
             $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri);
         }
     }
     // XPath
     $instruction->setAttribute('select', $this->dsParamXPATH);
     $template->appendChild($instruction);
     $stylesheet->appendChild($template);
     $stylesheet->setIncludeHeader(true);
     $xsl = $stylesheet->generate(true);
     $cache_id = md5($this->dsParamURL . serialize($this->dsParamFILTERS) . $this->dsParamXPATH);
     $cache = new Cacheable(Symphony::Database());
     $cachedData = $cache->read($cache_id);
     $writeToCache = false;
     $valid = true;
     $creation = DateTimeObj::get('c');
     $timeout = isset($this->dsParamTIMEOUT) ? (int) max(1, $this->dsParamTIMEOUT) : 6;
     // Execute if the cache doesn't exist, or if it is old.
     if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) {
         if (Mutex::acquire($cache_id, $timeout, TMP)) {
             $ch = new Gateway();
             $ch->init($this->dsParamURL);
             $ch->setopt('TIMEOUT', $timeout);
             $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*'));
             $data = $ch->exec();
             $info = $ch->getInfoLast();
             Mutex::release($cache_id, TMP);
             $data = trim($data);
             $writeToCache = true;
             // Handle any response that is not a 200, or the content type does not include XML, plain or text
             if ((int) $info['http_code'] !== 200 || !preg_match('/(xml|plain|text)/i', $info['content_type'])) {
                 $writeToCache = false;
                 $result->setAttribute('valid', 'false');
                 // 28 is CURLE_OPERATION_TIMEOUTED
                 if ($info['curl_error'] == 28) {
                     $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                 } else {
                     $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                 }
                 return $result;
                 // Handle where there is `$data`
             } elseif (strlen($data) > 0) {
                 // If the XML doesn't validate..
                 if (!General::validateXML($data, $errors, false, new XsltProcess())) {
                     $writeToCache = false;
                 }
                 // If the `$data` is invalid, return a result explaining why
                 if ($writeToCache === false) {
                     $element = new XMLElement('errors');
                     $result->setAttribute('valid', 'false');
                     $result->appendChild(new XMLElement('error', __('Data returned is invalid.')));
                     foreach ($errors as $e) {
                         if (strlen(trim($e['message'])) == 0) {
                             continue;
                         }
                         $element->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                     }
                     $result->appendChild($element);
                     return $result;
                 }
                 // If `$data` is empty, set the `force_empty_result` to true.
             } elseif (strlen($data) == 0) {
                 $this->_force_empty_result = true;
             }
             // Failed to acquire a lock
         } else {
             $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock, check that %s exists and is writable.', array('<code>Mutex</code>', '<code>' . TMP . '</code>'))));
         }
         // The cache is good, use it!
     } else {
         $data = trim($cachedData['data']);
         $creation = DateTimeObj::get('c', $cachedData['creation']);
     }
     // If `$writeToCache` is set to false, invalidate the old cache if it existed.
     if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) {
         $data = trim($cachedData['data']);
         $valid = false;
         $creation = DateTimeObj::get('c', $cachedData['creation']);
         if (empty($data)) {
             $this->_force_empty_result = true;
         }
     }
     // If `force_empty_result` is false and `$result` is an instance of
     // XMLElement, build the `$result`.
     if (!$this->_force_empty_result && is_object($result)) {
         $proc = new XsltProcess();
         $ret = $proc->process($data, $xsl);
         if ($proc->isErrors()) {
             $result->setAttribute('valid', 'false');
             $error = new XMLElement('error', __('Transformed XML is invalid.'));
             $result->appendChild($error);
             $element = new XMLElement('errors');
             foreach ($proc->getError() as $e) {
                 if (strlen(trim($e['message'])) == 0) {
                     continue;
                 }
                 $element->appendChild(new XMLElement('item', General::sanitize($e['message'])));
             }
             $result->appendChild($element);
         } elseif (strlen(trim($ret)) == 0) {
             $this->_force_empty_result = true;
         } else {
             if ($writeToCache) {
                 $cache->write($cache_id, $data, $this->dsParamCACHE);
             }
             $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret));
             $result->setAttribute('status', $valid === true ? 'fresh' : 'stale');
             $result->setAttribute('creation', $creation);
         }
     }
     return $result;
 }
Esempio n. 20
0
 public function getParameterOutputValue(StdClass $data, Entry $entry = NULL)
 {
     if (is_null($d->value)) {
         return;
     }
     $timestamp = DateTimeObj::toGMT($data->value);
     return DateTimeObj::get('Y-m-d H:i:s', $timestamp);
 }
Esempio n. 21
0
 /**
  * This function determines whether an there is a currently logged in
  * Author for Symphony by using the `$Cookie`'s username
  * and password. If an Author is found, they will be logged in, otherwise
  * the `$Cookie` will be destroyed.
  *
  * @see core.Cookie#expire()
  */
 public function isLoggedIn()
 {
     // Ensures that we're in the real world.. Also reduces three queries from database
     // We must return true otherwise exceptions are not shown
     if (is_null(self::$_instance)) {
         return true;
     }
     if ($this->Author) {
         return true;
     } else {
         $username = self::Database()->cleanValue($this->Cookie->get('username'));
         $password = self::Database()->cleanValue($this->Cookie->get('pass'));
         if (strlen(trim($username)) > 0 && strlen(trim($password)) > 0) {
             $author = AuthorManager::fetch('id', 'ASC', 1, null, sprintf("\n\t\t\t\t\t\t\t`username` = '%s'\n\t\t\t\t\t\t", $username));
             if (!empty($author) && Cryptography::compare($password, current($author)->get('password'), true)) {
                 $this->Author = current($author);
                 self::Database()->update(array('last_seen' => DateTimeObj::get('Y-m-d H:i:s')), 'tbl_authors', sprintf(" `id` = %d", $this->Author->get('id')));
                 // Only set custom author language in the backend
                 if (class_exists('Administration')) {
                     Lang::set($this->Author->get('language'));
                 }
                 return true;
             }
         }
         $this->Cookie->expire();
         return false;
     }
 }
 public function sendBatch($pauth)
 {
     if ($this->getPAuth() != $pauth) {
         $this->setStatus('error');
         throw new EmailNewsletterException('Incorrect Process Auth used. This usually means there is more than one process running. Aborting.');
     }
     $this->_completed = explode(', ', $this->getCompletedRecipientGroups());
     $recipients = $this->_getRecipients($this->limit);
     if (count($recipients) > 0) {
         try {
             $template = $this->getTemplate();
             $sender = $this->getSender();
             $about = $sender->about();
             $additional_headers = $sender->additional_headers;
             if (is_array($about['smtp'])) {
                 $email = Email::create('smtp');
                 $email->setSenderName($about['smtp']['from_name']);
                 $email->setSenderEmailAddress($about['smtp']['from_address']);
                 $email->setHost($about['smtp']['host']);
                 $email->setPort($about['smtp']['port']);
                 $email->setSecure($about['smtp']['secure']);
                 if ($about['smtp']['auth'] == 1) {
                     $email->setAuth(true);
                     $email->setUser($about['smtp']['username']);
                     $email->setPass($about['smtp']['password']);
                 }
             } elseif (is_array($about['amazon_ses'])) {
                 $email = Email::create('amazon_ses');
                 $email->setSenderName($about['amazon_ses']['from_name']);
                 $email->setSenderEmailAddress($about['amazon_ses']['from_address']);
                 $email->setAwsKey($about['amazon_ses']['aws_key']);
                 $email->setAwsSecretKey($about['amazon_ses']['aws_secret_key']);
                 $email->setFallback($about['amazon_ses']['fallback']);
                 $email->setReturnPath($about['amazon_ses']['return_path']);
             } elseif (is_array($about['sendmail'])) {
                 $email = Email::create('sendmail');
                 $email->setSenderName($about['sendmail']['from_name']);
                 $email->setSenderEmailAddress($about['sendmail']['from_address']);
             } else {
                 throw new EmailNewsletterException('Currently only sendmail and SMTP are supported. This will be fixed when the API supports it.');
             }
         } catch (Exception $e) {
             file_put_contents(DOCROOT . '/manifest/newsletter-log.txt', '[' . DateTimeObj::get('Y/m/d H:i:s') . '] newsletter-id: ' . $this->getId() . ' - ' . $e->getMessage() . "\r\n", FILE_APPEND);
             return false;
         }
         $email->openConnection();
         foreach ($recipients as $recipient) {
             try {
                 /**
                  * @delegate PreEmailGenerate
                  */
                 Symphony::ExtensionManager()->notifyMembers('PreEmailGenerate', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => &$recipient));
                 $email->setRecipients(array($recipient['name'] => $recipient['email']));
                 $template->recipients = '"' . $recipient['name'] . '" <' . $recipient['email'] . '>';
                 $template->addParams(array('etm-recipient' => $recipient['email']));
                 $email->setReplyToName($about['reply-to-name']);
                 $template->reply_to_name = $about['reply-to-name'];
                 $template->addParams(array('etm-reply-to-name' => $about['reply-to-name']));
                 $email->setReplyToEmailAddress($about['reply-to-email']);
                 $template->reply_to_email_address = $about['reply-to-email'];
                 $template->addParams(array('etm-reply-to-email-address' => $about['reply-to-email']));
                 if (!empty($additional_headers)) {
                     foreach ($additional_headers as $name => $body) {
                         $email->appendHeaderField($name, $body);
                     }
                 }
                 $template->addParams(array('enm-newsletter-id' => $this->getId()));
                 // add root and workspace parameters
                 $pseudo_root = $this->getPseudoRoot();
                 $template->addParams(array('root' => !empty($pseudo_root) ? $pseudo_root : NULL, 'workspace' => !empty($pseudo_root) ? $pseudo_root . '/workspace' : NULL));
                 $xml = $template->processDatasources();
                 $template->setXML($xml->generate());
                 $content = $template->render();
                 if (empty($content)) {
                     throw new EmailNewsletterException("ETM template could not be rendered");
                 }
                 if (!empty($content['subject'])) {
                     $email->subject = $content['subject'];
                 } else {
                     throw new EmailNewsletterException("Can not send emails without a subject");
                 }
                 if (isset($content['plain'])) {
                     $email->text_plain = $content['plain'];
                 }
                 if (isset($content['html'])) {
                     $email->text_html = $content['html'];
                 }
                 /**
                  * @delegate PreEmailSend
                  */
                 Symphony::ExtensionManager()->notifyMembers('PreEmailSend', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => $recipient));
                 $email->send();
                 /**
                  * @delegate PostEmailSend
                  */
                 Symphony::ExtensionManager()->notifyMembers('PostEmailSend', '/extension/email_newsletter_manager/', array('newsletter' => &$this, 'email' => &$email, 'template' => &$template, 'recipient' => $recipient));
                 $this->_markRecipient($recipient['email'], 'sent');
             } catch (Exception $e) {
                 file_put_contents(DOCROOT . '/manifest/newsletter-log.txt', '[' . DateTimeObj::get('Y/m/d H:i:s') . '] newsletter-id: ' . $this->getId() . ' - ' . $e->getMessage() . "\r\n", FILE_APPEND);
                 $this->_markRecipient($recipient['email'], 'failed');
                 continue;
             }
         }
         $email->closeConnection();
     }
     //To prevent timing problems, the completed recipient groups should only be marked as complete when the emails are actually sent.
     Symphony::Database()->update(array('completed_recipients' => implode(', ', $this->_completed)), 'tbl_email_newsletters', 'id = ' . $this->getId());
     if (count($recipients) == 0) {
         Symphony::Database()->query('DROP TABLE IF EXISTS `tbl_tmp_email_newsletters_sent_' . $this->getId() . '`');
         $this->setStatus('completed');
         Symphony::Database()->update(array('completed_on' => date('Y-m-d H:i:s', time())), 'tbl_email_newsletters', 'id = ' . $this->getId());
         return 'completed';
     }
     return 'sent';
 }
 function __viewInfo()
 {
     $this->setPageType('form');
     $DSManager = new DatasourceManager($this->_Parent);
     $datasource = $DSManager->create($this->_context[1], NULL, false);
     $about = $datasource->about();
     $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', array(__('Symphony'), __('Data Source'), $about['name'])));
     $this->appendSubheading($about['name']);
     $this->Form->setAttribute('id', 'controller');
     $link = $about['author']['name'];
     if (isset($about['author']['website'])) {
         $link = Widget::Anchor($about['author']['name'], General::validateURL($about['author']['website']));
     } elseif (isset($about['author']['email'])) {
         $link = Widget::Anchor($about['author']['name'], 'mailto:' . $about['author']['email']);
     }
     foreach ($about as $key => $value) {
         $fieldset = NULL;
         switch ($key) {
             case 'author':
                 $fieldset = new XMLElement('fieldset');
                 $fieldset->appendChild(new XMLElement('legend', 'Author'));
                 $fieldset->appendChild(new XMLElement('p', $link->generate(false)));
                 break;
             case 'version':
                 $fieldset = new XMLElement('fieldset');
                 $fieldset->appendChild(new XMLElement('legend', 'Version'));
                 $fieldset->appendChild(new XMLElement('p', $value . ', released on ' . DateTimeObj::get(__SYM_DATE_FORMAT__, strtotime($about['release-date']))));
                 break;
             case 'description':
                 $fieldset = new XMLElement('fieldset');
                 $fieldset->appendChild(new XMLElement('legend', 'Description'));
                 $fieldset->appendChild(is_object($about['description']) ? $about['description'] : new XMLElement('p', $about['description']));
             case 'example':
                 if (is_callable(array($datasource, 'example'))) {
                     $fieldset = new XMLElement('fieldset');
                     $fieldset->appendChild(new XMLElement('legend', 'Example XML'));
                     $example = $datasource->example();
                     if (is_object($example)) {
                         $fieldset->appendChild($example);
                     } else {
                         $p = new XMLElement('p');
                         $p->appendChild(new XMLElement('pre', '<code>' . str_replace('<', '&lt;', $example) . '</code>'));
                         $fieldset->appendChild($p);
                     }
                 }
                 break;
         }
         if ($fieldset) {
             $fieldset->setAttribute('class', 'settings');
             $this->Form->appendChild($fieldset);
         }
     }
     /*
     $dl->appendChild(new XMLElement('dt', __('URL Parameters')));
     if(!is_array($about['recognised-url-param']) || empty($about['recognised-url-param'])){
     	$dl->appendChild(new XMLElement('dd', '<code>'.__('None').'</code>'));
     }			
     else{
     	$dd = new XMLElement('dd');
     	$ul = new XMLElement('ul');
     	
     	foreach($about['recognised-url-param'] as $f) $ul->appendChild(new XMLElement('li', '<code>' . $f . '</code>'));
     
     	$dd->appendChild($ul);
     	$dl->appendChild($dd);
     }			
     $fieldset->appendChild($dl);
     */
 }
Esempio n. 24
0
    private function __buildPage()
    {
        $start = precision_timer();
        if (!($page = $this->resolvePage())) {
            $page = $this->_Parent->Database->fetchRow(0, "\n\t\t\t\t\t\t\t\tSELECT `tbl_pages`.* \n\t\t\t\t\t\t\t\tFROM `tbl_pages`, `tbl_pages_types` \n\t\t\t\t\t\t\t\tWHERE `tbl_pages_types`.page_id = `tbl_pages`.id \n\t\t\t\t\t\t\t\tAND tbl_pages_types.`type` = '404' \n\t\t\t\t\t\t\t\tLIMIT 1");
            if (empty($page)) {
                $this->_Parent->customError(E_USER_ERROR, __('Page Not Found'), __('The page you requested does not exist.'), false, true, 'error', array('header' => 'HTTP/1.0 404 Not Found'));
            }
            $page['filelocation'] = $this->resolvePageFileLocation($page['path'], $page['handle']);
            $page['type'] = $this->__fetchPageTypes($page['id']);
        }
        ####
        # Delegate: FrontendPageResolved
        # Description: Just after having resolved the page, but prior to any commencement of output creation
        # Global: Yes
        $this->ExtensionManager->notifyMembers('FrontendPageResolved', '/frontend/', array('page' => &$this, 'page_data' => &$page));
        $this->_pageData = $page;
        $root_page = @array_shift(explode('/', $page['path']));
        $current_path = explode(dirname($_SERVER['SCRIPT_NAME']), $_SERVER['REQUEST_URI'], 2);
        $current_path = '/' . ltrim(end($current_path), '/');
        // Get max upload size from php and symphony config then choose the smallest
        $upload_size_php = ini_size_to_bytes(ini_get('upload_max_filesize'));
        $upload_size_sym = Frontend::instance()->Configuration->get('max_upload_size', 'admin');
        $this->_param = array('today' => DateTimeObj::get('Y-m-d'), 'current-time' => DateTimeObj::get('H:i'), 'this-year' => DateTimeObj::get('Y'), 'this-month' => DateTimeObj::get('m'), 'this-day' => DateTimeObj::get('d'), 'timezone' => DateTimeObj::get('P'), 'website-name' => $this->_Parent->Configuration->get('sitename', 'general'), 'page-title' => $page['title'], 'root' => URL, 'workspace' => URL . '/workspace', 'root-page' => $root_page ? $root_page : $page['handle'], 'current-page' => $page['handle'], 'current-page-id' => $page['id'], 'current-path' => $current_path, 'parent-path' => '/' . $page['path'], 'current-url' => URL . $current_path, 'upload-limit' => min($upload_size_php, $upload_size_sym), 'symphony-build' => $this->_Parent->Configuration->get('build', 'symphony'));
        if (is_array($this->_env['url'])) {
            foreach ($this->_env['url'] as $key => $val) {
                $this->_param[$key] = $val;
            }
        }
        if (is_array($_GET) && !empty($_GET)) {
            foreach ($_GET as $key => $val) {
                if (!in_array($key, array('symphony-page', 'debug', 'profile'))) {
                    $this->_param['url-' . $key] = $val;
                }
            }
        }
        if (is_array($_COOKIE[__SYM_COOKIE_PREFIX_]) && !empty($_COOKIE[__SYM_COOKIE_PREFIX_])) {
            foreach ($_COOKIE[__SYM_COOKIE_PREFIX_] as $key => $val) {
                $this->_param['cookie-' . $key] = $val;
            }
        }
        // Flatten parameters:
        General::flattenArray($this->_param);
        ####
        # Delegate: FrontendParamsResolve
        # Description: Just after having resolved the page params, but prior to any commencement of output creation
        # Global: Yes
        $this->ExtensionManager->notifyMembers('FrontendParamsResolve', '/frontend/', array('params' => &$this->_param));
        $xml_build_start = precision_timer();
        $xml = new XMLElement('data');
        $xml->setIncludeHeader(true);
        $events = new XMLElement('events');
        $this->__processEvents($page['events'], $events);
        $xml->appendChild($events);
        $this->_events_xml = clone $events;
        $this->__processDatasources($page['data_sources'], $xml);
        $this->_Parent->Profiler->seed($xml_build_start);
        $this->_Parent->Profiler->sample('XML Built', PROFILE_LAP);
        if (is_array($this->_env['pool']) && !empty($this->_env['pool'])) {
            foreach ($this->_env['pool'] as $handle => $p) {
                if (!is_array($p)) {
                    $p = array($p);
                }
                foreach ($p as $key => $value) {
                    if (is_array($value) && !empty($value)) {
                        foreach ($value as $kk => $vv) {
                            $this->_param[$handle] .= @implode(', ', $vv) . ',';
                        }
                    } else {
                        $this->_param[$handle] = @implode(', ', $p);
                    }
                }
                $this->_param[$handle] = trim($this->_param[$handle], ',');
            }
        }
        ####
        # Delegate: FrontendParamsPostResolve
        # Description: Access to the resolved param pool, including additional parameters provided by Data Source outputs
        # Global: Yes
        $this->ExtensionManager->notifyMembers('FrontendParamsPostResolve', '/frontend/', array('params' => $this->_param));
        ## TODO: Add delegate for adding/removing items in the params
        $xsl = '<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:import href="./workspace/pages/' . basename($page['filelocation']) . '"/>
</xsl:stylesheet>';
        $this->_Parent->Profiler->seed();
        $this->setXML($xml->generate(true, 0));
        $this->_Parent->Profiler->sample('XML Generation', PROFILE_LAP);
        $this->setXSL($xsl, false);
        $this->setRuntimeParam($this->_param);
        $this->_Parent->Profiler->seed($start);
        $this->_Parent->Profiler->sample('Page Built', PROFILE_LAP);
    }
Esempio n. 25
0
 /**
  * Attempts to log an Author in given a username and password.
  * If the password is not hashed, it will be hashed using the sha1
  * algorithm. The username and password will be sanitized before
  * being used to query the Database. If an Author is found, they
  * will be logged in and the sanitized username and password (also hashed)
  * will be saved as values in the `$Cookie`.
  *
  * @see toolkit.Cryptography#hash()
  * @throws DatabaseException
  * @param string $username
  *  The Author's username. This will be sanitized before use.
  * @param string $password
  *  The Author's password. This will be sanitized and then hashed before use
  * @param boolean $isHash
  *  If the password provided is already hashed, setting this parameter to
  *  true will stop it becoming rehashed. By default it is false.
  * @return boolean
  *  True if the Author was logged in, false otherwise
  */
 public static function login($username, $password, $isHash = false)
 {
     $username = trim(self::Database()->cleanValue($username));
     $password = trim(self::Database()->cleanValue($password));
     if (strlen($username) > 0 && strlen($password) > 0) {
         $author = AuthorManager::fetch('id', 'ASC', 1, null, sprintf("`username` = '%s'", $username));
         if (!empty($author) && Cryptography::compare($password, current($author)->get('password'), $isHash)) {
             self::$Author = current($author);
             // Only migrate hashes if there is no update available as the update might change the tbl_authors table.
             if (self::isUpgradeAvailable() === false && Cryptography::requiresMigration(self::$Author->get('password'))) {
                 self::$Author->set('password', Cryptography::hash($password));
                 self::Database()->update(array('password' => self::$Author->get('password')), 'tbl_authors', sprintf(" `id` = %d", self::$Author->get('id')));
             }
             self::$Cookie->set('username', $username);
             self::$Cookie->set('pass', self::$Author->get('password'));
             self::Database()->update(array('last_seen' => DateTimeObj::get('Y-m-d H:i:s')), 'tbl_authors', sprintf(" `id` = %d", self::$Author->get('id')));
             // Only set custom author language in the backend
             if (class_exists('Administration', false)) {
                 Lang::set(self::$Author->get('language'));
             }
             return true;
         }
     }
     return false;
 }
Esempio n. 26
0
 /**
  * Writes a end of file block at the end of the log file with a datetime
  * stamp of when the log file was closed.
  */
 public function close()
 {
     $this->writeToLog('============================================', true);
     $this->writeToLog('Log Closed: ' . DateTimeObj::get('c'), true);
     $this->writeToLog("============================================" . PHP_EOL . PHP_EOL, true);
 }
 /**
  * Given an array of Entry data from `tbl_entries` and a section ID, return an
  * array of Entry objects. For performance reasons, it's possible to pass an array
  * of field handles via `$element_names`, so that only a subset of the section schema
  * will be queried. This function currently only supports Entry from one section at a
  * time.
  *
  * @param array $rows
  *  An array of Entry data from `tbl_entries` including the Entry ID, Entry section,
  *  the ID of the Author who created the Entry, and a Unix timestamp of creation
  * @param integer $section_id
  *  The section ID of the entries in the `$rows`
  * @param array $element_names
  *  Choose whether to get data from a subset of fields or all fields in a section,
  *  by providing an array of field names. Defaults to null, which will load data
  *  from all fields in a section.
  * @return array
  */
 public function __buildEntries(array $rows, $section_id, $element_names = null)
 {
     $entries = array();
     if (empty($rows)) {
         return $entries;
     }
     // choose whether to get data from a subset of fields or all fields in a section
     if (!is_null($element_names) && is_array($element_names)) {
         // allow for pseudo-fields containing colons (e.g. Textarea formatted/unformatted)
         foreach ($element_names as $index => $name) {
             $parts = explode(':', $name, 2);
             if (count($parts) == 1) {
                 continue;
             }
             unset($element_names[$index]);
             $element_names[] = trim($parts[0]);
         }
         $schema_sql = sprintf("SELECT `id` FROM `tbl_fields` WHERE `parent_section` = %d AND `element_name` IN ('%s')", $section_id, implode("', '", array_unique($element_names)));
     } else {
         $schema_sql = sprintf("SELECT `id` FROM `tbl_fields` WHERE `parent_section` = %d", $section_id);
     }
     $schema = Symphony::Database()->fetch($schema_sql);
     $raw = array();
     $rows_string = '';
     // Append meta data:
     foreach ($rows as $entry) {
         $raw[$entry['id']]['meta'] = $entry;
         $rows_string .= $entry['id'] . ',';
     }
     $rows_string = trim($rows_string, ',');
     // Append field data:
     foreach ($schema as $f) {
         $field_id = $f['id'];
         try {
             $row = Symphony::Database()->fetch("SELECT * FROM `tbl_entries_data_{$field_id}` WHERE `entry_id` IN ({$rows_string}) ORDER BY `id` ASC");
         } catch (Exception $e) {
             // No data due to error
             continue;
         }
         if (!is_array($row) || empty($row)) {
             continue;
         }
         foreach ($row as $r) {
             $entry_id = $r['entry_id'];
             unset($r['id']);
             unset($r['entry_id']);
             if (!isset($raw[$entry_id]['fields'][$field_id])) {
                 $raw[$entry_id]['fields'][$field_id] = $r;
             } else {
                 foreach (array_keys($r) as $key) {
                     if (isset($raw[$entry_id]['fields'][$field_id][$key]) && !is_array($raw[$entry_id]['fields'][$field_id][$key])) {
                         $raw[$entry_id]['fields'][$field_id][$key] = array($raw[$entry_id]['fields'][$field_id][$key], $r[$key]);
                     } else {
                         if (!isset($raw[$entry_id]['fields'][$field_id][$key])) {
                             $raw[$entry_id]['fields'][$field_id] = array($r[$key]);
                         } else {
                             $raw[$entry_id]['fields'][$field_id][$key][] = $r[$key];
                         }
                     }
                 }
             }
         }
     }
     // Loop over the array of entry data and convert it to an array of Entry objects
     foreach ($raw as $entry) {
         $obj = $this->create();
         $obj->creationDate = DateTimeObj::get('c', $entry['meta']['creation_date']);
         $obj->set('id', $entry['meta']['id']);
         $obj->set('author_id', $entry['meta']['author_id']);
         $obj->set('section_id', $entry['meta']['section_id']);
         if (isset($entry['fields']) && is_array($entry['fields'])) {
             foreach ($entry['fields'] as $field_id => $data) {
                 $obj->setData($field_id, $data);
             }
         }
         $entries[] = $obj;
     }
     return $entries;
 }
Esempio n. 28
0
 private static function __install()
 {
     $fields = $_POST['fields'];
     $start = time();
     Symphony::Log()->writeToLog(PHP_EOL . '============================================', true);
     Symphony::Log()->writeToLog('INSTALLATION PROCESS STARTED (' . DateTimeObj::get('c') . ')', true);
     Symphony::Log()->writeToLog('============================================', true);
     // MySQL: Establishing connection
     Symphony::Log()->pushToLog('MYSQL: Establishing Connection', E_NOTICE, true, true);
     try {
         Symphony::Database()->connect($fields['database']['host'], $fields['database']['user'], $fields['database']['password'], $fields['database']['port'], $fields['database']['db']);
     } catch (DatabaseException $e) {
         self::__abort('There was a problem while trying to establish a connection to the MySQL server. Please check your settings.', $start);
     }
     // MySQL: Setting prefix & character encoding
     Symphony::Database()->setPrefix($fields['database']['tbl_prefix']);
     Symphony::Database()->setCharacterEncoding();
     Symphony::Database()->setCharacterSet();
     // MySQL: Importing schema
     Symphony::Log()->pushToLog('MYSQL: Importing Table Schema', E_NOTICE, true, true);
     try {
         Symphony::Database()->import(file_get_contents(INSTALL . '/includes/install.sql'), true);
     } catch (DatabaseException $e) {
         self::__abort('There was an error while trying to import data to the database. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getDatabaseErrorMessage(), $start);
     }
     // MySQL: Creating default author
     Symphony::Log()->pushToLog('MYSQL: Creating Default Author', E_NOTICE, true, true);
     try {
         Symphony::Database()->insert(array('id' => 1, 'username' => Symphony::Database()->cleanValue($fields['user']['username']), 'password' => Cryptography::hash(Symphony::Database()->cleanValue($fields['user']['password'])), 'first_name' => Symphony::Database()->cleanValue($fields['user']['firstname']), 'last_name' => Symphony::Database()->cleanValue($fields['user']['lastname']), 'email' => Symphony::Database()->cleanValue($fields['user']['email']), 'last_seen' => NULL, 'user_type' => 'developer', 'primary' => 'yes', 'default_area' => NULL, 'auth_token_active' => 'no'), 'tbl_authors');
     } catch (DatabaseException $e) {
         self::__abort('There was an error while trying create the default author. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getDatabaseErrorMessage(), $start);
     }
     // Configuration: Populating array
     $conf = Symphony::Configuration()->get();
     foreach ($conf as $group => $settings) {
         foreach ($settings as $key => $value) {
             if (isset($fields[$group]) && isset($fields[$group][$key])) {
                 $conf[$group][$key] = $fields[$group][$key];
             }
         }
     }
     // Create manifest folder structure
     Symphony::Log()->pushToLog('WRITING: Creating ‘manifest’ folder (/manifest)', E_NOTICE, true, true);
     if (!General::realiseDirectory(DOCROOT . '/manifest', $conf['directory']['write_mode'])) {
         self::__abort('Could not create ‘manifest’ directory. Check permission on the root folder.', $start);
     }
     Symphony::Log()->pushToLog('WRITING: Creating ‘logs’ folder (/manifest/logs)', E_NOTICE, true, true);
     if (!General::realiseDirectory(DOCROOT . '/manifest/logs', $conf['directory']['write_mode'])) {
         self::__abort('Could not create ‘logs’ directory. Check permission on /manifest.', $start);
     }
     Symphony::Log()->pushToLog('WRITING: Creating ‘cache’ folder (/manifest/cache)', E_NOTICE, true, true);
     if (!General::realiseDirectory(DOCROOT . '/manifest/cache', $conf['directory']['write_mode'])) {
         self::__abort('Could not create ‘cache’ directory. Check permission on /manifest.', $start);
     }
     Symphony::Log()->pushToLog('WRITING: Creating ‘tmp’ folder (/manifest/tmp)', E_NOTICE, true, true);
     if (!General::realiseDirectory(DOCROOT . '/manifest/tmp', $conf['directory']['write_mode'])) {
         self::__abort('Could not create ‘tmp’ directory. Check permission on /manifest.', $start);
     }
     // Writing configuration file
     Symphony::Log()->pushToLog('WRITING: Configuration File', E_NOTICE, true, true);
     Symphony::Configuration()->setArray($conf);
     if (!Symphony::Configuration()->write(CONFIG, $conf['file']['write_mode'])) {
         self::__abort('Could not create config file ‘' . CONFIG . '’. Check permission on /manifest.', $start);
     }
     // Writing htaccess file
     Symphony::Log()->pushToLog('CONFIGURING: Frontend', E_NOTICE, true, true);
     $rewrite_base = ltrim(preg_replace('/\\/install$/i', NULL, dirname($_SERVER['PHP_SELF'])), '/');
     $htaccess = str_replace('<!-- REWRITE_BASE -->', $rewrite_base, file_get_contents(INSTALL . '/includes/htaccess.txt'));
     if (!General::writeFile(DOCROOT . "/.htaccess", $htaccess, $conf['file']['write_mode'], 'a')) {
         self::__abort('Could not write ‘.htaccess’ file. Check permission on ' . DOCROOT, $start);
     }
     // Writing /workspace folder
     if (!is_dir(DOCROOT . '/workspace')) {
         // Create workspace folder structure
         Symphony::Log()->pushToLog('WRITING: Creating ‘workspace’ folder (/workspace)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/workspace', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘workspace’ directory. Check permission on the root folder.', $start);
         }
         Symphony::Log()->pushToLog('WRITING: Creating ‘data-sources’ folder (/workspace/data-sources)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/workspace/data-sources', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘workspace/data-sources’ directory. Check permission on the root folder.', $start);
         }
         Symphony::Log()->pushToLog('WRITING: Creating ‘events’ folder (/workspace/events)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/workspace/events', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘workspace/events’ directory. Check permission on the root folder.', $start);
         }
         Symphony::Log()->pushToLog('WRITING: Creating ‘pages’ folder (/workspace/pages)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/workspace/pages', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘workspace/pages’ directory. Check permission on the root folder.', $start);
         }
         Symphony::Log()->pushToLog('WRITING: Creating ‘utilities’ folder (/workspace/utilities)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/workspace/utilities', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘workspace/utilities’ directory. Check permission on the root folder.', $start);
         }
     } else {
         Symphony::Log()->pushToLog('An existing ‘workspace’ directory was found at this location. Symphony will use this workspace.', E_NOTICE, true, true);
         // MySQL: Importing workspace data
         Symphony::Log()->pushToLog('MYSQL: Importing Workspace Data...', E_NOTICE, true, true);
         if (is_file(DOCROOT . '/workspace/install.sql')) {
             try {
                 Symphony::Database()->import(file_get_contents(DOCROOT . '/workspace/install.sql'), $fields['database']['use-server-encoding'] != 'yes' ? true : false, true);
             } catch (DatabaseException $e) {
                 self::__abort('There was an error while trying to import data to the database. MySQL returned: ' . $e->getDatabaseErrorCode() . ': ' . $e->getDatabaseErrorMessage(), $start);
             }
         }
     }
     // Write extensions folder
     if (!is_dir(DOCROOT . '/extensions')) {
         // Create extensions folder
         Symphony::Log()->pushToLog('WRITING: Creating ‘extensions’ folder (/extensions)', E_NOTICE, true, true);
         if (!General::realiseDirectory(DOCROOT . '/extensions', $conf['directory']['write_mode'])) {
             self::__abort('Could not create ‘extension’ directory. Check permission on the root folder.', $start);
         }
     }
     // Install existing extensions
     Symphony::Log()->pushToLog('CONFIGURING: Installing existing extensions', E_NOTICE, true, true);
     $disabled_extensions = array();
     foreach (new DirectoryIterator(EXTENSIONS) as $e) {
         if ($e->isDot() || $e->isFile() || !is_file($e->getRealPath() . '/extension.driver.php')) {
             continue;
         }
         $handle = $e->getBasename();
         try {
             if (!ExtensionManager::enable($handle)) {
                 $disabled_extensions[] = $handle;
                 Symphony::Log()->pushToLog('Could not enable the extension ‘' . $handle . '’.', E_NOTICE, true, true);
             }
         } catch (Exception $ex) {
             $disabled_extensions[] = $handle;
             Symphony::Log()->pushToLog('Could not enable the extension ‘' . $handle . '’. ' . $ex->getMessage(), E_NOTICE, true, true);
         }
     }
     // Loading default language
     if (isset($_REQUEST['lang']) && $_REQUEST['lang'] != 'en') {
         Symphony::Log()->pushToLog('CONFIGURING: Default language', E_NOTICE, true, true);
         $language = Lang::Languages();
         $language = $language[$_REQUEST['lang']];
         // Is the language extension enabled?
         if (in_array('lang_' . $language['handle'], ExtensionManager::listInstalledHandles())) {
             Symphony::Configuration()->set('lang', $_REQUEST['lang'], 'symphony');
             if (!Symphony::Configuration()->write(CONFIG, $conf['file']['write_mode'])) {
                 Symphony::Log()->pushToLog('Could not write default language ‘' . $language['name'] . '’ to config file.', E_NOTICE, true, true);
             }
         } else {
             Symphony::Log()->pushToLog('Could not enable the desired language ‘' . $language['name'] . '’.', E_NOTICE, true, true);
         }
     }
     // Installation completed. Woo-hoo!
     Symphony::Log()->writeToLog('============================================', true);
     Symphony::Log()->writeToLog(sprintf('INSTALLATION COMPLETED: Execution Time - %d sec (%s)', max(1, time() - $start), date('d.m.y H:i:s')), true);
     Symphony::Log()->writeToLog('============================================' . PHP_EOL . PHP_EOL . PHP_EOL, true);
     return $disabled_extensions;
 }
 public function execute(array &$param_pool = null)
 {
     $result = new XMLElement($this->dsParamROOTELEMENT);
     // When DS is called out of the Frontend context, this will enable
     // {$root} and {$workspace} parameters to be evaluated
     if (empty($this->_env)) {
         $this->_env['env']['pool'] = array('root' => URL, 'workspace' => WORKSPACE);
     }
     try {
         require_once TOOLKIT . '/class.gateway.php';
         require_once TOOLKIT . '/class.xsltprocess.php';
         require_once CORE . '/class.cacheable.php';
         $this->dsParamURL = $this->parseParamURL($this->dsParamURL);
         if (isset($this->dsParamXPATH)) {
             $this->dsParamXPATH = $this->__processParametersInString(stripslashes($this->dsParamXPATH), $this->_env);
         }
         // Builds a Default Stylesheet to transform the resulting XML with
         $stylesheet = new XMLElement('xsl:stylesheet');
         $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform'));
         $output = new XMLElement('xsl:output');
         $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes'));
         $stylesheet->appendChild($output);
         $template = new XMLElement('xsl:template');
         $template->setAttribute('match', '/');
         $instruction = new XMLElement('xsl:copy-of');
         // Namespaces
         if (isset($this->dsParamNAMESPACES) && is_array($this->dsParamNAMESPACES)) {
             foreach ($this->dsParamNAMESPACES as $name => $uri) {
                 $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri);
             }
         }
         // XPath
         $instruction->setAttribute('select', $this->dsParamXPATH);
         $template->appendChild($instruction);
         $stylesheet->appendChild($template);
         $stylesheet->setIncludeHeader(true);
         $xsl = $stylesheet->generate(true);
         // Check for an existing Cache for this Datasource
         $cache_id = self::buildCacheID($this);
         $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource');
         $cachedData = $cache->check($cache_id);
         $writeToCache = null;
         $isCacheValid = true;
         $creation = DateTimeObj::get('c');
         // Execute if the cache doesn't exist, or if it is old.
         if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) {
             if (Mutex::acquire($cache_id, $this->dsParamTIMEOUT, TMP)) {
                 $ch = new Gateway();
                 $ch->init($this->dsParamURL);
                 $ch->setopt('TIMEOUT', $this->dsParamTIMEOUT);
                 // Set the approtiate Accept: headers depending on the format of the URL.
                 if ($this->dsParamFORMAT == 'xml') {
                     $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*'));
                 } elseif ($this->dsParamFORMAT == 'json') {
                     $ch->setopt('HTTPHEADER', array('Accept: application/json, */*'));
                 } elseif ($this->dsParamFORMAT == 'csv') {
                     $ch->setopt('HTTPHEADER', array('Accept: text/csv, */*'));
                 }
                 self::prepareGateway($ch);
                 $data = $ch->exec();
                 $info = $ch->getInfoLast();
                 Mutex::release($cache_id, TMP);
                 $data = trim($data);
                 $writeToCache = true;
                 // Handle any response that is not a 200, or the content type does not include XML, JSON, plain or text
                 if ((int) $info['http_code'] != 200 || !preg_match('/(xml|json|csv|plain|text)/i', $info['content_type'])) {
                     $writeToCache = false;
                     $result->setAttribute('valid', 'false');
                     // 28 is CURLE_OPERATION_TIMEOUTED
                     if ($info['curl_error'] == 28) {
                         $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout)));
                     } else {
                         $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type'])));
                     }
                     return $result;
                 } else {
                     if (strlen($data) > 0) {
                         // Handle where there is `$data`
                         // If it's JSON, convert it to XML
                         if ($this->dsParamFORMAT == 'json') {
                             try {
                                 require_once TOOLKIT . '/class.json.php';
                                 $data = JSON::convertToXML($data);
                             } catch (Exception $ex) {
                                 $writeToCache = false;
                                 $errors = array(array('message' => $ex->getMessage()));
                             }
                         } elseif ($this->dsParamFORMAT == 'csv') {
                             try {
                                 require_once EXTENSIONS . '/remote_datasource/lib/class.csv.php';
                                 $data = CSV::convertToXML($data);
                             } catch (Exception $ex) {
                                 $writeToCache = false;
                                 $errors = array(array('message' => $ex->getMessage()));
                             }
                         } elseif ($this->dsParamFORMAT == 'txt') {
                             $txtElement = new XMLElement('entry');
                             $txtElement->setValue(General::wrapInCDATA($data));
                             $data = $txtElement->generate();
                             $txtElement = null;
                         } else {
                             if (!General::validateXML($data, $errors, false, new XsltProcess())) {
                                 // If the XML doesn't validate..
                                 $writeToCache = false;
                             }
                         }
                         // If the `$data` is invalid, return a result explaining why
                         if ($writeToCache === false) {
                             $error = new XMLElement('errors');
                             $error->setAttribute('valid', 'false');
                             $error->appendChild(new XMLElement('error', __('Data returned is invalid.')));
                             foreach ($errors as $e) {
                                 if (strlen(trim($e['message'])) == 0) {
                                     continue;
                                 }
                                 $error->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                             }
                             $result->appendChild($error);
                             return $result;
                         }
                     } elseif (strlen($data) == 0) {
                         // If `$data` is empty, set the `force_empty_result` to true.
                         $this->_force_empty_result = true;
                     }
                 }
             } else {
                 // Failed to acquire a lock
                 $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock.', array('<code>Mutex</code>'))));
             }
         } else {
             // The cache is good, use it!
             $data = trim($cachedData['data']);
             $creation = DateTimeObj::get('c', $cachedData['creation']);
         }
         // Visit the data
         $this->exposeData($data);
         // If `$writeToCache` is set to false, invalidate the old cache if it existed.
         if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) {
             $data = trim($cachedData['data']);
             $isCacheValid = false;
             $creation = DateTimeObj::get('c', $cachedData['creation']);
             if (empty($data)) {
                 $this->_force_empty_result = true;
             }
         }
         // If `force_empty_result` is false and `$result` is an instance of
         // XMLElement, build the `$result`.
         if (!$this->_force_empty_result && is_object($result)) {
             $proc = new XsltProcess();
             $ret = $proc->process($data, $xsl);
             if ($proc->isErrors()) {
                 $result->setAttribute('valid', 'false');
                 $error = new XMLElement('error', __('Transformed XML is invalid.'));
                 $result->appendChild($error);
                 $errors = new XMLElement('errors');
                 foreach ($proc->getError() as $e) {
                     if (strlen(trim($e['message'])) == 0) {
                         continue;
                     }
                     $errors->appendChild(new XMLElement('item', General::sanitize($e['message'])));
                 }
                 $result->appendChild($errors);
                 $result->appendChild(new XMLElement('raw-data', General::wrapInCDATA($data)));
             } elseif (strlen(trim($ret)) == 0) {
                 $this->_force_empty_result = true;
             } else {
                 if ($this->dsParamCACHE > 0 && $writeToCache) {
                     $cache->write($cache_id, $data, $this->dsParamCACHE);
                 }
                 $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret));
                 $result->setAttribute('status', $isCacheValid === true ? 'fresh' : 'stale');
                 $result->setAttribute('cache-id', $cache_id);
                 $result->setAttribute('creation', $creation);
             }
         }
     } catch (Exception $e) {
         $result->appendChild(new XMLElement('error', $e->getMessage()));
     }
     if ($this->_force_empty_result) {
         $result = $this->emptyXMLSet();
     }
     $result->setAttribute('url', General::sanitize($this->dsParamURL));
     return $result;
 }
 /**
  * Given an Entry object, this function will iterate over the `dsParamPARAMOUTPUT`
  * setting to see any of the Symphony system parameters need to be set.
  * The current system parameters supported are `system:id`, `system:author`
  * and `system:date`. If these parameters are found, the result is added
  * to the `$param_pool` array using the key, `ds-datasource-handle.parameter-name`
  * For the moment, this function also supports the pre Symphony 2.3 syntax,
  * `ds-datasource-handle` which did not support multiple parameters.
  *
  * @param Entry $entry
  *  The Entry object that contains the values that may need to be added
  *  into the parameter pool.
  */
 public function processSystemParameters(Entry $entry)
 {
     if (!isset($this->dsParamPARAMOUTPUT)) {
         return;
     }
     // Support the legacy parameter `ds-datasource-handle`
     $key = 'ds-' . $this->dsParamROOTELEMENT;
     $singleParam = count($this->dsParamPARAMOUTPUT) == 1;
     foreach ($this->dsParamPARAMOUTPUT as $param) {
         // The new style of paramater is `ds-datasource-handle.field-handle`
         $param_key = $key . '.' . str_replace(':', '-', $param);
         if ($param == 'system:id') {
             $this->_param_pool[$param_key][] = $entry->get('id');
             if ($singleParam) {
                 $this->_param_pool[$key][] = $entry->get('id');
             }
         } else {
             if ($param == 'system:author') {
                 $this->_param_pool[$param_key][] = $entry->get('author_id');
                 if ($singleParam) {
                     $this->_param_pool[$key][] = $entry->get('author_id');
                 }
             } else {
                 if ($param == 'system:date') {
                     $this->_param_pool[$param_key][] = DateTimeObj::get('c', $entry->creationDate);
                     if ($singleParam) {
                         $this->_param_pool[$key][] = DateTimeObj::get('c', $entry->creationDate);
                     }
                 }
             }
         }
     }
 }