public function view()
 {
     // Ensure we have been set $_POST data from Members events
     if (!array_key_exists('members', $_POST)) {
         $this->setHttpStatus(self::HTTP_STATUS_BAD_REQUEST);
         return;
     } else {
         if (!is_writable(CONFIG)) {
             $this->setHttpStatus(self::HTTP_STATUS_ERROR);
             $this->_Result->appendChild(new XMLElement('message', __('The Symphony configuration file, <code>/manifest/config.php</code>, is not writable. You will not be able to save changes to preferences.')));
             return;
         }
     }
     $settings = $_POST['members'];
     // Generate Recovery Code
     if (isset($settings['generate-recovery-code-template'])) {
         Symphony::Configuration()->set('generate-recovery-code-template', implode(',', array_filter($settings['generate-recovery-code-template'])), 'members');
     } else {
         if ($settings['event'] == 'generate-recovery-code') {
             Symphony::Configuration()->remove('generate-recovery-code-template', 'members');
         }
     }
     // Reset Password
     if (isset($settings['reset-password-template'])) {
         Symphony::Configuration()->set('reset-password-template', implode(',', array_filter($settings['reset-password-template'])), 'members');
     } else {
         if ($settings['event'] == 'reset-password') {
             Symphony::Configuration()->remove('reset-password-template', 'members');
         }
     }
     if ($settings['event'] == 'reset-password') {
         Symphony::Configuration()->set('reset-password-auto-login', $settings['auto-login'], 'members');
     }
     // Regenerate Activation Code
     if (isset($settings['regenerate-activation-code-template'])) {
         Symphony::Configuration()->set('regenerate-activation-code-template', implode(',', array_filter($settings['regenerate-activation-code-template'])), 'members');
     } else {
         if ($settings['event'] == 'regenerate-activation-code') {
             Symphony::Configuration()->remove('regenerate-activation-code-template', 'members');
         }
     }
     // Activate Account
     if (isset($settings['activate-account-template'])) {
         Symphony::Configuration()->set('activate-account-template', implode(',', array_filter($settings['activate-account-template'])), 'members');
     } else {
         if ($settings['event'] == 'activate-account') {
             Symphony::Configuration()->remove('activate-account-template', 'members');
         }
     }
     if ($settings['event'] == 'activate-account') {
         Symphony::Configuration()->set('activate-account-auto-login', $settings['auto-login'], 'members');
     }
     // Return successful
     if (Symphony::Configuration()->write()) {
         $this->setHttpStatus(self::HTTP_STATUS_OK);
         $this->_Result->appendChild(new XMLElement('message', __('Preferences saved.')));
         $this->_Result->appendChild(new XMLElement('timestamp', '<![CDATA[' . Widget::Time(null, __SYM_TIME_FORMAT__)->generate() . ']]>'));
     }
 }
 public function __viewIndex()
 {
     $this->driver = ExtensionManager::create('globalresourceloader');
     $bIsWritable = true;
     if (!is_writable(CONFIG)) {
         $this->pageAlert(__('The Symphony configuration file, %s, is not writable. You will not be able to save changes to preferences.', array('<code>/manifest/config.php</code>')), Alert::ERROR);
         $bIsWritable = false;
     }
     if (isset($this->_context[1]) == 'saved') {
         $this->pageAlert(__('Global Resource Loader settings updated at %s.', array(Widget::Time()->generate())), Alert::SUCCESS);
     }
     $this->setPageType('form');
     $this->setTitle('Symphony &ndash; ' . __('Global Resources'));
     $this->appendSubheading(__('Global Resources'));
     // Events --------------------------------------------------------
     $container = new XMLElement('fieldset');
     $container->setAttribute('class', 'settings');
     $container->appendChild(new XMLElement('legend', __('Events')));
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $this->__viewIndexEventNames($group);
     $this->__viewIndexEventPages($group);
     $container->appendChild($group);
     $this->Form->appendChild($container);
     // Datasources --------------------------------------------------------
     $container = new XMLElement('fieldset');
     $container->setAttribute('class', 'settings');
     $container->appendChild(new XMLElement('legend', __('Datasources')));
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $this->__viewIndexDSNames($group);
     $this->__viewIndexDSPages($group);
     $container->appendChild($group);
     $this->Form->appendChild($container);
     //---------------------------------------------------------------------
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $attr = array('accesskey' => 's');
     if (!$bIsWritable) {
         $attr['disabled'] = 'disabled';
     }
     $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', $attr));
     $this->Form->appendChild($div);
 }
 public function __viewEdit()
 {
     $this->doTheEdit();
     if (!($role_id = $this->_context[1])) {
         redirect(Extension_Sections_Event::baseURL() . 'permissions/');
     }
     if (!($existing = RoleManager::fetch($role_id))) {
         throw new SymphonyErrorPage(__('The role you requested to edit does not exist.'), __('Role not found'), 'error');
     }
     // check if sections exist
     $sections = SectionManager::fetch();
     if (!is_array($sections) || empty($sections)) {
         return $this->Form->appendChild($this->buildErrorMessage(__('No sections found. <a href="%s">Create a new one?</a>', array(SYMPHONY_URL . '/blueprints/sections/new/'))));
     }
     // Add in custom assets
     Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/sections_event/assets/sections_event.permissions_single.css', 'screen', 111);
     Administration::instance()->Page->addScriptToHead(URL . '/extensions/sections_event/assets/sections_event.permissions_single.js', 114);
     // Append any Page Alerts from the form's
     if (isset($this->_context[2])) {
         switch ($this->_context[2]) {
             case 'saved':
                 $this->pageAlert(__('Role permissions updated at %1$s. <a href="%2$s" accesskey="a">View all Roles</a>', array($time = Widget::Time('', __SYM_TIME_FORMAT__)->generate(), Extension_Sections_Event::baseURL() . 'permissions/')), Alert::SUCCESS);
                 break;
         }
     }
     $this->setPageType('form');
     $this->setTitle(__('Symphony &ndash; Section permissions &ndash; ') . $existing->get('name'));
     $this->appendSubheading($existing->get('name'));
     if (isset($_POST['permissions'])) {
         $permissions = $_POST['permissions'];
     } else {
         $permissions = array();
         $permissions['fields'] = SE_PerMan::getCrud('field')->fetchAll($role_id);
         $permissions['sections'] = SE_PerMan::getCrud('section')->fetchAll($role_id);
     }
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Section permissions'), Extension_Sections_Event::baseURL() . 'permissions/')));
     $div = new XMLElement('div', null, array('class' => 'permissions clearfix'));
     $div->appendChild($this->buildSectionPermissions($role_id, $permissions));
     $div->appendChild($this->buildFieldPermissions($role_id, $permissions));
     $this->Form->appendChild($div);
     $this->Form->appendChild($this->buildActions());
 }
 public function __form()
 {
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert(__('An error occurred while processing this form. See below for details.'), Alert::ERROR);
         // These alerts are only valid if the form doesn't have errors
     } elseif (isset($this->_context[2])) {
         $time = Widget::Time();
         switch ($this->_context[2]) {
             case 'saved':
                 $message = __('Data Source updated at %s.', array($time->generate()));
                 break;
             case 'created':
                 $message = __('Data Source created at %s.', array($time->generate()));
         }
         $this->pageAlert($message . ' <a href="' . SYMPHONY_URL . '/blueprints/datasources/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/blueprints/datasources/" accesskey="a">' . __('View all Data Sources') . '</a>', Alert::SUCCESS);
     }
     $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::DATASOURCE);
     $isEditing = false;
     $about = $handle = null;
     $fields = array('name' => null, 'source' => null, 'filter' => null, 'required_url_param' => null, 'negate_url_param' => null, 'param' => null);
     if (isset($_POST['fields'])) {
         $fields = $_POST['fields'];
         if (!in_array($fields['source'], array('authors', 'navigation', 'static_xml')) && !empty($fields['filter']) && is_array($fields['filter'])) {
             $filters = array();
             foreach ($fields['filter'] as $f) {
                 foreach ($f as $key => $val) {
                     $filters[$key] = $val;
                 }
             }
             $fields['filter'][$fields['source']] = $filters;
         }
         if (!isset($fields['xml_elements']) || !is_array($fields['xml_elements'])) {
             $fields['xml_elements'] = array();
         }
         if ($this->_context[0] == 'edit') {
             $isEditing = true;
         }
     } elseif ($this->_context[0] == 'edit') {
         $isEditing = true;
         $handle = $this->_context[1];
         $existing = DatasourceManager::create($handle, array(), false);
         $order = isset($existing->dsParamORDER) ? $existing->dsParamORDER : 'asc';
         if (!$existing->allowEditorToParse()) {
             redirect(SYMPHONY_URL . '/blueprints/datasources/info/' . $handle . '/');
         }
         $about = $existing->about();
         $fields['name'] = $about['name'];
         $fields['order'] = $order == 'rand' ? 'random' : $order;
         $fields['param'] = isset($existing->dsParamPARAMOUTPUT) ? $existing->dsParamPARAMOUTPUT : null;
         $fields['required_url_param'] = isset($existing->dsParamREQUIREDPARAM) ? trim($existing->dsParamREQUIREDPARAM) : null;
         $fields['negate_url_param'] = isset($existing->dsParamNEGATEPARAM) ? trim($existing->dsParamNEGATEPARAM) : null;
         if (isset($existing->dsParamINCLUDEDELEMENTS) && is_array($existing->dsParamINCLUDEDELEMENTS)) {
             $fields['xml_elements'] = $existing->dsParamINCLUDEDELEMENTS;
         } else {
             $fields['xml_elements'] = array();
         }
         $fields['sort'] = isset($existing->dsParamSORT) ? $existing->dsParamSORT : null;
         $fields['paginate_results'] = isset($existing->dsParamPAGINATERESULTS) ? $existing->dsParamPAGINATERESULTS : 'yes';
         $fields['page_number'] = isset($existing->dsParamSTARTPAGE) ? $existing->dsParamSTARTPAGE : '1';
         $fields['group'] = isset($existing->dsParamGROUP) ? $existing->dsParamGROUP : null;
         $fields['html_encode'] = isset($existing->dsParamHTMLENCODE) ? $existing->dsParamHTMLENCODE : 'no';
         $fields['associated_entry_counts'] = isset($existing->dsParamASSOCIATEDENTRYCOUNTS) ? $existing->dsParamASSOCIATEDENTRYCOUNTS : 'no';
         $fields['redirect_on_empty'] = isset($existing->dsParamREDIRECTONEMPTY) ? $existing->dsParamREDIRECTONEMPTY : 'no';
         $fields['redirect_on_forbidden'] = isset($existing->dsParamREDIRECTONFORBIDDEN) ? $existing->dsParamREDIRECTONFORBIDDEN : 'no';
         $fields['redirect_on_required'] = isset($existing->dsParamREDIRECTONREQUIRED) ? $existing->dsParamREDIRECTONREQUIRED : 'no';
         if (!isset($existing->dsParamFILTERS) || !is_array($existing->dsParamFILTERS)) {
             $existing->dsParamFILTERS = array();
         }
         if (!empty($existing->dsParamFILTERS)) {
             $existing->dsParamFILTERS = array_map('stripslashes', $existing->dsParamFILTERS);
         }
         $fields['source'] = $existing->getSource();
         $provided = false;
         if (!empty($providers)) {
             foreach ($providers as $providerClass => $provider) {
                 if ($fields['source'] == call_user_func(array($providerClass, 'getClass'))) {
                     $fields = array_merge($fields, $existing->settings());
                     $provided = true;
                     break;
                 }
             }
         }
         if ($provided === false) {
             switch ($fields['source']) {
                 case 'authors':
                     $fields['filter']['author'] = $existing->dsParamFILTERS;
                     break;
                 case 'navigation':
                     $fields['filter']['navigation'] = $existing->dsParamFILTERS;
                     break;
                 case 'static_xml':
                     // Symphony 2.3+
                     if (isset($existing->dsParamSTATIC)) {
                         $fields['static_xml'] = trim($existing->dsParamSTATIC);
                         // Handle Symphony 2.2.2 to 2.3 DS's
                     } elseif (isset($existing->dsSTATIC)) {
                         $fields['static_xml'] = trim($existing->dsSTATIC);
                         // Handle pre Symphony 2.2.1 Static DS's
                     } else {
                         $fields['static_xml'] = trim($existing->grab());
                     }
                     break;
                 default:
                     $fields['filter'][$fields['source']] = $existing->dsParamFILTERS;
                     $fields['max_records'] = $existing->dsParamLIMIT;
                     break;
             }
         }
     } else {
         $fields['max_records'] = '20';
         $fields['page_number'] = '1';
         $fields['order'] = 'desc';
     }
     // Handle name on edited changes, or from reading an edited datasource
     if (isset($about['name'])) {
         $name = $about['name'];
     } elseif (isset($fields['name'])) {
         $name = $fields['name'];
     }
     $this->setPageType('form');
     $this->setTitle(__($isEditing ? '%1$s &ndash; %2$s &ndash; %3$s' : '%2$s &ndash; %3$s', array($name, __('Data Sources'), __('Symphony'))));
     $this->appendSubheading($isEditing ? $name : __('Untitled'));
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Data Sources'), SYMPHONY_URL . '/blueprints/datasources/')));
     // Sources
     $sources = new XMLElement('div', null, array('class' => 'apply actions'));
     $div = new XMLElement('div');
     $label = Widget::Label(__('Source'), null, 'apply-label-left');
     $sources->appendChild($label);
     $sources->appendChild($div);
     $sections = SectionManager::fetch(null, 'ASC', 'name');
     if (!is_array($sections)) {
         $sections = array();
     }
     $field_groups = array();
     foreach ($sections as $section) {
         $field_groups[$section->get('id')] = array('fields' => $section->fetchFields(), 'section' => $section);
     }
     $options = array(array('label' => __('System'), 'data-label' => 'system', 'options' => array(array('authors', $fields['source'] == 'authors', __('Authors'), null, null, array('data-context' => 'authors')), array('navigation', $fields['source'] == 'navigation', __('Navigation'), null, null, array('data-context' => 'navigation')))), array('label' => __('Custom XML'), 'data-label' => 'custom-xml', 'options' => array(array('static_xml', $fields['source'] == 'static_xml', __('Static XML'), null, null, array('data-context' => 'static-xml')))));
     // Loop over the datasource providers
     if (!empty($providers)) {
         $p = array('label' => __('From extensions'), 'data-label' => 'from_extensions', 'options' => array());
         foreach ($providers as $providerClass => $provider) {
             $p['options'][] = array($providerClass, $fields['source'] == $providerClass, $provider, null, null, array('data-context' => Lang::createHandle($provider)));
         }
         $options[] = $p;
     }
     // Add Sections
     if (is_array($sections) && !empty($sections)) {
         array_unshift($options, array('label' => __('Sections'), 'data-label' => 'sections', 'options' => array()));
         foreach ($sections as $s) {
             $options[0]['options'][] = array($s->get('id'), $fields['source'] == $s->get('id'), General::sanitize($s->get('name')));
         }
     }
     $div->appendChild(Widget::Select('source', $options, array('id' => 'ds-context')));
     $this->Context->prependChild($sources);
     $this->Form->appendChild(Widget::Input('fields[source]', null, 'hidden', array('id' => 'ds-source')));
     // Name
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
     $group = new XMLElement('div');
     $label = Widget::Label(__('Name'));
     $label->appendChild(Widget::Input('fields[name]', General::sanitize($fields['name'])));
     if (isset($this->_errors['name'])) {
         $group->appendChild(Widget::Error($label, $this->_errors['name']));
     } else {
         $group->appendChild($label);
     }
     $fieldset->appendChild($group);
     $this->Form->appendChild($fieldset);
     // Conditions
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections', 'system', 'custom-xml'));
     $fieldset->appendChild(new XMLElement('legend', __('Conditions')));
     $p = new XMLElement('p', __('Leaving these fields empty will always execute the data source.'));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $label = Widget::Label(__('Required Parameter'));
     $label->setAttribute('class', 'column ds-param');
     $label->appendChild(new XMLElement('i', __('Optional')));
     $input = Widget::Input('fields[required_url_param]', trim($fields['required_url_param']), 'text', array('placeholder' => __('$param'), 'data-search-types' => 'parameters', 'data-trigger' => '$'));
     $label->appendChild($input);
     $group->appendChild($label);
     $label = Widget::Label(__('Forbidden Parameter'));
     $label->setAttribute('class', 'column ds-param');
     $label->appendChild(new XMLElement('i', __('Optional')));
     $input = Widget::Input('fields[negate_url_param]', trim($fields['negate_url_param']), 'text', array('placeholder' => __('$param'), 'data-search-types' => 'parameters', 'data-trigger' => '$'));
     $label->appendChild($input);
     $group->appendChild($label);
     $fieldset->appendChild($group);
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns ds-param');
     $label = Widget::Checkbox('fields[redirect_on_required]', $fields['redirect_on_required'], __('Redirect to 404 page when the required parameter is not present'));
     $label->setAttribute('class', 'column');
     $group->appendChild($label);
     $label = Widget::Checkbox('fields[redirect_on_forbidden]', $fields['redirect_on_forbidden'], __('Redirect to 404 page when the forbidden parameter is present'));
     $label->setAttribute('class', 'column');
     $group->appendChild($label);
     $fieldset->appendChild($group);
     $label = Widget::Checkbox('fields[redirect_on_empty]', $fields['redirect_on_empty'], __('Redirect to 404 page when no results are found'));
     $label->setAttribute('class', 'column');
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     // Filters
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections', 'system'));
     $fieldset->appendChild(new XMLElement('legend', __('Filters')));
     $p = new XMLElement('p', __('Use %s syntax to filter by page parameters. A default value can be set using %s.', array('<code>{' . __('$param') . '}</code>', '<code>{' . __('$param:default') . '}</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     foreach ($field_groups as $section_id => $section_data) {
         $div = new XMLElement('div');
         $div->setAttribute('class', 'contextual frame filters-duplicator');
         $div->setAttribute('data-context', 'section-' . $section_id);
         $div->setAttribute('data-interactive', 'data-interactive');
         $ol = new XMLElement('ol');
         $ol->setAttribute('class', 'suggestable');
         $ol->setAttribute('data-interactive', 'data-interactive');
         $ol->setAttribute('data-add', __('Add filter'));
         $ol->setAttribute('data-remove', __('Remove filter'));
         // Add system:id filter
         if (isset($fields['filter'][$section_id]['system:id']) || isset($fields['filter'][$section_id]['id'])) {
             $id = isset($fields['filter'][$section_id]['system:id']) ? $fields['filter'][$section_id]['system:id'] : $fields['filter'][$section_id]['id'];
             $li = new XMLElement('li');
             $li->setAttribute('class', 'unique');
             $li->setAttribute('data-type', 'system:id');
             $li->appendChild(new XMLElement('header', '<h4>' . __('System ID') . '</h4>'));
             $label = Widget::Label(__('Value'));
             $input = Widget::Input('fields[filter][' . $section_id . '][system:id]', General::sanitize($id));
             $input->setAttribute('data-search-types', 'parameters');
             $input->setAttribute('data-trigger', '{$');
             $label->appendChild($input);
             $li->appendChild($label);
             $ol->appendChild($li);
         }
         $li = new XMLElement('li');
         $li->setAttribute('class', 'unique template');
         $li->setAttribute('data-type', 'system:id');
         $li->appendChild(new XMLElement('header', '<h4>' . __('System ID') . '</h4>'));
         $label = Widget::Label(__('Value'));
         $input = Widget::Input('fields[filter][' . $section_id . '][system:id]', General::sanitize($id));
         $input->setAttribute('data-search-types', 'parameters');
         $input->setAttribute('data-trigger', '{$');
         $label->appendChild($input);
         $li->appendChild($label);
         $ol->appendChild($li);
         // Add system:date filter
         if (isset($fields['filter'][$section_id]['system:creation-date']) || isset($fields['filter'][$section_id]['system:date'])) {
             $creation_date = isset($fields['filter'][$section_id]['system:creation-date']) ? $fields['filter'][$section_id]['system:creation-date'] : $fields['filter'][$section_id]['system:date'];
             $li = new XMLElement('li');
             $li->setAttribute('class', 'unique');
             $li->setAttribute('data-type', 'system:creation-date');
             $li->appendChild(new XMLElement('header', '<h4>' . __('System Creation Date') . '</h4>'));
             $label = Widget::Label(__('Value'));
             $input = Widget::Input('fields[filter][' . $section_id . '][system:creation-date]', General::sanitize($creation_date));
             $input->setAttribute('data-search-types', 'parameters');
             $input->setAttribute('data-trigger', '{$');
             $label->appendChild($input);
             $li->appendChild($label);
             $ol->appendChild($li);
         }
         $li = new XMLElement('li');
         $li->setAttribute('class', 'unique template');
         $li->setAttribute('data-type', 'system:creation-date');
         $li->appendChild(new XMLElement('header', '<h4>' . __('System Creation Date') . '</h4>'));
         $label = Widget::Label(__('Value'));
         $input = Widget::Input('fields[filter][' . $section_id . '][system:creation-date]');
         $input->setAttribute('data-search-types', 'parameters');
         $input->setAttribute('data-trigger', '{$');
         $label->appendChild($input);
         $li->appendChild($label);
         $ol->appendChild($li);
         if (isset($fields['filter'][$section_id]['system:modification-date'])) {
             $li = new XMLElement('li');
             $li->setAttribute('class', 'unique');
             $li->setAttribute('data-type', 'system:modification-date');
             $li->appendChild(new XMLElement('header', '<h4>' . __('System Modification Date') . '</h4>'));
             $label = Widget::Label(__('Value'));
             $input = Widget::Input('fields[filter][' . $section_id . '][system:modification-date]', General::sanitize($fields['filter'][$section_id]['system:modification-date']));
             $input->setAttribute('data-search-types', 'parameters');
             $input->setAttribute('data-trigger', '{$');
             $label->appendChild($input);
             $li->appendChild($label);
             $ol->appendChild($li);
         }
         $li = new XMLElement('li');
         $li->setAttribute('class', 'unique template');
         $li->setAttribute('data-type', 'system:modification-date');
         $li->appendChild(new XMLElement('header', '<h4>' . __('System Modification Date') . '</h4>'));
         $label = Widget::Label(__('Value'));
         $input = Widget::Input('fields[filter][' . $section_id . '][system:modification-date]');
         $input->setAttribute('data-search-types', 'parameters');
         $input->setAttribute('data-trigger', '{$');
         $label->appendChild($input);
         $li->appendChild($label);
         $ol->appendChild($li);
         if (is_array($section_data['fields']) && !empty($section_data['fields'])) {
             foreach ($section_data['fields'] as $field) {
                 if (!$field->canFilter()) {
                     continue;
                 }
                 if (isset($fields['filter'][$section_id], $fields['filter'][$section_id][$field->get('id')])) {
                     $wrapper = new XMLElement('li');
                     $wrapper->setAttribute('class', 'unique');
                     $wrapper->setAttribute('data-type', $field->get('element_name'));
                     $errors = isset($this->_errors[$field->get('id')]) ? $this->_errors[$field->get('id')] : array();
                     $field->displayDatasourceFilterPanel($wrapper, $fields['filter'][$section_id][$field->get('id')], $errors, $section_id);
                     $ol->appendChild($wrapper);
                 }
                 $wrapper = new XMLElement('li');
                 $wrapper->setAttribute('class', 'unique template');
                 $wrapper->setAttribute('data-type', $field->get('element_name'));
                 $field->displayDatasourceFilterPanel($wrapper, null, null, $section_id);
                 $ol->appendChild($wrapper);
             }
         }
         $div->appendChild($ol);
         $fieldset->appendChild($div);
     }
     $div = new XMLElement('div');
     $div->setAttribute('class', 'contextual frame filters-duplicator');
     $div->setAttribute('data-context', 'authors');
     $div->setAttribute('data-interactive', 'data-interactive');
     $ol = new XMLElement('ol');
     $ol->setAttribute('class', 'suggestable');
     $ol->setAttribute('data-interactive', 'data-interactive');
     $ol->setAttribute('data-add', __('Add filter'));
     $ol->setAttribute('data-remove', __('Remove filter'));
     if (!isset($fields['filter']['author'])) {
         $fields['filter']['author'] = array('id' => null, 'username' => null, 'first_name' => null, 'last_name' => null, 'email' => null, 'user_type' => null);
     }
     $this->__appendAuthorFilter($ol, __('ID'), 'id', $fields['filter']['author']['id'], !isset($fields['filter']['author']['id']));
     $this->__appendAuthorFilter($ol, __('Username'), 'username', $fields['filter']['author']['username'], !isset($fields['filter']['author']['username']));
     $this->__appendAuthorFilter($ol, __('First Name'), 'first_name', $fields['filter']['author']['first_name'], !isset($fields['filter']['author']['first_name']));
     $this->__appendAuthorFilter($ol, __('Last Name'), 'last_name', $fields['filter']['author']['last_name'], !isset($fields['filter']['author']['last_name']));
     $this->__appendAuthorFilter($ol, __('Email'), 'email', $fields['filter']['author']['email'], !isset($fields['filter']['author']['email']));
     $this->__appendAuthorFilter($ol, __('User Type'), 'user_type', $fields['filter']['author']['user_type'], !isset($fields['filter']['author']['user_type']));
     $div->appendChild($ol);
     $fieldset->appendChild($div);
     $div = new XMLElement('div');
     $div->setAttribute('class', 'contextual frame filters-duplicator');
     $div->setAttribute('data-context', 'navigation');
     $div->setAttribute('data-interactive', 'data-interactive');
     $ol = new XMLElement('ol');
     $ol->setAttribute('class', 'suggestable');
     $ol->setAttribute('data-interactive', 'data-interactive');
     $ol->setAttribute('data-add', __('Add filter'));
     $ol->setAttribute('data-remove', __('Remove filter'));
     $ul = new XMLElement('ul');
     $ul->setAttribute('class', 'tags');
     $ul->setAttribute('data-interactive', 'data-interactive');
     $pages = PageManager::fetch(false, array('*'), array(), 'title ASC');
     foreach ($pages as $page) {
         $ul->appendChild(new XMLElement('li', preg_replace('/\\/{2,}/i', '/', '/' . $page['path'] . '/' . $page['handle'])));
     }
     if (isset($fields['filter']['navigation']['parent'])) {
         $li = new XMLElement('li');
         $li->setAttribute('class', 'unique');
         $li->setAttribute('data-type', 'parent');
         $li->appendChild(new XMLElement('header', '<h4>' . __('Parent Page') . '</h4>'));
         $label = Widget::Label(__('Value'));
         $label->appendChild(Widget::Input('fields[filter][navigation][parent]', General::sanitize($fields['filter']['navigation']['parent'])));
         $li->appendChild($label);
         $li->appendChild($ul);
         $ol->appendChild($li);
     }
     $li = new XMLElement('li');
     $li->setAttribute('class', 'unique template');
     $li->setAttribute('data-type', 'parent');
     $li->appendChild(new XMLElement('header', '<h4>' . __('Parent Page') . '</h4>'));
     $label = Widget::Label(__('Value'));
     $label->appendChild(Widget::Input('fields[filter][navigation][parent]'));
     $li->appendChild($label);
     $li->appendChild($ul);
     $ol->appendChild($li);
     $ul = new XMLElement('ul');
     $ul->setAttribute('class', 'tags');
     $ul->setAttribute('data-interactive', 'data-interactive');
     if ($types = PageManager::fetchAvailablePageTypes()) {
         foreach ($types as $type) {
             $ul->appendChild(new XMLElement('li', $type));
         }
     }
     if (isset($fields['filter']['navigation']['type'])) {
         $li = new XMLElement('li');
         $li->setAttribute('class', 'unique');
         $li->setAttribute('data-type', 'type');
         $li->appendChild(new XMLElement('header', '<h4>' . __('Page Type') . '</h4>'));
         $label = Widget::Label(__('Value'));
         $label->appendChild(Widget::Input('fields[filter][navigation][type]', General::sanitize($fields['filter']['navigation']['type'])));
         $li->appendChild($label);
         $li->appendChild($ul);
         $ol->appendChild($li);
     }
     $li = new XMLElement('li');
     $li->setAttribute('class', 'unique template');
     $li->appendChild(new XMLElement('header', '<h4>' . __('Page Type') . '</h4>'));
     $li->setAttribute('data-type', 'type');
     $label = Widget::Label(__('Value'));
     $label->appendChild(Widget::Input('fields[filter][navigation][type]'));
     $li->appendChild($label);
     $li->appendChild($ul);
     $ol->appendChild($li);
     $div->appendChild($ol);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     // Sorting
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections', 'system'));
     $fieldset->appendChild(new XMLElement('legend', __('Sorting')));
     $p = new XMLElement('p', __('Use %s syntax to order by page parameters.', array('<code>{' . __('$param') . '}</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $div = new XMLElement('div');
     $label = Widget::Label(__('Sort By'));
     $options = array(array('label' => __('Authors'), 'data-label' => 'authors', 'options' => array(array('id', $fields['source'] == 'authors' && $fields['sort'] == 'id', __('Author ID')), array('username', $fields['source'] == 'authors' && $fields['sort'] == 'username', __('Username')), array('first-name', $fields['source'] == 'authors' && $fields['sort'] == 'first-name', __('First Name')), array('last-name', $fields['source'] == 'authors' && $fields['sort'] == 'last-name', __('Last Name')), array('email', $fields['source'] == 'authors' && $fields['sort'] == 'email', __('Email')), array('status', $fields['source'] == 'authors' && $fields['sort'] == 'status', __('Status')))), array('label' => __('Navigation'), 'data-label' => 'navigation', 'options' => array(array('id', $fields['source'] == 'navigation' && $fields['sort'] == 'id', __('Page ID')), array('handle', $fields['source'] == 'navigation' && $fields['sort'] == 'handle', __('Handle')), array('sortorder', $fields['source'] == 'navigation' && $fields['sort'] == 'sortorder', __('Sort Order')))));
     foreach ($field_groups as $section_id => $section_data) {
         $optgroup = array('label' => General::sanitize($section_data['section']->get('name')), 'data-label' => 'section-' . $section_data['section']->get('id'), 'options' => array(array('system:id', $fields['source'] == $section_id && $fields['sort'] == 'system:id', __('System ID')), array('system:creation-date', $fields['source'] == $section_id && ($fields['sort'] == 'system:creation-date' || $fields['sort'] == 'system:date'), __('System Creation Date')), array('system:modification-date', $fields['source'] == $section_id && $fields['sort'] == 'system:modification-date', __('System Modification Date'))));
         if (is_array($section_data['fields']) && !empty($section_data['fields'])) {
             foreach ($section_data['fields'] as $input) {
                 if (!$input->isSortable()) {
                     continue;
                 }
                 $optgroup['options'][] = array($input->get('element_name'), $fields['source'] == $section_id && $input->get('element_name') == $fields['sort'], $input->get('label'));
             }
         }
         $options[] = $optgroup;
     }
     $label->appendChild(Widget::Select('fields[sort]', $options));
     $div->appendChild($label);
     $label = Widget::Label(__('Sort Order'));
     $label->setAttribute('class', 'ds-param');
     $input = Widget::Input('fields[order]', $fields['order'], 'text', array('placeholder' => __('{$param}'), 'data-search-types' => 'parameters', 'data-trigger' => '{$'));
     $label->appendChild($input);
     $div->appendChild($label);
     $orders = new XMLElement('ul');
     $orders->setAttribute('class', 'tags singular');
     $orders->setAttribute('data-interactive', 'data-interactive');
     $orders->appendChild(new XMLElement('li', 'asc'));
     $orders->appendChild(new XMLElement('li', 'desc'));
     $orders->appendChild(new XMLElement('li', 'random'));
     $div->appendChild($orders);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     // Grouping
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections', 'authors'));
     $fieldset->appendChild(new XMLElement('legend', __('Grouping')));
     $label = Widget::Label(__('Group By'));
     $options = array(array('', null, __('None')));
     foreach ($field_groups as $section_id => $section_data) {
         $optgroup = array('label' => $section_data['section']->get('name'), 'data-label' => 'section-' . $section_data['section']->get('id'), 'options' => array());
         if (is_array($section_data['fields']) && !empty($section_data['fields'])) {
             foreach ($section_data['fields'] as $input) {
                 if (!$input->allowDatasourceOutputGrouping()) {
                     continue;
                 }
                 $optgroup['options'][] = array($input->get('id'), $fields['source'] == $section_id && $fields['group'] == $input->get('id'), $input->get('label'));
             }
         }
         $options[] = $optgroup;
     }
     $label->appendChild(Widget::Select('fields[group]', $options));
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     // Pagination
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections'));
     $fieldset->appendChild(new XMLElement('legend', __('Pagination')));
     $p = new XMLElement('p', __('Use %s syntax to limit by page parameters.', array('<code>{' . __('$param') . '}</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns pagination');
     $label = Widget::Label(__('Entries per Page'));
     $label->setAttribute('class', 'column ds-param');
     $input = Widget::Input('fields[max_records]', isset($fields['max_records']) ? $fields['max_records'] : '10', 'text', array('placeholder' => __('{$param}'), 'data-search-types' => 'parameters', 'data-trigger' => '{$'));
     $label->appendChild($input);
     $group->appendChild($label);
     $label = Widget::Label(__('Page Number'));
     $label->setAttribute('class', 'column ds-param');
     $input = Widget::Input('fields[page_number]', $fields['page_number'], 'text', array('placeholder' => __('{$param}'), 'data-search-types' => 'parameters', 'data-trigger' => '{$'));
     $label->appendChild($input);
     $group->appendChild($label);
     $fieldset->appendChild($group);
     $label = Widget::Checkbox('fields[paginate_results]', $fields['paginate_results'], __('Enable pagination'));
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     // Content
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('sections', 'authors'));
     $fieldset->appendChild(new XMLElement('legend', __('Content')));
     // XML
     $group = new XMLElement('div', null, array('class' => 'two columns'));
     $label = Widget::Label(__('Included Elements'));
     $label->setAttribute('class', 'column');
     $options = array(array('label' => __('Authors'), 'data-label' => 'authors', 'options' => array(array('username', $fields['source'] == 'authors' && in_array('username', $fields['xml_elements']), 'username'), array('name', $fields['source'] == 'authors' && in_array('name', $fields['xml_elements']), 'name'), array('email', $fields['source'] == 'authors' && in_array('email', $fields['xml_elements']), 'email'), array('author-token', $fields['source'] == 'authors' && in_array('author-token', $fields['xml_elements']), 'author-token'), array('default-area', $fields['source'] == 'authors' && in_array('default-area', $fields['xml_elements']), 'default-area'))));
     foreach ($field_groups as $section_id => $section_data) {
         $optgroup = array('label' => General::sanitize($section_data['section']->get('name')), 'data-label' => 'section-' . $section_data['section']->get('id'), 'options' => array(array('system:pagination', $fields['source'] == $section_id && in_array('system:pagination', $fields['xml_elements']), 'system: pagination'), array('system:date', $fields['source'] == $section_id && in_array('system:date', $fields['xml_elements']), 'system: date')));
         if (is_array($section_data['fields']) && !empty($section_data['fields'])) {
             foreach ($section_data['fields'] as $field) {
                 $elements = $field->fetchIncludableElements();
                 if (is_array($elements) && !empty($elements)) {
                     foreach ($elements as $name) {
                         $selected = false;
                         if ($fields['source'] == $section_id && in_array($name, $fields['xml_elements'])) {
                             $selected = true;
                         }
                         $optgroup['options'][] = array($name, $selected, $name);
                     }
                 }
             }
         }
         $options[] = $optgroup;
     }
     $label->appendChild(Widget::Select('fields[xml_elements][]', $options, array('multiple' => 'multiple')));
     $group->appendChild($label);
     // Support multiple parameters
     if (!isset($fields['param'])) {
         $fields['param'] = array();
     } elseif (!is_array($fields['param'])) {
         $fields['param'] = array($fields['param']);
     }
     $label = Widget::Label(__('Parameters'));
     $label->setAttribute('class', 'column');
     $prefix = '$ds-' . (isset($this->_context[1]) ? Lang::createHandle($fields['name']) : __('untitled')) . '.';
     $options = array(array('label' => __('Authors'), 'data-label' => 'authors', 'options' => array()));
     foreach (array('id', 'username', 'name', 'email', 'user_type') as $p) {
         $options[0]['options'][] = array($p, $fields['source'] == 'authors' && in_array($p, $fields['param']), $prefix . $p, null, null, array('data-handle' => $p));
     }
     foreach ($field_groups as $section_id => $section_data) {
         $optgroup = array('label' => $section_data['section']->get('name'), 'data-label' => 'section-' . $section_data['section']->get('id'), 'options' => array());
         foreach (array('id', 'creation-date', 'modification-date', 'author') as $p) {
             $option = array('system:' . $p, $fields['source'] == $section_id && in_array('system:' . $p, $fields['param']), $prefix . 'system-' . $p, null, null, array('data-handle' => 'system-' . $p));
             // Handle 'system:date' as an output paramater (backwards compatibility)
             if ($p === 'creation-date') {
                 if ($fields['source'] == $section_id && in_array('system:date', $fields['param'])) {
                     $option[1] = true;
                 }
             }
             $optgroup['options'][] = $option;
         }
         if (is_array($section_data['fields']) && !empty($section_data['fields'])) {
             foreach ($section_data['fields'] as $input) {
                 if (!$input->allowDatasourceParamOutput()) {
                     continue;
                 }
                 $optgroup['options'][] = array($input->get('element_name'), $fields['source'] == $section_id && in_array($input->get('element_name'), $fields['param']), $prefix . $input->get('element_name'), null, null, array('data-handle' => $input->get('element_name')));
             }
         }
         $options[] = $optgroup;
     }
     $label->appendChild(Widget::Select('fields[param][]', $options, array('multiple' => 'multiple')));
     $group->appendChild($label);
     $fieldset->appendChild($group);
     // Associations
     $label = Widget::Checkbox('fields[associated_entry_counts]', $fields['associated_entry_counts'], __('Include a count of entries in associated sections'));
     $this->setContext($label, array('sections'));
     $fieldset->appendChild($label);
     // Encoding
     $label = Widget::Checkbox('fields[html_encode]', $fields['html_encode'], __('HTML-encode text'));
     $this->setContext($label, array('sections'));
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     // Static XML
     if (!isset($fields['static_xml'])) {
         $fields['static_xml'] = null;
     }
     $fieldset = new XMLElement('fieldset');
     $this->setContext($fieldset, array('static-xml'));
     $fieldset->appendChild(new XMLElement('legend', __('Static XML')));
     $p = new XMLElement('p', __('Enter valid XML, exclude XML declaration'));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $label = Widget::Label();
     $label->appendChild(Widget::Textarea('fields[static_xml]', 12, 50, General::sanitize(stripslashes($fields['static_xml'])), array('class' => 'code', 'placeholder' => '<static>content</static>')));
     if (isset($this->_errors['static_xml'])) {
         $fieldset->appendChild(Widget::Error($label, $this->_errors['static_xml']));
     } else {
         $fieldset->appendChild($label);
     }
     $this->Form->appendChild($fieldset);
     // Connections
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Attach to Pages')));
     $p = new XMLElement('p', __('The data will only be available on the selected pages.'));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $div = new XMLElement('div');
     $label = Widget::Label(__('Pages'));
     $pages = PageManager::fetch();
     $ds_handle = str_replace('-', '_', Lang::createHandle($fields['name']));
     $connections = ResourceManager::getAttachedPages(ResourceManager::RESOURCE_TYPE_DS, $ds_handle);
     $selected = array();
     foreach ($connections as $connection) {
         $selected[] = $connection['id'];
     }
     $options = array();
     foreach ($pages as $page) {
         $options[] = array($page['id'], in_array($page['id'], $selected), PageManager::resolvePageTitle($page['id']));
     }
     $label->appendChild(Widget::Select('fields[connections][]', $options, array('multiple' => 'multiple')));
     $div->appendChild($label);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     // Call the provided datasources to let them inject their filters
     // @todo Ideally when a new Datasource is chosen an AJAX request will fire
     // to get the HTML from the extension. This is hardcoded for now into
     // creating a 'big' page and then hiding the fields with JS
     if (!empty($providers)) {
         foreach ($providers as $providerClass => $provider) {
             call_user_func_array(array($providerClass, 'buildEditor'), array($this->Form, &$this->_errors, $fields, $handle));
         }
     }
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $isEditing ? __('Save Changes') : __('Create Data Source'), 'submit', array('accesskey' => 's')));
     if ($isEditing) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this data source'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this data source?')));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
 }
 public function __viewEdit()
 {
     if (!($section_id = SectionManager::fetchIDFromHandle($this->_context['section_handle']))) {
         Administration::instance()->throwCustomError(__('The Section, %s, could not be found.', array('<code>' . $this->_context['section_handle'] . '</code>')), __('Unknown Section'), Page::HTTP_STATUS_NOT_FOUND);
     }
     $section = SectionManager::fetch($section_id);
     $entry_id = intval($this->_context['entry_id']);
     $base = '/publish/' . $this->_context['section_handle'] . '/';
     $new_link = $base . 'new/';
     $filter_link = $base;
     EntryManager::setFetchSorting('id', 'DESC');
     if (!($existingEntry = EntryManager::fetch($entry_id))) {
         Administration::instance()->throwCustomError(__('Unknown Entry'), __('The Entry, %s, could not be found.', array($entry_id)), Page::HTTP_STATUS_NOT_FOUND);
     }
     $existingEntry = $existingEntry[0];
     // If there is post data floating around, due to errors, create an entry object
     if (isset($_POST['fields'])) {
         $fields = $_POST['fields'];
         $entry = EntryManager::create();
         $entry->set('id', $entry_id);
         $entry->set('author_id', $existingEntry->get('author_id'));
         $entry->set('section_id', $existingEntry->get('section_id'));
         $entry->set('creation_date', $existingEntry->get('creation_date'));
         $entry->set('modification_date', $existingEntry->get('modification_date'));
         $entry->setDataFromPost($fields, $errors, true);
         // Editing an entry, so need to create some various objects
     } else {
         $entry = $existingEntry;
         $fields = array();
         if (!$section) {
             $section = SectionManager::fetch($entry->get('section_id'));
         }
     }
     /**
      * Just prior to rendering of an Entry edit form.
      *
      * @delegate EntryPreRender
      * @param string $context
      * '/publish/edit/'
      * @param Section $section
      * @param Entry $entry
      * @param array $fields
      */
     Symphony::ExtensionManager()->notifyMembers('EntryPreRender', '/publish/edit/', array('section' => $section, 'entry' => &$entry, 'fields' => $fields));
     // Iterate over the `prepopulate` parameters to build a URL
     // to remember this state for Create New, View all Entries and
     // Breadcrumb links. If `prepopulate` doesn't exist, this will
     // just use the standard pages (ie. no filtering)
     if (isset($_REQUEST['prepopulate'])) {
         $new_link .= $this->getPrepopulateString();
         $filter_link .= $this->getFilterString();
     }
     if (isset($this->_context['flag'])) {
         // These flags are only relevant if there are no errors
         if (empty($this->_errors)) {
             $time = Widget::Time();
             switch ($this->_context['flag']) {
                 case 'saved':
                     $message = __('Entry updated at %s.', array($time->generate()));
                     break;
                 case 'created':
                     $message = __('Entry created at %s.', array($time->generate()));
             }
             $this->pageAlert($message . ' <a href="' . SYMPHONY_URL . $new_link . '" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . $filter_link . '" accesskey="a">' . __('View all Entries') . '</a>', Alert::SUCCESS);
         }
     }
     // Determine the page title
     $field_id = Symphony::Database()->fetchVar('id', 0, sprintf("\n            SELECT `id`\n            FROM `tbl_fields`\n            WHERE `parent_section` = %d\n            ORDER BY `sortorder` LIMIT 1", $section->get('id')));
     if (!is_null($field_id)) {
         $field = FieldManager::fetch($field_id);
     }
     if ($field) {
         $title = $field->prepareReadableValue($existingEntry->getData($field->get('id')), $entry_id, true);
     } else {
         $title = '';
     }
     if (trim($title) == '') {
         $title = __('Untitled');
     }
     // Check if there is a field to prepopulate
     if (isset($_REQUEST['prepopulate'])) {
         foreach ($_REQUEST['prepopulate'] as $field_id => $value) {
             $this->Form->prependChild(Widget::Input("prepopulate[{$field_id}]", rawurlencode($value), 'hidden'));
         }
     }
     $this->setPageType('form');
     $this->Form->setAttribute('enctype', 'multipart/form-data');
     $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', array($title, $section->get('name'), __('Symphony'))));
     $sidebar_fields = $section->fetchFields(null, 'sidebar');
     $main_fields = $section->fetchFields(null, 'main');
     if (!empty($sidebar_fields) && !empty($main_fields)) {
         $this->Form->setAttribute('class', 'two columns');
     } else {
         $this->Form->setAttribute('class', 'columns');
     }
     // Only show the Edit Section button if the Author is a developer. #938 ^BA
     if (Symphony::Author()->isDeveloper()) {
         $this->appendSubheading($title, Widget::Anchor(__('Edit Section'), SYMPHONY_URL . '/blueprints/sections/edit/' . $section_id . '/', __('Edit Section Configuration'), 'button'));
     } else {
         $this->appendSubheading($title);
     }
     $this->insertBreadcrumbs(array(Widget::Anchor($section->get('name'), SYMPHONY_URL . (isset($filter_link) ? $filter_link : $base))));
     $this->Form->appendChild(Widget::Input('MAX_FILE_SIZE', Symphony::Configuration()->get('max_upload_size', 'admin'), 'hidden'));
     $primary = new XMLElement('fieldset');
     $primary->setAttribute('class', 'primary column');
     if ((!is_array($main_fields) || empty($main_fields)) && (!is_array($sidebar_fields) || empty($sidebar_fields))) {
         $message = __('Fields must be added to this section before an entry can be created.');
         if (Symphony::Author()->isDeveloper()) {
             $message .= ' <a href="' . SYMPHONY_URL . '/blueprints/sections/edit/' . $section->get('id') . '/" accesskey="c">' . __('Add fields') . '</a>';
         }
         $this->pageAlert($message, Alert::ERROR);
     } else {
         if (is_array($main_fields) && !empty($main_fields)) {
             foreach ($main_fields as $field) {
                 $primary->appendChild($this->__wrapFieldWithDiv($field, $entry));
             }
             $this->Form->appendChild($primary);
         }
         if (is_array($sidebar_fields) && !empty($sidebar_fields)) {
             $sidebar = new XMLElement('fieldset');
             $sidebar->setAttribute('class', 'secondary column');
             foreach ($sidebar_fields as $field) {
                 $sidebar->appendChild($this->__wrapFieldWithDiv($field, $entry));
             }
             $this->Form->appendChild($sidebar);
         }
         $div = new XMLElement('div');
         $div->setAttribute('class', 'actions');
         $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', array('accesskey' => 's')));
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this entry'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this entry?')));
         $div->appendChild($button);
         $this->Form->appendChild($div);
         // Create a Drawer for Associated Sections
         $this->prepareAssociationsDrawer($section);
     }
 }
 function __viewEdit($new = false)
 {
     $this->setPageType('form');
     if ($this->_context[2] == 'saved' || $this->_context[3] == 'saved') {
         $this->pageAlert(__(__('Email Sender updated at %1$s. <a href="%2$s" accesskey="c">Create another?</a> <a href="%3$s" accesskey="a">View all Senders</a>'), array(Widget::Time()->generate(), SYMPHONY_URL . '/extension/email_newsletter_manager/senders/new/', SYMPHONY_URL . '/extension/email_newsletter_manager/senders/')), Alert::SUCCESS);
     }
     $senders = new XMLElement('senders');
     $title = __('New Sender');
     $breadcrumbs = array(Widget::Anchor(__('Email Newsletter Senders'), SYMPHONY_URL . '/extension/email_newsletter_manager/senders/'));
     // Fix for 2.4 and XSRF
     if (Symphony::Configuration()->get("enable_xsrf", "symphony") == "yes" && class_exists('XSRF')) {
         $xsrf_input = new XMLElement('xsrf_input');
         $xsrf_input->appendChild(XSRF::formToken());
         $this->_XML->appendChild($xsrf_input);
     }
     if (!$new) {
         $sender = SenderManager::create($this->_context[1]);
         // Make sure the POSTED values are always shown when present.
         // This will make sure the form is always up-to-date, even where there are errors.
         if (!empty($_POST['fields']) && !empty($_POST['settings'])) {
             $posted_array = $_POST['fields'];
             $posted_array[$_POST['settings']['gateway']] = $_POST['settings']['email_' . $_POST['settings']['gateway']];
         }
         $about = empty($_POST['fields']) && empty($_POST['settings']) ? (array) $sender->about() : $posted_array;
         $about['handle'] = Lang::createHandle($about['name'], 225, '-');
         $entry = new XMLElement('entry');
         General::array_to_xml($entry, $about);
         $senders->appendChild($entry);
         $title = $about['name'];
         //$breadcrumbs[] = Widget::Anchor('hi', SYMPHONY_URL . '/extension/email_newsletter_manager/senders/edit/' . $sender->getHandle());
     }
     $el_gateways = new XMLElement('gateways');
     $gateways = EmailGatewayManager::listAll();
     foreach ($gateways as $gateway) {
         // to be removed in later versions. Right now only smtp and sendmail are supported.
         if (in_array($gateway['handle'], array('smtp', 'sendmail', 'amazon_ses'))) {
             $gw = EmailGatewayManager::create($gateway['handle']);
             if (!empty($about[$gateway['handle']])) {
                 $config = $about[$gateway['handle']];
                 if ($gateway['handle'] == 'smtp') {
                     $gw->setFrom($config['from_address'], $config['from_name']);
                     $gw->setHost($config['host']);
                     $gw->setSecure($config['secure']);
                     $gw->setPort($config['port']);
                     $gw->setAuth($config['auth']);
                     $gw->setUser($config['username']);
                     $gw->setPass($config['password']);
                 }
                 if ($gateway['handle'] == 'amazon_ses') {
                     $gw->setFrom($config['from_address'], $config['from_name']);
                     $gw->setAwsKey($config['aws_key']);
                     $gw->setAwsSecretKey($config['aws_secret_key']);
                     $gw->setFallback($config['fallback']);
                     $gw->setReturnPath($config['return_path']);
                 }
                 if ($gateway['handle'] == 'sendmail') {
                     $gw->setFrom($config['from_address'], $config['from_name']);
                 }
             }
             $entry = new XMLElement('entry');
             General::array_to_xml($entry, $gateway);
             $config_panel = new XMLElement('config_panel');
             $config_panel->appendChild($gw->getPreferencesPane());
             $entry->appendChild($config_panel);
             $el_gateways->appendChild($entry);
         }
     }
     $senders->appendChild($el_gateways);
     $this->insertBreadcrumbs($breadcrumbs);
     $this->appendSubheading($title);
     $this->_XML->appendChild($senders);
 }
 public function __form()
 {
     // Handle unknown context
     if (!in_array($this->_context[0], array('new', 'edit'))) {
         Administration::instance()->errorPageNotFound();
     }
     if ($this->_context[0] == 'new' && !Symphony::Author()->isDeveloper() && !Symphony::Author()->isManager()) {
         Administration::instance()->throwCustomError(__('You are not authorised to access this page.'), __('Access Denied'), Page::HTTP_STATUS_UNAUTHORIZED);
     }
     if (isset($this->_context[2])) {
         $time = Widget::Time();
         switch ($this->_context[2]) {
             case 'saved':
                 $message = __('Author updated at %s.', array($time->generate()));
                 break;
             case 'created':
                 $message = __('Author created at %s.', array($time->generate()));
         }
         $this->pageAlert($message . ' <a href="' . SYMPHONY_URL . '/system/authors/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/system/authors/" accesskey="a">' . __('View all Authors') . '</a>', Alert::SUCCESS);
     }
     $this->setPageType('form');
     $isOwner = false;
     $isEditing = $this->_context[0] == 'edit';
     if (isset($_POST['fields'])) {
         $author = $this->_Author;
     } elseif ($this->_context[0] == 'edit') {
         if (!($author_id = (int) $this->_context[1])) {
             redirect(SYMPHONY_URL . '/system/authors/');
         }
         if (!($author = AuthorManager::fetchByID($author_id))) {
             Administration::instance()->throwCustomError(__('The author profile you requested does not exist.'), __('Author not found'), Page::HTTP_STATUS_NOT_FOUND);
         }
     } else {
         $author = new Author();
     }
     if ($isEditing && $author->get('id') == Symphony::Author()->get('id')) {
         $isOwner = true;
     }
     if ($isEditing && !$isOwner && !Symphony::Author()->isDeveloper() && !Symphony::Author()->isManager()) {
         Administration::instance()->throwCustomError(__('You are not authorised to edit other authors.'), __('Access Denied'), Page::HTTP_STATUS_FORBIDDEN);
     }
     $this->setTitle(__($this->_context[0] == 'new' ? '%2$s &ndash; %3$s' : '%1$s &ndash; %2$s &ndash; %3$s', array($author->getFullName(), __('Authors'), __('Symphony'))));
     $this->appendSubheading($this->_context[0] == 'new' ? __('Untitled') : $author->getFullName());
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Authors'), SYMPHONY_URL . '/system/authors/')));
     // Essentials
     $group = new XMLElement('fieldset');
     $group->setAttribute('class', 'settings');
     $group->appendChild(new XMLElement('legend', __('Essentials')));
     $div = new XMLElement('div');
     $div->setAttribute('class', 'two columns');
     $label = Widget::Label(__('First Name'), null, 'column');
     $label->appendChild(Widget::Input('fields[first_name]', $author->get('first_name')));
     $div->appendChild(isset($this->_errors['first_name']) ? Widget::Error($label, $this->_errors['first_name']) : $label);
     $label = Widget::Label(__('Last Name'), null, 'column');
     $label->appendChild(Widget::Input('fields[last_name]', $author->get('last_name')));
     $div->appendChild(isset($this->_errors['last_name']) ? Widget::Error($label, $this->_errors['last_name']) : $label);
     $group->appendChild($div);
     $label = Widget::Label(__('Email Address'));
     $label->appendChild(Widget::Input('fields[email]', $author->get('email'), 'text', array('autocomplete' => 'off')));
     $group->appendChild(isset($this->_errors['email']) ? Widget::Error($label, $this->_errors['email']) : $label);
     $this->Form->appendChild($group);
     // Login Details
     $group = new XMLElement('fieldset');
     $group->setAttribute('class', 'settings');
     $group->appendChild(new XMLElement('legend', __('Login Details')));
     $div = new XMLElement('div');
     $label = Widget::Label(__('Username'));
     $label->appendChild(Widget::Input('fields[username]', $author->get('username'), 'text', array('autocomplete' => 'off')));
     $div->appendChild(isset($this->_errors['username']) ? Widget::Error($label, $this->_errors['username']) : $label);
     // Only developers can change the user type. Primary account should NOT be able to change this
     if ((Symphony::Author()->isDeveloper() || Symphony::Author()->isManager()) && !$author->isPrimaryAccount()) {
         // Create columns
         $div->setAttribute('class', 'two columns');
         $label->setAttribute('class', 'column');
         // User type
         $label = Widget::Label(__('User Type'), null, 'column');
         $options = array(array('author', false, __('Author')), array('manager', $author->isManager(), __('Manager')));
         if (Symphony::Author()->isDeveloper()) {
             $options[] = array('developer', $author->isDeveloper(), __('Developer'));
         }
         $label->appendChild(Widget::Select('fields[user_type]', $options));
         $div->appendChild($label);
     }
     $group->appendChild($div);
     // Password
     $fieldset = new XMLElement('fieldset', null, array('class' => 'two columns', 'id' => 'password'));
     $legend = new XMLElement('legend', __('Password'));
     $help = new XMLElement('i', __('Leave password fields blank to keep the current password'));
     $fieldset->appendChild($legend);
     $fieldset->appendChild($help);
     /*
         Password reset rules:
         - Primary account can edit all accounts.
         - Developers can edit all developers, managers and authors, and their own.
         - Managers can edit all Authors, and their own.
         - Authors can edit their own.
     */
     if ($isEditing && !($isOwner || Symphony::Author()->isManager() && $author->isAuthor() || Symphony::Author()->isPrimaryAccount() || Symphony::Author()->isDeveloper() && $author->isPrimaryAccount() === false)) {
         $fieldset->setAttribute('class', 'three columns');
         $label = Widget::Label(null, null, 'column');
         $label->appendChild(Widget::Input('fields[old-password]', null, 'password', array('placeholder' => __('Old Password'), 'autocomplete' => 'off')));
         $fieldset->appendChild(isset($this->_errors['old-password']) ? Widget::Error($label, $this->_errors['old-password']) : $label);
     }
     // New password
     $placeholder = $isEditing ? __('New Password') : __('Password');
     $label = Widget::Label(null, null, 'column');
     $label->appendChild(Widget::Input('fields[password]', null, 'password', array('placeholder' => $placeholder, 'autocomplete' => 'off')));
     $fieldset->appendChild(isset($this->_errors['password']) ? Widget::Error($label, $this->_errors['password']) : $label);
     // Confirm password
     $label = Widget::Label(null, null, 'column');
     $label->appendChild(Widget::Input('fields[password-confirmation]', null, 'password', array('placeholder' => __('Confirm Password'), 'autocomplete' => 'off')));
     $fieldset->appendChild(isset($this->_errors['password-confirmation']) ? Widget::Error($label, $this->_errors['password']) : $label);
     $group->appendChild($fieldset);
     // Auth token
     if (Symphony::Author()->isDeveloper() || Symphony::Author()->isManager()) {
         $label = Widget::Label();
         $group->appendChild(Widget::Input('fields[auth_token_active]', 'no', 'hidden'));
         $input = Widget::Input('fields[auth_token_active]', 'yes', 'checkbox');
         if ($author->isTokenActive()) {
             $input->setAttribute('checked', 'checked');
         }
         $temp = SYMPHONY_URL . '/login/' . $author->createAuthToken() . '/';
         $label->setValue(__('%s Allow remote login via', array($input->generate())) . ' <a href="' . $temp . '">' . $temp . '</a>');
         $group->appendChild($label);
     }
     $label = Widget::Label(__('Default Area'));
     $sections = SectionManager::fetch(null, 'ASC', 'sortorder');
     $options = array();
     // If the Author is the Developer, allow them to set the Default Area to
     // be the Sections Index.
     if ($author->isDeveloper()) {
         $options[] = array('/blueprints/sections/', $author->get('default_area') == '/blueprints/sections/', __('Sections Index'));
     }
     if (is_array($sections) && !empty($sections)) {
         foreach ($sections as $s) {
             $options[] = array($s->get('id'), $author->get('default_area') == $s->get('id'), $s->get('name'));
         }
     }
     /**
      * Allows injection or manipulation of the Default Area dropdown for an Author.
      * Take care with adding in options that are only valid for Developers, as if a
      * normal Author is set to that option, they will be redirected to their own
      * Author record.
      *
      *
      * @delegate AddDefaultAuthorAreas
      * @since Symphony 2.2
      * @param string $context
      * '/system/authors/'
      * @param array $options
      * An associative array of options, suitable for use for the Widget::Select
      * function. By default this will be an array of the Sections in the current
      * installation. New options should be the path to the page after the `SYMPHONY_URL`
      * constant.
      * @param string $default_area
      * The current `default_area` for this Author.
      */
     Symphony::ExtensionManager()->notifyMembers('AddDefaultAuthorAreas', '/system/authors/', array('options' => &$options, 'default_area' => $author->get('default_area')));
     $label->appendChild(Widget::Select('fields[default_area]', $options));
     $group->appendChild($label);
     $this->Form->appendChild($group);
     // Custom Language Selection
     $languages = Lang::getAvailableLanguages();
     if (count($languages) > 1) {
         // Get language names
         asort($languages);
         $group = new XMLElement('fieldset');
         $group->setAttribute('class', 'settings');
         $group->appendChild(new XMLElement('legend', __('Custom Preferences')));
         $label = Widget::Label(__('Language'));
         $options = array(array(null, is_null($author->get('language')), __('System Default')));
         foreach ($languages as $code => $name) {
             $options[] = array($code, $code == $author->get('language'), $name);
         }
         $select = Widget::Select('fields[language]', $options);
         $label->appendChild($select);
         $group->appendChild($label);
         $this->Form->appendChild($group);
     }
     // Administration password double check
     if ($isEditing && !$isOwner) {
         $group = new XMLElement('fieldset');
         $group->setAttribute('class', 'settings');
         $group->setAttribute('id', 'confirmation');
         $group->appendChild(new XMLElement('legend', __('Confirmation')));
         $group->appendChild(new XMLELement('p', __('Please confirm changes to this author with your password.'), array('class' => 'help')));
         $label = Widget::Label(__('Password'));
         $label->appendChild(Widget::Input('fields[confirm-change-password]', null, 'password', array('autocomplete' => 'off', 'placeholder' => __('Your Password'))));
         $group->appendChild(isset($this->_errors['confirm-change-password']) ? Widget::Error($label, $this->_errors['confirm-change-password']) : $label);
         $this->Form->appendChild($group);
     }
     // Actions
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $this->_context[0] == 'edit' ? __('Save Changes') : __('Create Author'), 'submit', array('accesskey' => 's')));
     if ($isEditing && !$isOwner && !$author->isPrimaryAccount()) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this author'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this author?')));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
     /**
      * Allows the injection of custom form fields given the current `$this->Form`
      * object. Please note that this custom data should be saved in own extension
      * tables and that modifying `tbl_authors` to house your data is highly discouraged.
      *
      * @delegate AddElementstoAuthorForm
      * @since Symphony 2.2
      * @param string $context
      * '/system/authors/'
      * @param XMLElement $form
      * The contents of `$this->Form` after all the default form elements have been appended.
      * @param Author $author
      * The current Author object that is being edited
      */
     Symphony::ExtensionManager()->notifyMembers('AddElementstoAuthorForm', '/system/authors/', array('form' => &$this->Form, 'author' => $author));
 }
 public function dAppendPageAlert()
 {
     $callback = Administration::instance()->getPageCallback();
     // manipulate success message
     if (in_array($callback['context']['page'], array('new', 'edit'))) {
         $flag_create = false;
         $flag_all = false;
         // if entry was created or saved
         if (isset($callback['context']['flag'])) {
             // if there is a limit
             if ($this->_max > 0) {
                 $flag_create = true;
                 // if not static section
                 if ($this->_max > 1) {
                     $flag_all = true;
                 }
             }
         }
         // if the status message must be changed
         if ($flag_create || $flag_all) {
             $alerts = Administration::instance()->Page->Alert;
             // remove old message
             foreach ($alerts as $key => $alert) {
                 /** @var $alert Alert */
                 if ($alert->type === Alert::SUCCESS) {
                     unset($alerts[$key]);
                 }
             }
             $msg_create = '';
             $msg_all = '';
             // create / update message
             if ($flag_create === true) {
                 switch ($callback['context']['flag']) {
                     case 'saved':
                         $msg_create = __('Entry updated at %s.', array(Widget::Time('now')->generate()));
                         break;
                     case 'created':
                         $msg_create = __('Entry created at %s.', array(Widget::Time('now')->generate()));
                         break;
                 }
             }
             // view all message
             if ($flag_all === true) {
                 $link = '/publish/' . $callback['context']['section_handle'] . '/';
                 $msg_all = ' <a href="' . SYMPHONY_URL . $link . '" accesskey="a">' . __('View all Entries') . '</a>';
             }
             // append alert
             $alerts[] = new Alert($msg_create . $msg_all, Alert::SUCCESS);
             // replace Alerts
             Administration::instance()->Page->Alert = $alerts;
         }
     }
 }
 public function __form($readonly = false)
 {
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert(__('An error occurred while processing this form. See below for details.'), Alert::ERROR);
         // These alerts are only valid if the form doesn't have errors
     } elseif (isset($this->_context[2])) {
         $time = Widget::Time();
         switch ($this->_context[2]) {
             case 'saved':
                 $this->pageAlert(__('Event updated at %s.', array($time->generate())) . ' <a href="' . SYMPHONY_URL . '/blueprints/events/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/blueprints/events/" accesskey="a">' . __('View all Events') . '</a>', Alert::SUCCESS);
                 break;
             case 'created':
                 $this->pageAlert(__('Event created at %s.', array($time->generate())) . ' <a href="' . SYMPHONY_URL . '/blueprints/events/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/blueprints/events/" accesskey="a">' . __('View all Events') . '</a>', Alert::SUCCESS);
                 break;
         }
     }
     $isEditing = $readonly ? true : false;
     $fields = array("name" => null, "filters" => null);
     $about = array("name" => null);
     $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::EVENT);
     if (isset($_POST['fields'])) {
         $fields = $_POST['fields'];
         if ($this->_context[0] == 'edit') {
             $isEditing = true;
         }
     } elseif ($this->_context[0] == 'edit' || $this->_context[0] == 'info') {
         $isEditing = true;
         $handle = $this->_context[1];
         $existing = EventManager::create($handle);
         $about = $existing->about();
         if ($this->_context[0] == 'edit' && !$existing->allowEditorToParse()) {
             redirect(SYMPHONY_URL . '/blueprints/events/info/' . $handle . '/');
         }
         $fields['name'] = $about['name'];
         $fields['source'] = $existing->getSource();
         $provided = false;
         if (!empty($providers)) {
             foreach ($providers as $providerClass => $provider) {
                 if ($fields['source'] == call_user_func(array($providerClass, 'getClass'))) {
                     $fields = array_merge($fields, $existing->settings());
                     $provided = true;
                     break;
                 }
             }
         }
         if (!$provided) {
             if (isset($existing->eParamFILTERS)) {
                 $fields['filters'] = $existing->eParamFILTERS;
             }
         }
     }
     // Handle name on edited changes, or from reading an edited datasource
     if (isset($about['name'])) {
         $name = $about['name'];
     } elseif (isset($fields['name'])) {
         $name = $fields['name'];
     }
     $this->setPageType('form');
     $this->setTitle(__($isEditing ? '%1$s &ndash; %2$s &ndash; %3$s' : '%2$s &ndash; %3$s', array($about['name'], __('Events'), __('Symphony'))));
     $this->appendSubheading($isEditing ? $about['name'] : __('Untitled'));
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Events'), SYMPHONY_URL . '/blueprints/events/')));
     if (!$readonly) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
         // Target
         $sources = new XMLElement('div', null, array('class' => 'apply actions'));
         $div = new XMLElement('div');
         $label = Widget::Label(__('Target'), null, 'apply-label-left');
         $sources->appendChild($label);
         $sources->appendChild($div);
         $sections = SectionManager::fetch(null, 'ASC', 'name');
         $options = array();
         $section_options = array();
         $source = isset($fields['source']) ? $fields['source'] : null;
         if (is_array($sections) && !empty($sections)) {
             $section_options = array('label' => __('Sections'), 'options' => array());
             foreach ($sections as $s) {
                 $section_options['options'][] = array($s->get('id'), $source == $s->get('id'), General::sanitize($s->get('name')));
             }
         }
         $options[] = $section_options;
         // Loop over the event providers
         if (!empty($providers)) {
             $p = array('label' => __('From extensions'), 'options' => array());
             foreach ($providers as $providerClass => $provider) {
                 $p['options'][] = array($providerClass, $fields['source'] == $providerClass, $provider);
             }
             $options[] = $p;
         }
         $div->appendChild(Widget::Select('source', $options, array('id' => 'event-context')));
         if (isset($this->_errors['source'])) {
             $this->Context->prependChild(Widget::Error($sources, $this->_errors['source']));
         } else {
             $this->Context->prependChild($sources);
         }
         $this->Form->appendChild(Widget::Input('fields[source]', $options[0]['options'][0][0], 'hidden', array('id' => 'event-source')));
         // Name
         $group = new XMLElement('div');
         $label = Widget::Label(__('Name'));
         $label->appendChild(Widget::Input('fields[name]', General::sanitize($fields['name'])));
         $div = new XMLElement('div');
         $div->setAttribute('class', 'column');
         if (isset($this->_errors['name'])) {
             $div->appendChild(Widget::Error($label, $this->_errors['name']));
         } else {
             $div->appendChild($label);
         }
         $group->appendChild($div);
         $fieldset->appendChild($group);
         $this->Form->appendChild($fieldset);
         // Filters
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings pickable');
         $fieldset->appendChild(new XMLElement('legend', __('Filters')));
         $p = new XMLElement('p', __('Event Filters add additional conditions or actions to an event.'));
         $p->setAttribute('class', 'help');
         $fieldset->appendChild($p);
         $filters = isset($fields['filters']) ? $fields['filters'] : array();
         $options = array(array('admin-only', in_array('admin-only', $filters), __('Admin Only')), array('send-email', in_array('send-email', $filters), __('Send Notification Email')), array('expect-multiple', in_array('expect-multiple', $filters), __('Allow Multiple')));
         /**
          * Allows adding of new filter rules to the Event filter rule select box
          *
          * @delegate AppendEventFilter
          * @param string $context
          * '/blueprints/events/(edit|new|info)/'
          * @param array $selected
          *  An array of all the selected filters for this Event
          * @param array $options
          *  An array of all the filters that are available, passed by reference
          */
         Symphony::ExtensionManager()->notifyMembers('AppendEventFilter', '/blueprints/events/' . $this->_context[0] . '/', array('selected' => $filters, 'options' => &$options));
         $fieldset->appendChild(Widget::Select('fields[filters][]', $options, array('multiple' => 'multiple', 'id' => 'event-filters')));
         $this->Form->appendChild($fieldset);
         // Connections
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', __('Attach to Pages')));
         $p = new XMLElement('p', __('The event will only be available on the selected pages.'));
         $p->setAttribute('class', 'help');
         $fieldset->appendChild($p);
         $div = new XMLElement('div');
         $label = Widget::Label(__('Pages'));
         $pages = PageManager::fetch();
         $event_handle = str_replace('-', '_', Lang::createHandle($fields['name']));
         $connections = ResourceManager::getAttachedPages(RESOURCE_TYPE_EVENT, $event_handle);
         $selected = array();
         foreach ($connections as $connection) {
             $selected[] = $connection['id'];
         }
         $options = array();
         foreach ($pages as $page) {
             $options[] = array($page['id'], in_array($page['id'], $selected), PageManager::resolvePageTitle($page['id']));
         }
         $label->appendChild(Widget::Select('fields[connections][]', $options, array('multiple' => 'multiple')));
         $div->appendChild($label);
         $fieldset->appendChild($div);
         $this->Form->appendChild($fieldset);
         // Providers
         if (!empty($providers)) {
             foreach ($providers as $providerClass => $provider) {
                 if ($isEditing && $fields['source'] !== call_user_func(array($providerClass, 'getSource'))) {
                     continue;
                 }
                 call_user_func_array(array($providerClass, 'buildEditor'), array($this->Form, &$this->_errors, $fields, $handle));
             }
         }
     } else {
         // Author
         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']);
         } else {
             $link = $about['author']['name'];
         }
         if ($link) {
             $fieldset = new XMLElement('fieldset');
             $fieldset->setAttribute('class', 'settings');
             $fieldset->appendChild(new XMLElement('legend', __('Author')));
             $fieldset->appendChild(new XMLElement('p', $link->generate(false)));
             $this->Form->appendChild($fieldset);
         }
         // Version
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', __('Version')));
         $version = array_key_exists('version', $about) ? $about['version'] : null;
         $release_date = array_key_exists('release-date', $about) ? $about['release-date'] : filemtime(EventManager::__getDriverPath($handle));
         if (preg_match('/^\\d+(\\.\\d+)*$/', $version)) {
             $fieldset->appendChild(new XMLElement('p', __('%1$s released on %2$s', array($version, DateTimeObj::format($release_date, __SYM_DATE_FORMAT__)))));
         } elseif (!is_null($version)) {
             $fieldset->appendChild(new XMLElement('p', __('Created by %1$s at %2$s', array($version, DateTimeObj::format($release_date, __SYM_DATE_FORMAT__)))));
         } else {
             $fieldset->appendChild(new XMLElement('p', __('Last modified on %s', array(DateTimeObj::format($release_date, __SYM_DATE_FORMAT__)))));
         }
         $this->Form->appendChild($fieldset);
     }
     // If we are editing an event, it assumed that the event has documentation
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('id', 'event-documentation');
     $fieldset->setAttribute('class', 'settings');
     if ($isEditing && method_exists($existing, 'documentation')) {
         $doc = $existing->documentation();
         if ($doc) {
             $fieldset->setValue('<legend>' . __('Documentation') . '</legend>' . PHP_EOL . General::tabsToSpaces(is_object($doc) ? $doc->generate(true, 4) : $doc));
         }
     }
     $this->Form->appendChild($fieldset);
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $isEditing ? __('Save Changes') : __('Create Event'), 'submit', array('accesskey' => 's')));
     if ($isEditing) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this event'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this event?')));
         $div->appendChild($button);
     }
     if (!$readonly) {
         $this->Form->appendChild($div);
     }
 }
 /**
  * A wrapper for get, this function will return a HTML string representing
  * an `<abbr>` element which contained the formatted date of now, and an
  * RFC 2822 formatted date (Thu, 21 Dec 2000 16:01:07 +0200) as the title
  * attribute. Symphony uses this in it's status messages so that it can
  * dynamically update how long ago the action took place using Javascript.
  *
  * @deprecated This will be removed in the next version of Symphony
  * @param string $format
  *  A valid PHP date format
  * @return string
  *  A HTML string of an `<abbr>` element with a class of 'timeago' and the current
  *  date (RFC 2822) as the title element. The value is the current time as
  *  specified by the `$format`.
  */
 public static function getTimeAgo($format = __SYM_TIME_FORMAT__)
 {
     $time = Widget::Time($string, $format);
     return $time->generate();
 }
 public function __viewEdit()
 {
     $isNew = true;
     $time = Widget::Time();
     // Verify role exists
     if ($this->_context[0] == 'edit') {
         $isNew = false;
         if (!($role_id = $this->_context[1])) {
             redirect(extension_Members::baseURL() . 'roles/');
         }
         if (!($existing = RoleManager::fetch($role_id))) {
             throw new SymphonyErrorPage(__('The role you requested to edit does not exist.'), __('Role not found'));
         }
     }
     // Add in custom assets
     Administration::instance()->Page->addStylesheetToHead(URL . '/extensions/members/assets/members.roles.css', 'screen', 101);
     Administration::instance()->Page->addScriptToHead(URL . '/extensions/members/assets/members.roles.js', 104);
     // Append any Page Alerts from the form's
     if (isset($this->_context[2])) {
         switch ($this->_context[2]) {
             case 'saved':
                 $this->pageAlert(__('Role updated at %s.', array($time->generate())) . ' <a href="' . extension_members::baseURL() . 'roles/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . extension_members::baseURL() . 'roles/" accesskey="a">' . __('View all Roles') . '</a>', Alert::SUCCESS);
                 break;
             case 'created':
                 $this->pageAlert(__('Role created at %s.', array($time->generate())) . ' <a href="' . extension_members::baseURL() . 'roles/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . extension_members::baseURL() . 'roles/" accesskey="a">' . __('View all Roles') . '</a>', Alert::SUCCESS);
                 break;
         }
     }
     // Has the form got any errors?
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert(__('An error occurred while processing this form. <a href="#error">See below for details.</a>'), Alert::ERROR);
     }
     $this->setPageType('form');
     if ($isNew) {
         $this->setTitle(__('Symphony &ndash; Member Roles'));
         $this->appendSubheading(__('Untitled'));
         $fields = array('name' => null, 'permissions' => null, 'page_access' => null);
     } else {
         $this->setTitle(__('Symphony &ndash; Member Roles &ndash; ') . $existing->get('name'));
         $this->appendSubheading($existing->get('name'));
         if (isset($_POST['fields'])) {
             $fields = $_POST['fields'];
         } else {
             $fields = array('name' => $existing->get('name'), 'permissions' => $existing->get('event_permissions'), 'page_access' => $existing->get('forbidden_pages'));
         }
     }
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Member Roles'), extension_members::baseURL() . 'roles/')));
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings type-file');
     $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
     $label = Widget::Label(__('Name'));
     $label->appendChild(Widget::Input('fields[name]', General::sanitize($fields['name'])));
     if (isset($this->_errors['name'])) {
         $fieldset->appendChild(Widget::Error($label, $this->_errors['name']));
     } else {
         $fieldset->appendChild($label);
     }
     $this->Form->appendChild($fieldset);
     $events = EventManager::listAll();
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings type-file');
     $fieldset->appendChild(new XMLElement('legend', __('Event Level Permissions')));
     $aTableBody = array();
     if (is_array($events) && !empty($events)) {
         foreach ($events as $event_handle => $event) {
             $permissions = $fields['permissions'][$event_handle];
             $td_name = Widget::TableData($event['name'], 'name');
             $td_permission_create = Widget::TableData(sprintf('<label title="%s">%s <span>%s</span></label>', __('User can create new entries'), Widget::Input("fields[permissions][{$event_handle}][create]", (string) EventPermissions::CREATE, 'checkbox', $permissions['create'] == EventPermissions::CREATE ? array('checked' => 'checked') : NULL)->generate(), 'Create'), 'create');
             $td_permission_none = Widget::TableData(sprintf('<label title="%s">%s <span>%s</span></label>', __('User cannot edit existing entries'), Widget::Input("fields[permissions][{$event_handle}][edit]", (string) EventPermissions::NO_PERMISSIONS, 'radio', $permissions['edit'] == EventPermissions::NO_PERMISSIONS ? array('checked' => 'checked') : NULL)->generate(), 'None'));
             $td_permission_own = Widget::TableData(sprintf('<label title="%s">%s <span>%s</span></label>', __('User can edit their own entries only'), Widget::Input("fields[permissions][{$event_handle}][edit]", (string) EventPermissions::OWN_ENTRIES, 'radio', $permissions['edit'] == EventPermissions::OWN_ENTRIES ? array('checked' => 'checked') : NULL)->generate(), 'Own'));
             $td_permission_all = Widget::TableData(sprintf('<label title="%s">%s <span>%s</span></label>', __('User can edit all entries'), Widget::Input("fields[permissions][{$event_handle}][edit]", (string) EventPermissions::ALL_ENTRIES, 'radio', $permissions['edit'] == EventPermissions::ALL_ENTRIES ? array('checked' => 'checked') : NULL)->generate(), 'All'));
             // Create an Event instance
             $ev = EventManager::create($event_handle, array());
             $aTableBody[] = Widget::TableRow(array($td_name, $td_permission_create, $td_permission_none, $td_permission_own, $td_permission_all), method_exists($ev, 'ignoreRolePermissions') && $ev->ignoreRolePermissions() == true ? 'inactive' : '');
             unset($ev);
         }
     }
     $thead = Widget::TableHead(array(array(__('Event'), 'col', array('class' => 'name')), array(__('Create New'), 'col', array('class' => 'new', 'title' => __('Toggle all'))), array(__('No Edit'), 'col', array('class' => 'edit', 'title' => __('Toggle all'))), array(__('Edit Own'), 'col', array('class' => 'edit', 'title' => __('Toggle all'))), array(__('Edit All'), 'col', array('class' => 'edit', 'title' => __('Toggle all')))));
     $table = Widget::Table($thead, NULL, Widget::TableBody($aTableBody), 'role-permissions');
     $fieldset->appendChild($table);
     $this->Form->appendChild($fieldset);
     // Add Page Permissions [simple Deny/Allow]
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings type-file');
     $fieldset->appendChild(new XMLElement('legend', __('Page Level Permissions')));
     $label = Widget::Label(__('Deny Access'));
     if (!is_array($fields['page_access'])) {
         $fields['page_access'] = array();
     }
     $options = array();
     $pages = PageManager::fetch(false, array('id'));
     if (!empty($pages)) {
         foreach ($pages as $page) {
             $options[] = array($page['id'], in_array($page['id'], $fields['page_access']), '/' . PageManager::resolvePagePath($page['id']));
         }
     }
     $label->appendChild(Widget::Select('fields[page_access][]', $options, array('multiple' => 'multiple')));
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', array('accesskey' => 's')));
     if (!$isNew && $existing->get('id') != Role::PUBLIC_ROLE) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this Role'), 'type' => 'submit', 'accesskey' => 'd'));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
 }
Exemple #12
0
 public static function buildEditor(XMLElement $wrapper, array &$errors = array(), array $settings = null, $handle = null)
 {
     if (!is_null($handle) && isset($settings[self::getClass()])) {
         $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource');
         $cache_id = self::buildCacheID($settings[self::getClass()]);
     }
     // If `clear_cache` is set, clear it..
     if (isset($cache_id) && in_array('clear_cache', Administration::instance()->Page->getContext())) {
         $cache->delete($cache_id);
         Administration::instance()->Page->pageAlert(__('Data source cache cleared at %s.', array(Widget::Time()->generate())) . '<a href="' . SYMPHONY_URL . '/blueprints/datasources/" accesskey="a">' . __('View all Data sources') . '</a>', Alert::SUCCESS);
     }
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings contextual ' . __CLASS__);
     $fieldset->setAttribute('data-context', Lang::createHandle(self::getName()));
     $fieldset->appendChild(new XMLElement('legend', self::getName()));
     $p = new XMLElement('p', __('Use %s syntax to specify dynamic portions of the URL.', array('<code>{' . __('$param') . '}</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     // URL
     $label = Widget::Label(__('URL'));
     $url = isset($settings[self::getClass()]['url']) ? General::sanitize($settings[self::getClass()]['url']) : null;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][url]', $url, 'text', array('placeholder' => 'http://')));
     if (isset($errors[self::getClass()]['url'])) {
         $fieldset->appendChild(Widget::Error($label, $errors[self::getClass()]['url']));
     } else {
         $fieldset->appendChild($label);
     }
     // Namespaces
     static::addNamespaces($fieldset, $errors, $settings, $handle);
     // Included Elements
     $label = Widget::Label(__('Included Elements'));
     $help = new XMLElement('i', __('xPath expression'));
     $label->appendChild($help);
     $xpath = isset($settings[self::getClass()]['xpath']) ? stripslashes($settings[self::getClass()]['xpath']) : null;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][xpath]', $xpath, 'text', array('placeholder' => '/')));
     if (isset($errors[self::getClass()]['xpath'])) {
         $fieldset->appendChild(Widget::Error($label, $errors[self::getClass()]['xpath']));
     } else {
         $fieldset->appendChild($label);
     }
     $group = new XMLElement('div', null, array('class' => 'three columns'));
     $fieldset->appendChild($group);
     // Caching
     $label = Widget::Label(__('Cache expiration'));
     $label->setAttribute('class', 'column');
     $help = new XMLElement('i', __('in minutes'));
     $label->appendChild($help);
     $cache_time = isset($settings[self::getClass()]['cache']) ? max(0, intval($settings[self::getClass()]['cache'])) : 5;
     $input = Widget::Input('fields[' . self::getClass() . '][cache]', (string) $cache_time);
     $label->appendChild($input);
     if (isset($errors[self::getClass()]['cache'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['cache']));
     } else {
         $group->appendChild($label);
     }
     // Timeout
     $label = Widget::Label(__('Timeout'));
     $label->setAttribute('class', 'column');
     $help = new XMLElement('i', __('in seconds'));
     $label->appendChild($help);
     $timeout_time = isset($settings[self::getClass()]['timeout']) ? max(1, intval($settings[self::getClass()]['timeout'])) : 6;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][timeout]', (string) $timeout_time, 'text'));
     if (isset($errors[self::getClass()]['timeout'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['timeout']));
     } else {
         $group->appendChild($label);
     }
     // Format
     $label = Widget::Label(__('Format'));
     $label->setAttribute('class', 'column');
     $format = isset($settings[self::getClass()]['format']) ? $settings[self::getClass()]['format'] : null;
     $label->appendChild(Widget::Select('fields[' . self::getClass() . '][format]', array(array('xml', $settings[self::getClass()]['format'] == 'xml', 'XML'), array('json', $settings[self::getClass()]['format'] == 'json', 'JSON'), array('csv', $settings[self::getClass()]['format'] == 'csv', 'CSV'), array('txt', $settings[self::getClass()]['format'] == 'txt', 'TEXT')), array('class' => 'picker')));
     if (isset($errors[self::getClass()]['format'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['format']));
     } else {
         $group->appendChild($label);
     }
     // Check for existing Cache objects
     if (isset($cache_id)) {
         static::buildCacheInformation($fieldset, $cache, $cache_id);
     }
     $wrapper->appendChild($fieldset);
     // Parameters
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings contextual ' . __CLASS__);
     $fieldset->setAttribute('data-context', Lang::createHandle(self::getName()));
     $fieldset->appendChild(new XMLElement('legend', 'Parameters'));
     $p = new XMLElement('p', __('Appended to datasource handle, eg. %s', array('<code>$ds-handle.parameter-name</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     // Output Parameters
     static::addOutputParameters($fieldset, $errors, $settings, $handle);
     $wrapper->appendChild($fieldset);
 }
Exemple #13
0
 public function View()
 {
     if (!file_exists(realpath(MANIFEST . '/cron') . '/' . $this->_context[0])) {
         throw new SymphonyErrorPage('The cron task <code>' . $this->_context[0] . '</code> could not be found.', 'Task Not Found');
     }
     $task = (new Lib\CronTask(Symphony::Database()))->load(realpath(MANIFEST . '/cron') . '/' . $this->_context[0]);
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert(__('An error occurred while processing this form. See below for details.'), Alert::ERROR);
         // These alerts are only valid if the form doesn't have errors
     } elseif (isset($this->_context[1])) {
         $time = Widget::Time();
         switch ($this->_context[1]) {
             case 'saved':
                 $message = __('Cron task updated at %s.', array($time->generate()));
                 break;
             case 'created':
                 $message = __('Cron task created at %s.', array($time->generate()));
         }
         $this->pageAlert($message, Alert::SUCCESS);
     }
     $this->setPageType('form');
     $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', [$task->name, __('Cron'), __('Symphony')]));
     $this->appendSubheading($task->name);
     if (!empty($_POST)) {
         $fields = $_POST['fields'];
     } else {
         $fields = ['name' => General::sanitize($task->name), 'command' => General::sanitize($task->command), 'description' => General::sanitize($task->description), 'interval' => $task->interval, 'interval-type' => $task->{'interval-type'}, 'start' => !is_null($task->start) ? DateTimeObj::get('Y-m-d H:i:s', $task->start) : null, 'finish' => !is_null($task->finish) ? DateTimeObj::get('Y-m-d H:i:s', $task->finish) : null];
         if ($task->enabled === true) {
             $fields['enabled'] = 'yes';
         }
     }
     // Essentials
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
     $label = Widget::Label('Name');
     $label->appendChild(Widget::Input('fields[name]', $fields['name']));
     $fieldset->appendChild(isset($this->_errors['name']) ? Widget::Error($label, $this->_errors['name']) : $label);
     $label = Widget::Label('Command');
     $label->appendChild(Widget::Input('fields[command]', $fields['command']));
     $fieldset->appendChild(isset($this->_errors['command']) ? Widget::Error($label, $this->_errors['command']) : $label);
     $p = new XMLElement('p', '&uarr; This is any command that can be executed from the command line.');
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $label = Widget::Label('Description <i>Optional</i>');
     $label->appendChild(Widget::Input('fields[description]', $fields['description']));
     $fieldset->appendChild(isset($this->_errors['description']) ? Widget::Error($label, $this->_errors['description']) : $label);
     $label = Widget::Label();
     $input = Widget::Input('fields[interval]', (string) max(1, $fields['interval']), null, array('size' => '6'));
     $options = [['minute', $fields['interval'] == 'minute', 'minutes'], ['hour', $fields['interval'] == 'hour', 'hours'], ['day', $fields['interval'] == 'day', 'days'], ['week', $fields['interval'] == 'week', 'weeks']];
     $select = Widget::Select('fields[interval-type]', $options, ['class' => 'inline', 'style' => 'display: inline; width: auto;']);
     $label->setValue(__('Run this task every %s %s', [$input->generate(false), $select->generate(false)]));
     if (isset($this->_errors['interval'])) {
         $fieldset->appendChild(Widget::Error($label, $this->_errors['interval']));
     } else {
         $fieldset->appendChild($label);
     }
     $label = Widget::Label();
     $input = Widget::Input('fields[enabled]', 'yes', 'checkbox', isset($fields['enabled']) ? array('checked' => 'checked') : null);
     $label->setValue(__('%s Enable this task', array($input->generate(false))));
     $fieldset->appendChild($label);
     $p = new XMLElement('p', '&uarr; Unless a <strong>start date</strong> has been specified, this task will be executed once the current date plus the interval specified has passed.');
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $this->Form->appendChild($fieldset);
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Timing')));
     $group = new XMLElement('div', null, array('class' => 'group'));
     $label = Widget::Label('Start Date <i>Optional</i>');
     $label->appendChild(Widget::Input('fields[start]', $fields['start']));
     $group->appendChild(isset($this->_errors['start']) ? Widget::Error($label, $this->_errors['start']) : $label);
     $label = Widget::Label('Finish Date <i>Optional</i>');
     $label->appendChild(Widget::Input('fields[finish]', $fields['finish']));
     $group->appendChild(isset($this->_errors['finish']) ? Widget::Error($label, $this->_errors['finish']) : $label);
     $fieldset->appendChild($group);
     $p = new XMLElement('p', 'This task will be not run until after the <strong>start date</strong>, and will cease to trigger beyond the <strong>finish date</strong>.');
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $this->Form->appendChild($fieldset);
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', 'Save', 'submit', ['accesskey' => 's']));
     $button = new XMLElement('button', __('Delete'));
     $button->setAttributeArray(['name' => 'action[delete]', 'class' => 'confirm delete', 'title' => 'Delete this task']);
     $div->appendChild($button);
     $this->Form->appendChild($div);
 }
 public function __viewEdit($new = false)
 {
     $this->setPageType('form');
     $this->setTitle(sprintf(__("Symphony - Newsletter Recipient Groups - %s", array(), false), ucfirst($this->_context[1])));
     $errors = new XMLElement('errors');
     $context = new XMLElement('context');
     General::array_to_xml($context, $this->_context);
     $this->_XML->appendChild($context);
     // Fix for 2.4 and XSRF
     if (Symphony::Configuration()->get("enable_xsrf", "symphony") == "yes" && class_exists('XSRF')) {
         $xsrf_input = new XMLElement('xsrf_input');
         $xsrf_input->appendChild(XSRF::formToken());
         $this->_XML->appendChild($xsrf_input);
     }
     $section_xml = new XMLElement('sections');
     $sectionManager = new SectionManager($this);
     $sections = $sectionManager->fetch();
     foreach ($sections as $section) {
         $entry = new XMLElement('entry');
         General::array_to_xml($entry, $section->get());
         foreach ($section->fetchFields() as $field) {
             $field_xml = new XMLElement('field');
             General::array_to_xml($field_xml, $field->get());
             $filter_html = new XMLElement('filter_html');
             $field->displayDatasourceFilterPanel($filter_html, NULL, $errors, $section->get('id'));
             $field_xml->appendChild($filter_html);
             $field_elements = new XMLElement('elements');
             General::array_to_xml($field_elements, $field->fetchIncludableElements());
             $field_xml->appendChild($field_elements);
             $entry->appendChild($field_xml);
         }
         $section_xml->appendChild($entry);
     }
     $this->_XML->appendChild($section_xml);
     $title = __('New Group');
     $breadcrumbs = array(Widget::Anchor(__('Email Newsletter Recipients'), SYMPHONY_URL . '/extension/email_newsletter_manager/recipientgroups/'));
     $recipientgroups = new XMLElement('recipientgroups');
     if ($this->_context[2] == 'saved' || $this->_context[3] == 'saved') {
         $this->pageAlert(__(__('Email Recipient updated at %1$s. <a href="%2$s" accesskey="c">Create another?</a> <a href="%3$s" accesskey="a">View all Recipient Groups</a>'), array(Widget::Time()->generate(), SYMPHONY_URL . '/extension/email_newsletter_manager/recipientgroups/new/', SYMPHONY_URL . '/extension/email_newsletter_manager/recipientgroups/')), Alert::SUCCESS);
     }
     if ($new == false) {
         /*
             TODO add POST values to XML
         */
         $group = RecipientgroupManager::create($this->_context[1]);
         if (is_object($group)) {
             $entry = new XMLElement('entry');
             $properties = $group->getProperties();
             $about = $group->about();
             $title = $about['name'];
             General::array_to_xml($entry, $about);
             $source = new XMLElement('source', $properties['source']);
             $entry->appendChild($source);
             // Section Only
             if (is_numeric($properties['source'])) {
                 $fields = new XMLElement('fields');
                 $email = new XMLElement('email', $properties['email']);
                 $fields->appendChild($email);
                 $name = new XMLElement('name');
                 General::array_to_xml($name, $properties['name']);
                 $fields->appendChild($name);
                 $entry->appendChild($fields);
             }
             // Hack to make sure filter data is preserved in the UI when there is an error in the form.
             // For next versions: always do the local/user differentiation in php, rather than xslt.
             // This will make the xslt cleaner and easier to understand and debug.
             if (!empty($_POST['fields'])) {
                 $properties['filters'] = $_POST['fields']['filter'][0];
             }
             if (!empty($properties['filters'])) {
                 $filters = new XMLElement('filters');
                 foreach ($properties['filters'] as $filter => $val) {
                     // Section and Author
                     if ($filter == 'id') {
                         $title = new XMLElement('h4', 'System ID');
                         $label = Widget::Label(__('Value'));
                         $label->appendChild(Widget::Input('fields[filter][' . $properties['source'] . '][id]', General::sanitize($val)));
                         $filter_entry = new XMLElement('entry', NULL, array('id' => 'id', 'data-type' => 'id'));
                         $filter_entry->appendChild($title);
                         $filter_entry->appendChild($label);
                         $filters->appendChild($filter_entry);
                     }
                     if ($filter == 'system:date') {
                         $title = new XMLElement('h4', 'System Date');
                         $label = Widget::Label(__('Value'));
                         $label->appendChild(Widget::Input('fields[filter][' . $properties['source'] . '][system:date]', General::sanitize($val)));
                         $filter_entry = new XMLElement('entry', NULL, array('id' => 'id', 'data-type' => 'system:date'));
                         $filter_entry->appendChild($title);
                         $filter_entry->appendChild($label);
                         $filters->appendChild($filter_entry);
                     }
                     // Section Only
                     if (is_numeric($properties['source'])) {
                         $section = SectionManager::fetch($properties['source']);
                         if (is_object($section)) {
                             $section_fields = $section->fetchFields();
                             foreach ($section_fields as $field) {
                                 $field_ids[] = $field->get('id');
                             }
                             // only add filters to the duplicator if the field id
                             // belongs to the current section
                             if (is_numeric($filter) && in_array($filter, $field_ids)) {
                                 $filter_obj = FieldManager::fetch($filter);
                                 if (is_object($filter_obj)) {
                                     $filter_entry = new XMLElement('entry', NULL, array('id' => $filter, 'data-type' => FieldManager::fetchHandleFromID($filter)));
                                     $filter_obj->displayDatasourceFilterPanel($filter_entry, $val, $errors, is_numeric($properties['source']) ? $properties['source'] : 1);
                                     $filters->appendChild($filter_entry);
                                 }
                             }
                         }
                     }
                     // Author only
                     if ($properties['source'] == 'authors') {
                         $filter_names = array('username' => 'Username', 'first_name' => 'First Name', 'last_name' => 'Last Name', 'email' => 'Email Address', 'user_type' => 'User Type');
                         if (in_array($filter, array_keys($filter_names))) {
                             $title = new XMLElement('h4', $filter_names[$filter]);
                             $label = Widget::Label(__('Value'));
                             $label->appendChild(Widget::Input('fields[filter][' . $properties['source'] . '][username]', General::sanitize($val)));
                             $filter_entry = new XMLElement('entry', NULL, array('id' => 'id', 'data-type' => 'username'));
                             $filter_entry->appendChild($title);
                             $filter_entry->appendChild($label);
                             $filters->appendChild($filter_entry);
                         }
                     }
                 }
                 $entry->appendChild($filters);
                 $title = $about['name'];
             }
             if ($properties['source'] == 'static_recipients') {
                 $entry->appendChild(new XMLElement('static_recipients', '<![CDATA[' . $group->recipients . ']]>'));
             }
             $recipientgroups->appendChild($entry);
             $this->_XML->appendChild($recipientgroups);
         } else {
             Administration::instance()->errorPageNotFound();
         }
     }
     $this->insertBreadcrumbs($breadcrumbs);
     $this->appendSubheading($title);
 }
 public function __viewEdit()
 {
     $this->setPageType('form');
     $fields = array("title" => null, "handle" => null, "parent" => null, "params" => null, "type" => null, "data_sources" => null);
     $existing = $fields;
     $nesting = Symphony::Configuration()->get('pages_table_nest_children', 'symphony') == 'yes';
     // Verify page exists:
     if ($this->_context[0] === 'edit') {
         if (!($page_id = (int) $this->_context[1])) {
             redirect(SYMPHONY_URL . '/blueprints/pages/');
         }
         $existing = PageManager::fetchPageByID($page_id);
         if (!$existing) {
             Administration::instance()->errorPageNotFound();
         } else {
             $existing['type'] = PageManager::fetchPageTypes($page_id);
         }
     }
     // Status message:
     if (isset($this->_context[2])) {
         $flag = $this->_context[2];
         $parent_link_suffix = $message = '';
         $time = Widget::Time();
         if (isset($_REQUEST['parent']) && is_numeric($_REQUEST['parent'])) {
             $parent_link_suffix = "?parent=" . $_REQUEST['parent'];
         } elseif ($nesting && isset($existing) && !is_null($existing['parent'])) {
             $parent_link_suffix = '?parent=' . $existing['parent'];
         }
         switch ($flag) {
             case 'saved':
                 $message = __('Page updated at %s.', array($time->generate()));
                 break;
             case 'created':
                 $message = __('Page created at %s.', array($time->generate()));
         }
         $this->pageAlert($message . ' <a href="' . SYMPHONY_URL . '/blueprints/pages/new/' . $parent_link_suffix . '" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/blueprints/pages/" accesskey="a">' . __('View all Pages') . '</a>', Alert::SUCCESS);
     }
     // Find values:
     if (isset($_POST['fields'])) {
         $fields = $_POST['fields'];
     } elseif ($this->_context[0] == 'edit') {
         $fields = $existing;
         if (!is_null($fields['type'])) {
             $fields['type'] = implode(', ', $fields['type']);
         }
         $fields['data_sources'] = preg_split('/,/i', $fields['data_sources'], -1, PREG_SPLIT_NO_EMPTY);
         $fields['events'] = preg_split('/,/i', $fields['events'], -1, PREG_SPLIT_NO_EMPTY);
     } elseif (isset($_REQUEST['parent']) && is_numeric($_REQUEST['parent'])) {
         $fields['parent'] = $_REQUEST['parent'];
     }
     $title = $fields['title'];
     if (trim($title) == '') {
         $title = $existing['title'];
     }
     $this->setTitle(__($title ? '%1$s &ndash; %2$s &ndash; %3$s' : '%2$s &ndash; %3$s', array($title, __('Pages'), __('Symphony'))));
     $page_id = isset($page_id) ? $page_id : null;
     if (!empty($title)) {
         $page_url = URL . '/' . PageManager::resolvePagePath($page_id) . '/';
         $this->appendSubheading($title, array(Widget::Anchor(__('View Page'), $page_url, __('View Page on Frontend'), 'button', null, array('target' => '_blank', 'accesskey' => 'v'))));
     } else {
         $this->appendSubheading(!empty($title) ? $title : __('Untitled'));
     }
     if (isset($page_id)) {
         $this->insertBreadcrumbsUsingPageIdentifier($page_id, false);
     } else {
         $_GET['parent'] = isset($_GET['parent']) ? $_GET['parent'] : null;
         $this->insertBreadcrumbsUsingPageIdentifier((int) $_GET['parent'], true);
     }
     // Title --------------------------------------------------------------
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Page Settings')));
     $label = Widget::Label(__('Name'));
     $label->appendChild(Widget::Input('fields[title]', General::sanitize($fields['title'])));
     if (isset($this->_errors['title'])) {
         $label = Widget::Error($label, $this->_errors['title']);
     }
     $fieldset->appendChild($label);
     // Handle -------------------------------------------------------------
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $column = new XMLElement('div');
     $column->setAttribute('class', 'column');
     $label = Widget::Label(__('Handle'));
     $label->appendChild(Widget::Input('fields[handle]', $fields['handle']));
     if (isset($this->_errors['handle'])) {
         $label = Widget::Error($label, $this->_errors['handle']);
     }
     $column->appendChild($label);
     // Parent ---------------------------------------------------------
     $label = Widget::Label(__('Parent Page'));
     $where = array(sprintf('id != %d', $page_id));
     $pages = PageManager::fetch(false, array('id'), $where, 'title ASC');
     $options = array(array('', false, '/'));
     if (!empty($pages)) {
         foreach ($pages as $page) {
             $options[] = array($page['id'], $fields['parent'] == $page['id'], '/' . PageManager::resolvePagePath($page['id']));
         }
         usort($options, array($this, '__compare_pages'));
     }
     $label->appendChild(Widget::Select('fields[parent]', $options));
     $column->appendChild($label);
     $group->appendChild($column);
     // Parameters ---------------------------------------------------------
     $column = new XMLElement('div');
     $column->setAttribute('class', 'column');
     $label = Widget::Label(__('Parameters'));
     $label->appendChild(Widget::Input('fields[params]', $fields['params'], 'text', array('placeholder' => 'param1/param2')));
     $column->appendChild($label);
     // Type -----------------------------------------------------------
     $label = Widget::Label(__('Type'));
     $label->appendChild(Widget::Input('fields[type]', $fields['type']));
     if (isset($this->_errors['type'])) {
         $label = Widget::Error($label, $this->_errors['type']);
     }
     $column->appendChild($label);
     $tags = new XMLElement('ul');
     $tags->setAttribute('class', 'tags');
     $tags->setAttribute('data-interactive', 'data-interactive');
     $types = PageManager::fetchAvailablePageTypes();
     foreach ($types as $type) {
         $tags->appendChild(new XMLElement('li', $type));
     }
     $column->appendChild($tags);
     $group->appendChild($column);
     $fieldset->appendChild($group);
     $this->Form->appendChild($fieldset);
     // Events -------------------------------------------------------------
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Page Resources')));
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $label = Widget::Label(__('Events'));
     $label->setAttribute('class', 'column');
     $events = ResourceManager::fetch(ResourceManager::RESOURCE_TYPE_EVENT, array(), array(), 'name ASC');
     $options = array();
     if (is_array($events) && !empty($events)) {
         if (!isset($fields['events'])) {
             $fields['events'] = array();
         }
         foreach ($events as $name => $about) {
             $options[] = array($name, in_array($name, $fields['events']), $about['name']);
         }
     }
     $label->appendChild(Widget::Select('fields[events][]', $options, array('multiple' => 'multiple')));
     $group->appendChild($label);
     // Data Sources -------------------------------------------------------
     $label = Widget::Label(__('Data Sources'));
     $label->setAttribute('class', 'column');
     $datasources = ResourceManager::fetch(ResourceManager::RESOURCE_TYPE_DS, array(), array(), 'name ASC');
     $options = array();
     if (is_array($datasources) && !empty($datasources)) {
         if (!isset($fields['data_sources'])) {
             $fields['data_sources'] = array();
         }
         foreach ($datasources as $name => $about) {
             $options[] = array($name, in_array($name, $fields['data_sources']), $about['name']);
         }
     }
     $label->appendChild(Widget::Select('fields[data_sources][]', $options, array('multiple' => 'multiple')));
     $group->appendChild($label);
     $fieldset->appendChild($group);
     $this->Form->appendChild($fieldset);
     // Controls -----------------------------------------------------------
     /**
      * After all Page related Fields have been added to the DOM, just before the
      * actions.
      *
      * @delegate AppendPageContent
      * @param string $context
      *  '/blueprints/pages/'
      * @param XMLElement $form
      * @param array $fields
      * @param array $errors
      */
     Symphony::ExtensionManager()->notifyMembers('AppendPageContent', '/blueprints/pages/', array('form' => &$this->Form, 'fields' => &$fields, 'errors' => $this->_errors));
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $this->_context[0] == 'edit' ? __('Save Changes') : __('Create Page'), 'submit', array('accesskey' => 's')));
     if ($this->_context[0] == 'edit') {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this page'), 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this page?')));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
     if (isset($_REQUEST['parent']) && is_numeric($_REQUEST['parent'])) {
         $this->Form->appendChild(new XMLElement('input', null, array('type' => 'hidden', 'name' => 'parent', 'value' => $_REQUEST['parent'])));
     }
 }
Exemple #16
0
 function render()
 {
     $this->setPageType('form');
     $fields = array();
     // If we're editing, make sure the item exists
     if ($this->_context[0]) {
         if (!($doc_id = $this->_context[0])) {
             redirect(URL . '/symphony/extension/documenter/manage');
         }
         $existing = Symphony::Database()->fetchRow(0, "\n\t\t\t\t\tSELECT\n\t\t\t\t\t\td.*\n\t\t\t\t\tFROM\n\t\t\t\t\t\t`tbl_documentation` AS d\n\t\t\t\t\tWHERE\n\t\t\t\t\t\td.id = '{$doc_id}'\n\t\t\t\t\tLIMIT 1\n\t\t\t\t");
         if (!$existing) {
             $this->_Parent->customError(E_USER_ERROR, __('Documentation Item not found'), __('The documentation item you requested to edit does not exist.'), false, true, 'error', array('header' => 'HTTP/1.0 404 Not Found'));
         }
     }
     // Build the status message
     if (isset($this->_context[1])) {
         if ($this->_context[1] == 'saved') {
             $this->pageAlert(__('Documentation Item updated at %1$s. <a href="%2$s">Create another?</a> <a href="%3$s">View all Documentation</a>', array(Widget::Time()->generate(__SYM_TIME_FORMAT__), URL . '/symphony/extension/documenter/new/', URL . '/symphony/extension/documenter/')), Alert::SUCCESS);
         } else {
             $this->pageAlert(__('Documentation Item created at %1$s. <a href="%2$s">Create another?</a> <a href="%3$s">View all Documentation</a>', array(Widget::Time()->generate(__SYM_TIME_FORMAT__), URL . '/symphony/extension/documenter/new/', URL . '/symphony/extension/documenter/')), Alert::SUCCESS);
         }
     }
     // Find values
     if (isset($_POST['fields'])) {
         $fields = $_POST['fields'];
     } else {
         if ($this->_context[0]) {
             $fields = $existing;
             $fields['content'] = General::sanitize($fields['content']);
         }
     }
     $title = $fields['title'];
     if (trim($title) == '') {
         $title = $existing['title'];
     }
     // Start building the page
     $this->setTitle(__($title ? '%1$s &ndash; %2$s &ndash; %3$s' : '%1$s &ndash; %2$s', array(__('Symphony'), __('Documentation'), $title)));
     $this->appendSubheading($title ? $title : __('Untitled'));
     // Start building the fieldsets
     $this->Form->setAttribute('class', 'two columns');
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'primary column');
     // Title text input
     $label = Widget::Label(__('Title'));
     $label->appendChild(Widget::Input('fields[title]', General::sanitize($fields['title'])));
     if (isset($this->_errors['title'])) {
         $label = Widget::Error($label, $this->_errors['title']);
     }
     $fieldset->appendChild($label);
     // Content textarea
     $label = Widget::Label(__('Content'));
     $content = Widget::Textarea('fields[content]', 30, 80, $fields['content']);
     if (Symphony::Configuration()->get('text-formatter', 'documentation') != 'none') {
         $content->setAttribute('class', Symphony::Configuration()->get('text-formatter', 'documentation'));
     }
     $label->appendChild($content);
     $fieldset->appendChild(isset($this->_errors['content']) ? Widget::Error($label, $this->_errors['content']) : $label);
     $fieldset->appendChild(Widget::Input('autogenerate', __('Auto-generate content according to selected section(s)'), 'button', array('class' => 'button')));
     $this->Form->appendChild($fieldset);
     // Pages multi-select
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'secondary column');
     $label = Widget::Label(__('Pages'));
     if (!is_array($fields['pages'])) {
         $pages_array = explode(',', $fields['pages']);
     } else {
         $pages_array = $fields['pages'];
     }
     $options = array();
     // Generate a list of sectionField-data for auto-generation of documentation:
     $arr = array();
     // Build the options list using the navigation array
     foreach (Administration::instance()->Page->_navigation as $menu) {
         $items = array();
         foreach ($menu['children'] as $item) {
             $items[] = array($item['link'], in_array($item['link'], $pages_array), $menu['name'] . " > " . $item['name']);
             // If it's a section, add New and Edit pages
             // NOTE: This will likely break when extensions add custom nav groups
             if ($menu['name'] != 'Blueprints' and $menu['name'] != 'System') {
                 $items[] = array($item['link'] . 'new/', in_array($item['link'] . 'new/', $pages_array), $menu['name'] . " > " . $item['name'] . " New");
                 $items[] = array($item['link'] . 'edit/', in_array($item['link'] . 'edit/', $pages_array), $menu['name'] . " > " . $item['name'] . " Edit");
             }
             // Generate a list of sectionField-data for auto-generation of documentation:
             if ($item['type'] == 'section') {
                 $arr2 = array('name' => $item['name'], 'link' => $item['link'], 'items' => array());
                 $fields = FieldManager::fetch(null, $item['section']['id']);
                 foreach ($fields as $field) {
                     /* @var $field Field */
                     $arr2['items'][] = array('label' => $field->get('label'));
                 }
                 $arr[] = $arr2;
             }
         }
         $options[] = array('label' => $menu['name'], 'options' => $items);
     }
     Administration::instance()->Page->addElementToHead(new XMLElement('script', 'var sectionFields = ' . json_encode($arr) . ';', array('type' => 'text/javascript')));
     $label->appendChild(Widget::Select('fields[pages][]', $options, array('multiple' => 'multiple', 'id' => 'documenter-pagelist')));
     if (isset($this->_errors['pages'])) {
         $label = Widget::Error($label, $this->_errors['pages']);
     }
     $fieldset->appendChild($label);
     $this->Form->appendChild($fieldset);
     // Form actions
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $this->_context[0] ? __('Save Changes') : __('Document It'), 'submit', array('accesskey' => 's')));
     if ($this->_context[0]) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'confirm delete', 'title' => __('Delete this template')));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
 }
 public function __viewEdit()
 {
     $section_id = $this->_context[1];
     if (!($section = SectionManager::fetch($section_id))) {
         Administration::instance()->throwCustomError(__('The Section, %s, could not be found.', array($section_id)), __('Unknown Section'), Page::HTTP_STATUS_NOT_FOUND);
     }
     $meta = $section->get();
     $section_id = $meta['id'];
     $types = array();
     $formHasErrors = is_array($this->_errors) && !empty($this->_errors);
     if ($formHasErrors) {
         $this->pageAlert(__('An error occurred while processing this form. See below for details.'), Alert::ERROR);
         // These alerts are only valid if the form doesn't have errors
     } elseif (isset($this->_context[2])) {
         $time = Widget::Time();
         switch ($this->_context[2]) {
             case 'saved':
                 $message = __('Section updated at %s.', array($time->generate()));
                 break;
             case 'created':
                 $message = __('Section created at %s.', array($time->generate()));
         }
         $this->pageAlert($message . ' <a href="' . SYMPHONY_URL . '/blueprints/sections/new/" accesskey="c">' . __('Create another?') . '</a> <a href="' . SYMPHONY_URL . '/blueprints/sections/" accesskey="a">' . __('View all Sections') . '</a>', Alert::SUCCESS);
     }
     if (isset($_POST['fields'])) {
         $fields = array();
         if (is_array($_POST['fields']) && !empty($_POST['fields'])) {
             foreach ($_POST['fields'] as $position => $data) {
                 if ($fields[$position] = FieldManager::create($data['type'])) {
                     $fields[$position]->setArray($data);
                     $fields[$position]->set('sortorder', $position);
                 }
             }
         }
     } else {
         $fields = FieldManager::fetch(null, $section_id);
         $fields = array_values($fields);
     }
     if (isset($_POST['meta'])) {
         $meta = $_POST['meta'];
         if ($meta['name'] == '') {
             $meta['name'] = $section->get('name');
         }
     }
     $this->setPageType('form');
     $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', array($meta['name'], __('Sections'), __('Symphony'))));
     $this->appendSubheading($meta['name'], Widget::Anchor(__('View Entries'), SYMPHONY_URL . '/publish/' . $section->get('handle'), __('View Section Entries'), 'button'));
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Sections'), SYMPHONY_URL . '/blueprints/sections/')));
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
     $namediv = new XMLElement('div', null, array('class' => 'column'));
     $label = Widget::Label(__('Name'));
     $label->appendChild(Widget::Input('meta[name]', isset($meta['name']) ? General::sanitize($meta['name']) : null));
     if (isset($this->_errors['name'])) {
         $namediv->appendChild(Widget::Error($label, $this->_errors['name']));
     } else {
         $namediv->appendChild($label);
     }
     $fieldset->appendChild($namediv);
     $div = new XMLElement('div', null, array('class' => 'two columns'));
     $handlediv = new XMLElement('div', null, array('class' => 'column'));
     $label = Widget::Label(__('Handle'));
     $label->appendChild(Widget::Input('meta[handle]', isset($meta['handle']) ? General::sanitize($meta['handle']) : null));
     if (isset($this->_errors['handle'])) {
         $handlediv->appendChild(Widget::Error($label, $this->_errors['handle']));
     } else {
         $handlediv->appendChild($label);
     }
     $div->appendChild($handlediv);
     $navgroupdiv = new XMLElement('div', null, array('class' => 'column'));
     $sections = SectionManager::fetch(null, 'ASC', 'sortorder');
     $label = Widget::Label(__('Navigation Group'));
     $label->appendChild(Widget::Input('meta[navigation_group]', $meta['navigation_group']));
     if (isset($this->_errors['navigation_group'])) {
         $navgroupdiv->appendChild(Widget::Error($label, $this->_errors['navigation_group']));
     } else {
         $navgroupdiv->appendChild($label);
     }
     if (is_array($sections) && !empty($sections)) {
         $ul = new XMLElement('ul', null, array('class' => 'tags singular', 'data-interactive' => 'data-interactive'));
         $groups = array();
         foreach ($sections as $s) {
             if (in_array($s->get('navigation_group'), $groups)) {
                 continue;
             }
             $ul->appendChild(new XMLElement('li', $s->get('navigation_group')));
             $groups[] = $s->get('navigation_group');
         }
         $navgroupdiv->appendChild($ul);
     }
     $div->appendChild($navgroupdiv);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     $this->addSectionOptions($meta);
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $legend = new XMLElement('legend', __('Fields'));
     $legend->setAttribute('id', 'fields-legend');
     $fieldset->appendChild($legend);
     $div = new XMLElement('div', null, array('class' => 'frame', 'id' => 'fields-duplicator'));
     $ol = new XMLElement('ol');
     $ol->setAttribute('data-add', __('Add field'));
     $ol->setAttribute('data-remove', __('Remove field'));
     if (is_array($fields) && !empty($fields)) {
         foreach ($fields as $position => $field) {
             $wrapper = new XMLElement('li', null, array('class' => 'field-' . $field->handle() . ($field->mustBeUnique() ? ' unique' : null)));
             $wrapper->setAttribute('data-type', $field->handle());
             $field->set('sortorder', $position);
             $field->displaySettingsPanel($wrapper, isset($this->_errors[$position]) ? $this->_errors[$position] : null);
             $ol->appendChild($wrapper);
         }
     }
     foreach (FieldManager::listAll() as $type) {
         if ($type = FieldManager::create($type)) {
             array_push($types, $type);
         }
     }
     uasort($types, create_function('$a, $b', 'return strnatcasecmp($a->_name, $b->_name);'));
     foreach ($types as $type) {
         $defaults = array();
         $type->findDefaults($defaults);
         $type->setArray($defaults);
         $wrapper = new XMLElement('li');
         $wrapper->setAttribute('class', 'template field-' . $type->handle() . ($type->mustBeUnique() ? ' unique' : null));
         $wrapper->setAttribute('data-type', $type->handle());
         $type->set('sortorder', '-1');
         $type->displaySettingsPanel($wrapper);
         $ol->appendChild($wrapper);
     }
     $div->appendChild($ol);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', __('Save Changes'), 'submit', array('accesskey' => 's')));
     $button = new XMLElement('button', __('Delete'));
     $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'button confirm delete', 'title' => __('Delete this section'), 'type' => 'submit', 'accesskey' => 'd', 'data-message' => __('Are you sure you want to delete this section?')));
     $div->appendChild($button);
     $this->Form->appendChild($div);
 }
 public static function buildEditor(XMLElement $wrapper, array &$errors = array(), array $settings = null, $handle = null)
 {
     if (!is_null($handle) && isset($settings[self::getClass()])) {
         $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource');
         $cache_id = self::buildCacheID($settings[self::getClass()]);
     }
     // If `clear_cache` is set, clear it..
     if (isset($cache_id) && in_array('clear_cache', Administration::instance()->Page->getContext())) {
         $cache->forceExpiry($cache_id);
         Administration::instance()->Page->pageAlert(__('Data source cache cleared at %s.', array(Widget::Time()->generate())) . '<a href="' . SYMPHONY_URL . '/blueprints/datasources/" accesskey="a">' . __('View all Data sources') . '</a>', Alert::SUCCESS);
     }
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings contextual ' . __CLASS__);
     $fieldset->setAttribute('data-context', Lang::createHandle(self::getName()));
     $fieldset->appendChild(new XMLElement('legend', self::getName()));
     $p = new XMLElement('p', __('Use %s syntax to specify dynamic portions of the URL.', array('<code>{' . __('$param') . '}</code>')));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     // URL
     $label = Widget::Label(__('URL'));
     $url = isset($settings[self::getClass()]['url']) ? General::sanitize($settings[self::getClass()]['url']) : null;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][url]', $url, 'text', array('placeholder' => 'http://')));
     if (isset($errors[self::getClass()]['url'])) {
         $fieldset->appendChild(Widget::Error($label, $errors[self::getClass()]['url']));
     } else {
         $fieldset->appendChild($label);
     }
     // Included Elements
     $label = Widget::Label(__('Included Elements'));
     $help = new XMLElement('i', __('xPath expression'));
     $label->appendChild($help);
     $xpath = isset($settings[self::getClass()]['xpath']) ? stripslashes($settings[self::getClass()]['xpath']) : null;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][xpath]', $xpath, 'text', array('placeholder' => '/')));
     if (isset($errors[self::getClass()]['xpath'])) {
         $fieldset->appendChild(Widget::Error($label, $errors[self::getClass()]['xpath']));
     } else {
         $fieldset->appendChild($label);
     }
     // Timeout
     $group = new XMLElement('div', null, array('class' => 'three columns'));
     $fieldset->appendChild($group);
     $label = Widget::Label(__('Timeout'));
     $label->setAttribute('class', 'column');
     $help = new XMLElement('i', __('in seconds'));
     $label->appendChild($help);
     $timeout_time = isset($settings[self::getClass()]['timeout']) ? max(1, intval($settings[self::getClass()]['timeout'])) : 6;
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][timeout]', (string) $timeout_time, 'text'));
     if (isset($errors[self::getClass()]['timeout'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['timeout']));
     } else {
         $group->appendChild($label);
     }
     // Caching
     $label = Widget::Label(__('Cache expiration'));
     $label->setAttribute('class', 'column');
     $help = new XMLElement('i', __('in minutes'));
     $label->appendChild($help);
     $cache_time = isset($settings[self::getClass()]['cache']) ? max(0, intval($settings[self::getClass()]['cache'])) : 5;
     $input = Widget::Input('fields[' . self::getClass() . '][cache]', (string) $cache_time);
     $label->appendChild($input);
     if (isset($errors[self::getClass()]['cache'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['cache']));
     } else {
         $group->appendChild($label);
     }
     // Format
     $label = Widget::Label(__('Format'));
     $label->setAttribute('class', 'column');
     $format = isset($settings[self::getClass()]['format']) ? $settings[self::getClass()]['format'] : null;
     $label->appendChild(Widget::Select('fields[' . self::getClass() . '][format]', array(array('xml', $settings[self::getClass()]['format'] == 'xml', 'XML'), array('json', $settings[self::getClass()]['format'] == 'json', 'JSON'), array('csv', $settings[self::getClass()]['format'] == 'csv', 'CSV'), array('txt', $settings[self::getClass()]['format'] == 'txt', 'TEXT')), array('class' => 'picker')));
     if (isset($errors[self::getClass()]['format'])) {
         $group->appendChild(Widget::Error($label, $errors[self::getClass()]['format']));
     } else {
         $group->appendChild($label);
     }
     // Namespaces
     $div = new XMLElement('div', false, array('id' => 'xml', 'class' => 'pickable'));
     $p = new XMLElement('p', __('Namespace Declarations'));
     $p->appendChild(new XMLElement('i', __('optional')));
     $p->setAttribute('class', 'label');
     $div->appendChild($p);
     $frame = new XMLElement('div', null, array('class' => 'frame filters-duplicator'));
     $frame->setAttribute('data-interactive', 'data-interactive');
     $ol = new XMLElement('ol');
     $ol->setAttribute('data-add', __('Add namespace'));
     $ol->setAttribute('data-remove', __('Remove namespace'));
     if (isset($settings[self::getClass()], $settings[self::getClass()]['namespaces']) && is_array($settings[self::getClass()]['namespaces']) && !empty($settings[self::getClass()]['namespaces'])) {
         $ii = 0;
         foreach ($settings[self::getClass()]['namespaces'] as $name => $uri) {
             // Namespaces get saved to the file as $name => $uri, however in
             // the $_POST they are represented as $index => array. This loop
             // patches the difference.
             if (is_array($uri)) {
                 $name = $uri['name'];
                 $uri = $uri['uri'];
             }
             $li = new XMLElement('li');
             $li->setAttribute('class', 'instance');
             $header = new XMLElement('header');
             $header->appendChild(new XMLElement('h4', __('Namespace')));
             $li->appendChild($header);
             $group = new XMLElement('div');
             $group->setAttribute('class', 'two columns');
             $label = Widget::Label(__('Name'));
             $label->setAttribute('class', 'column');
             $label->appendChild(Widget::Input("fields[" . self::getClass() . "][namespaces][{$ii}][name]", General::sanitize($name)));
             $group->appendChild($label);
             $label = Widget::Label(__('URI'));
             $label->setAttribute('class', 'column');
             $label->appendChild(Widget::Input("fields[" . self::getClass() . "][namespaces][{$ii}][uri]", General::sanitize($uri)));
             $group->appendChild($label);
             $li->appendChild($group);
             $ol->appendChild($li);
             $ii++;
         }
     }
     $li = new XMLElement('li');
     $li->setAttribute('class', 'template');
     $li->setAttribute('data-type', 'namespace');
     $header = new XMLElement('header');
     $header->appendChild(new XMLElement('h4', __('Namespace')));
     $li->appendChild($header);
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $label = Widget::Label(__('Name'));
     $label->setAttribute('class', 'column');
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][namespaces][-1][name]'));
     $group->appendChild($label);
     $label = Widget::Label(__('URI'));
     $label->setAttribute('class', 'column');
     $label->appendChild(Widget::Input('fields[' . self::getClass() . '][namespaces][-1][uri]'));
     $group->appendChild($label);
     $li->appendChild($group);
     $ol->appendChild($li);
     $frame->appendChild($ol);
     $div->appendChild($frame);
     $fieldset->appendChild($div);
     // Check for existing Cache objects
     if (isset($cache_id)) {
         self::buildCacheInformation($fieldset, $cache, $cache_id);
     }
     $wrapper->appendChild($fieldset);
 }
 public function view()
 {
     Administration::instance()->Page->addScriptToHead(URL . '/extensions/templatedtextformatters/assets/templatedtextformatters.settings.js', 101, false);
     $about = array();
     if ($this->_context[0] && !is_object($this->formatter)) {
         $this->formatter = TextformatterManager::create($this->_context[0]);
     }
     if (is_object($this->formatter)) {
         $about = TextformatterManager::about($this->_context[0]);
     }
     if ($_SESSION['templatedtextformatters-alert']) {
         switch ($_SESSION['templatedtextformatters-alert']) {
             case 'saved':
                 $this->pageAlert(__('Templated Text Formatter updated at %1$s. <a href="%2$s" accesskey="c">Create another?</a> <a href="%3$s" accesskey="a">View all Templated Text Formatters</a>', array(Widget::Time()->generate(), SYMPHONY_URL . '/extension/templatedtextformatters/edit/', SYMPHONY_URL . '/extension/templatedtextformatters')), Alert::SUCCESS);
                 break;
             case 'created':
                 $this->pageAlert(__('Templated Text Formatter created at %1$s. <a href="%2$s" accesskey="c">Create another?</a> <a href="%3$s" accesskey="a">View all Templated Text Formatters</a>', array(Widget::Time()->generate(), SYMPHONY_URL . '/extension/templatedtextformatters/edit/', SYMPHONY_URL . '/extension/templatedtextformatters')), Alert::SUCCESS);
                 break;
         }
         unset($_SESSION['templatedtextformatters-alert']);
     }
     $fields = $_POST['fields'];
     $this->setPageType('form');
     $this->setTitle(__('%1$s &ndash; %2$s &ndash; %3$s', array(__('Symphony'), __('Templated Text Formatters'), $fields['name'] ? $fields['name'] : $about['name'])));
     $this->appendSubheading($fields['name'] ? $fields['name'] : ($about['name'] ? $about['name'] : 'Untitled'));
     $this->insertBreadcrumbs(array(Widget::Anchor(__('Templated Text Formatters'), SYMPHONY_URL . '/extension/templatedtextformatters')));
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', __('Essentials')));
     $p = new XMLElement('p', __('WARNING: Name change will disconnect this formatter from any chains and/or fields it may have been added to!'));
     $p->setAttribute('class', 'help');
     $fieldset->appendChild($p);
     $group = new XMLElement('div');
     $group->setAttribute('class', 'two columns');
     $div = new XMLElement('div', NULL, array('class' => 'column'));
     $label = Widget::Label(__('Name'));
     $label->appendChild(Widget::Input('fields[name]', $fields['name'] ? $fields['name'] : $about['name']));
     $div->appendChild(isset($this->_errors['name']) ? Widget::Error($label, $this->_errors['name']) : $label);
     $group->appendChild($div);
     $div = new XMLElement('div', NULL, array('class' => 'column'));
     $label = Widget::Label(__('Type'));
     $types = $this->_driver->listTypes();
     $options = array();
     if ($about['templatedtextformatters-type']) {
         $options[] = array($about['templatedtextformatters-type'], TRUE, $about['templatedtextformatters-type']);
     } else {
         foreach ($types as $t => $info) {
             $options[] = array($t, $fields['type'] ? $fields['type'] == $t : FALSE, $info['name'] ? $info['name'] : $t);
         }
     }
     $label->appendChild(Widget::Select('fields[type]', $options, array('id' => 'ds-context')));
     $div->appendChild($label);
     $group->appendChild($div);
     $fieldset->appendChild($group);
     $div = new XMLElement('div');
     $label = Widget::Label(__('Description'));
     $label->appendChild(new XMLElement('i', __('Optional')));
     $label->appendChild(Widget::Input('fields[description]', General::sanitize(isset($fields['description']) ? $fields['description'] : $about['description'])));
     $div->appendChild(isset($this->_errors['description']) ? Widget::Error($label, $this->_errors['description']) : $label);
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     if (is_object($this->formatter) && method_exists($this->formatter, 'ttf_form')) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', __('Format Options')));
         $this->formatter->ttf_form($fieldset, $this);
         $this->Form->appendChild($fieldset);
     }
     if (is_object($this->formatter)) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', __('Testing grounds')));
         $p = new XMLElement('p', __('Save changes each time you want to see updated output'));
         $p->setAttribute('class', 'help');
         $fieldset->appendChild($p);
         $group = new XMLElement('div');
         $group->setAttribute('class', 'two columns');
         $div = new XMLElement('div', NULL, array('class' => 'column'));
         $label = Widget::Label(__('Test input'));
         $label->appendChild(Widget::Textarea('fields[testin]', 5, 50, $fields['testin']));
         $div->appendChild($label);
         $group->appendChild($div);
         $div = new XMLElement('div', NULL, array('class' => 'column'));
         $label = Widget::Label(__('Test output'));
         $temp = '';
         if ($fields['testin']) {
             $temp = $this->formatter->run($fields['testin']);
         }
         $label->appendChild(Widget::Textarea('fields[testout]', 5, 50, $temp));
         $div->appendChild($label);
         $group->appendChild($div);
         $fieldset->appendChild($group);
         $this->Form->appendChild($fieldset);
     }
     $div = new XMLElement('div');
     $div->setAttribute('class', 'actions');
     $div->appendChild(Widget::Input('action[save]', $about['handle'] ? __('Save Changes') : __('Create formatter'), 'submit', array('accesskey' => 's')));
     if ($about['name']) {
         $button = new XMLElement('button', __('Delete'));
         $button->setAttributeArray(array('name' => 'action[delete]', 'class' => 'confirm delete', 'title' => __('Delete this formatter')));
         $div->appendChild($button);
     }
     $this->Form->appendChild($div);
 }