public static function updatePagesOfPrototype($prototype_id, $types)
 {
     if (empty($prototype_id)) {
         return;
     }
     $prototype = PageManager::fetchPageByID($prototype_id);
     $pages = self::fetchPagesOfPrototype($prototype_id);
     $fields = array();
     if (is_array($pages) && !empty($pages)) {
         foreach ($pages as $page) {
             $fields['params'] = $prototype['params'];
             $fields['events'] = $prototype['events'];
             $fields['data_sources'] = $prototype['data_sources'];
             PageManager::edit($page['id'], $fields, true);
             PageManager::addPageTypesToPage($page['id'], array_values(array_diff($types, array('prototype'))));
         }
     }
 }
Ejemplo n.º 2
0
 public function view()
 {
     $items = $_REQUEST['items'];
     if (!is_array($items) || empty($items)) {
         return;
     }
     $destination = self::kREORDER_UNKNOWN;
     if ($this->_context[0] == 'blueprints' && $this->_context[1] == 'pages') {
         $destination = self::kREORDER_PAGES;
     } elseif ($this->_context[0] == 'blueprints' && $this->_context[1] == 'sections') {
         $destination = self::kREORDER_SECTIONS;
     } elseif ($this->_context[0] == 'extensions') {
         $destination = self::kREORDER_EXTENSION;
     }
     switch ($destination) {
         case self::kREORDER_PAGES:
             foreach ($items as $id => $position) {
                 if (!PageManager::edit($id, array('sortorder' => $position))) {
                     $this->setHttpStatus(self::HTTP_STATUS_ERROR);
                     $this->_Result->setValue(__('A database error occurred while attempting to reorder.'));
                     break;
                 }
             }
             break;
         case self::kREORDER_SECTIONS:
             foreach ($items as $id => $position) {
                 if (!SectionManager::edit($id, array('sortorder' => $position))) {
                     $this->setHttpStatus(self::HTTP_STATUS_ERROR);
                     $this->_Result->setValue(__('A database error occurred while attempting to reorder.'));
                     break;
                 }
             }
             break;
         case self::kREORDER_EXTENSION:
             // TODO
             break;
         case self::kREORDER_UNKNOWN:
         default:
             $this->setHttpStatus(self::HTTP_STATUS_BAD_REQUEST);
             break;
     }
 }
 /**
  * This function will update all children of a particular page (if any)
  * by renaming/moving all related files to their new path and updating
  * their database information. This is a recursive function and will work
  * to any depth.
  *
  * @param integer $page_id
  *  The ID of the Page whose children need to be updated
  * @param string $page_path
  *  The path of the Page, which is the handles of the Page parents. If the
  *  page has multiple parents, they will be separated by a forward slash.
  *  eg. article/read. If a page has no parents, this parameter should be null.
  * @return boolean
  */
 public static function editPageChildren($page_id = null, $page_path = null)
 {
     if (!is_int($page_id)) {
         return false;
     }
     $page_path = trim($page_path, '/');
     $children = PageManager::fetchChildPages($page_id);
     foreach ($children as $child) {
         $child_id = $child['id'];
         $fields = array('path' => $page_path);
         if (!PageManager::createPageFiles($page_path, $child['handle'], $child['path'], $child['handle'])) {
             $success = false;
         }
         if (!PageManager::edit($child_id, $fields)) {
             $success = false;
         }
         self::editPageChildren($child_id, $page_path . '/' . $child['handle']);
     }
     return $success;
 }
Ejemplo n.º 4
0
 public function __formAction()
 {
     $fields = $_POST['fields'];
     $this->_errors = array();
     $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::EVENT);
     $providerClass = null;
     if (trim($fields['name']) == '') {
         $this->_errors['name'] = __('This is a required field');
     }
     if (trim($fields['source']) == '') {
         $this->_errors['source'] = __('This is a required field');
     }
     $filters = isset($fields['filters']) ? $fields['filters'] : array();
     // See if a Provided Datasource is saved
     if (!empty($providers)) {
         foreach ($providers as $providerClass => $provider) {
             if ($fields['source'] == call_user_func(array($providerClass, 'getSource'))) {
                 call_user_func_array(array($providerClass, 'validate'), array(&$fields, &$this->_errors));
                 break;
             }
             unset($providerClass);
         }
     }
     $classname = Lang::createHandle($fields['name'], 255, '_', false, true, array('@^[^a-z\\d]+@i' => '', '/[^\\w-\\.]/i' => ''));
     $rootelement = str_replace('_', '-', $classname);
     $extends = 'SectionEvent';
     // Check to make sure the classname is not empty after handlisation.
     if (empty($classname) && !isset($this->_errors['name'])) {
         $this->_errors['name'] = __('Please ensure name contains at least one Latin-based character.', array($classname));
     }
     $file = EVENTS . '/event.' . $classname . '.php';
     $isDuplicate = false;
     $queueForDeletion = null;
     if ($this->_context[0] == 'new' && is_file($file)) {
         $isDuplicate = true;
     } elseif ($this->_context[0] == 'edit') {
         $existing_handle = $this->_context[1];
         if ($classname != $existing_handle && is_file($file)) {
             $isDuplicate = true;
         } elseif ($classname != $existing_handle) {
             $queueForDeletion = EVENTS . '/event.' . $existing_handle . '.php';
         }
     }
     // Duplicate
     if ($isDuplicate) {
         $this->_errors['name'] = __('An Event with the name %s already exists', array('<code>' . $classname . '</code>'));
     }
     if (empty($this->_errors)) {
         $multiple = in_array('expect-multiple', $filters);
         $elements = null;
         $placeholder = '<!-- GRAB -->';
         $source = $fields['source'];
         $params = array('rootelement' => $rootelement);
         $about = array('name' => $fields['name'], 'version' => 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), 'release date' => DateTimeObj::getGMT('c'), 'author name' => Symphony::Author()->getFullName(), 'author website' => URL, 'author email' => Symphony::Author()->get('email'));
         // If there is a provider, get their template
         if ($providerClass) {
             $eventShell = file_get_contents(call_user_func(array($providerClass, 'getTemplate')));
         } else {
             $eventShell = file_get_contents($this->getTemplate('blueprints.event'));
             $about['trigger condition'] = $rootelement;
         }
         $this->__injectAboutInformation($eventShell, $about);
         // Replace the name
         $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
         // Build the templates
         if ($providerClass) {
             $eventShell = call_user_func(array($providerClass, 'prepare'), $fields, $params, $eventShell);
         } else {
             $this->__injectFilters($eventShell, $filters);
             // Add Documentation
             require_once CONTENT . '/content.ajaxeventdocumentation.php';
             $ajaxEventDoc = new contentAjaxEventDocumentation();
             $documentation = null;
             $doc_parts = array();
             // Add Documentation (Success/Failure)
             $ajaxEventDoc->addEntrySuccessDoc($doc_parts, $rootelement, $fields['source'], $filters);
             $ajaxEventDoc->addEntryFailureDoc($doc_parts, $rootelement, $fields['source'], $filters);
             // Filters
             $ajaxEventDoc->addDefaultFiltersDoc($doc_parts, $rootelement, $fields['source'], $filters);
             // Frontend Markup
             $ajaxEventDoc->addFrontendMarkupDoc($doc_parts, $rootelement, $fields['source'], $filters);
             $ajaxEventDoc->addSendMailFilterDoc($doc_parts, $rootelement, $fields['source'], $filters);
             /**
              * Allows adding documentation for new filters. A reference to the $documentation
              * array is provided, along with selected filters
              * @delegate AppendEventFilterDocumentation
              * @param string $context
              * '/blueprints/events/(edit|new|info)/'
              * @param array $selected
              *  An array of all the selected filters for this Event
              * @param array $documentation
              *  An array of all the documentation XMLElements, passed by reference
              */
             Symphony::ExtensionManager()->notifyMembers('AppendEventFilterDocumentation', '/blueprints/events/' . $rootelement . '/', array('selected' => $filters, 'documentation' => &$doc_parts));
             $documentation = join(PHP_EOL, array_map(create_function('$x', 'return rtrim($x->generate(true, 4));'), $doc_parts));
             $documentation = str_replace('\'', '\\\'', $documentation);
             $eventShell = str_replace('<!-- CLASS EXTENDS -->', $extends, $eventShell);
             $eventShell = str_replace('<!-- DOCUMENTATION -->', General::tabsToSpaces($documentation, 4), $eventShell);
         }
         $eventShell = str_replace('<!-- ROOT ELEMENT -->', $rootelement, $eventShell);
         $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
         $eventShell = str_replace('<!-- SOURCE -->', $source, $eventShell);
         // Remove left over placeholders
         $eventShell = preg_replace(array('/<!--[\\w ]++-->/'), '', $eventShell);
         if ($this->_context[0] == 'new') {
             /**
              * Prior to creating an Event, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate EventsPreCreate
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/events/'
              * @param string $file
              *  The path to the Event file
              * @param string $contents
              *  The contents for this Event as a string passed by reference
              * @param array $filters
              *  An array of the filters attached to this event
              */
             Symphony::ExtensionManager()->notifyMembers('EventPreCreate', '/blueprints/events/', array('file' => $file, 'contents' => &$eventShell, 'filters' => $filters));
         } else {
             /**
              * Prior to editing an Event, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate EventPreEdit
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/events/'
              * @param string $file
              *  The path to the Event file
              * @param string $contents
              *  The contents for this Event as a string passed by reference
              * @param array $filters
              *  An array of the filters attached to this event
              */
             Symphony::ExtensionManager()->notifyMembers('EventPreEdit', '/blueprints/events/', array('file' => $file, 'contents' => &$eventShell, 'filters' => $filters));
         }
         // Write the file
         if (!is_writable(dirname($file)) || !($write = General::writeFile($file, $eventShell, Symphony::Configuration()->get('write_mode', 'file')))) {
             $this->pageAlert(__('Failed to write Event to disk.') . ' ' . __('Please check permissions on %s.', array('<code>/workspace/events</code>')), Alert::ERROR);
             // Write successful
         } else {
             if (function_exists('opcache_invalidate')) {
                 opcache_invalidate($file, true);
             }
             // Attach this event to pages
             $connections = $fields['connections'];
             ResourceManager::setPages(RESOURCE_TYPE_EVENT, is_null($existing_handle) ? $classname : $existing_handle, $connections);
             if ($queueForDeletion) {
                 General::deleteFile($queueForDeletion);
                 $pages = PageManager::fetch(false, array('events', 'id'), array("\n                        `events` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]'\n                    "));
                 if (is_array($pages) && !empty($pages)) {
                     foreach ($pages as $page) {
                         $page['events'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['events']);
                         PageManager::edit($page['id'], $page);
                     }
                 }
             }
             if ($this->_context[0] == 'new') {
                 /**
                  * After creating the Event, the path to the Event file is provided
                  *
                  * @delegate EventPostCreate
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/events/'
                  * @param string $file
                  *  The path to the Event file
                  */
                 Symphony::ExtensionManager()->notifyMembers('EventPostCreate', '/blueprints/events/', array('file' => $file));
             } else {
                 /**
                  * After editing the Event, the path to the Event file is provided
                  *
                  * @delegate EventPostEdit
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/events/'
                  * @param string $file
                  *  The path to the Event file
                  * @param string $previous_file
                  *  The path of the previous Event file in the case where an Event may
                  *  have been renamed. To get the handle from this value, see
                  *  `EventManager::__getHandleFromFilename`
                  */
                 Symphony::ExtensionManager()->notifyMembers('EventPostEdit', '/blueprints/events/', array('file' => $file, 'previous_file' => $queueForDeletion ? $queueForDeletion : null));
             }
             redirect(SYMPHONY_URL . '/blueprints/events/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
         }
     }
 }
 /**
  * Given a resource type, a handle and a page, this function detaches
  * the given handle (which represents either a datasource or event) to that page.
  *
  * @param integer $type
  *  The resource type, either `RESOURCE_TYPE_EVENT` or `RESOURCE_TYPE_DS`
  * @param string $r_handle
  *  The handle of the resource.
  * @param integer $page_id
  *  The ID of the page.
  */
 public static function detach($type, $r_handle, $page_id)
 {
     $col = self::getColumnFromType($type);
     $pages = PageManager::fetch(false, array($col), array(sprintf('`id` = %d', $page_id)));
     if (is_array($pages) && count($pages) == 1) {
         $result = $pages[0][$col];
         $values = explode(',', $result);
         $idx = array_search($r_handle, $values, false);
         if ($idx !== false) {
             array_splice($values, $idx, 1);
             $result = implode(',', $values);
             return PageManager::edit($page_id, array($col => MySQL::cleanValue($result)));
         }
     }
     return false;
 }
 public function __formAction()
 {
     $fields = $_POST['fields'];
     $this->_errors = array();
     $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::DATASOURCE);
     $providerClass = null;
     if (trim($fields['name']) == '') {
         $this->_errors['name'] = __('This is a required field');
     }
     if ($fields['source'] == 'static_xml') {
         if (trim($fields['static_xml']) == '') {
             $this->_errors['static_xml'] = __('This is a required field');
         } else {
             $xml_errors = null;
             include_once TOOLKIT . '/class.xsltprocess.php';
             General::validateXML($fields['static_xml'], $xml_errors, false, new XsltProcess());
             if (!empty($xml_errors)) {
                 $this->_errors['static_xml'] = __('XML is invalid.');
             }
         }
     } elseif (is_numeric($fields['source'])) {
         if (strlen(trim($fields['max_records'])) == 0 || is_numeric($fields['max_records']) && $fields['max_records'] < 1) {
             if ($fields['paginate_results'] === 'yes') {
                 $this->_errors['max_records'] = __('A result limit must be set');
             }
         } elseif (!self::__isValidPageString($fields['max_records'])) {
             $this->_errors['max_records'] = __('Must be a valid number or parameter');
         }
         if (strlen(trim($fields['page_number'])) == 0 || is_numeric($fields['page_number']) && $fields['page_number'] < 1) {
             if ($fields['paginate_results'] === 'yes') {
                 $this->_errors['page_number'] = __('A page number must be set');
             }
         } elseif (!self::__isValidPageString($fields['page_number'])) {
             $this->_errors['page_number'] = __('Must be a valid number or parameter');
         }
         // See if a Provided Datasource is saved
     } elseif (!empty($providers)) {
         foreach ($providers as $providerClass => $provider) {
             if ($fields['source'] == call_user_func(array($providerClass, 'getSource'))) {
                 call_user_func_array(array($providerClass, 'validate'), array(&$fields, &$this->_errors));
                 break;
             }
             unset($providerClass);
         }
     }
     $classname = Lang::createHandle($fields['name'], 255, '_', false, true, array('@^[^a-z\\d]+@i' => '', '/[^\\w-\\.]/i' => ''));
     $rootelement = str_replace('_', '-', $classname);
     // Check to make sure the classname is not empty after handlisation.
     if (empty($classname) && !isset($this->_errors['name'])) {
         $this->_errors['name'] = __('Please ensure name contains at least one Latin-based character.', array($classname));
     }
     $file = DATASOURCES . '/data.' . $classname . '.php';
     $isDuplicate = false;
     $queueForDeletion = null;
     if ($this->_context[0] == 'new' && is_file($file)) {
         $isDuplicate = true;
     } elseif ($this->_context[0] == 'edit') {
         $existing_handle = $this->_context[1];
         if ($classname != $existing_handle && is_file($file)) {
             $isDuplicate = true;
         } elseif ($classname != $existing_handle) {
             $queueForDeletion = DATASOURCES . '/data.' . $existing_handle . '.php';
         }
     }
     // Duplicate
     if ($isDuplicate) {
         $this->_errors['name'] = __('A Data source with the name %s already exists', array('<code>' . $classname . '</code>'));
     }
     if (empty($this->_errors)) {
         $filters = array();
         $elements = null;
         $source = $fields['source'];
         $params = array('rootelement' => $rootelement);
         $about = array('name' => $fields['name'], 'version' => 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), 'release date' => DateTimeObj::getGMT('c'), 'author name' => Symphony::Author()->getFullName(), 'author website' => URL, 'author email' => Symphony::Author()->get('email'));
         // If there is a provider, get their template
         if ($providerClass) {
             $dsShell = file_get_contents(call_user_func(array($providerClass, 'getTemplate')));
         } else {
             $dsShell = file_get_contents($this->getTemplate('blueprints.datasource'));
         }
         // Author metadata
         self::injectAboutInformation($dsShell, $about);
         // Do dependencies, the template file must have <!-- CLASS NAME -->
         $dsShell = str_replace('<!-- CLASS NAME -->', $classname, $dsShell);
         // If there is a provider, let them do the prepartion work
         if ($providerClass) {
             $dsShell = call_user_func(array($providerClass, 'prepare'), $fields, $params, $dsShell);
         } else {
             switch ($source) {
                 case 'authors':
                     $extends = 'AuthorDatasource';
                     if (isset($fields['filter']['author'])) {
                         $filters = $fields['filter']['author'];
                     }
                     $elements = $fields['xml_elements'];
                     $params['order'] = $fields['order'];
                     $params['redirectonempty'] = $fields['redirect_on_empty'];
                     $params['redirectonforbidden'] = $fields['redirect_on_forbidden'];
                     $params['redirectonrequired'] = $fields['redirect_on_required'];
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     $params['negateparam'] = trim($fields['negate_url_param']);
                     $params['paramoutput'] = $fields['param'];
                     $params['sort'] = $fields['sort'];
                     break;
                 case 'navigation':
                     $extends = 'NavigationDatasource';
                     if (isset($fields['filter']['navigation'])) {
                         $filters = $fields['filter']['navigation'];
                     }
                     $params['order'] = $fields['order'];
                     $params['redirectonempty'] = $fields['redirect_on_empty'];
                     $params['redirectonforbidden'] = $fields['redirect_on_forbidden'];
                     $params['redirectonrequired'] = $fields['redirect_on_required'];
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     $params['negateparam'] = trim($fields['negate_url_param']);
                     break;
                 case 'static_xml':
                     $extends = 'StaticXMLDatasource';
                     $fields['static_xml'] = trim($fields['static_xml']);
                     if (preg_match('/^<\\?xml/i', $fields['static_xml']) == true) {
                         // Need to remove any XML declaration
                         $fields['static_xml'] = preg_replace('/^<\\?xml[^>]+>/i', null, $fields['static_xml']);
                     }
                     $params['static'] = sprintf('%s', trim($fields['static_xml']));
                     break;
                 default:
                     $extends = 'SectionDatasource';
                     $elements = $fields['xml_elements'];
                     if (is_array($fields['filter']) && !empty($fields['filter'])) {
                         $filters = array();
                         foreach ($fields['filter'] as $f) {
                             foreach ($f as $key => $val) {
                                 $filters[$key] = $val;
                             }
                         }
                     }
                     $params['order'] = $fields['order'];
                     $params['group'] = $fields['group'];
                     $params['paginateresults'] = $fields['paginate_results'];
                     $params['limit'] = $fields['max_records'];
                     $params['startpage'] = $fields['page_number'];
                     $params['redirectonempty'] = $fields['redirect_on_empty'];
                     $params['redirectonforbidden'] = $fields['redirect_on_forbidden'];
                     $params['redirectonrequired'] = $fields['redirect_on_required'];
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     $params['negateparam'] = trim($fields['negate_url_param']);
                     $params['paramoutput'] = $fields['param'];
                     $params['sort'] = $fields['sort'];
                     $params['htmlencode'] = $fields['html_encode'];
                     $params['associatedentrycounts'] = $fields['associated_entry_counts'];
                     break;
             }
             $this->__injectVarList($dsShell, $params);
             $this->__injectIncludedElements($dsShell, $elements);
             self::injectFilters($dsShell, $filters);
             if (preg_match_all('@(\\$ds-[0-9a-z_\\.\\-]+)@i', $dsShell, $matches)) {
                 $dependencies = General::array_remove_duplicates($matches[1]);
                 $dsShell = str_replace('<!-- DS DEPENDENCY LIST -->', "'" . implode("', '", $dependencies) . "'", $dsShell);
             }
             $dsShell = str_replace('<!-- CLASS EXTENDS -->', $extends, $dsShell);
             $dsShell = str_replace('<!-- SOURCE -->', $source, $dsShell);
         }
         if ($this->_context[0] == 'new') {
             /**
              * Prior to creating the Datasource, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate DatasourcePreCreate
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/datasources/'
              * @param string $file
              *  The path to the Datasource file
              * @param string $contents
              *  The contents for this Datasource as a string passed by reference
              * @param array $params
              *  An array of all the `$dsParam*` values
              * @param array $elements
              *  An array of all the elements included in this datasource
              * @param array $filters
              *  An associative array of all the filters for this datasource with the key
              *  being the `field_id` and the value the filter.
              * @param array $dependencies
              *  An array of dependencies that this datasource has
              */
             Symphony::ExtensionManager()->notifyMembers('DatasourcePreCreate', '/blueprints/datasources/', array('file' => $file, 'contents' => &$dsShell, 'params' => $params, 'elements' => $elements, 'filters' => $filters, 'dependencies' => $dependencies));
         } else {
             /**
              * Prior to editing a Datasource, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate DatasourcePreEdit
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/datasources/'
              * @param string $file
              *  The path to the Datasource file
              * @param string $contents
              *  The contents for this Datasource as a string passed by reference
              * @param array $dependencies
              *  An array of dependencies that this datasource has
              * @param array $params
              *  An array of all the `$dsParam*` values
              * @param array $elements
              *  An array of all the elements included in this datasource
              * @param array $filters
              *  An associative array of all the filters for this datasource with the key
              *  being the `field_id` and the value the filter.
              */
             Symphony::ExtensionManager()->notifyMembers('DatasourcePreEdit', '/blueprints/datasources/', array('file' => $file, 'contents' => &$dsShell, 'dependencies' => $dependencies, 'params' => $params, 'elements' => $elements, 'filters' => $filters));
         }
         // Remove left over placeholders
         $dsShell = preg_replace(array('/<!--[\\w ]++-->/', '/(\\t+[\\r\\n]){2,}/', '/(\\r\\n){2,}/'), '$1', $dsShell);
         // Write the file
         if (!is_writable(dirname($file)) || !General::writeFile($file, $dsShell, Symphony::Configuration()->get('write_mode', 'file'), 'w', true)) {
             $this->pageAlert(__('Failed to write Data source to disk.') . ' ' . __('Please check permissions on %s.', array('<code>/workspace/data-sources</code>')), Alert::ERROR);
             // Write successful
         } else {
             if (function_exists('opcache_invalidate')) {
                 opcache_invalidate($file, true);
             }
             // Attach this datasources to pages
             $connections = $fields['connections'];
             ResourceManager::setPages(ResourceManager::RESOURCE_TYPE_DS, is_null($existing_handle) ? $classname : $existing_handle, $connections);
             // If the datasource has been updated and the name changed, then adjust all the existing pages that have the old datasource name
             if ($queueForDeletion) {
                 General::deleteFile($queueForDeletion);
                 // Update pages that use this DS
                 $pages = PageManager::fetch(false, array('data_sources', 'id'), array("\n                        `data_sources` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]'\n                    "));
                 if (is_array($pages) && !empty($pages)) {
                     foreach ($pages as $page) {
                         $page['data_sources'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['data_sources']);
                         PageManager::edit($page['id'], $page);
                     }
                 }
             }
             if ($this->_context[0] == 'new') {
                 /**
                  * After creating the Datasource, the path to the Datasource file is provided
                  *
                  * @delegate DatasourcePostCreate
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/datasources/'
                  * @param string $file
                  *  The path to the Datasource file
                  */
                 Symphony::ExtensionManager()->notifyMembers('DatasourcePostCreate', '/blueprints/datasources/', array('file' => $file));
             } else {
                 /**
                  * After editing the Datasource, the path to the Datasource file is provided
                  *
                  * @delegate DatasourcePostEdit
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/datasources/'
                  * @param string $file
                  *  The path to the Datasource file
                  * @param string $previous_file
                  *  The path of the previous Datasource file in the case where a Datasource may
                  *  have been renamed. To get the handle from this value, see
                  *  `DatasourceManager::__getHandleFromFilename`
                  */
                 Symphony::ExtensionManager()->notifyMembers('DatasourcePostEdit', '/blueprints/datasources/', array('file' => $file, 'previous_file' => $queueForDeletion ? $queueForDeletion : null));
             }
             redirect(SYMPHONY_URL . '/blueprints/datasources/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
         }
     }
 }
 public function __actionEdit()
 {
     if ($this->_context[0] != 'new' && !($page_id = (int) $this->_context[1])) {
         redirect(SYMPHONY_URL . '/blueprints/pages/');
     }
     $parent_link_suffix = NULL;
     if (isset($_REQUEST['parent']) && is_numeric($_REQUEST['parent'])) {
         $parent_link_suffix = '?parent=' . $_REQUEST['parent'];
     }
     if (@array_key_exists('delete', $_POST['action'])) {
         $this->__actionDelete($page_id, SYMPHONY_URL . '/blueprints/pages/' . $parent_link_suffix);
     }
     if (@array_key_exists('save', $_POST['action'])) {
         $fields = $_POST['fields'];
         $this->_errors = array();
         $autogenerated_handle = false;
         if (!isset($fields['title']) || trim($fields['title']) == '') {
             $this->_errors['title'] = __('This is a required field');
         }
         if (trim($fields['type']) != '' && preg_match('/(index|404|403)/i', $fields['type'])) {
             $types = preg_split('/\\s*,\\s*/', strtolower($fields['type']), -1, PREG_SPLIT_NO_EMPTY);
             if (in_array('index', $types) && PageManager::hasPageTypeBeenUsed($page_id, 'index')) {
                 $this->_errors['type'] = __('An index type page already exists.');
             } elseif (in_array('404', $types) && PageManager::hasPageTypeBeenUsed($page_id, '404')) {
                 $this->_errors['type'] = __('A 404 type page already exists.');
             } elseif (in_array('403', $types) && PageManager::hasPageTypeBeenUsed($page_id, '403')) {
                 $this->_errors['type'] = __('A 403 type page already exists.');
             }
         }
         if (trim($fields['handle']) == '') {
             $fields['handle'] = $fields['title'];
             $autogenerated_handle = true;
         }
         $fields['handle'] = PageManager::createHandle($fields['handle']);
         if (empty($fields['handle']) && !isset($this->_errors['title'])) {
             $this->_errors['handle'] = __('Please ensure handle contains at least one Latin-based character.');
         }
         /**
          * Just after the Symphony validation has run, allows Developers
          * to run custom validation logic on a Page
          *
          * @delegate PagePostValidate
          * @since Symphony 2.2
          * @param string $context
          * '/blueprints/pages/'
          * @param array $fields
          *  The `$_POST['fields']` array. This should be read-only and not changed
          *  through this delegate.
          * @param array $errors
          *  An associative array of errors, with the key matching a key in the
          *  `$fields` array, and the value being the string of the error. `$errors`
          *  is passed by reference.
          */
         Symphony::ExtensionManager()->notifyMembers('PagePostValidate', '/blueprints/pages/', array('fields' => $fields, 'errors' => &$errors));
         if (empty($this->_errors)) {
             $autogenerated_handle = false;
             if ($fields['params']) {
                 $fields['params'] = trim(preg_replace('@\\/{2,}@', '/', $fields['params']), '/');
             }
             // Clean up type list
             $types = preg_split('/\\s*,\\s*/', $fields['type'], -1, PREG_SPLIT_NO_EMPTY);
             $types = @array_map('trim', $types);
             unset($fields['type']);
             $fields['parent'] = $fields['parent'] != __('None') ? $fields['parent'] : null;
             $fields['data_sources'] = is_array($fields['data_sources']) ? implode(',', $fields['data_sources']) : NULL;
             $fields['events'] = is_array($fields['events']) ? implode(',', $fields['events']) : NULL;
             $fields['path'] = null;
             if ($fields['parent']) {
                 $fields['path'] = PageManager::resolvePagePath((int) $fields['parent']);
             }
             // Check for duplicates:
             $current = PageManager::fetchPageByID($page_id);
             if (empty($current)) {
                 $fields['sortorder'] = PageManager::fetchNextSortOrder();
             }
             $where = array();
             if (!empty($current)) {
                 $where[] = "p.id != {$page_id}";
             }
             $where[] = "p.handle = '" . $fields['handle'] . "'";
             $where[] = is_null($fields['path']) ? "p.path IS NULL" : "p.path = '" . $fields['path'] . "'";
             $duplicate = PageManager::fetch(false, array('*'), $where);
             // If duplicate
             if (!empty($duplicate)) {
                 if ($autogenerated_handle) {
                     $this->_errors['title'] = __('A page with that title already exists');
                 } else {
                     $this->_errors['handle'] = __('A page with that handle already exists');
                 }
             } else {
                 // New page?
                 if (empty($current)) {
                     $file_created = PageManager::createPageFiles($fields['path'], $fields['handle']);
                 } else {
                     $file_created = PageManager::createPageFiles($fields['path'], $fields['handle'], $current['path'], $current['handle']);
                 }
                 // If the file wasn't created, it's usually permissions related
                 if (!$file_created) {
                     $redirect = null;
                     return $this->pageAlert(__('Page Template could not be written to disk.') . ' ' . __('Please check permissions on %s.', array('<code>/workspace/pages</code>')), Alert::ERROR);
                 }
                 // Insert the new data:
                 if (empty($current)) {
                     /**
                      * Just prior to creating a new Page record in `tbl_pages`, provided
                      * with the `$fields` associative array. Use with caution, as no
                      * duplicate page checks are run after this delegate has fired
                      *
                      * @delegate PagePreCreate
                      * @since Symphony 2.2
                      * @param string $context
                      * '/blueprints/pages/'
                      * @param array $fields
                      *  The `$_POST['fields']` array passed by reference
                      */
                     Symphony::ExtensionManager()->notifyMembers('PagePreCreate', '/blueprints/pages/', array('fields' => &$fields));
                     if (!($page_id = PageManager::add($fields))) {
                         $this->pageAlert(__('Unknown errors occurred while attempting to save.') . '<a href="' . SYMPHONY_URL . '/system/log/">' . __('Check your activity log') . '</a>.', Alert::ERROR);
                     } else {
                         /**
                          * Just after the creation of a new page in `tbl_pages`
                          *
                          * @delegate PagePostCreate
                          * @since Symphony 2.2
                          * @param string $context
                          * '/blueprints/pages/'
                          * @param integer $page_id
                          *  The ID of the newly created Page
                          * @param array $fields
                          *  An associative array of data that was just saved for this page
                          */
                         Symphony::ExtensionManager()->notifyMembers('PagePostCreate', '/blueprints/pages/', array('page_id' => $page_id, 'fields' => &$fields));
                         $redirect = "/blueprints/pages/edit/{$page_id}/created/{$parent_link_suffix}";
                     }
                 } else {
                     /**
                      * Just prior to updating a Page record in `tbl_pages`, provided
                      * with the `$fields` associative array. Use with caution, as no
                      * duplicate page checks are run after this delegate has fired
                      *
                      * @delegate PagePreEdit
                      * @since Symphony 2.2
                      * @param string $context
                      * '/blueprints/pages/'
                      * @param integer $page_id
                      *  The ID of the Page that is about to be updated
                      * @param array $fields
                      *  The `$_POST['fields']` array passed by reference
                      */
                     Symphony::ExtensionManager()->notifyMembers('PagePreEdit', '/blueprints/pages/', array('page_id' => $page_id, 'fields' => &$fields));
                     if (!PageManager::edit($page_id, $fields, true)) {
                         return $this->pageAlert(__('Unknown errors occurred while attempting to save.') . '<a href="' . SYMPHONY_URL . '/system/log/">' . __('Check your activity log') . '</a>.', Alert::ERROR);
                     } else {
                         /**
                          * Just after updating a page in `tbl_pages`
                          *
                          * @delegate PagePostEdit
                          * @since Symphony 2.2
                          * @param string $context
                          * '/blueprints/pages/'
                          * @param integer $page_id
                          *  The ID of the Page that was just updated
                          * @param array $fields
                          *  An associative array of data that was just saved for this page
                          */
                         Symphony::ExtensionManager()->notifyMembers('PagePostEdit', '/blueprints/pages/', array('page_id' => $page_id, 'fields' => $fields));
                         $redirect = "/blueprints/pages/edit/{$page_id}/saved/{$parent_link_suffix}";
                     }
                 }
             }
             // Only proceed if there was no errors saving/creating the page
             if (empty($this->_errors)) {
                 /**
                  * Just before the page's types are saved into `tbl_pages_types`.
                  * Use with caution as no further processing is done on the `$types`
                  * array to prevent duplicate `$types` from occurring (ie. two index
                  * page types). Your logic can use the PageManger::hasPageTypeBeenUsed
                  * function to perform this logic.
                  *
                  * @delegate PageTypePreCreate
                  * @since Symphony 2.2
                  * @see toolkit.PageManager#hasPageTypeBeenUsed
                  * @param string $context
                  * '/blueprints/pages/'
                  * @param integer $page_id
                  *  The ID of the Page that was just created or updated
                  * @param array $types
                  *  An associative array of the types for this page passed by reference.
                  */
                 Symphony::ExtensionManager()->notifyMembers('PageTypePreCreate', '/blueprints/pages/', array('page_id' => $page_id, 'types' => &$types));
                 // Assign page types:
                 PageManager::addPageTypesToPage($page_id, $types);
                 // Find and update children:
                 if ($this->_context[0] == 'edit') {
                     PageManager::editPageChildren($page_id, $fields['path'] . '/' . $fields['handle']);
                 }
                 if ($redirect) {
                     redirect(SYMPHONY_URL . $redirect);
                 }
             }
         }
         // If there was any errors, either with pre processing or because of a
         // duplicate page, return.
         if (is_array($this->_errors) && !empty($this->_errors)) {
             return $this->pageAlert(__('An error occurred while processing this form. See below for details.'), Alert::ERROR);
         }
     }
 }
    public function __formAction()
    {
        $fields = $_POST['fields'];
        $this->_errors = array();
        $providers = Symphony::ExtensionManager()->getProvidersOf(iProvider::EVENT);
        $providerClass = null;
        if (trim($fields['name']) == '') {
            $this->_errors['name'] = __('This is a required field');
        }
        if (trim($fields['source']) == '') {
            $this->_errors['source'] = __('This is a required field');
        }
        $filters = isset($fields['filters']) ? $fields['filters'] : array();
        // See if a Provided Datasource is saved
        if (!empty($providers)) {
            foreach ($providers as $providerClass => $provider) {
                if ($fields['source'] == call_user_func(array($providerClass, 'getSource'))) {
                    call_user_func_array(array($providerClass, 'validate'), array(&$fields, &$this->_errors));
                    break;
                }
                unset($providerClass);
            }
        }
        $classname = Lang::createHandle($fields['name'], 255, '_', false, true, array('@^[^a-z\\d]+@i' => '', '/[^\\w-\\.]/i' => ''));
        $rootelement = str_replace('_', '-', $classname);
        $extends = 'SectionEvent';
        // Check to make sure the classname is not empty after handlisation.
        if (empty($classname) && !isset($this->_errors['name'])) {
            $this->_errors['name'] = __('Please ensure name contains at least one Latin-based character.', array($classname));
        }
        $file = EVENTS . '/event.' . $classname . '.php';
        $isDuplicate = false;
        $queueForDeletion = NULL;
        if ($this->_context[0] == 'new' && is_file($file)) {
            $isDuplicate = true;
        } else {
            if ($this->_context[0] == 'edit') {
                $existing_handle = $this->_context[1];
                if ($classname != $existing_handle && is_file($file)) {
                    $isDuplicate = true;
                } else {
                    if ($classname != $existing_handle) {
                        $queueForDeletion = EVENTS . '/event.' . $existing_handle . '.php';
                    }
                }
            }
        }
        // Duplicate
        if ($isDuplicate) {
            $this->_errors['name'] = __('An Event with the name %s already exists', array('<code>' . $classname . '</code>'));
        }
        if (empty($this->_errors)) {
            $multiple = in_array('expect-multiple', $filters);
            $elements = NULL;
            $placeholder = '<!-- GRAB -->';
            $source = $fields['source'];
            $params = array('rootelement' => $rootelement);
            $about = array('name' => $fields['name'], 'version' => 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), 'release date' => DateTimeObj::getGMT('c'), 'author name' => Administration::instance()->Author->getFullName(), 'author website' => URL, 'author email' => Administration::instance()->Author->get('email'));
            // If there is a provider, get their template
            if ($providerClass) {
                $eventShell = file_get_contents(call_user_func(array($providerClass, 'getTemplate')));
            } else {
                $eventShell = file_get_contents($this->getTemplate('blueprints.event'));
                $about['trigger condition'] = $rootelement;
            }
            $this->__injectAboutInformation($eventShell, $about);
            // Replace the name
            $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
            // Build the templates
            if ($providerClass) {
                $eventShell = call_user_func(array($providerClass, 'prepare'), $fields, $params, $eventShell);
            } else {
                $this->__injectFilters($eventShell, $filters);
                // Add Documentation
                $documentation = NULL;
                $documentation_parts = array();
                $documentation_parts[] = new XMLElement('h3', __('Success and Failure XML Examples'));
                $documentation_parts[] = new XMLElement('p', __('When saved successfully, the following XML will be returned:'));
                if ($multiple) {
                    $code = new XMLElement($rootelement);
                    $entry = new XMLElement('entry', NULL, array('index' => '0', 'result' => 'success', 'type' => 'create | edit'));
                    $entry->appendChild(new XMLElement('message', __('Entry [created | edited] successfully.')));
                    $code->appendChild($entry);
                } else {
                    $code = new XMLElement($rootelement, NULL, array('result' => 'success', 'type' => 'create | edit'));
                    $code->appendChild(new XMLElement('message', __('Entry [created | edited] successfully.')));
                }
                $documentation_parts[] = self::processDocumentationCode($code);
                $documentation_parts[] = new XMLElement('p', __('When an error occurs during saving, due to either missing or invalid fields, the following XML will be returned') . ($multiple ? ' (<strong> ' . __('Notice that it is possible to get mixtures of success and failure messages when using the ‘Allow Multiple’ option') . '</strong>)' : NULL) . ':');
                if ($multiple) {
                    $code = new XMLElement($rootelement);
                    $entry = new XMLElement('entry', NULL, array('index' => '0', 'result' => 'error'));
                    $entry->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
                    $entry->appendChild(new XMLElement('field-name', NULL, array('type' => 'invalid | missing')));
                    $code->appendChild($entry);
                    $entry = new XMLElement('entry', NULL, array('index' => '1', 'result' => 'success', 'type' => 'create | edit'));
                    $entry->appendChild(new XMLElement('message', __('Entry [created | edited] successfully.')));
                    $code->appendChild($entry);
                } else {
                    $code = new XMLElement($rootelement, NULL, array('result' => 'error'));
                    $code->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
                    $code->appendChild(new XMLElement('field-name', NULL, array('type' => 'invalid | missing')));
                }
                $code->setValue('...', false);
                $documentation_parts[] = self::processDocumentationCode($code);
                if (is_array($filters) && !empty($filters)) {
                    $documentation_parts[] = new XMLElement('p', __('The following is an example of what is returned if any options return an error:'));
                    $code = new XMLElement($rootelement, NULL, array('result' => 'error'));
                    $code->appendChild(new XMLElement('message', __('Entry encountered errors when saving.')));
                    $code->appendChild(new XMLElement('filter', NULL, array('name' => 'admin-only', 'status' => 'failed')));
                    $code->appendChild(new XMLElement('filter', __('Recipient not found'), array('name' => 'send-email', 'status' => 'failed')));
                    $code->setValue('...', false);
                    $documentation_parts[] = self::processDocumentationCode($code);
                }
                $documentation_parts[] = new XMLElement('h3', __('Example Front-end Form Markup'));
                $documentation_parts[] = new XMLElement('p', __('This is an example of the form markup you can use on your frontend:'));
                $container = new XMLElement('form', NULL, array('method' => 'post', 'action' => '', 'enctype' => 'multipart/form-data'));
                $container->appendChild(Widget::Input('MAX_FILE_SIZE', (string) min(ini_size_to_bytes(ini_get('upload_max_filesize')), Symphony::Configuration()->get('max_upload_size', 'admin')), 'hidden'));
                if (is_numeric($fields['source'])) {
                    $section = SectionManager::fetch($fields['source']);
                    if ($section instanceof Section) {
                        $section_fields = $section->fetchFields();
                        if (is_array($section_fields) && !empty($section_fields)) {
                            foreach ($section_fields as $f) {
                                if ($f->getExampleFormMarkup() instanceof XMLElement) {
                                    $container->appendChild($f->getExampleFormMarkup());
                                }
                            }
                        }
                    }
                }
                $container->appendChild(Widget::Input('action[' . $rootelement . ']', __('Submit'), 'submit'));
                $code = $container->generate(true);
                $documentation_parts[] = self::processDocumentationCode($multiple ? str_replace('fields[', 'fields[0][', $code) : $code);
                $documentation_parts[] = new XMLElement('p', __('To edit an existing entry, include the entry ID value of the entry in the form. This is best as a hidden field like so:'));
                $documentation_parts[] = self::processDocumentationCode(Widget::Input('id' . ($multiple ? '[0]' : NULL), '23', 'hidden'));
                $documentation_parts[] = new XMLElement('p', __('To redirect to a different location upon a successful save, include the redirect location in the form. This is best as a hidden field like so, where the value is the URL to redirect to:'));
                $documentation_parts[] = self::processDocumentationCode(Widget::Input('redirect', URL . '/success/', 'hidden'));
                if (in_array('send-email', $filters)) {
                    $documentation_parts[] = new XMLElement('h3', __('Send Notification Email'));
                    $documentation_parts[] = new XMLElement('p', __('Upon the event successfully saving the entry, this option takes input from the form and send an email to the desired recipient.') . ' <strong>' . __('It currently does not work with ‘Allow Multiple’') . '</strong>. ' . __('The following are the recognised fields:'));
                    $documentation_parts[] = self::processDocumentationCode('send-email[sender-email] // ' . __('Optional') . PHP_EOL . 'send-email[sender-name] // ' . __('Optional') . PHP_EOL . 'send-email[reply-to-email] // ' . __('Optional') . PHP_EOL . 'send-email[reply-to-name] // ' . __('Optional') . PHP_EOL . 'send-email[subject]' . PHP_EOL . 'send-email[body]' . PHP_EOL . 'send-email[recipient] // ' . __('list of comma-separated author usernames.'));
                    $documentation_parts[] = new XMLElement('p', __('All of these fields can be set dynamically using the exact field name of another field in the form as shown below in the example form:'));
                    $documentation_parts[] = self::processDocumentationCode('<form action="" method="post">
		<fieldset>
			<label>' . __('Name') . ' <input type="text" name="fields[author]" value="" /></label>
			<label>' . __('Email') . ' <input type="text" name="fields[email]" value="" /></label>
			<label>' . __('Message') . ' <textarea name="fields[message]" rows="5" cols="21"></textarea></label>
			<input name="send-email[sender-email]" value="fields[email]" type="hidden" />
			<input name="send-email[sender-name]" value="fields[author]" type="hidden" />
			<input name="send-email[reply-to-email]" value="fields[email]" type="hidden" />
			<input name="send-email[reply-to-name]" value="fields[author]" type="hidden" />
			<input name="send-email[subject]" value="You are being contacted" type="hidden" />
			<input name="send-email[body]" value="fields[message]" type="hidden" />
			<input name="send-email[recipient]" value="fred" type="hidden" />
			<input id="submit" type="submit" name="action[save-contact-form]" value="Send" />
		</fieldset>
	</form>');
                }
                /**
                 * Allows adding documentation for new filters. A reference to the $documentation
                 * array is provided, along with selected filters
                 * @delegate AppendEventFilterDocumentation
                 * @param string $context
                 * '/blueprints/events/(edit|new|info)/'
                 * @param array $selected
                 *  An array of all the selected filters for this Event
                 * @param array $documentation
                 *  An array of all the documentation XMLElements, passed by reference
                 */
                Symphony::ExtensionManager()->notifyMembers('AppendEventFilterDocumentation', '/blueprints/events/' . $this->_context[0] . '/', array('selected' => $filters, 'documentation' => &$documentation_parts));
                $documentation = join(PHP_EOL, array_map(create_function('$x', 'return rtrim($x->generate(true, 4));'), $documentation_parts));
                $documentation = str_replace('\'', '\\\'', $documentation);
                $eventShell = str_replace('<!-- CLASS EXTENDS -->', $extends, $eventShell);
                $eventShell = str_replace('<!-- DOCUMENTATION -->', General::tabsToSpaces($documentation, 2), $eventShell);
            }
            $eventShell = str_replace('<!-- ROOT ELEMENT -->', $rootelement, $eventShell);
            $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
            $eventShell = str_replace('<!-- SOURCE -->', $source, $eventShell);
            // Remove left over placeholders
            $eventShell = preg_replace(array('/<!--[\\w ]++-->/'), '', $eventShell);
            if ($this->_context[0] == 'new') {
                /**
                 * Prior to creating an Event, the file path where it will be written to
                 * is provided and well as the contents of that file.
                 *
                 * @delegate EventsPreCreate
                 * @since Symphony 2.2
                 * @param string $context
                 * '/blueprints/events/'
                 * @param string $file
                 *  The path to the Event file
                 * @param string $contents
                 *  The contents for this Event as a string passed by reference
                 * @param array $filters
                 *  An array of the filters attached to this event
                 */
                Symphony::ExtensionManager()->notifyMembers('EventPreCreate', '/blueprints/events/', array('file' => $file, 'contents' => &$eventShell, 'filters' => $filters));
            } else {
                /**
                 * Prior to editing an Event, the file path where it will be written to
                 * is provided and well as the contents of that file.
                 *
                 * @delegate EventPreEdit
                 * @since Symphony 2.2
                 * @param string $context
                 * '/blueprints/events/'
                 * @param string $file
                 *  The path to the Event file
                 * @param string $contents
                 *  The contents for this Event as a string passed by reference
                 * @param array $filters
                 *  An array of the filters attached to this event
                 */
                Symphony::ExtensionManager()->notifyMembers('EventPreEdit', '/blueprints/events/', array('file' => $file, 'contents' => &$eventShell, 'filters' => $filters));
            }
            // Write the file
            if (!is_writable(dirname($file)) || !($write = General::writeFile($file, $eventShell, Symphony::Configuration()->get('write_mode', 'file')))) {
                $this->pageAlert(__('Failed to write Event to disk.') . ' ' . __('Please check permissions on %s.', array('<code>/workspace/events</code>')), Alert::ERROR);
            } else {
                if ($queueForDeletion) {
                    General::deleteFile($queueForDeletion);
                    $pages = PageManager::fetch(false, array('events', 'id'), array("\n\t\t\t\t\t\t\t`events` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]'\n\t\t\t\t\t\t"));
                    if (is_array($pages) && !empty($pages)) {
                        foreach ($pages as $page) {
                            $page['events'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['events']);
                            PageManager::edit($page['id'], $page);
                        }
                    }
                }
                if ($this->_context[0] == 'new') {
                    /**
                     * After creating the Event, the path to the Event file is provided
                     *
                     * @delegate EventPostCreate
                     * @since Symphony 2.2
                     * @param string $context
                     * '/blueprints/events/'
                     * @param string $file
                     *  The path to the Event file
                     */
                    Symphony::ExtensionManager()->notifyMembers('EventPostCreate', '/blueprints/events/', array('file' => $file));
                } else {
                    /**
                     * After editing the Event, the path to the Event file is provided
                     *
                     * @delegate EventPostEdit
                     * @since Symphony 2.2
                     * @param string $context
                     * '/blueprints/events/'
                     * @param string $file
                     *  The path to the Event file
                     * @param string $previous_file
                     *  The path of the previous Event file in the case where an Event may
                     *  have been renamed. To get the handle from this value, see
                     *  `EventManager::__getHandleFromFilename`
                     */
                    Symphony::ExtensionManager()->notifyMembers('EventPostEdit', '/blueprints/events/', array('file' => $file, 'previous_file' => $queueForDeletion ? $queueForDeletion : null));
                }
                redirect(SYMPHONY_URL . '/blueprints/events/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
            }
        }
    }
 public function __formAction()
 {
     $fields = $_POST['fields'];
     $this->_errors = array();
     $providers = Symphony::ExtensionManager()->getProvidersOf('data-sources');
     $providerClass = null;
     if (trim($fields['name']) == '') {
         $this->_errors['name'] = __('This is a required field');
     }
     if ($fields['source'] == 'static_xml') {
         if (trim($fields['static_xml']) == '') {
             $this->_errors['static_xml'] = __('This is a required field');
         } else {
             $xml_errors = NULL;
             include_once TOOLKIT . '/class.xsltprocess.php';
             General::validateXML($fields['static_xml'], $xml_errors, false, new XsltProcess());
             if (!empty($xml_errors)) {
                 $this->_errors['static_xml'] = __('XML is invalid');
             }
         }
     } elseif ($fields['source'] == 'dynamic_xml') {
         if (trim($fields['dynamic_xml']['url']) == '') {
             $this->_errors['dynamic_xml']['url'] = __('This is a required field');
         }
         // Use the TIMEOUT that was specified by the user for a real world indication
         $timeout = isset($fields['dynamic_xml']['timeout']) ? (int) $fields['dynamic_xml']['timeout'] : 6;
         // If there is a parameter in the URL, we can't validate the existence of the URL
         // as we don't have the environment details of where this datasource is going
         // to be executed.
         if (!preg_match('@{([^}]+)}@i', $fields['dynamic_xml']['url'])) {
             $valid_url = self::__isValidURL($fields['dynamic_xml']['url'], $timeout, $error);
             if ($valid_url) {
                 $data = $valid_url['data'];
             } else {
                 $this->_errors['dynamic_xml']['url'] = $error;
             }
         }
         if (trim($fields['dynamic_xml']['xpath']) == '') {
             $this->_errors['dynamic_xml']['xpath'] = __('This is a required field');
         }
         if (!is_numeric($fields['dynamic_xml']['cache'])) {
             $this->_errors['dynamic_xml']['cache'] = __('Must be a valid number');
         } elseif ($fields['dynamic_xml']['cache'] < 1) {
             $this->_errors['dynamic_xml']['cache'] = __('Must be greater than zero');
         }
     } elseif (is_numeric($fields['source'])) {
         if (strlen(trim($fields['max_records'])) == 0 || is_numeric($fields['max_records']) && $fields['max_records'] < 1) {
             if (isset($fields['paginate_results'])) {
                 $this->_errors['max_records'] = __('A result limit must be set');
             }
         } else {
             if (!self::__isValidPageString($fields['max_records'])) {
                 $this->_errors['max_records'] = __('Must be a valid number or parameter');
             }
         }
         if (strlen(trim($fields['page_number'])) == 0 || is_numeric($fields['page_number']) && $fields['page_number'] < 1) {
             if (isset($fields['paginate_results'])) {
                 $this->_errors['page_number'] = __('A page number must be set');
             }
         } else {
             if (!self::__isValidPageString($fields['page_number'])) {
                 $this->_errors['page_number'] = __('Must be a valid number or parameter');
             }
         }
     } elseif (!empty($providers)) {
         foreach ($providers as $providerClass => $provider) {
             if ($fields['source'] == call_user_func(array($providerClass, 'getSource'))) {
                 call_user_func(array($providerClass, 'validate'), &$fields, &$this->_errors);
                 break;
             }
             unset($providerClass);
         }
     }
     $classname = Lang::createHandle($fields['name'], 255, '_', false, true, array('@^[^a-z\\d]+@i' => '', '/[^\\w-\\.]/i' => ''));
     $rootelement = str_replace('_', '-', $classname);
     // Check to make sure the classname is not empty after handlisation.
     if (empty($classname) && !isset($this->_errors['name'])) {
         $this->_errors['name'] = __('Please ensure name contains at least one Latin-based character.', array($classname));
     }
     $file = DATASOURCES . '/data.' . $classname . '.php';
     $isDuplicate = false;
     $queueForDeletion = NULL;
     if ($this->_context[0] == 'new' && is_file($file)) {
         $isDuplicate = true;
     } elseif ($this->_context[0] == 'edit') {
         $existing_handle = $this->_context[1];
         if ($classname != $existing_handle && is_file($file)) {
             $isDuplicate = true;
         } elseif ($classname != $existing_handle) {
             $queueForDeletion = DATASOURCES . '/data.' . $existing_handle . '.php';
         }
     }
     // Duplicate
     if ($isDuplicate) {
         $this->_errors['name'] = __('A Data source with the name %s already exists', array('<code>' . $classname . '</code>'));
     }
     if (empty($this->_errors)) {
         $filters = array();
         $elements = NULL;
         $placeholder = '<!-- GRAB -->';
         $source = $fields['source'];
         $params = array('rootelement' => $rootelement);
         $about = array('name' => $fields['name'], 'version' => 'Symphony ' . Symphony::Configuration()->get('version', 'symphony'), 'release date' => DateTimeObj::getGMT('c'), 'author name' => Administration::instance()->Author->getFullName(), 'author website' => URL, 'author email' => Administration::instance()->Author->get('email'));
         // If there is a provider, get their template
         if ($providerClass) {
             $dsShell = file_get_contents(call_user_func(array($providerClass, 'getTemplate')));
         } else {
             $dsShell = file_get_contents($this->getTemplate('blueprints.datasource'));
         }
         // Author metadata
         self::injectAboutInformation($dsShell, $about);
         // Do dependencies, the template file must have <!-- CLASS NAME -->
         // and <!-- DS DEPENDENCY LIST --> tokens
         $dsShell = str_replace('<!-- CLASS NAME -->', $classname, $dsShell);
         // If there is a provider, let them do the prepartion work
         if ($providerClass) {
             $dsShell = call_user_func(array($providerClass, 'prepare'), $fields, $params, $dsShell);
         } else {
             switch ($source) {
                 case 'authors':
                     $extends = 'AuthorDatasource';
                     if (isset($fields['filter']['author'])) {
                         $filters = $fields['filter']['author'];
                     }
                     $elements = $fields['xml_elements'];
                     $params['order'] = $fields['order'];
                     $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no';
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     $params['paramoutput'] = $fields['param'];
                     $params['sort'] = $fields['sort'];
                     break;
                 case 'navigation':
                     $extends = 'NavigationDatasource';
                     if (isset($fields['filter']['navigation'])) {
                         $filters = $fields['filter']['navigation'];
                     }
                     $params['order'] = $fields['order'];
                     $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no';
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     break;
                 case 'dynamic_xml':
                     $extends = 'DynamicXMLDatasource';
                     // Automatically detect namespaces
                     if (isset($data)) {
                         preg_match_all('/xmlns:([a-z][a-z-0-9\\-]*)="([^\\"]+)"/i', $data, $matches);
                         if (!is_array($fields['dynamic_xml']['namespace'])) {
                             $fields['dynamic_xml']['namespace'] = array();
                         }
                         if (isset($matches[2][0])) {
                             $detected_namespaces = array();
                             foreach ($fields['dynamic_xml']['namespace'] as $name => $uri) {
                                 $detected_namespaces[] = $name;
                                 $detected_namespaces[] = $uri;
                             }
                             foreach ($matches[2] as $index => $uri) {
                                 $name = $matches[1][$index];
                                 if (in_array($name, $detected_namespaces) or in_array($uri, $detected_namespaces)) {
                                     continue;
                                 }
                                 $detected_namespaces[] = $name;
                                 $detected_namespaces[] = $uri;
                                 $fields['dynamic_xml']['namespace'][] = array('name' => $name, 'uri' => $uri);
                             }
                         }
                     }
                     $filters = array();
                     if (is_array($fields['dynamic_xml']['namespace'])) {
                         foreach ($fields['dynamic_xml']['namespace'] as $index => $data) {
                             $filters[$data['name']] = $data['uri'];
                         }
                     }
                     $params['url'] = $fields['dynamic_xml']['url'];
                     $params['xpath'] = $fields['dynamic_xml']['xpath'];
                     $params['cache'] = $fields['dynamic_xml']['cache'];
                     $params['format'] = $fields['dynamic_xml']['format'];
                     $params['timeout'] = isset($fields['dynamic_xml']['timeout']) ? (int) $fields['dynamic_xml']['timeout'] : '6';
                     break;
                 case 'static_xml':
                     $extends = 'StaticXMLDatasource';
                     $fields['static_xml'] = trim($fields['static_xml']);
                     if (preg_match('/^<\\?xml/i', $fields['static_xml']) == true) {
                         // Need to remove any XML declaration
                         $fields['static_xml'] = preg_replace('/^<\\?xml[^>]+>/i', NULL, $fields['static_xml']);
                     }
                     $params['static'] = sprintf('%s', addslashes(trim($fields['static_xml'])));
                     break;
                 default:
                     $extends = 'SectionDatasource';
                     $elements = $fields['xml_elements'];
                     if (is_array($fields['filter']) && !empty($fields['filter'])) {
                         $filters = array();
                         foreach ($fields['filter'] as $f) {
                             foreach ($f as $key => $val) {
                                 $filters[$key] = $val;
                             }
                         }
                     }
                     $params['order'] = $fields['order'];
                     $params['group'] = $fields['group'];
                     $params['paginateresults'] = isset($fields['paginate_results']) ? 'yes' : 'no';
                     $params['limit'] = $fields['max_records'];
                     $params['startpage'] = $fields['page_number'];
                     $params['redirectonempty'] = isset($fields['redirect_on_empty']) ? 'yes' : 'no';
                     $params['requiredparam'] = trim($fields['required_url_param']);
                     $params['paramoutput'] = $fields['param'];
                     $params['sort'] = $fields['sort'];
                     $params['htmlencode'] = $fields['html_encode'];
                     $params['associatedentrycounts'] = $fields['associated_entry_counts'];
                     if ($params['associatedentrycounts'] == NULL) {
                         $params['associatedentrycounts'] = 'no';
                     }
                     break;
             }
             $this->__injectVarList($dsShell, $params);
             $this->__injectIncludedElements($dsShell, $elements);
             self::injectFilters($dsShell, $filters);
             if (preg_match_all('@(\\$ds-[0-9a-z_\\.\\-]+)@i', $dsShell, $matches)) {
                 $dependencies = General::array_remove_duplicates($matches[1]);
                 $dsShell = str_replace('<!-- DS DEPENDENCY LIST -->', "'" . implode("', '", $dependencies) . "'", $dsShell);
             }
             $dsShell = str_replace('<!-- CLASS EXTENDS -->', $extends, $dsShell);
             $dsShell = str_replace('<!-- SOURCE -->', $source, $dsShell);
         }
         if ($this->_context[0] == 'new') {
             /**
              * Prior to creating the Datasource, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate DatasourcePreCreate
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/datasources/'
              * @param string $file
              *  The path to the Datasource file
              * @param string $contents
              *  The contents for this Datasource as a string passed by reference
              * @param array $params
              *  An array of all the `$dsParam*` values
              * @param array $elements
              *  An array of all the elements included in this datasource
              * @param array $filters
              *  An associative array of all the filters for this datasource with the key
              *  being the `field_id` and the value the filter.
              * @param array $dependencies
              *  An array of dependencies that this datasource has
              */
             Symphony::ExtensionManager()->notifyMembers('DatasourcePreCreate', '/blueprints/datasources/', array('file' => $file, 'contents' => &$dsShell, 'params' => $params, 'elements' => $elements, 'filters' => $filters, 'dependencies' => $dependencies));
         } else {
             /**
              * Prior to editing a Datasource, the file path where it will be written to
              * is provided and well as the contents of that file.
              *
              * @delegate DatasourcePreEdit
              * @since Symphony 2.2
              * @param string $context
              * '/blueprints/datasources/'
              * @param string $file
              *  The path to the Datasource file
              * @param string $contents
              *  The contents for this Datasource as a string passed by reference
              * @param array $dependencies
              *  An array of dependencies that this datasource has
              * @param array $params
              *  An array of all the `$dsParam*` values
              * @param array $elements
              *  An array of all the elements included in this datasource
              * @param array $filters
              *  An associative array of all the filters for this datasource with the key
              *  being the `field_id` and the value the filter.
              */
             Symphony::ExtensionManager()->notifyMembers('DatasourcePreEdit', '/blueprints/datasources/', array('file' => $file, 'contents' => &$dsShell, 'dependencies' => $dependencies, 'params' => $params, 'elements' => $elements, 'filters' => $filters));
         }
         // Remove left over placeholders
         $dsShell = preg_replace(array('/<!--[\\w ]++-->/', '/(\\r\\n){2,}/', '/(\\t+[\\r\\n]){2,}/'), '', $dsShell);
         // Write the file
         if (!is_writable(dirname($file)) || !($write = General::writeFile($file, $dsShell, Symphony::Configuration()->get('write_mode', 'file')))) {
             $this->pageAlert(__('Failed to write Data source to disk.') . ' ' . __('Please check permissions on %s.', array('<code>/workspace/data-sources</code>')), Alert::ERROR);
         } else {
             if ($queueForDeletion) {
                 General::deleteFile($queueForDeletion);
                 // Update pages that use this DS
                 $pages = PageManager::fetch(false, array('data_sources', 'id'), array("\n\t\t\t\t\t\t\t`data_sources` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]'\n\t\t\t\t\t\t"));
                 if (is_array($pages) && !empty($pages)) {
                     foreach ($pages as $page) {
                         $page['data_sources'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['data_sources']);
                         PageManager::edit($page['id'], $page);
                     }
                 }
             }
             if ($this->_context[0] == 'new') {
                 /**
                  * After creating the Datasource, the path to the Datasource file is provided
                  *
                  * @delegate DatasourcePostCreate
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/datasources/'
                  * @param string $file
                  *  The path to the Datasource file
                  */
                 Symphony::ExtensionManager()->notifyMembers('DatasourcePostCreate', '/blueprints/datasources/', array('file' => $file));
             } else {
                 /**
                  * After editing the Datasource, the path to the Datasource file is provided
                  *
                  * @delegate DatasourcePostEdit
                  * @since Symphony 2.2
                  * @param string $context
                  * '/blueprints/datasources/'
                  * @param string $file
                  *  The path to the Datasource file
                  */
                 Symphony::ExtensionManager()->notifyMembers('DatasourcePostEdit', '/blueprints/datasources/', array('file' => $file));
             }
             redirect(SYMPHONY_URL . '/blueprints/datasources/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
         }
     }
 }