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') . '/');
         }
     }
 }
    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();
        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 = is_array($fields['filters']) ? $fields['filters'] : array();
        $classname = Lang::createHandle($fields['name'], NULL, '_', false, true, array('@^[^a-z]+@i' => '', '/[^\\w-\\.]/i' => ''));
        $rootelement = str_replace('_', '-', $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 <code>%s</code> name already exists', array($classname));
        }
        if (empty($this->_errors)) {
            $multiple = in_array('expect-multiple', $filters);
            $eventShell = file_get_contents(TEMPLATE . '/event.tpl');
            $about = array('name' => $fields['name'], 'version' => '1.0', 'release date' => DateTimeObj::getGMT('c'), 'author name' => Administration::instance()->Author->getFullName(), 'author website' => URL, 'author email' => Administration::instance()->Author->get('email'), 'trigger condition' => $rootelement);
            $source = $fields['source'];
            $filter = NULL;
            $elements = NULL;
            $this->__injectAboutInformation($eventShell, $about);
            $this->__injectFilters($eventShell, $filters);
            $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 ? __(' (<b>Notice that it is possible to get mixtures of success and failure messages when using the "Allow Multiple" option</b>)') : 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', Symphony::Configuration()->get('max_upload_size', 'admin'), 'hidden'));
            $sectionManager = new SectionManager($this->_Parent);
            $section = $sectionManager->fetch($fields['source']);
            $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. <b>It currently does not work with "Allow Multiple".</b> The following are the recognised fields:'));
                $documentation_parts[] = self::processDocumentationCode('send-email[sender-email] // ' . __('Optional') . self::CRLF . 'send-email[sender-name] // ' . __('Optional') . self::CRLF . 'send-email[reply-to-email] // ' . __('Optional') . self::CRLF . 'send-email[reply-to-name] // ' . __('Optional') . self::CRLF . 'send-email[subject]' . self::CRLF . 'send-email[body]' . self::CRLF . '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(self::CRLF, array_map(create_function('$x', 'return rtrim($x->generate(true, 4));'), $documentation_parts));
            $documentation = str_replace('\'', '\\\'', $documentation);
            $eventShell = str_replace('<!-- CLASS NAME -->', $classname, $eventShell);
            $eventShell = str_replace('<!-- SOURCE -->', $source, $eventShell);
            $eventShell = str_replace('<!-- DOCUMENTATION -->', General::tabsToSpaces($documentation, 2), $eventShell);
            $eventShell = str_replace('<!-- ROOT ELEMENT -->', $rootelement, $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 <code>%s</code>. Please check permissions.', array(EVENTS)), Alert::ERROR);
            } else {
                if ($queueForDeletion) {
                    General::deleteFile($queueForDeletion);
                    $sql = "SELECT * FROM `tbl_pages` WHERE `events` REGEXP '[[:<:]]" . $existing_handle . "[[:>:]]' ";
                    $pages = Symphony::Database()->fetch($sql);
                    if (is_array($pages) && !empty($pages)) {
                        foreach ($pages as $page) {
                            $page['events'] = preg_replace('/\\b' . $existing_handle . '\\b/i', $classname, $page['events']);
                            Symphony::Database()->update($page, 'tbl_pages', "`id` = '" . $page['id'] . "'");
                        }
                    }
                }
                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
                     */
                    Symphony::ExtensionManager()->notifyMembers('EventPostEdit', '/blueprints/events/', array('file' => $file));
                }
                redirect(SYMPHONY_URL . '/blueprints/events/edit/' . $classname . '/' . ($this->_context[0] == 'new' ? 'created' : 'saved') . '/');
            }
        }
    }
 function view()
 {
     $this->Form->setAttribute('action', extension_filemanager::baseURL() . 'properties/?file=' . $_GET['file']);
     $file = new File(DOCROOT . $this->_FileManager->getStartLocation() . $_GET['file']);
     $FileManager =& $this->_Parent->ExtensionManager->create('filemanager');
     $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>', AdministrationPage::PAGE_ALERT_ERROR);
     }
     if (isset($this->_context[0])) {
         switch ($this->_context[0]) {
             case 'saved':
                 $this->pageAlert('{1} updated successfully.', AdministrationPage::PAGE_ALERT_NOTICE, array($file->isDir() ? 'Folder' : 'File'));
                 break;
         }
     }
     $this->setPageType('form');
     $path = extension_filemanager::baseURL() . 'browse/';
     $breadcrumb = '';
     $pathelements = explode('/', $_GET['file']);
     foreach ($pathelements as $element) {
         if ($element != '') {
             $path .= $element . '/';
             $breadcrumb .= ' / ' . ($element == end($pathelements) ? $element : Widget::Anchor($element, $path)->generate());
         }
     }
     $this->appendSubheading(trim($FileManager->getStartLocationLink(), '/') . $breadcrumb);
     $fields = array();
     $fieldset = new XMLElement('fieldset');
     $fieldset->setAttribute('class', 'settings');
     $fieldset->appendChild(new XMLElement('legend', 'Essentials'));
     $div = new XMLElement('div');
     $div->setAttribute('class', 'group');
     $label = Widget::Label('Name');
     $label->appendChild(Widget::Input('fields[name]', General::sanitize($file->name())));
     if (isset($this->_errors['name'])) {
         $div->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['name']));
     } else {
         $div->appendChild($label);
     }
     $label = Widget::Label('Permissions');
     $label->appendChild(Widget::Input('fields[permissions]', General::sanitize($file->permissions())));
     if (isset($this->_errors['permissions'])) {
         $div->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['permissions']));
     } else {
         $div->appendChild($label);
     }
     $fieldset->appendChild($div);
     $this->Form->appendChild($fieldset);
     if (!$file->isDir() && in_array(File::fileType($file->name()), array(File::CODE, File::DOC))) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', 'Editor'));
         $label = Widget::Label('Contents');
         $label->appendChild(Widget::Textarea('fields[contents]', '25', '50', General::sanitize(General::tabsToSpaces($file->contents(), 2)), array('class' => 'code')));
         if (isset($this->_errors['contents'])) {
             $fieldset->appendChild(Widget::wrapFormElementWithError($label, $this->_errors['contents']));
         } else {
             $fieldset->appendChild($label);
         }
         $this->Form->appendChild($fieldset);
     }
     if (!$file->isDir() && File::fileType($file->name()) == File::IMAGE) {
         $fieldset = new XMLElement('fieldset');
         $fieldset->setAttribute('class', 'settings');
         $fieldset->appendChild(new XMLElement('legend', 'Preview'));
         $img = new XMLElement('img');
         $img->setAttribute('src', URL . $FileManager->getStartLocation() . $_GET['file']);
         $img->setAttribute('alt', $file->name());
         $fieldset->appendChild($img);
         $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' => 'confirm delete', 'title' => 'Delete this ' . ($file->isDir() ? 'Folder' : 'File')));
     $div->appendChild($button);
     $this->Form->appendChild($div);
 }