/**
  * the singleton pattern
  *
  * @return Calendar_Controller
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new Calendar_Controller();
     }
     return self::$_instance;
 }
 /**
  * Test create a scheduled import
  */
 public function createScheduledImport($source = 'http://localhost/test.ics')
 {
     $id = Tinebase_Record_Abstract::generateUID();
     $import = new Tinebase_Model_Import(array('id' => $id, 'user_id' => $this->_originalTestUser->getId(), 'interval' => Tinebase_Model_Import::INTERVAL_HOURLY, 'model' => Calendar_Controller::getInstance()->getDefaultModel(), 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(), 'container_id' => $this->_testCalendar->getId(), 'sourcetype' => Tinebase_Model_Import::SOURCETYPE_REMOTE, 'source' => $source, 'options' => json_encode(array('forceUpdateExisting' => TRUE, 'import_defintion' => NULL, 'plugin' => 'Calendar_Import_Ical'))));
     $record = $this->_uit->create($import);
     $this->assertEquals(Calendar_Controller::getInstance()->getDefaultModel(), $this->_uit->get($id)->model);
     return $record;
 }
Exemple #3
0
 public function index()
 {
     $dayofweek = intval(date('N')) - 1;
     $days = array();
     for ($i = $dayofweek; $i >= 0; $i--) {
         $days[] = Calendar_Controller::day(date('Y-m-d', strtotime("-{$i} days")));
     }
     for ($i = $dayofweek + 1; $i < 7; $i++) {
         $days[] = Calendar_Controller::day(date('Y-m-d', strtotime('+' . ($i - $dayofweek) . ' days')));
     }
     $this->template->content = new View('homepage');
     $this->template->content->week = new View('calendar/week');
     $this->template->content->week->days = $days;
     $this->template->content->week->doNotJumpToCalendar = true;
     $this->template->title = 'Smart Student - Ce faci azi?';
 }
 public function MonthJumpForm()
 {
     $controller = Controller::curr();
     if ($controller->class == "Calendar_Controller" || is_subclass_of($controller, "Calendar_Controller")) {
         return Controller::curr()->MonthJumpForm();
     }
     $c = new Calendar_Controller($this);
     return $c->MonthJumpForm();
 }
 /**
  * inspect before create/update
  * 
  * @TODO move stuff from other places here
  * @param   Calendar_Model_Event $_record      the record to inspect
  */
 protected function _inspectEvent($_record)
 {
     $_record->uid = $_record->uid ? $_record->uid : Tinebase_Record_Abstract::generateUID();
     $_record->organizer = $_record->organizer ? $_record->organizer : Tinebase_Core::getUser()->contact_id;
     $_record->transp = $_record->transp ? $_record->transp : Calendar_Model_Event::TRANSP_OPAQUE;
     $this->_inspectOriginatorTZ($_record);
     if ($_record->hasExternalOrganizer()) {
         // assert calendarUser as attendee. This is important to keep the event in the loop via its displaycontianer(s)
         try {
             $container = Tinebase_Container::getInstance()->getContainerById($_record->container_id);
             $owner = $container->getOwner();
             $calendarUserId = Addressbook_Controller_Contact::getInstance()->getContactByUserId($owner, true)->getId();
         } catch (Exception $e) {
             $container = NULL;
             $calendarUserId = Tinebase_Core::getUser()->contact_id;
         }
         $attendee = $_record->assertAttendee(new Calendar_Model_Attender(array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $calendarUserId)), false, false, true);
         if ($attendee && $container instanceof Tinebase_Model_Container) {
             $attendee->displaycontainer_id = $container->getId();
         }
         if (!$container instanceof Tinebase_Model_Container || $container->type == Tinebase_Model_Container::TYPE_PERSONAL) {
             // move into special (external users) container
             $container = Calendar_Controller::getInstance()->getInvitationContainer($_record->resolveOrganizer());
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Setting container_id to ' . $container->getId() . ' for external organizer ' . $_record->organizer->email);
             }
             $_record->container_id = $container->getId();
         }
     }
     if ($_record->is_all_day_event) {
         // harmonize datetimes of all day events
         $_record->setTimezone($_record->originator_tz);
         if (!$_record->dtend) {
             $_record->dtend = clone $_record->dtstart;
             $_record->dtend->setTime(23, 59, 59);
         }
         $_record->dtstart->setTime(0, 0, 0);
         $_record->dtend->setTime(23, 59, 59);
         $_record->setTimezone('UTC');
     }
     $_record->setRruleUntil();
     if ($_record->rrule instanceof Calendar_Model_Rrule) {
         $_record->rrule->normalize($_record);
     }
     if ($_record->isRecurException()) {
         $baseEvent = $this->getRecurBaseEvent($_record);
         // remove invalid rrules
         if ($_record->rrule !== NULL) {
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Removing invalid rrule from recur exception: ' . $_record->rrule);
             }
             $_record->rrule = NULL;
         }
         //            // Maybe Later
         //            // exdates needs to stay in baseEvents container
         //            if($_record->container_id != $baseEvent->container_id) {
         //                throw new Calendar_Exception_ExdateContainer();
         //            }
     }
 }
Exemple #6
0
    /**
     * Handles showing the post screen, loading the post to be modified, and loading any post quoted.
     *
     * - additionally handles previews of posts.
     * - requires different permissions depending on the actions, but most notably post_new, post_reply_own, and post_reply_any.
     * - shows options for the editing and posting of calendar events and attachments, as well as the posting of polls.
     * - accessed from ?action=post.
     *
     * @uses the Post template and language file, main sub template.
     */
    public function action_post()
    {
        global $txt, $scripturl, $topic, $modSettings, $board, $user_info, $context, $options;
        loadLanguage('Post');
        loadLanguage('Errors');
        require_once SOURCEDIR . '/AttachmentErrorContext.class.php';
        // You can't reply with a poll... hacker.
        if (isset($_REQUEST['poll']) && !empty($topic) && !isset($_REQUEST['msg'])) {
            unset($_REQUEST['poll']);
        }
        $post_errors = Error_Context::context('post', 1);
        $attach_errors = Attachment_Error_Context::context();
        $attach_errors->activate();
        $first_subject = '';
        // Posting an event?
        $context['make_event'] = isset($_REQUEST['calendar']);
        $context['robot_no_index'] = true;
        $template_layers = Template_Layers::getInstance();
        $template_layers->add('postarea');
        // You must be posting to *some* board.
        if (empty($board) && !$context['make_event']) {
            fatal_lang_error('no_board', false);
        }
        if ($context['make_event']) {
            $template_layers->add('make_event');
        }
        // All those wonderful modifiers and attachments
        $template_layers->add('additional_options', 200);
        require_once SUBSDIR . '/Post.subs.php';
        require_once SUBSDIR . '/Messages.subs.php';
        require_once SUBSDIR . '/Topic.subs.php';
        if (isset($_REQUEST['xml'])) {
            $context['sub_template'] = 'post';
            // Just in case of an earlier error...
            $context['preview_message'] = '';
            $context['preview_subject'] = '';
        }
        if (!empty($modSettings['mentions_enabled']) && !empty($_REQUEST['uid'])) {
            $context['member_ids'] = array_unique(array_map('intval', $_REQUEST['uid']));
        }
        // No message is complete without a topic.
        if (empty($topic) && !empty($_REQUEST['msg'])) {
            $topic = associatedTopic((int) $_REQUEST['msg']);
            if (empty($topic)) {
                unset($_REQUEST['msg'], $_POST['msg'], $_GET['msg']);
            }
        }
        // Check if it's locked. It isn't locked if no topic is specified.
        if (!empty($topic)) {
            list($locked, $context['notify'], $sticky, $pollID, $context['topic_last_message'], $id_member_poster, $id_first_msg, $first_subject, $lastPostTime) = array_values(topicUserAttributes($topic, $user_info['id']));
            // If this topic already has a poll, they sure can't add another.
            if (isset($_REQUEST['poll']) && $pollID > 0) {
                unset($_REQUEST['poll']);
            }
            if (empty($_REQUEST['msg'])) {
                if ($user_info['is_guest'] && !allowedTo('post_reply_any') && (!$modSettings['postmod_active'] || !allowedTo('post_unapproved_replies_any'))) {
                    is_not_guest();
                }
                // By default the reply will be approved...
                $context['becomes_approved'] = true;
                if ($id_member_poster != $user_info['id']) {
                    if ($modSettings['postmod_active'] && allowedTo('post_unapproved_replies_any') && !allowedTo('post_reply_any')) {
                        $context['becomes_approved'] = false;
                    } else {
                        isAllowedTo('post_reply_any');
                    }
                } elseif (!allowedTo('post_reply_any')) {
                    if ($modSettings['postmod_active']) {
                        if (allowedTo('post_unapproved_replies_own') && !allowedTo('post_reply_own')) {
                            $context['becomes_approved'] = false;
                        } elseif ($user_info['is_guest'] && allowedTo('post_unapproved_replies_any')) {
                            $context['becomes_approved'] = false;
                        } else {
                            isAllowedTo('post_reply_own');
                        }
                    } else {
                        isAllowedTo('post_reply_own');
                    }
                }
            } else {
                $context['becomes_approved'] = true;
            }
            $context['can_lock'] = allowedTo('lock_any') || $user_info['id'] == $id_member_poster && allowedTo('lock_own');
            $context['can_sticky'] = allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']);
            $context['notify'] = !empty($context['notify']);
            $context['sticky'] = isset($_REQUEST['sticky']) ? !empty($_REQUEST['sticky']) : $sticky;
            // It's a new reply
            if (empty($_REQUEST['msg'])) {
                $context['can_add_poll'] = false;
            } else {
                $context['can_add_poll'] = (allowedTo('poll_add_any') || !empty($_REQUEST['msg']) && $id_first_msg == $_REQUEST['msg'] && allowedTo('poll_add_own')) && !empty($modSettings['pollMode']) && $pollID <= 0;
            }
        } else {
            $context['becomes_approved'] = true;
            if (!$context['make_event'] || !empty($board)) {
                if ($modSettings['postmod_active'] && !allowedTo('post_new') && allowedTo('post_unapproved_topics')) {
                    $context['becomes_approved'] = false;
                } else {
                    isAllowedTo('post_new');
                }
            }
            $locked = 0;
            // @todo These won't work if you're making an event.
            $context['can_lock'] = allowedTo(array('lock_any', 'lock_own'));
            $context['can_sticky'] = allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']);
            $context['notify'] = !empty($context['notify']);
            $context['sticky'] = !empty($_REQUEST['sticky']);
            $context['can_add_poll'] = (allowedTo('poll_add_any') || allowedTo('poll_add_own')) && !empty($modSettings['pollMode']);
        }
        // @todo These won't work if you're posting an event!
        $context['can_notify'] = allowedTo('mark_any_notify');
        $context['can_move'] = allowedTo('move_any');
        $context['move'] = !empty($_REQUEST['move']);
        $context['announce'] = !empty($_REQUEST['announce']);
        if ($context['can_add_poll']) {
            addJavascriptVar(array('poll_remove' => $txt['poll_remove'], 'poll_add' => $txt['add_poll']), true);
        }
        // You can only announce topics that will get approved...
        $context['can_announce'] = allowedTo('announce_topic') && $context['becomes_approved'];
        $context['locked'] = !empty($locked) || !empty($_REQUEST['lock']);
        $context['can_quote'] = empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC']));
        // Generally don't show the approval box... (Assume we want things approved)
        $context['show_approval'] = allowedTo('approve_posts') && $context['becomes_approved'] ? 2 : (allowedTo('approve_posts') ? 1 : 0);
        // An array to hold all the attachments for this topic.
        $context['attachments']['current'] = array();
        // Don't allow a post if it's locked and you aren't all powerful.
        if ($locked && !allowedTo('moderate_board')) {
            fatal_lang_error('topic_locked', false);
        }
        // Check the users permissions - is the user allowed to add or post a poll?
        if (isset($_REQUEST['poll']) && !empty($modSettings['pollMode'])) {
            // New topic, new poll.
            if (empty($topic)) {
                isAllowedTo('poll_post');
            } elseif ($user_info['id'] == $id_member_poster && !allowedTo('poll_add_any')) {
                isAllowedTo('poll_add_own');
            } else {
                isAllowedTo('poll_add_any');
            }
            $context['can_moderate_poll'] = true;
            require_once SUBSDIR . '/Members.subs.php';
            $allowedVoteGroups = groupsAllowedTo('poll_vote', $board);
            // Set up the poll options.
            $context['poll'] = array('max_votes' => empty($_POST['poll_max_votes']) ? '1' : max(1, $_POST['poll_max_votes']), 'hide_results' => empty($_POST['poll_hide']) ? 0 : $_POST['poll_hide'], 'expiration' => !isset($_POST['poll_expire']) ? '' : $_POST['poll_expire'], 'change_vote' => isset($_POST['poll_change_vote']), 'guest_vote' => isset($_POST['poll_guest_vote']), 'guest_vote_allowed' => in_array(-1, $allowedVoteGroups['allowed']));
            // Make all five poll choices empty.
            $context['choices'] = array(array('id' => 0, 'number' => 1, 'label' => '', 'is_last' => false), array('id' => 1, 'number' => 2, 'label' => '', 'is_last' => false), array('id' => 2, 'number' => 3, 'label' => '', 'is_last' => false), array('id' => 3, 'number' => 4, 'label' => '', 'is_last' => false), array('id' => 4, 'number' => 5, 'label' => '', 'is_last' => true));
            $context['last_choice_id'] = 4;
        }
        if ($context['make_event']) {
            // They might want to pick a board.
            if (!isset($context['current_board'])) {
                $context['current_board'] = 0;
            }
            // Start loading up the event info.
            $context['event'] = array();
            $context['event']['title'] = isset($_REQUEST['evtitle']) ? htmlspecialchars(stripslashes($_REQUEST['evtitle']), ENT_COMPAT, 'UTF-8') : '';
            $context['event']['id'] = isset($_REQUEST['eventid']) ? (int) $_REQUEST['eventid'] : -1;
            $context['event']['new'] = $context['event']['id'] == -1;
            // Permissions check!
            isAllowedTo('calendar_post');
            // Editing an event?  (but NOT previewing!?)
            if (empty($context['event']['new']) && !isset($_REQUEST['subject'])) {
                // If the user doesn't have permission to edit the post in this topic, redirect them.
                if ((empty($id_member_poster) || $id_member_poster != $user_info['id'] || !allowedTo('modify_own')) && !allowedTo('modify_any')) {
                    require_once CONTROLLERDIR . '/Calendar.controller.php';
                    $controller = new Calendar_Controller();
                    return $controller->action_post();
                }
                // Get the current event information.
                require_once SUBSDIR . '/Calendar.subs.php';
                $event_info = getEventProperties($context['event']['id']);
                // Make sure the user is allowed to edit this event.
                if ($event_info['member'] != $user_info['id']) {
                    isAllowedTo('calendar_edit_any');
                } elseif (!allowedTo('calendar_edit_any')) {
                    isAllowedTo('calendar_edit_own');
                }
                $context['event']['month'] = $event_info['month'];
                $context['event']['day'] = $event_info['day'];
                $context['event']['year'] = $event_info['year'];
                $context['event']['title'] = $event_info['title'];
                $context['event']['span'] = $event_info['span'];
            } else {
                // Posting a new event? (or preview...)
                $today = getdate();
                // You must have a month and year specified!
                if (!isset($_REQUEST['month'])) {
                    $_REQUEST['month'] = $today['mon'];
                }
                if (!isset($_REQUEST['year'])) {
                    $_REQUEST['year'] = $today['year'];
                }
                $context['event']['month'] = (int) $_REQUEST['month'];
                $context['event']['year'] = (int) $_REQUEST['year'];
                $context['event']['day'] = isset($_REQUEST['day']) ? $_REQUEST['day'] : ($_REQUEST['month'] == $today['mon'] ? $today['mday'] : 0);
                $context['event']['span'] = isset($_REQUEST['span']) ? $_REQUEST['span'] : 1;
                // Make sure the year and month are in the valid range.
                if ($context['event']['month'] < 1 || $context['event']['month'] > 12) {
                    fatal_lang_error('invalid_month', false);
                }
                if ($context['event']['year'] < $modSettings['cal_minyear'] || $context['event']['year'] > $modSettings['cal_maxyear']) {
                    fatal_lang_error('invalid_year', false);
                }
                // Get a list of boards they can post in.
                require_once SUBSDIR . '/Boards.subs.php';
                $boards = boardsAllowedTo('post_new');
                if (empty($boards)) {
                    fatal_lang_error('cannot_post_new', 'user');
                }
                // Load a list of boards for this event in the context.
                $boardListOptions = array('included_boards' => in_array(0, $boards) ? null : $boards, 'not_redirection' => true, 'selected_board' => empty($context['current_board']) ? $modSettings['cal_defaultboard'] : $context['current_board']);
                $context += getBoardList($boardListOptions);
            }
            // Find the last day of the month.
            $context['event']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['event']['month'] == 12 ? 1 : $context['event']['month'] + 1, 0, $context['event']['month'] == 12 ? $context['event']['year'] + 1 : $context['event']['year']));
            $context['event']['board'] = !empty($board) ? $board : $modSettings['cal_defaultboard'];
        }
        // See if any new replies have come along.
        if (empty($_REQUEST['msg']) && !empty($topic)) {
            if (empty($options['no_new_reply_warning']) && isset($_REQUEST['last_msg']) && $context['topic_last_message'] > $_REQUEST['last_msg']) {
                $context['new_replies'] = countMessagesSince($topic, (int) $_REQUEST['last_msg'], false, $modSettings['postmod_active'] && !allowedTo('approve_posts'));
                if (!empty($context['new_replies'])) {
                    if ($context['new_replies'] == 1) {
                        $txt['error_new_replies'] = isset($_GET['last_msg']) ? $txt['error_new_reply_reading'] : $txt['error_new_reply'];
                    } else {
                        $txt['error_new_replies'] = sprintf(isset($_GET['last_msg']) ? $txt['error_new_replies_reading'] : $txt['error_new_replies'], $context['new_replies']);
                    }
                    $post_errors->addError('new_replies', 0);
                    $modSettings['topicSummaryPosts'] = $context['new_replies'] > $modSettings['topicSummaryPosts'] ? max($modSettings['topicSummaryPosts'], 5) : $modSettings['topicSummaryPosts'];
                }
            }
        }
        // Get a response prefix (like 'Re:') in the default forum language.
        $context['response_prefix'] = response_prefix();
        // Previewing, modifying, or posting?
        // Do we have a body, but an error happened.
        if (isset($_REQUEST['message']) || $post_errors->hasErrors() || $attach_errors->hasErrors()) {
            // Validate inputs.
            if (!$post_errors->hasErrors() && !$attach_errors->hasErrors()) {
                // This means they didn't click Post and get an error.
                $really_previewing = true;
            } else {
                if (!isset($_REQUEST['subject'])) {
                    $_REQUEST['subject'] = '';
                }
                if (!isset($_REQUEST['message'])) {
                    $_REQUEST['message'] = '';
                }
                if (!isset($_REQUEST['icon'])) {
                    $_REQUEST['icon'] = 'xx';
                }
                // They are previewing if they asked to preview (i.e. came from quick reply).
                $really_previewing = !empty($_REQUEST['preview']);
            }
            // In order to keep the approval status flowing through, we have to pass it through the form...
            $context['becomes_approved'] = empty($_REQUEST['not_approved']);
            $context['show_approval'] = isset($_REQUEST['approve']) ? $_REQUEST['approve'] ? 2 : 1 : 0;
            $context['can_announce'] &= $context['becomes_approved'];
            // Set up the inputs for the form.
            $form_subject = strtr(Util::htmlspecialchars($_REQUEST['subject']), array("\r" => '', "\n" => '', "\t" => ''));
            $form_message = Util::htmlspecialchars($_REQUEST['message'], ENT_QUOTES);
            // Make sure the subject isn't too long - taking into account special characters.
            if (Util::strlen($form_subject) > 100) {
                $form_subject = Util::substr($form_subject, 0, 100);
            }
            if (isset($_REQUEST['poll'])) {
                $context['poll']['question'] = isset($_REQUEST['question']) ? Util::htmlspecialchars(trim($_REQUEST['question'])) : '';
                $context['choices'] = array();
                $choice_id = 0;
                $_POST['options'] = empty($_POST['options']) ? array() : htmlspecialchars__recursive($_POST['options']);
                foreach ($_POST['options'] as $option) {
                    if (trim($option) == '') {
                        continue;
                    }
                    $context['choices'][] = array('id' => $choice_id++, 'number' => $choice_id, 'label' => $option, 'is_last' => false);
                }
                // One empty option for those with js disabled...I know are few... :P
                $context['choices'][] = array('id' => $choice_id++, 'number' => $choice_id, 'label' => '', 'is_last' => false);
                if (count($context['choices']) < 2) {
                    $context['choices'][] = array('id' => $choice_id++, 'number' => $choice_id, 'label' => '', 'is_last' => false);
                }
                $context['last_choice_id'] = $choice_id;
                $context['choices'][count($context['choices']) - 1]['is_last'] = true;
            }
            // Are you... a guest?
            if ($user_info['is_guest']) {
                $context['name'] = !isset($_REQUEST['guestname']) ? '' : Util::htmlspecialchars(trim($_REQUEST['guestname']));
                $context['email'] = !isset($_REQUEST['email']) ? '' : Util::htmlspecialchars(trim($_REQUEST['email']));
                $user_info['name'] = $context['name'];
            }
            // Only show the preview stuff if they hit Preview.
            if (($really_previewing === true || isset($_REQUEST['xml'])) && !isset($_REQUEST['save_draft'])) {
                // Set up the preview message and subject
                $context['preview_message'] = $form_message;
                preparsecode($form_message, true);
                // Do all bulletin board code thing on the message
                preparsecode($context['preview_message']);
                $context['preview_message'] = parse_bbc($context['preview_message'], isset($_REQUEST['ns']) ? 0 : 1);
                censorText($context['preview_message']);
                // Don't forget the subject
                $context['preview_subject'] = $form_subject;
                censorText($context['preview_subject']);
                // Any errors we should tell them about?
                if ($form_subject === '') {
                    $post_errors->addError('no_subject');
                    $context['preview_subject'] = '<em>' . $txt['no_subject'] . '</em>';
                }
                if ($context['preview_message'] === '') {
                    $post_errors->addError('no_message');
                } elseif (!empty($modSettings['max_messageLength']) && Util::strlen($form_message) > $modSettings['max_messageLength']) {
                    $post_errors->addError(array('long_message', array($modSettings['max_messageLength'])));
                }
                // Protect any CDATA blocks.
                if (isset($_REQUEST['xml'])) {
                    $context['preview_message'] = strtr($context['preview_message'], array(']]>' => ']]]]><![CDATA[>'));
                }
            }
            // Set up the checkboxes.
            $context['notify'] = !empty($_REQUEST['notify']);
            $context['use_smileys'] = !isset($_REQUEST['ns']);
            $context['icon'] = isset($_REQUEST['icon']) ? preg_replace('~[\\./\\\\*\':"<>]~', '', $_REQUEST['icon']) : 'xx';
            // Set the destination action for submission.
            $context['destination'] = 'post2;start=' . $_REQUEST['start'] . (isset($_REQUEST['msg']) ? ';msg=' . $_REQUEST['msg'] . ';' . $context['session_var'] . '=' . $context['session_id'] : '') . (isset($_REQUEST['poll']) ? ';poll' : '');
            $context['submit_label'] = isset($_REQUEST['msg']) ? $txt['save'] : $txt['post'];
            // Previewing an edit?
            if (isset($_REQUEST['msg']) && !empty($topic)) {
                require_once SUBSDIR . '/Messages.subs.php';
                // Get the existing message.
                $message = messageDetails((int) $_REQUEST['msg'], $topic);
                // The message they were trying to edit was most likely deleted.
                // @todo Change this error message?
                if ($message === false) {
                    fatal_lang_error('no_board', false);
                }
                $errors = checkMessagePermissions($message['message']);
                if (!empty($errors)) {
                    foreach ($errors as $error) {
                        $post_errors->addError($error);
                    }
                }
                prepareMessageContext($message);
            } elseif (isset($_REQUEST['last_msg'])) {
                list($form_subject, ) = getFormMsgSubject(false, $topic, $first_subject);
            }
            // No check is needed, since nothing is really posted.
            checkSubmitOnce('free');
        } elseif (isset($_REQUEST['msg']) && !empty($topic)) {
            $_REQUEST['msg'] = (int) $_REQUEST['msg'];
            $message = getFormMsgSubject(true, $topic);
            if (!empty($message['errors'])) {
                foreach ($errors as $error) {
                    $post_errors->addError($error);
                }
            }
            // Get the stuff ready for the form.
            $form_subject = $message['message']['subject'];
            $form_message = un_preparsecode($message['message']['body']);
            censorText($form_message);
            censorText($form_subject);
            // Check the boxes that should be checked.
            $context['use_smileys'] = !empty($message['message']['smileys_enabled']);
            $context['icon'] = $message['message']['icon'];
            // Set the destination.
            $context['destination'] = 'post2;start=' . $_REQUEST['start'] . ';msg=' . $_REQUEST['msg'] . ';' . $context['session_var'] . '=' . $context['session_id'] . (isset($_REQUEST['poll']) ? ';poll' : '');
            $context['submit_label'] = $txt['save'];
        } else {
            // By default....
            $context['use_smileys'] = true;
            $context['icon'] = 'xx';
            if ($user_info['is_guest']) {
                $context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
                $context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
            }
            $context['destination'] = 'post2;start=' . $_REQUEST['start'] . (isset($_REQUEST['poll']) ? ';poll' : '');
            $context['submit_label'] = $txt['post'];
            list($form_subject, $form_message) = getFormMsgSubject(false, $topic, $first_subject);
        }
        // Check whether this is a really old post being bumped...
        if (!empty($topic) && !empty($modSettings['oldTopicDays']) && $lastPostTime + $modSettings['oldTopicDays'] * 86400 < time() && empty($sticky) && !isset($_REQUEST['subject'])) {
            $post_errors->addError(array('old_topic', array($modSettings['oldTopicDays'])), 0);
        }
        // Are we moving a discussion to its own topic?
        if (!empty($modSettings['enableFollowup']) && !empty($_REQUEST['followup'])) {
            $context['original_post'] = isset($_REQUEST['quote']) ? (int) $_REQUEST['quote'] : (int) $_REQUEST['followup'];
            $context['show_boards_dropdown'] = true;
            require_once SUBSDIR . '/Boards.subs.php';
            $context += getBoardList(array('not_redirection' => true, 'allowed_to' => 'post_new'));
            $context['boards_current_disabled'] = false;
            if (!empty($board)) {
                foreach ($context['categories'] as $id => $values) {
                    if (isset($values['boards'][$board])) {
                        $context['categories'][$id]['boards'][$board]['selected'] = true;
                        break;
                    }
                }
            }
        }
        $context['attachments']['can']['post'] = !empty($modSettings['attachmentEnable']) && $modSettings['attachmentEnable'] == 1 && (allowedTo('post_attachment') || $modSettings['postmod_active'] && allowedTo('post_unapproved_attachments'));
        if ($context['attachments']['can']['post']) {
            // If there are attachments, calculate the total size and how many.
            $attachments = array();
            $attachments['total_size'] = 0;
            $attachments['quantity'] = 0;
            // If this isn't a new post, check the current attachments.
            if (isset($_REQUEST['msg'])) {
                $attachments['quantity'] = count($context['attachments']['current']);
                foreach ($context['attachments']['current'] as $attachment) {
                    $attachments['total_size'] += $attachment['size'];
                }
            }
            // A bit of house keeping first.
            if (!empty($_SESSION['temp_attachments']) && count($_SESSION['temp_attachments']) == 1) {
                unset($_SESSION['temp_attachments']);
            }
            if (!empty($_SESSION['temp_attachments'])) {
                // Is this a request to delete them?
                if (isset($_GET['delete_temp'])) {
                    foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                        if (strpos($attachID, 'post_tmp_' . $user_info['id']) !== false) {
                            @unlink($attachment['tmp_name']);
                        }
                    }
                    $attach_errors->addError('temp_attachments_gone');
                    $_SESSION['temp_attachments'] = array();
                } elseif ($context['current_action'] != 'post2' || !empty($_POST['from_qr'])) {
                    // Let's be nice and see if they belong here first.
                    if (empty($_REQUEST['msg']) && empty($_SESSION['temp_attachments']['post']['msg']) && $_SESSION['temp_attachments']['post']['board'] == $board || !empty($_REQUEST['msg']) && $_SESSION['temp_attachments']['post']['msg'] == $_REQUEST['msg']) {
                        // See if any files still exist before showing the warning message and the files attached.
                        foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                            if (strpos($attachID, 'post_tmp_' . $user_info['id']) === false) {
                                continue;
                            }
                            if (file_exists($attachment['tmp_name'])) {
                                $attach_errors->addError('temp_attachments_new');
                                $context['files_in_session_warning'] = $txt['attached_files_in_session'];
                                unset($_SESSION['temp_attachments']['post']['files']);
                                break;
                            }
                        }
                    } else {
                        // Since, they don't belong here. Let's inform the user that they exist..
                        if (!empty($topic)) {
                            $delete_url = $scripturl . '?action=post' . (!empty($_REQUEST['msg']) ? ';msg=' . $_REQUEST['msg'] : '') . (!empty($_REQUEST['last_msg']) ? ';last_msg=' . $_REQUEST['last_msg'] : '') . ';topic=' . $topic . ';delete_temp';
                        } else {
                            $delete_url = $scripturl . '?action=post;board=' . $board . ';delete_temp';
                        }
                        // Compile a list of the files to show the user.
                        $file_list = array();
                        foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                            if (strpos($attachID, 'post_tmp_' . $user_info['id']) !== false) {
                                $file_list[] = $attachment['name'];
                            }
                        }
                        $_SESSION['temp_attachments']['post']['files'] = $file_list;
                        $file_list = '<div class="attachments">' . implode('<br />', $file_list) . '</div>';
                        if (!empty($_SESSION['temp_attachments']['post']['msg'])) {
                            // We have a message id, so we can link back to the old topic they were trying to edit..
                            $goback_link = '<a href="' . $scripturl . '?action=post' . (!empty($_SESSION['temp_attachments']['post']['msg']) ? ';msg=' . $_SESSION['temp_attachments']['post']['msg'] : '') . (!empty($_SESSION['temp_attachments']['post']['last_msg']) ? ';last_msg=' . $_SESSION['temp_attachments']['post']['last_msg'] : '') . ';topic=' . $_SESSION['temp_attachments']['post']['topic'] . ';additionalOptions">' . $txt['here'] . '</a>';
                            $attach_errors->addError(array('temp_attachments_found', array($delete_url, $goback_link, $file_list)));
                            $context['ignore_temp_attachments'] = true;
                        } else {
                            $attach_errors->addError(array('temp_attachments_lost', array($delete_url, $file_list)));
                            $context['ignore_temp_attachments'] = true;
                        }
                    }
                }
                foreach ($_SESSION['temp_attachments'] as $attachID => $attachment) {
                    // Skipping over these
                    if (isset($context['ignore_temp_attachments']) || isset($_SESSION['temp_attachments']['post']['files'])) {
                        break;
                    }
                    // Initial errors (such as missing directory), we can recover
                    if ($attachID != 'initial_error' && strpos($attachID, 'post_tmp_' . $user_info['id']) === false) {
                        continue;
                    }
                    if ($attachID == 'initial_error') {
                        if ($context['current_action'] != 'post2') {
                            $txt['error_attach_initial_error'] = $txt['attach_no_upload'] . '<div class="attachmenterrors">' . (is_array($attachment) ? vsprintf($txt[$attachment[0]], $attachment[1]) : $txt[$attachment]) . '</div>';
                            $attach_errors->addError('attach_initial_error');
                        }
                        unset($_SESSION['temp_attachments']);
                        break;
                    }
                    // Show any errors which might have occurred.
                    if (!empty($attachment['errors'])) {
                        if ($context['current_action'] != 'post2') {
                            $txt['error_attach_errors'] = empty($txt['error_attach_errors']) ? '<br />' : '';
                            $txt['error_attach_errors'] .= vsprintf($txt['attach_warning'], $attachment['name']) . '<div class="attachmenterrors">';
                            foreach ($attachment['errors'] as $error) {
                                $txt['error_attach_errors'] .= (is_array($error) ? vsprintf($txt[$error[0]], $error[1]) : $txt[$error]) . '<br  />';
                            }
                            $txt['error_attach_errors'] .= '</div>';
                            $attach_errors->addError('attach_errors');
                        }
                        // Take out the trash.
                        unset($_SESSION['temp_attachments'][$attachID]);
                        @unlink($attachment['tmp_name']);
                        continue;
                    }
                    // More house keeping.
                    if (!file_exists($attachment['tmp_name'])) {
                        unset($_SESSION['temp_attachments'][$attachID]);
                        continue;
                    }
                    $attachments['quantity']++;
                    $attachments['total_size'] += $attachment['size'];
                    if (!isset($context['files_in_session_warning'])) {
                        $context['files_in_session_warning'] = $txt['attached_files_in_session'];
                    }
                    $context['attachments']['current'][] = array('name' => '<u>' . htmlspecialchars($attachment['name'], ENT_COMPAT, 'UTF-8') . '</u>', 'size' => $attachment['size'], 'id' => $attachID, 'unchecked' => false, 'approved' => 1);
                }
            }
        }
        // Do we need to show the visual verification image?
        $context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || $user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1);
        if ($context['require_verification']) {
            require_once SUBSDIR . '/VerificationControls.class.php';
            $verificationOptions = array('id' => 'post');
            $context['require_verification'] = create_control_verification($verificationOptions);
            $context['visual_verification_id'] = $verificationOptions['id'];
        }
        // If they came from quick reply, and have to enter verification details, give them some notice.
        if (!empty($_REQUEST['from_qr']) && !empty($context['require_verification'])) {
            $post_errors->addError('need_qr_verification');
        }
        // Any errors occurred?
        $context['post_error'] = array('errors' => $post_errors->prepareErrors(), 'type' => $post_errors->getErrorType() == 0 ? 'minor' : 'serious', 'title' => $post_errors->getErrorType() == 0 ? $txt['warning_while_submitting'] : $txt['error_while_submitting']);
        // If there are attachment errors. Let's show a list to the user.
        if ($attach_errors->hasErrors()) {
            loadTemplate('Errors');
            $errors = $attach_errors->prepareErrors();
            foreach ($errors as $key => $error) {
                $context['attachment_error_keys'][] = $key . '_error';
                $context[$key . '_error'] = $error;
            }
        }
        // What are you doing? Posting a poll, modifying, previewing, new post, or reply...
        if (isset($_REQUEST['poll'])) {
            $context['page_title'] = $txt['new_poll'];
        } elseif ($context['make_event']) {
            $context['page_title'] = $context['event']['id'] == -1 ? $txt['calendar_post_event'] : $txt['calendar_edit'];
        } elseif (isset($_REQUEST['msg'])) {
            $context['page_title'] = $txt['modify_msg'];
        } elseif (isset($_REQUEST['subject'], $context['preview_subject'])) {
            $context['page_title'] = $txt['post_reply'];
        } elseif (empty($topic)) {
            $context['page_title'] = $txt['start_new_topic'];
        } else {
            $context['page_title'] = $txt['post_reply'];
        }
        // Update the topic summary, needed to show new posts in a preview
        if (!empty($topic) && !empty($modSettings['topicSummaryPosts'])) {
            $only_approved = $modSettings['postmod_active'] && !allowedTo('approve_posts');
            if (isset($_REQUEST['xml'])) {
                $limit = empty($context['new_replies']) ? 0 : (int) $context['new_replies'];
            } else {
                $limit = $modSettings['topicSummaryPosts'];
            }
            $before = isset($_REQUEST['msg']) ? array('before' => (int) $_REQUEST['msg']) : array();
            $counter = 0;
            $context['previous_posts'] = empty($limit) ? array() : selectMessages($topic, 0, $limit, $before, $only_approved);
            foreach ($context['previous_posts'] as &$post) {
                $post['is_new'] = !empty($context['new_replies']);
                $post['counter'] = $counter++;
                $post['is_ignored'] = !empty($modSettings['enable_buddylist']) && in_array($post['id_poster'], $user_info['ignoreusers']);
                if (!empty($context['new_replies'])) {
                    $context['new_replies']--;
                }
            }
        }
        // Just ajax previewing then lets stop now
        if (isset($_REQUEST['xml'])) {
            obExit();
        }
        // Build the link tree.
        if (empty($topic)) {
            $context['linktree'][] = array('name' => '<em>' . $txt['start_new_topic'] . '</em>');
        } else {
            $context['linktree'][] = array('url' => $scripturl . '?topic=' . $topic . '.' . $_REQUEST['start'], 'name' => $form_subject, 'extra_before' => '<span><strong class="nav">' . $context['page_title'] . ' ( </strong></span>', 'extra_after' => '<span><strong class="nav"> )</strong></span>');
        }
        $context['subject'] = addcslashes($form_subject, '"');
        $context['message'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), $form_message);
        // Are post drafts enabled?
        $context['drafts_save'] = !empty($modSettings['drafts_enabled']) && !empty($modSettings['drafts_post_enabled']) && allowedTo('post_draft');
        $context['drafts_autosave'] = !empty($context['drafts_save']) && !empty($modSettings['drafts_autosave_enabled']) && allowedTo('post_autosave_draft');
        if (!empty($modSettings['mentions_enabled'])) {
            $context['mentions_enabled'] = true;
            loadCSSFile('jquery.atwho.css');
            addInlineJavascript('
			$(document).ready(function () {
				for (var i = 0, count = all_elk_mentions.length; i < count; i++)
					all_elk_mentions[i].oMention = new elk_mentions(all_elk_mentions[i].oOptions);
			});');
        }
        // Build a list of drafts that they can load into the editor
        if (!empty($context['drafts_save'])) {
            $this->_prepareDraftsContext($user_info['id'], $topic);
            if (!empty($context['drafts'])) {
                $template_layers->add('load_drafts', 100);
            }
        }
        // Needed for the editor and message icons.
        require_once SUBSDIR . '/Editor.subs.php';
        // Now create the editor.
        $editorOptions = array('id' => 'message', 'value' => $context['message'], 'labels' => array('post_button' => $context['submit_label']), 'height' => '275px', 'width' => '100%', 'preview_type' => 2);
        create_control_richedit($editorOptions);
        $context['attached'] = '';
        $context['make_poll'] = isset($_REQUEST['poll']);
        if ($context['make_poll']) {
            loadTemplate('Poll');
            $template_layers->add('poll_edit');
        }
        // Message icons - customized or not, retrieve them...
        $context['icons'] = getMessageIcons($board);
        $context['icon_url'] = '';
        if (!empty($context['icons'])) {
            $context['icons'][count($context['icons']) - 1]['is_last'] = true;
            $context['icons'][0]['selected'] = true;
            // $context['icon'] is set when editing a message
            if (!isset($context['icon'])) {
                $context['icon'] = $context['icons'][0]['value'];
            }
            $found = false;
            foreach ($context['icons'] as $icon) {
                if ($icon['value'] === $context['icon']) {
                    $found = true;
                    $context['icon_url'] = $icon['url'];
                    break;
                }
            }
            // Failsafe
            if (!$found) {
                $context['icon'] = $context['icons'][0]['value'];
                $context['icon_url'] = $context['icons'][0]['url'];
            }
        }
        // Are we starting a poll? if set the poll icon as selected if its available
        if (isset($_REQUEST['poll'])) {
            for ($i = 0, $n = count($context['icons']); $i < $n; $i++) {
                if ($context['icons'][$i]['value'] == 'poll') {
                    $context['icons'][$i]['selected'] = true;
                    $context['icon'] = 'poll';
                    $context['icon_url'] = $context['icons'][$i]['url'];
                    break;
                }
            }
        }
        // If the user can post attachments prepare the warning labels.
        if ($context['attachments']['can']['post']) {
            // If they've unchecked an attachment, they may still want to attach that many more files, but don't allow more than num_allowed_attachments.
            $context['attachments']['num_allowed'] = empty($modSettings['attachmentNumPerPostLimit']) ? 50 : min($modSettings['attachmentNumPerPostLimit'] - count($context['attachments']['current']), $modSettings['attachmentNumPerPostLimit']);
            $context['attachments']['can']['post_unapproved'] = allowedTo('post_attachment');
            $context['attachments']['restrictions'] = array();
            if (!empty($modSettings['attachmentCheckExtensions'])) {
                $context['attachments']['allowed_extensions'] = strtr(strtolower($modSettings['attachmentExtensions']), array(',' => ', '));
            } else {
                $context['attachments']['allowed_extensions'] = '';
            }
            $context['attachments']['templates'] = array('add_new' => 'template_add_new_attachments', 'existing' => 'template_show_existing_attachments');
            $attachmentRestrictionTypes = array('attachmentNumPerPostLimit', 'attachmentPostLimit', 'attachmentSizeLimit');
            foreach ($attachmentRestrictionTypes as $type) {
                if (!empty($modSettings[$type])) {
                    $context['attachments']['restrictions'][] = sprintf($txt['attach_restrict_' . $type], comma_format($modSettings[$type], 0));
                    // Show some numbers. If they exist.
                    if ($type == 'attachmentNumPerPostLimit' && $attachments['quantity'] > 0) {
                        $context['attachments']['restrictions'][] = sprintf($txt['attach_remaining'], $modSettings['attachmentNumPerPostLimit'] - $attachments['quantity']);
                    } elseif ($type == 'attachmentPostLimit' && $attachments['total_size'] > 0) {
                        $context['attachments']['restrictions'][] = sprintf($txt['attach_available'], comma_format(round(max($modSettings['attachmentPostLimit'] - $attachments['total_size'] / 1028, 0)), 0));
                    }
                }
            }
            // Load up the drag and drop attachment magic
            addInlineJavascript('
			var dropAttach = dragDropAttachment.prototype.init({
				board: ' . $board . ',
				allowedExtensions: ' . JavaScriptEscape($context['attachments']['allowed_extensions']) . ',
				totalSizeAllowed: ' . JavaScriptEscape(empty($modSettings['attachmentPostLimit']) ? '' : $modSettings['attachmentPostLimit']) . ',
				individualSizeAllowed: ' . JavaScriptEscape(empty($modSettings['attachmentSizeLimit']) ? '' : $modSettings['attachmentSizeLimit']) . ',
				numOfAttachmentAllowed: ' . $context['attachments']['num_allowed'] . ',
				totalAttachSizeUploaded: ' . (isset($context['attachments']['total_size']) && !empty($context['attachments']['total_size']) ? $context['attachments']['total_size'] : 0) . ',
				numAttachUploaded: ' . (isset($context['attachments']['quantity']) && !empty($context['attachments']['quantity']) ? $context['attachments']['quantity'] : 0) . ',
				oTxt: ({
					allowedExtensions : ' . JavaScriptEscape(sprintf($txt['cant_upload_type'], $context['attachments']['allowed_extensions'])) . ',
					totalSizeAllowed : ' . JavaScriptEscape($txt['attach_max_total_file_size']) . ',
					individualSizeAllowed : ' . JavaScriptEscape(sprintf($txt['file_too_big'], comma_format($modSettings['attachmentSizeLimit'], 0))) . ',
					numOfAttachmentAllowed : ' . JavaScriptEscape(sprintf($txt['attachments_limit_per_post'], $modSettings['attachmentNumPerPostLimit'])) . ',
					postUploadError : ' . JavaScriptEscape($txt['post_upload_error']) . ',
				}),
			});', true);
        }
        $context['back_to_topic'] = isset($_REQUEST['goback']) || isset($_REQUEST['msg']) && !isset($_REQUEST['subject']);
        $context['show_additional_options'] = !empty($_POST['additional_options']) || isset($_SESSION['temp_attachments']['post']) || isset($_GET['additionalOptions']);
        $context['is_new_topic'] = empty($topic);
        $context['is_new_post'] = !isset($_REQUEST['msg']);
        $context['is_first_post'] = $context['is_new_topic'] || isset($_REQUEST['msg']) && $_REQUEST['msg'] == $id_first_msg;
        $context['current_action'] = 'post';
        // Register this form in the session variables.
        checkSubmitOnce('register');
        // Finally, load the template.
        if (!isset($_REQUEST['xml'])) {
            loadTemplate('Post');
            $context['sub_template'] = 'post_page';
        }
    }