/** * Given a CSV file, generate a resulting XML tree * * @param string $data * @return string */ public static function convertToXML($data) { $headers = array(); // Get CSV settings $settings = array('csv-delimiter' => ',', 'csv-enclosure' => '"', 'csv-escape' => '\\'); $settings = array_merge($settings, (array) Symphony::Configuration()->get('remote_datasource')); // DOMDocument $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = $doc->createElement('data'); $doc->appendChild($root); foreach (str_getcsv($data, PHP_EOL) as $i => $row) { if (empty($row)) { continue; } if ($i == 0) { foreach (str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']) as $i => $head) { if (class_exists('Lang')) { $head = Lang::createHandle($head); } $headers[] = $head; } } else { self::addRow($doc, $root, str_getcsv($row, $settings['csv-delimiter'], $settings['csv-enclosure'], $settings['csv-escape']), $headers); } } $output = $doc->saveXML($doc->documentElement); return trim($output); }
function displayPublishPanel(XMLElement &$wrapper, $data = null, $flagWithError = null, $fieldnamePrefix = null, $fieldnamePostfix = null, $entry_id = null) { $note = isset($data['value']) ? $data['value'] : $this->get('note'); $editable = $this->get('editable'); # Add <div> $div = new XMLElement("div", $note, array("id" => Lang::createHandle($this->get('label')), "class" => "publishnotes-note")); $wrapper->appendChild($div); # Editable if (isset($editable) && $editable) { $wrapper->setAttribute('class', $wrapper->getAttribute('class') . " editable"); $edit = new XMLElement("a", __("Edit note"), array("class" => "publishnotes-edit", "href" => "#edit")); $wrapper->appendChild($edit); # Add <textarea> $label = Widget::Label("Edit: " . $this->get('label'), NULL, Lang::createHandle($this->get('label'))); $textarea = Widget::Textarea('fields' . $fieldnamePrefix . '[' . $this->get('element_name') . ']' . $fieldnamePostfix, 8, 50, strlen($note) != 0 ? General::sanitize($note) : NULL); $label->appendChild($textarea); $control = new XMLElement("div", '<input type="submit" value="Change note"/> or <a href="#">cancel</a>', array("class" => "control")); $label->appendChild($control); if ($flagWithError != NULL) { $wrapper->appendChild(Widget::Error($label, $flagWithError)); } else { $wrapper->appendChild($label); } } }
function __actionIndex() { $checked = @array_keys($_POST['items']); if (is_array($checked) && !empty($checked)) { switch ($_POST['with-selected']) { case 'delete': $pages = $checked; ## TODO: Fix Me ### # Delegate: Delete # Description: Prior to deletion. Provided with an array of pages for deletion that can be modified. //$ExtensionManager->notifyMembers('Delete', getCurrentPage(), array('pages' => &$pages)); $pagesList = join(', ', array_map('intval', $pages)); // 1. Fetch page details $query = 'SELECT `id`, `sortorder`, `handle`, `path`, `title` FROM tbl_pages_templates WHERE `id` IN (' . $pagesList . ')'; $details = $this->_Parent->Database->fetch($query); $this->_Parent->Database->delete('tbl_pages_templates', " `id` IN('" . implode("','", $checked) . "')"); $this->_Parent->Database->delete('tbl_pages_types', " `page_id` IN('" . implode("','", $checked) . "')"); foreach ($details as $r) { $filename = Lang::createHandle($r['title']); // echo PAGES . "/templates/" . $filename . ".xsl"; $this->_Parent->Database->query("UPDATE tbl_pages_templates SET `sortorder` = (`sortorder` + 1) WHERE `sortorder` < '" . $r['sortorder'] . "'"); General::deleteFile(PAGES . "/templates/" . $filename . ".xsl"); } redirect($this->_Parent->getCurrentPageURL()); break; } } }
public function view() { $params = array('{$today}', '{$current-time}', '{$this-year}', '{$this-month}', '{$this-day}', '{$timezone}', '{$website-name}', '{$page-title}', '{$root}', '{$workspace}', '{$root-page}', '{$current-page}', '{$current-page-id}', '{$current-path}', '{$current-query-string}', '{$current-url}', '{$cookie-username}', '{$cookie-pass}', '{$page-types}', '{$upload-limit}'); // Get page parameters $pages = PageManager::fetch(true, array('params')); foreach ($pages as $key => $pageparams) { if (empty($pageparams['params'])) { continue; } $pageparams = explode('/', $pageparams['params']); foreach ($pageparams as $pageparam) { $param = '{$' . $pageparam . '}'; if (!in_array($param, $params)) { $params[] = $param; } } } // Get Data Sources output parameters $datasources = DatasourceManager::listAll(); foreach ($datasources as $datasource) { $current = DatasourceManager::create($datasource['handle'], array(), false); $prefix = '{$ds-' . Lang::createHandle($datasource['name']) . '.'; $suffix = '}'; // Get parameters if (is_array($current->dsParamPARAMOUTPUT)) { foreach ($current->dsParamPARAMOUTPUT as $id => $param) { $params[] = $prefix . $param . $suffix; } } } sort($params); $this->_Result = json_encode($params); }
/** * * Convert the $source string into a array. * This array should always respect the scheme defined by the * getDataFromSource method of the ServiceDriver * @param string $source * @return string */ public function createArray($source, $driver, $url, &$errorFlag) { // trying to load XML into DOM Document $doc = new DOMDocument(); $doc->preserveWhiteSpace = false; $doc->formatOutput = false; // ignore errors, but save it if was successful $errorFlag = !@$doc->loadXML($source); if (!$errorFlag) { $xml['xml'] = @$doc->saveXML(); if ($xml['xml'] === FALSE) { $errorFlag = true; } else { // add id to array $idTagName = $driver->getIdTagName(); if ($idTagName == null) { $xml['id'] = Lang::createHandle($url); } else { $xml['id'] = $doc->getElementsByTagName($idTagName)->item(0)->nodeValue; } $xml['title'] = $doc->getElementsByTagName($driver->getTitleTagName())->item(0)->nodeValue; $xml['thumb'] = $doc->getElementsByTagName($driver->getThumbnailTagName())->item(0)->nodeValue; } } if ($errorFlag) { // return error message $xml['error'] = __('Symphony could not parse XML from oEmbed remote service'); } return $xml; }
public function grab(&$param_pool) { $result = new XMLElement($this->dsParamROOTELEMENT); foreach ($this->_env as $key => $value) { switch ($key) { case 'param': //$group = new XMLElement('params'); foreach ($this->_env[$key] as $key => $value) { $param = new XMLElement($key, General::sanitize($value)); $result->appendChild($param); } //$result->appendChild($group); break; case 'env': //$group = new XMLElement('pool'); foreach ($this->_env[$key]['pool'] as $key => $value) { $param = new XMLElement($key); if (is_array($value)) { $param->setAttribute('count', count($value)); foreach ($value as $key => $value) { $item = new XMLElement('item', General::sanitize($value)); $item->setAttribute('handle', Lang::createHandle($value)); $param->appendChild($item); } } else { $param->setValue(General::sanitize($value)); } $result->appendChild($param); } //$result->appendChild($group); break; } } return $result; }
public static function get() { $response = new XMLElement('response'); foreach (self::$_sections as $section) { $section_xml = new XMLElement('section'); $meta = $section->get(); foreach ($meta as $key => $value) { $section_xml->setAttribute(Lang::createHandle($key), $value); } $fields = $section->fetchFields(); foreach ($fields as $field) { $meta = $field->get(); unset($meta['field_id']); $field_xml = new XMLElement($meta['element_name'], null); foreach (self::$_field_attributes as $attr) { $field_xml->setAttribute(Lang::createHandle($attr), $meta[$attr]); } foreach ($meta as $key => $value) { if (in_array($key, self::$_field_attributes)) { continue; } $value = General::sanitize($value); if ($value != '') { $field_xml->appendChild(new XMLElement(Lang::createHandle($key), General::sanitize($value))); } } $section_xml->appendChild($field_xml); } $response->appendChild($section_xml); } REST_API::sendOutput($response); }
/** * Given a CSV file, generate a resulting XML tree * * @param string $data * @return string */ public static function convertToXML($data) { $headers = array(); // DOMDocument $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = $doc->createElement('data'); $doc->appendChild($root); foreach (str_getcsv($data, PHP_EOL) as $i => $row) { if (empty($row)) { continue; } if ($i == 0) { foreach (str_getcsv($row) as $i => $head) { if (class_exists('Lang')) { $head = Lang::createHandle($head); } $headers[] = $head; } } else { self::addRow($doc, $root, str_getcsv($row), $headers); } } $output = $doc->saveXML($doc->documentElement); return trim($output); }
public function view() { $name = General::sanitize($_REQUEST['name']); $section = General::sanitize($_REQUEST['section']); $filters = self::processFilters($_REQUEST['filters']); $rootelement = Lang::createHandle($name); $doc_parts = array(); // Add Documentation (Success/Failure) $this->addEntrySuccessDoc($doc_parts, $rootelement, $filters); $this->addEntryFailureDoc($doc_parts, $rootelement, $filters); // Filters $this->addDefaultFiltersDoc($doc_parts, $rootelement, $filters); // Frontend Markup $this->addFrontendMarkupDoc($doc_parts, $rootelement, $section, $filters); $this->addSendMailFilterDoc($doc_parts, $filters); /** * Allows adding documentation for new filters. A reference to the $documentation * array is provided, along with selected filters * * @delegate AppendEventFilterDocumentation * @param string $context * '/blueprints/events/(edit|new|info)/' * @param array $selected * An array of all the selected filters for this Event * @param array $documentation * An array of all the documentation XMLElements, passed by reference * @param string $rootelment * The name of this event, as a handle. */ Symphony::ExtensionManager()->notifyMembers('AppendEventFilterDocumentation', '/blueprints/events/', array('selected' => $filters, 'documentation' => &$doc_parts, 'rootelement' => $rootelement)); $documentation = join(PHP_EOL, array_map(create_function('$x', 'return rtrim($x->generate(true, 4));'), $doc_parts)); $documentation = str_replace('\'', '\\\'', $documentation); $documentation = '<fieldset id="event-documentation" class="settings"><legend>' . __('Documentation') . '</legend>' . $documentation . '</fieldset>'; $this->_Result = $documentation; }
/** * * Convert the $source string into a array. * This array should always respect the scheme defined by the * getDataFromSource method of the ServiceDriver * @param string $source * @return string */ public function createArray($source, $driver, $url, &$errorFlag) { // get the data as an array $data = @json_decode($source, true); if ($data === FALSE) { $errorFlag = true; } if (!$errorFlag) { // original content $xml['xml'] = $source; $idTagName = $driver->getIdTagName(); if ($idTagName == null || !isset($data[$idTagName])) { $xml['id'] = Lang::createHandle($url); } else { $xml['id'] = $data[$idTagName]; } $xml['title'] = $data[$driver->getTitleTagName()]; $xml['thumb'] = $data[$driver->getThumbnailTagName()]; } if ($errorFlag) { // return error message $xml['error'] = __('Symphony could not parse JSON from oEmbed remote service'); } return $xml; }
function displayPublishPanel(&$wrapper, $data = NULL, $flagWithError = NULL, $fieldnamePrefix = NULL, $fieldnamePostfix = NULL) { $note = $this->get('note'); if (!isset($note)) { return; } $div = new XMLElement("div", $note, array("id" => Lang::createHandle($this->get('label')))); $wrapper->appendChild($div); }
public function __get($name) { if ($name == 'handle') { return Lang::createHandle($this->name); } else { if (!isset($this->{$name})) { return null; } } return $this->about[$name]; }
private static function __buildAuthorXML($author) { $author_xml = new XMLElement('author'); foreach ($author->get() as $key => $value) { $value = General::sanitize($value); if ($value != '') { $author_xml->appendChild(new XMLElement(Lang::createHandle($key), General::sanitize($value))); } } return $author_xml; }
public static function getSectionIDByName($section_name) { self::_assert(false, true); if (is_array($section_name)) { $ret = array(); foreach ($section_name as $name) { $ret[$name] = self::$sm->fetchIDFromHandle(Lang::createHandle($name)); } return $ret; } return self::$sm->fetchIDFromHandle(Lang::createHandle($section_name)); }
function grab($param = array()) { extract($this->_env, EXTR_PREFIX_ALL, 'env'); include_once TOOLKIT . '/class.entrymanager.php'; $entryManager = new EntryManager($this->_parent); $section_id = $entryManager->fetchSectionIDFromHandle($this->__resolveDefine("dsFilterPARENTSECTION")); $schema = $entryManager->fetchEntryFieldSchema($section_id, NULL, $this->_dsFilterCUSTOMFIELD); $schema = $schema[0]; ##Check the cache $hash_id = md5(get_class($this)); if ($param['caching'] && ($cache = $this->check_cache($hash_id))) { return $cache; exit; } ##------------------------------ ##Create the XML container $xml = new XMLElement("categories-list"); $xml->setAttribute("section", "customfield"); ##Populate the XML if (empty($schema) || !is_array($schema)) { $xml->addChild(new XMLElement("error", "No Records Found.")); return $xml; } else { $ops = preg_split('/,/', $schema['values'], -1, PREG_SPLIT_NO_EMPTY); $ops = array_map("trim", $ops); $xml->addChild(new XMLElement("name", $schema['name'])); $xml->setAttribute("handle", $schema['handle']); $options = new XMLElement("options"); foreach ($ops as $o) { if ($schema['type'] == 'multiselect') { $table = 'tbl_entries2customfields_list'; } else { $table = 'tbl_entries2customfields'; } $count = $this->_db->fetchVar('count', 0, "SELECT count(id) AS `count` FROM `{$table}` WHERE `field_id` = '" . $schema['id'] . "' AND value_raw = '{$o}' "); $xO = new XMLElement("option", $o); $xO->setAttribute('entry-count', $count); $xO->setAttribute('handle', Lang::createHandle($o, $this->_parent->getConfigVar('handle_length', 'admin'))); $options->addChild($xO); } $xml->addChild($options); } ##------------------------------ ##Write To Cache if ($param['caching']) { $result = $xml->generate($param['indent'], $param['indent-depth']); $this->write_to_cache($hash_id, $result, $this->_cache_sections); return $result; } return $xml; }
private function __getDSParams() { $params = array(); $datasources = DatasourceManager::listAll(); foreach ($datasources as $datasource) { $current = DatasourceManager::create($datasource['handle'], array(), false); // Get parameters if (is_array($current->dsParamPARAMOUTPUT)) { foreach ($current->dsParamPARAMOUTPUT as $id => $param) { $params[] = sprintf($this->template, 'ds-' . Lang::createHandle($datasource['name']) . '.' . Lang::createHandle($param)); } } } return $params; }
public function createHandle($value, $entry_id) { $handle = Lang::createHandle(strip_tags(html_entity_decode($value))); if ($this->isHandleLocked($handle, $entry_id)) { if ($this->isHandleFresh($handle, $value, $entry_id)) { return $this->getCurrentHandle($entry_id); } else { $count = 2; while ($this->isHandleLocked("{$handle}-{$count}", $entry_id)) { $count++; } return "{$handle}-{$count}"; } } return $handle; }
public function grab(array &$param_pool = NULL) { $result = new XMLElement($this->dsParamROOTELEMENT); // Set up keywords /*-----------------------------------------------------------------------*/ $keywords = (string) $_GET['keywords']; $keywords = trim($keywords); $sort = (string) $_GET['sort']; if ($sort == '' || $sort == 'alphabetical') { $sort = '`keywords`.`keyword` ASC'; } elseif ($sort == 'frequency') { $sort = '`frequency` DESC'; } if (strlen($keywords) <= 2) { return $result; } // Set up sections /*-----------------------------------------------------------------------*/ if (isset($_GET['sections'])) { $param_sections = $_GET['sections']; // allow sections to be sent as an array if the user wishes (multi-select or checkboxes) if (is_array($param_sections)) { implode(',', $param_sections); } } else { $param_sections = ''; } $sections = array(); foreach (array_map('trim', explode(',', $param_sections)) as $handle) { $section = Symphony::Database()->fetchRow(0, sprintf("SELECT `id`, `name` FROM `tbl_sections` WHERE handle = '%s' LIMIT 1", Symphony::Database()->cleanValue($handle))); if ($section) { $sections[$section['id']] = array('handle' => $handle, 'name' => $section['name']); } } // Build SQL /*-----------------------------------------------------------------------*/ $sql = sprintf("SELECT\n\t\t\t\t\t`keywords`.`keyword`,\n\t\t\t\t\tSUM(`entry_keywords`.`frequency`) AS `frequency`\n\t\t\t\tFROM\n\t\t\t\t\t`tbl_search_index_keywords` AS `keywords`\n\t\t\t\t\tINNER JOIN `tbl_search_index_entry_keywords` AS `entry_keywords` ON (`keywords`.`id` = `entry_keywords`.`keyword_id`)\n\t\t\t\t\tINNER JOIN `tbl_entries` AS `entry` ON (`entry_keywords`.`entry_id` = `entry`.`id`)\n\t\t\t\tWHERE\n\t\t\t\t\t`keywords`.`keyword` LIKE '%s%%'\n\t\t\t\t\t%s\n\t\t\t\tGROUP BY `keywords`.`keyword`\n\t\t\t\tORDER BY %s\n\t\t\t\tLIMIT 0, 50", Symphony::Database()->cleanValue($keywords), count($sections) > 0 ? sprintf('AND `entry`.section_id IN (%s)', implode(',', array_keys($sections))) : NULL, $sort); // Run! /*-----------------------------------------------------------------------*/ // get our entries, returns entry IDs $words = Symphony::Database()->fetch($sql); foreach ($words as $word) { $result->appendChild(new XMLElement('word', General::sanitize($word['keyword']), array('frequency' => $word['frequency'], 'handle' => Lang::createHandle($word['keyword'])))); } return $result; }
/** * Given a `$needle`, this function will return the Member object. * If the `$needle` passed is an array, this function expects a * key of 'username' * * @param string|array $needle * @return Entry */ public function fetchMemberIDBy($needle, $member_id = null) { if (is_array($needle)) { extract($needle); } else { $username = $needle; } if (empty($username)) { extension_Members::$_errors[$this->get('element_name')] = array('message' => __('\'%s\' is a required field.', array($this->get('label'))), 'message-id' => EventMessages::FIELD_MISSING, 'type' => 'missing', 'label' => $this->get('label')); return null; } $member_id = Symphony::Database()->fetchVar('entry_id', 0, sprintf("SELECT `entry_id` FROM `tbl_entries_data_%d` WHERE `handle` = '%s' LIMIT 1", $this->get('id'), Lang::createHandle($username))); if (is_null($member_id)) { extension_Members::$_errors[$this->get('element_name')] = array('message' => __("Member not found."), 'message-id' => MemberEventMessages::MEMBER_INVALID, 'type' => 'invalid', 'label' => $this->get('label')); return null; } else { return $member_id; } }
public function frontendOutputPreGenerate(&$context) { $pairs_config = @simplexml_load_file(MANIFEST . '/entry-attribute-counts.xml'); if (!$pairs_config) { return; } $pairs = $pairs_config->xpath('pair'); $xml = simplexml_load_string($context['xml']); foreach ($pairs as $pair) { foreach ($xml as $name => $node) { if ($name != $pair->attributes()->{'add-attribute-to'}) { continue; } foreach ($node as $name => $entry) { if ($name != 'entry') { continue; } $dsm = new DataSourceManager(Frontend::instance()); $ds_copy = $dsm->create($pair->attributes()->{'get-count-from'}); require_once EXTENSIONS . '/entry_attribute_counts/lib/class.datasource_count.php'; $ds = new CountDataSource(Frontend::instance(), NULL, FALSE); $ds->dsSource = $ds_copy->getSource(); $ds->dsParamROOTELEMENT = $ds_copy->dsParamROOTELEMENT; $ds->dsParamORDER = $ds_copy->dsParamORDER; $ds->dsParamLIMIT = 999999; $ds->dsParamREDIRECTONEMPTY = 'no'; $ds->dsParamREQUIREDPARAM = ''; $ds->dsParamSORT = $ds_copy->dsParamSORT; $ds->dsParamSTARTPAGE = 1; $ds->dsParamASSOCIATEDENTRYCOUNTS = 'no'; $ds->dsParamFILTERS = $ds_copy->dsParamFILTERS; $ds->dsParamINCLUDEDELEMENTS = $ds_copy->dsParamINCLUDEDELEMENTS; $this->param_pool['ds-' . $pair->attributes()->{'add-attribute-to'}] = $entry->attributes()->id; $ds->processParameters(array('env' => array(), 'param' => $this->param_pool)); $grab_xml = $ds->grab($this->param_pool); $entry->addAttribute(Lang::createHandle($pair->attributes()->{'get-count-from'}), $grab_xml->getValue()); } } } $context['xml'] = $xml->asXML(); }
/** * Process the page's parameters. This is used to extract the page id * and set the associated data source to the id of the Page Fields section * for it. * * @param array env The parameters. */ function processParameters($env = NULL) { // Get the handle of the PF section associated with the page. // $pageId = $env['param']['current-page-id']; $pageFieldsSectionHandle = Lang::createHandle(PF_SECTION_TITLE_PREFIX . $pageId); // Retrieve and store the Id of the section so we can return it from getSource() // $sectionManager = new SectionManager($this->_Parent); $this->pageFieldsSectionId = $sectionManager->fetchIDFromHandle($pageFieldsSectionHandle); // Initialise $dsParamINCLUDEDELEMENTS with the names of all fields for the section. // $fieldNames = $this->_Parent->Database->fetchCol('element_name', "SELECT `element_name` FROM `tbl_fields` WHERE `parent_section` = '{$this->pageFieldsSectionId}'"); $this->dsParamINCLUDEDELEMENTS = array(); if (is_array($fieldNames) && !empty($fieldNames)) { foreach ($fieldNames as $elementName) { $this->dsParamINCLUDEDELEMENTS[] = $elementName; } } // Call parent class implementation. // parent::processParameters($env); }
/** * This is the meat and potatoes method where the driver builds * its content */ public function buildDataXML($data) { // Create the <views> container element $views_xml = $this->document->createElement('views'); foreach (new ViewIterator() as $v) { // Create the <view> element $view = $this->document->createElement('view'); // Set the guid attribute $view->setAttribute('guid', $v->guid); // Create the <title> $title = $this->document->createElement('title', $v->title); // Set the title's handle attribute $title->setAttribute('handle', Lang::createHandle($v->title)); // Append the title $view->appendChild($title); // Append the view's <url> $view->appendChild($this->document->createElement('path', $v->path)); // Append the <url-params> if (is_array($v->{'url-parameters'}) && count($v->{'url-parameters'}) > 0) { $params_xml = $this->document->createElement('url-params'); foreach ($v->{'url-parameters'} as $p) { $params_xml->appendChild($this->document->createElement('item', $p)); } $view->appendChild($params_xml); } // Append the view's <types> if (is_array($v->types) && count($v->types) > 0) { $types_xml = $this->document->createElement('types'); foreach ($v->types as $t) { $types_xml->appendChild($this->document->createElement('item', $t)); } $view->appendChild($types_xml); } $views_xml->appendChild($view); } $data->appendChild($views_xml); }
public function processRawFieldData($data, &$status, &$message = null, $simulate = false, $entry_id = null) { $status = self::__OK__; $data = preg_split('/\\,\\s*/i', $data, -1, PREG_SPLIT_NO_EMPTY); $data = array_map('trim', $data); $result = array('value' => array(), 'handle' => array()); if (empty($data)) { return null; } // Do a case insensitive removal of duplicates $data = General::array_remove_duplicates($data, true); sort($data); $result = array(); foreach ($data as $value) { $result['value'][] = $value; $result['handle'][] = Lang::createHandle($value); } return $result; }
General::redirect(URL . "/symphony/?page=/structure/customfields/&_f=complete"); } if (@array_key_exists("save", $_POST['action']) || @array_key_exists("done", $_POST['action'])) { $required = array('name'); extract($_POST); for ($i = 0; $i < count($required); $i++) { if (trim($fields[$required[$i]]) == "") { $errors[$required[$i]] = true; } } if (is_array($errors)) { define("__SYM_ENTRY_MISSINGFIELDS__", true); } else { $field_id = $_REQUEST['id']; if (!empty($field_id)) { $fields['handle'] = Lang::createHandle($fields['name'], $Admin->getConfigVar('handle_length', 'admin')); if ($fields['type'] == 'input' && $fields['create_input_as_list'] == 'on') { $fields['type'] = 'list'; } unset($fields['create_input_as_list']); if ($fields['type'] == 'select' && isset($fields['select_multiple'])) { $fields['type'] = 'multiselect'; } unset($fields['select_multiple']); if ($fields['type'] == 'foreign' && isset($fields['foreign_select_multiple'])) { $fields['foreign_select_multiple'] = 'yes'; } else { $fields['foreign_select_multiple'] = 'no'; } $current_handle = $DB->fetchVar('handle', 0, "SELECT `handle` FROM `tbl_customfields` WHERE `id` = " . $_REQUEST['id']); if ($current_handle != $fields['handle'] && $DB->fetchRow(0, "SELECT * FROM `tbl_customfields` WHERE `handle` = '" . $fields['handle'] . "' AND `parent_section` = '" . $fields['parent_section'] . "' LIMIT 1")) {
/** * Commit the settings of this field from the section editor to * create an instance of this field in a section. * * @return boolean * true if the commit was successful, false otherwise. */ public function commit() { $fields = array(); $fields['label'] = General::sanitize($this->get('label')); $fields['element_name'] = $this->get('element_name') ? $this->get('element_name') : Lang::createHandle($this->get('label')); $fields['parent_section'] = $this->get('parent_section'); $fields['location'] = $this->get('location'); $fields['required'] = $this->get('required'); $fields['type'] = $this->_handle; $fields['show_column'] = $this->get('show_column'); $fields['sortorder'] = (string) $this->get('sortorder'); if ($id = $this->get('id')) { return FieldManager::edit($id, $fields); } else { if ($id = FieldManager::add($fields)) { $this->set('id', $id); $this->createTable(); return true; } } return false; }
public function __actionEdit() { if ($this->_context[0] != 'new' && !($page_id = (int) $this->_context[1])) { redirect(URL . '/symphony/blueprints/pages/'); } if (@array_key_exists('delete', $_POST['action'])) { $this->__actionDelete($page_id, URL . '/symphony/blueprints/pages/'); } if (@array_key_exists('save', $_POST['action'])) { $fields = $_POST['fields']; $this->_errors = array(); $current = $this->_Parent->Database->fetchRow(0, "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tp.*\n\t\t\t\t\tFROM\n\t\t\t\t\t\t`tbl_pages` AS p\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tp.id = '{$page_id}'\n\t\t\t\t\tLIMIT 1\n\t\t\t\t"); if (!isset($fields['title']) || trim($fields['title']) == '') { $this->_errors['title'] = __('Title is a required field'); } if (trim($fields['type']) != '' && preg_match('/(index|404|403)/i', $fields['type'])) { $types = preg_split('/\\s*,\\s*/', strtolower($fields['type']), -1, PREG_SPLIT_NO_EMPTY); if (in_array('index', $types) && $this->__typeUsed($page_id, 'index')) { $this->_errors['type'] = __('An index type page already exists.'); } else { if (in_array('404', $types) && $this->__typeUsed($page_id, '404')) { $this->_errors['type'] = __('A 404 type page already exists.'); } else { if (in_array('403', $types) && $this->__typeUsed($page_id, '403')) { $this->_errors['type'] = __('A 403 type page already exists.'); } } } } if (empty($this->_errors)) { $autogenerated_handle = false; if (empty($current)) { $fields['sortorder'] = $this->_Parent->Database->fetchVar('next', 0, "\n\t\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\t\tMAX(p.sortorder) + 1 AS `next`\n\t\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t\t`tbl_pages` AS p\n\t\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t\t"); if (empty($fields['sortorder']) || !is_numeric($fields['sortorder'])) { $fields['sortorder'] = 1; } } if (trim($fields['handle']) == '') { $fields['handle'] = $fields['title']; $autogenerated_handle = true; } $fields['handle'] = Lang::createHandle($fields['handle']); if ($fields['params']) { $fields['params'] = trim(preg_replace('@\\/{2,}@', '/', $fields['params']), '/'); } // Clean up type list $types = preg_split('/\\s*,\\s*/', $fields['type'], -1, PREG_SPLIT_NO_EMPTY); $types = @array_map('trim', $types); unset($fields['type']); $fields['parent'] = $fields['parent'] != __('None') ? $fields['parent'] : null; $fields['data_sources'] = @implode(',', $fields['data_sources']); $fields['events'] = @implode(',', $fields['events']); $fields['path'] = null; if ($fields['parent']) { $fields['path'] = $this->_Parent->resolvePagePath((int) $fields['parent']); } // Check for duplicates: $duplicate = $this->_Parent->Database->fetchRow(0, "\n\t\t\t\t\t\tSELECT\n\t\t\t\t\t\t\tp.*\n\t\t\t\t\t\tFROM\n\t\t\t\t\t\t\t`tbl_pages` AS p\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\tp.id != '{$page_id}'\n\t\t\t\t\t\t\tAND p.handle = '" . $fields['handle'] . "'\n\t\t\t\t\t\t\tAND p.path " . ($fields['path'] ? " = '" . $fields['path'] . "'" : ' IS NULL') . " \n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t"); // Create or move files: if (empty($current)) { $file_created = $this->__updatePageFiles($fields['path'], $fields['handle']); } else { $file_created = $this->__updatePageFiles($fields['path'], $fields['handle'], $current['path'], $current['handle']); } if (!$file_created) { $redirect = null; $this->pageAlert(__('Page could not be written to disk. Please check permissions on <code>/workspace/pages</code>.'), Alert::ERROR); } if ($duplicate) { if ($autogenerated_handle) { $this->_errors['title'] = __('A page with that title already exists'); } else { $this->_errors['handle'] = __('A page with that handle already exists'); } // Insert the new data: } else { if (empty($current)) { if (!$this->_Parent->Database->insert($fields, 'tbl_pages')) { $this->pageAlert(__('Unknown errors occurred while attempting to save. Please check your <a href="%s">activity log</a>.', array(URL . '/symphony/system/log/')), Alert::ERROR); } else { $page_id = $this->_Parent->Database->getInsertID(); $redirect = "/symphony/blueprints/pages/edit/{$page_id}/created/"; } // Update existing: } else { if (!$this->_Parent->Database->update($fields, 'tbl_pages', "`id` = '{$page_id}'")) { $this->pageAlert(__('Unknown errors occurred while attempting to save. Please check your <a href="%s">activity log</a>.', array(URL . '/symphony/system/log/')), Alert::ERROR); } else { $this->_Parent->Database->delete('tbl_pages_types', " `page_id` = '{$page_id}'"); $redirect = "/symphony/blueprints/pages/edit/{$page_id}/saved/"; } } } // Assign page types: if (is_array($types) && !empty($types)) { foreach ($types as $type) { $this->_Parent->Database->insert(array('page_id' => $page_id, 'type' => $type), 'tbl_pages_types'); } } // Find and update children: if ($this->_context[0] == 'edit') { $this->__updatePageChildren($page_id, $fields['path'] . '/' . $fields['handle']); } if ($redirect) { redirect(URL . $redirect); } } if (is_array($this->_errors) && !empty($this->_errors)) { $this->pageAlert(__('An error occurred while processing this form. <a href="#error">See below for details.</a>'), Alert::ERROR); } } }
public function __actionEdit() { if (@array_key_exists('save', $_POST['action']) || @array_key_exists('done', $_POST['action'])) { $canProceed = true; $fields = $_POST['fields']; $meta = $_POST['meta']; $section_id = $this->_context[1]; $sectionManager = new SectionManager($this->_Parent); $existing_section = $sectionManager->fetch($section_id); $fieldManager = new FieldManager($this->_Parent); $this->_errors = array(); ## Check to ensure all the required section fields are filled if (!isset($meta['name']) || trim($meta['name']) == '') { $required = array('Name'); $this->_errors['name'] = __('This is a required field.'); $canProceed = false; } elseif ($meta['name'] != $existing_section->get('name') && Symphony::Database()->fetchRow(0, "SELECT * FROM `tbl_sections` WHERE `name` = '" . $meta['name'] . "' AND `id` != {$section_id} LIMIT 1")) { $this->_errors['name'] = __('A Section with the name <code>%s</code> name already exists', array($meta['name'])); $canProceed = false; } ## Check to ensure all the required section fields are filled if (!isset($meta['navigation_group']) || strlen(trim($meta['navigation_group'])) == 0) { $required = array('Navigation Group'); $this->_errors['navigation_group'] = __('This is a required field.'); $canProceed = false; } elseif (is_array($fields) && !empty($fields)) { ## Check for duplicate CF names if ($canProceed) { $name_list = array(); foreach ($fields as $position => $data) { if (trim($data['element_name']) == '') { $data['element_name'] = $fields[$position]['element_name'] = Lang::createHandle($data['label'], NULL, '-', false, true, array('@^[\\d-]+@i' => '')); } if (trim($data['element_name']) != '' && in_array($data['element_name'], $name_list)) { $this->_errors[$position] = array('label' => __('Two custom fields have the same element name. All element names must be unique.')); $canProceed = false; break; } $name_list[] = $data['element_name']; } } if ($canProceed) { $fieldManager = new FieldManager($this->_Parent); $unique = array(); foreach ($fields as $position => $data) { $required = NULL; $field = $fieldManager->create($data['type']); $field->setFromPOST($data); if ($field->mustBeUnique() && !in_array($field->get('type'), $unique)) { $unique[] = $field->get('type'); } elseif ($field->mustBeUnique() && in_array($field->get('type'), $unique)) { ## Warning. cannot have 2 of this field! $canProceed = false; $this->_errors[$position] = array('label' => __('There is already a field of type <code>%s</code>. There can only be one per section.', array($field->name()))); } $errors = array(); if (Field::__OK__ != $field->checkFields($errors, false, false) && !empty($errors)) { $this->_errors[$position] = $errors; $canProceed = false; break; } } } } if ($canProceed) { $meta['handle'] = Lang::createHandle($meta['name']); $meta['hidden'] = isset($meta['hidden']) ? 'yes' : 'no'; if (!$sectionManager->edit($section_id, $meta)) { $this->pageAlert(__('An unknown database occurred while attempting to create the section.'), Alert::ERROR); } else { ## Delete missing CF's $id_list = array(); if (is_array($fields) && !empty($fields)) { foreach ($fields as $position => $data) { if (isset($data['id'])) { $id_list[] = $data['id']; } } } $missing_cfs = Symphony::Database()->fetchCol('id', "SELECT `id` FROM `tbl_fields` WHERE `parent_section` = '{$section_id}' AND `id` NOT IN ('" . @implode("', '", $id_list) . "')"); if (is_array($missing_cfs) && !empty($missing_cfs)) { foreach ($missing_cfs as $id) { $fieldManager->delete($id); } } ## Save each custom field if (is_array($fields) && !empty($fields)) { foreach ($fields as $position => $data) { $field = $fieldManager->create($data['type']); $field->setFromPOST($data); $field->set('sortorder', (string) $position); $field->set('parent_section', $section_id); $bEdit = true; if (!$field->get('id')) { $bEdit = false; } ## Creation if ($field->commit()) { $field_id = $field->get('id'); ### # Delegate: FieldPostCreate # Delegate: FieldPostEdit # Description: After creation/editing of an Field. New Field object is provided. $this->_Parent->ExtensionManager->notifyMembers($bEdit ? 'FieldPostEdit' : 'FieldPostCreate', '/blueprints/sections/', array('field' => &$field, 'data' => &$data)); } } } ## TODO: Fix Me ### # Delegate: Edit # Description: After editing a Section. The ID is provided. #$ExtensionManager->notifyMembers('Edit', getCurrentPage(), array('section_id' => $section_id)); redirect(URL . "/symphony/blueprints/sections/edit/{$section_id}/saved/"); } } } if (@array_key_exists("delete", $_POST['action'])) { $section_id = $this->_context[1]; $sectionManager = new SectionManager($this->_Parent); $sectionManager->delete($section_id); redirect(URL . '/symphony/blueprints/sections/'); } }
public function appendFormattedElement(XMLElement &$wrapper, $data, $encode = false, $mode = null, $entry_id = null) { if (!is_array($data['author_id'])) { $data['author_id'] = array($data['author_id']); } $list = new XMLElement($this->get('element_name')); $authors = AuthorManager::fetchByID($data['author_id']); foreach ($authors as $author) { if (is_null($author)) { continue; } $list->appendChild(new XMLElement('item', $author->getFullName(), array('id' => (string) $author->get('id'), 'handle' => Lang::createHandle($author->getFullName()), 'username' => General::sanitize($author->get('username'))))); } $wrapper->appendChild($list); }
public function appendPreferences($context) { $config = Symphony::Configuration()->get('elasticsearch'); $fieldset = new XMLElement('fieldset'); $fieldset->setAttribute('class', 'settings'); $fieldset->appendChild(new XMLElement('legend', 'ElasticSearch')); $group = new XMLElement('div'); $group->setAttribute('class', 'group'); $label = Widget::Label(__('Host')); $label->appendChild(Widget::Input('settings[elasticsearch][host]', $config['host'], 'text', array('placeholder' => 'e.g. http://localhost:9200/'))); $label->appendChild(new XMLElement('span', __('Include trailing slash.'), array('class' => 'help'))); $group->appendChild($label); $label = Widget::Label(__('Index Name')); $label->appendChild(Widget::Input('settings[elasticsearch][index-name]', $config['index-name'], 'text', array('placeholder' => 'e.g. ' . Lang::createHandle(Symphony::Configuration()->get('sitename', 'general'))))); $label->appendChild(new XMLElement('span', __('Use handle format (no spaces).'), array('class' => 'help'))); $group->appendChild($label); $fieldset->appendChild($group); $group = new XMLElement('div'); $group->setAttribute('class', 'group'); $label = Widget::Label(__('Username <i>Optional</i>')); $label->appendChild(Widget::Input('settings[elasticsearch][username]', $config['username'])); $group->appendChild($label); $label = Widget::Label(__('Password <i>Optional</i>')); $label->appendChild(Widget::Input('settings[elasticsearch][password]', $config['password'])); $group->appendChild($label); $label->appendChild(Widget::Input('settings[elasticsearch][index_name_original]', $config['index-name'], 'text', array('type' => 'hidden'))); $fieldset->appendChild($group); $context['wrapper']->appendChild($fieldset); }
function __formAction() { $fields = $_POST['fields']; $this->_errors = array(); if (trim($fields['name']) == '') { $this->_errors['name'] = __('This is a required field'); } if ($fields['source'] == 'static_xml') { if (trim($fields['static_xml']) == '') { $this->_errors['static_xml'] = __('This is a required field'); } else { $xml_errors = NULL; include_once TOOLKIT . '/class.xsltprocess.php'; General::validateXML($fields['static_xml'], $xml_errors, false, new XsltProcess()); if (!empty($xml_errors)) { $this->_errors['static_xml'] = __('XML is invalid'); } } } elseif ($fields['source'] == 'dynamic_xml') { if (trim($fields['dynamic_xml']['url']) == '') { $this->_errors['dynamic_xml']['url'] = __('This is a required field'); } if (trim($fields['dynamic_xml']['xpath']) == '') { $this->_errors['dynamic_xml']['xpath'] = __('This is a required field'); } if (!is_numeric($fields['dynamic_xml']['cache'])) { $this->_errors['dynamic_xml']['cache'] = __('Must be a valid number'); } elseif ($fields['dynamic_xml']['cache'] < 1) { $this->_errors['dynamic_xml']['cache'] = __('Must be greater than zero'); } } else { if ($fields['source'] != 'navigation') { if (strlen(trim($fields['max_records'])) == 0 || is_numeric($fields['max_records']) && $fields['max_records'] < 1) { $this->_errors['max_records'] = __('A result limit must be set'); } elseif (!self::__isValidPageString($fields['max_records'])) { $this->_errors['max_records'] = __('Must be a valid number or parameter'); } if (strlen(trim($fields['page_number'])) == 0 || is_numeric($fields['page_number']) && $fields['page_number'] < 1) { $this->_errors['page_number'] = __('A page number must be set'); } elseif (!self::__isValidPageString($fields['page_number'])) { $this->_errors['page_number'] = __('Must be a valid number or parameter'); } } } $classname = Lang::createHandle($fields['name'], NULL, '_', false, true, array('@^[^a-z]+@i' => '', '/[^\\w-\\.]/i' => '')); $rootelement = str_replace('_', '-', $classname); $file = DATASOURCES . '/data.' . $classname . '.php'; $isDuplicate = false; $queueForDeletion = NULL; if ($this->_context[0] == 'new' && @is_file($file)) { $isDuplicate = true; } elseif ($this->_context[0] == 'edit') { $existing_handle = $this->_context[1]; if ($classname != $existing_handle && @is_file($file)) { $isDuplicate = true; } elseif ($classname != $existing_handle) { $queueForDeletion = DATASOURCES . '/data.' . $existing_handle . '.php'; } } ##Duplicate if ($isDuplicate) { $this->_errors['name'] = __('A Data source with the name <code>%s</code> name already exists', array($classname)); } if (empty($this->_errors)) { $dsShell = file_get_contents(TEMPLATE . '/datasource.tpl'); //$oDate = $this->_Parent->getDateObj(); $params = array('rootelement' => $rootelement); $about = array('name' => $fields['name'], 'version' => '1.0', 'release date' => DateTimeObj::getGMT('c'), 'author name' => $this->_Parent->Author->getFullName(), 'author website' => URL, 'author email' => $this->_Parent->Author->get('email')); $source = $fields['source']; $filter = NULL; $elements = NULL; switch ($source) { case 'authors': $filters = $fields['filter']['author']; $elements = $fields['xml_elements']; $params['order'] = $fields['order']; $params['limit'] = $fields['max_records']; $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no'; $params['requiredparam'] = $fields['required_url_param']; $params['paramoutput'] = $fields['param']; $params['sort'] = $fields['sort']; $params['startpage'] = $fields['page_number']; $dsShell = str_replace('<!-- GRAB -->', "include(TOOLKIT . '/data-sources/datasource.author.php');", $dsShell); break; case 'navigation': $filters = $fields['filter']['navigation']; $params['order'] = $fields['order']; $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no'; $params['requiredparam'] = $fields['required_url_param']; $dsShell = str_replace('<!-- GRAB -->', "include(TOOLKIT . '/data-sources/datasource.navigation.php');", $dsShell); break; case 'dynamic_xml': $namespaces = $fields['dynamic_xml']['namespace']; $filters = array(); for ($ii = 0; $ii < count($namespaces['name']); $ii++) { $filters[$namespaces['name'][$ii]] = $namespaces['uri'][$ii]; } $params['url'] = $fields['dynamic_xml']['url']; $params['xpath'] = $fields['dynamic_xml']['xpath']; $params['cache'] = $fields['dynamic_xml']['cache']; $dsShell = str_replace('<!-- GRAB -->', "include(TOOLKIT . '/data-sources/datasource.dynamic_xml.php');", $dsShell); break; case 'static_xml': $value = sprintf('$result = "%s";', addslashes($fields['static_xml'])); $dsShell = str_replace('<!-- GRAB -->', $value, $dsShell); break; default: $elements = $fields['xml_elements']; if (is_array($fields['filter']) && !empty($fields['filter'])) { $filters = array(); foreach ($fields['filter'] as $f) { foreach ($f as $key => $val) { $filters[$key] = $val; } } } $params['order'] = $fields['order']; $params['group'] = $fields['group']; $params['limit'] = $fields['max_records']; $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no'; $params['requiredparam'] = $fields['required_url_param']; $params['paramoutput'] = $fields['param']; $params['sort'] = $fields['sort']; $params['startpage'] = $fields['page_number']; $params['htmlencode'] = $fields['html_encode']; $dsShell = str_replace('<!-- GRAB -->', "include(TOOLKIT . '/data-sources/datasource.section.php');", $dsShell); break; } $this->__injectVarList($dsShell, $params); $this->__injectAboutInformation($dsShell, $about); $this->__injectIncludedElements($dsShell, $elements); $this->__injectFilters($dsShell, $filters); $dsShell = str_replace('<!-- CLASS NAME -->', $classname, $dsShell); $dsShell = str_replace('<!-- SOURCE -->', $source, $dsShell); if (preg_match_all('@{(\\$ds-[^}]+)}@i', $dsShell, $matches)) { $dependancies = array(); foreach ($matches[1] as $match) { if (preg_match_all('/(\\$ds-[^:]+)/i', $match, $inner_matches)) { $dependancies = array_merge($dependancies, $inner_matches[1]); } } $dependancies = General::array_remove_duplicates($dependancies); $dsShell = str_replace('<!-- DS DEPENDANCY LIST -->', "'" . implode("', '", $dependancies) . "'", $dsShell); } ## Remove left over placeholders $dsShell = preg_replace(array('/<!--[\\w ]++-->/', '/(\\r\\n){2,}/', '/(\\t+[\\r\\n]){2,}/'), '', $dsShell); ##Write the file if (!is_writable(dirname($file)) || !($write = General::writeFile($file, $dsShell, $this->_Parent->Configuration->get('write_mode', 'file')))) { $this->pageAlert(__('Failed to write Data source to <code>%s</code>. Please check permissions.', array(DATASOURCES)), Alert::ERROR); } else { if ($queueForDeletion) { General::deleteFile($queueForDeletion); ## Update pages that use this DS $sql = "SELECT * FROM `tbl_pages` WHERE `data_sources` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]' "; $pages = $this->_Parent->Database->fetch($sql); if (is_array($pages) && !empty($pages)) { foreach ($pages as $page) { $page['data_sources'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['data_sources']); $this->_Parent->Database->update($page, 'tbl_pages', "`id` = '" . $page['id'] . "'"); } } } ### TODO: Fix me ### # Delegate: Create # Description: After saving the datasource, the file path is provided and an array # of variables set by the editor #$ExtensionManager->notifyMembers('Create', getCurrentPage(), array('file' => $file, 'defines' => $defines, 'var' => $var)); redirect(URL . '/symphony/blueprints/datasources/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/'); } } }