/**
  * Generates list of available canned messages.
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function indexAction(Request $request)
 {
     $operator = $this->getOperator();
     $page = array('errors' => array());
     // Build list of available locales
     $all_locales = get_available_locales();
     $locales_with_label = array();
     foreach ($all_locales as $id) {
         $locale_info = get_locale_info($id);
         $locales_with_label[] = array('id' => $id, 'name' => $locale_info ? $locale_info['name'] : $id);
     }
     $page['locales'] = $locales_with_label;
     // Get selected locale, if any.
     $lang = $this->extractLocale($request);
     if (!$lang) {
         $lang = in_array(get_current_locale(), $all_locales) ? get_current_locale() : $all_locales[0];
     }
     // Get selected group ID, if any.
     $group_id = $this->extractGroupId($request);
     if ($group_id) {
         $group = group_by_id($group_id);
         if (!$group) {
             $page['errors'][] = getlocal('No such group');
             $group_id = false;
         }
     }
     // Build list of available groups
     $all_groups = in_isolation($operator) ? get_groups_for_operator($operator) : get_all_groups();
     $page['groups'] = array();
     $page['groups'][] = array('groupid' => '', 'vclocalname' => getlocal('-all operators-'), 'level' => 0);
     foreach ($all_groups as $g) {
         $page['groups'][] = $g;
     }
     // Get messages and setup pagination
     $canned_messages = load_canned_messages($lang, $group_id);
     foreach ($canned_messages as &$message) {
         $message['vctitle'] = $message['vctitle'];
         $message['vcvalue'] = $message['vcvalue'];
     }
     unset($message);
     $pagination = setup_pagination($canned_messages);
     $page['pagination'] = $pagination['info'];
     $page['pagination.items'] = $pagination['items'];
     // Buil form values
     $page['formlang'] = $lang;
     $page['formgroup'] = $group_id;
     // Set other needed page values and render the response
     $page['title'] = getlocal('Canned Messages');
     $page['menuid'] = 'canned';
     $page = array_merge($page, prepare_menu($operator));
     return $this->render('canned_messages', $page);
 }
Esempio n. 2
0
 /**
  * Builds a page with form for add/edit group.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  * @throws NotFoundException If the operator's group with specified ID is
  *   not found in the system.
  */
 public function showFormAction(Request $request)
 {
     $operator = $this->getOperator();
     $group_id = $request->attributes->getInt('group_id');
     $page = array('gid' => false, 'errors' => $request->attributes->get('errors', array()));
     if ($group_id) {
         // Check if the group exisits
         $group = group_by_id($group_id);
         if (!$group) {
             throw new NotFoundException('The group is not found.');
         }
         // Set form values
         $page['formname'] = $group['vclocalname'];
         $page['formdescription'] = $group['vclocaldescription'];
         $page['formcommonname'] = $group['vccommonname'];
         $page['formcommondescription'] = $group['vccommondescription'];
         $page['formemail'] = $group['vcemail'];
         $page['formweight'] = $group['iweight'];
         $page['formparentgroup'] = $group['parent'];
         $page['grid'] = $group['groupid'];
         $page['formtitle'] = $group['vctitle'];
         $page['formchattitle'] = $group['vcchattitle'];
         $page['formhosturl'] = $group['vchosturl'];
         $page['formlogo'] = $group['vclogo'];
     }
     // Override group's fields from the request if it's needed. This
     // case will take place when save handler fails.
     if ($request->isMethod('POST')) {
         $page['formname'] = $request->request->get('name');
         $page['formdescription'] = $request->request->get('description');
         $page['formcommonname'] = $request->request->get('commonname');
         $page['formcommondescription'] = $request->request->get('commondescription');
         $page['formemail'] = $request->request->get('email');
         $page['formweight'] = $request->request->get('weight');
         $page['formparentgroup'] = $request->request->get('parentgroup');
         $page['formtitle'] = $request->request->get('title');
         $page['formchattitle'] = $request->request->get('chattitle');
         $page['formhosturl'] = $request->request->get('hosturl');
         $page['formlogo'] = $request->request->get('logo');
     }
     // Set other page variables and render the template.
     $page['stored'] = $request->query->has('stored');
     $page['availableParentGroups'] = get_available_parent_groups($group_id);
     $page['formaction'] = $request->getBaseUrl() . $request->getPathInfo();
     $page['title'] = getlocal('Group details');
     $page['menuid'] = 'groups';
     $page = array_merge($page, prepare_menu($operator));
     $page['tabs'] = $this->buildTabs($request);
     $this->getAssetManager()->attachJs('js/compiled/group.js');
     return $this->render('group_edit', $page);
 }
Esempio n. 3
0
function verifyparam_groupid($paramid)
{
    global $settings, $errors;
    $groupid = "";
    if ($settings['enablegroups'] == '1') {
        $groupid = verifyparam($paramid, "/^\\d{0,10}\$/", "");
        if ($groupid) {
            $group = group_by_id($groupid);
            if (!$group) {
                $errors[] = getlocal("page.group.no_such");
                $groupid = "";
            }
        }
    }
    return $groupid;
}
Esempio n. 4
0
 /**
  * Process submitting of the mail form.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  * @throws NotFoundException If the thread with specified ID and token is
  * not found.
  */
 public function submitFormAction(Request $request)
 {
     $errors = array();
     $thread_id = $request->attributes->get('thread_id');
     $token = $request->attributes->get('token');
     // Try to load the thread
     $thread = Thread::load($thread_id, $token);
     if (!$thread) {
         throw new NotFoundException('The thread is not found.');
     }
     $email = $request->request->get('email');
     $group = $thread->groupId ? group_by_id($thread->groupId) : null;
     if (!$email) {
         $errors[] = no_field('Your email');
     } elseif (!MailUtils::isValidAddress($email)) {
         $errors[] = wrong_field('Your email');
     }
     if (count($errors) > 0) {
         $request->attributes->set('errors', $errors);
         // Render the mail form again
         return $this->showFormAction($request);
     }
     $history = '';
     $last_id = -1;
     $messages = $thread->getMessages(true, $last_id);
     foreach ($messages as $msg) {
         $history .= message_to_text($msg);
     }
     // Load mail templates and substitute placeholders there.
     $mail_template = MailTemplate::loadByName('user_history', get_current_locale());
     if ($mail_template) {
         $this->sendMail(MailUtils::buildMessage($email, MIBEW_MAILBOX, $mail_template->buildSubject(), $mail_template->buildBody(array($thread->userName, $history, Settings::get('title'), Settings::get('hosturl')))));
     } else {
         trigger_error('Cannot send e-mail because "user_history" mail template cannot be loaded.', E_USER_WARNING);
     }
     $page = setup_logo($group);
     $page['email'] = $email;
     return $this->render('mailsent', $page);
 }
Esempio n. 5
0
 /**
  * Processes submitting of the form which is generated in
  * {@link \Mibew\Controller\GroupController::showMembersFormAction()} method.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  * @throws NotFoundException If the operator's group with specified ID is
  *   not found in the system.
  */
 public function submitFormAction(Request $request)
 {
     csrf_check_token($request);
     $operators = get_operators_list();
     $group_id = $request->attributes->getInt('group_id');
     $group = group_by_id($group_id);
     // Check if specified group exists
     if (!$group) {
         throw new NotFoundException('The group is not found.');
     }
     // Update members list
     $new_members = array();
     foreach ($operators as $op) {
         if ($request->request->get('op' . $op['operatorid']) == 'on') {
             $new_members[] = $op['operatorid'];
         }
     }
     update_group_members($group_id, $new_members);
     // Redirect opeartor to group members page.
     $parameters = array('group_id' => $group_id, 'stored' => true);
     return $this->redirect($this->generateUrl('group_members', $parameters));
 }
Esempio n. 6
0
    /**
     * Starts the chat.
     *
     * @param Request $request Incoming request.
     * @return string|\Symfony\Component\HttpFoundation\RedirectResponse
     *   Rendered page content or a redirect response.
     * @todo Split the action into pieces.
     */
    public function startAction(Request $request)
    {
        // Check if we should force the user to use SSL
        $ssl_redirect = $this->sslRedirect($request);
        if ($ssl_redirect !== false) {
            return $ssl_redirect;
        }

        // Initialize client side application
        $this->getAssetManager()->attachJs('js/compiled/chat_app.js');

        $thread = null;
        // Try to get thread from the session
        if (isset($_SESSION[SESSION_PREFIX . 'threadid'])) {
            $thread = Thread::reopen($_SESSION[SESSION_PREFIX . 'threadid']);
        }

        // Create new thread
        if (!$thread) {
            // Load group info
            $group_id = '';
            $group_name = '';
            $group = null;
            if (Settings::get('enablegroups') == '1') {
                $group_id = $request->query->get('group');
                if (!preg_match("/^\d{1,10}$/", $group_id)) {
                    $group_id = false;
                }

                if ($group_id) {
                    $group = group_by_id($group_id);
                    if (!$group) {
                        $group_id = false;
                    } else {
                        $group_name = get_group_name($group);
                    }
                }
            }

            // Get operator code
            $operator_code = $request->query->get('operator_code');
            if (!preg_match("/^[A-z0-9_]+$/", $operator_code)) {
                $operator_code = false;
            }

            // Get visitor info
            $visitor = visitor_from_request();
            $info = $request->query->get('info');
            $email = $request->query->get('email');

            // Get referrer
            $referrer = $request->query->get('url', $request->headers->get('referer'));
            if ($request->query->get('referrer')) {
                $referrer .= "\n" . $request->query->get('referrer');
            }

            // Check if there are online operators
            if (!has_online_operators($group_id)) {
                // Display leave message page
                $page = array_merge_recursive(
                    setup_logo($group),
                    setup_leavemessage(
                        $visitor['name'],
                        $email,
                        $group_id,
                        $info,
                        $referrer
                    )
                );
                $page['leaveMessageOptions'] = $page['leaveMessage'];

                $this->getAssetManager()->attachJs(
                    $this->startJsApplication($request, $page),
                    AssetManagerInterface::INLINE,
                    1000
                );

                return $this->render('chat', $page);
            }

            // Get invitation info
            if (Settings::get('enabletracking') && !empty($_SESSION[SESSION_PREFIX . 'visitorid'])) {
                $invitation_state = invitation_state($_SESSION[SESSION_PREFIX . 'visitorid']);
                $visitor_is_invited = $invitation_state['invited'];
            } else {
                $visitor_is_invited = false;
            }

            // Get operator info
            $requested_operator = false;
            if ($operator_code) {
                $requested_operator = operator_by_code($operator_code);
            }

            // Check if survey should be displayed
            if (Settings::get('enablepresurvey') == '1' && !$visitor_is_invited && !$requested_operator) {
                // Display prechat survey
                $page = array_merge_recursive(
                    setup_logo($group),
                    setup_survey(
                        $visitor['name'],
                        $email,
                        $group_id,
                        $info,
                        $referrer
                    )
                );
                $page['surveyOptions'] = $page['survey'];

                $this->getAssetManager()->attachJs(
                    $this->startJsApplication($request, $page),
                    AssetManagerInterface::INLINE,
                    1000
                );

                return $this->render('chat', $page);
            }

            // Start chat thread
            $thread = chat_start_for_user(
                $group_id,
                $requested_operator,
                $visitor['id'],
                $visitor['name'],
                $referrer,
                $info
            );
        }
        $path_args = array(
            'thread_id' => intval($thread->id),
            'token' => urlencode($thread->lastToken),
        );

        $chat_style_name = $request->query->get('style');
        if (preg_match("/^\w+$/", $chat_style_name)) {
            $path_args['style'] = $chat_style_name;
        }

        return $this->redirect($this->generateUrl('chat_user', $path_args));
    }
Esempio n. 7
0
    /**
     * Process submitted leave message form.
     *
     * Send message to operator email and create special meil thread.
     * @param array $args Associative array of arguments. It must contains the
     *   following keys:
     *    - 'threadId': for this function this param equals to null;
     *    - 'token': for this function this param equals to null;
     *    - 'name': string, user name;
     *    - 'email': string, user email;
     *    - 'message': string, user message;
     *    - 'info': string, some info about user;
     *    - 'referrer': string, page user came from;
     *    - 'captcha': string, captcha value;
     *    - 'groupId': selected group id.
     *
     * @throws \Mibew\RequestProcessor\ThreadProcessorException Can throw an
     *   exception if captcha or email is wrong.
     */
    protected function apiProcessLeaveMessage($args)
    {
        // Check captcha
        if (Settings::get('enablecaptcha') == '1' && can_show_captcha()) {
            $captcha = $args['captcha'];
            $original = isset($_SESSION[SESSION_PREFIX . 'mibew_captcha'])
                ? $_SESSION[SESSION_PREFIX . 'mibew_captcha']
                : '';
            unset($_SESSION[SESSION_PREFIX . 'mibew_captcha']);
            if (empty($original) || empty($captcha) || $captcha != $original) {
                throw new ThreadProcessorException(
                    getlocal('The letters you typed don\'t match the letters that were shown in the picture.'),
                    ThreadProcessorException::ERROR_WRONG_CAPTCHA
                );
            }
        }

        // Get form fields
        $email = $args['email'];
        $name = $args['name'];
        $message = $args['message'];
        $info = $args['info'];
        $referrer = $args['referrer'];

        if (!MailUtils::isValidAddress($email)) {
            throw new ThreadProcessorException(
                wrong_field("Your email"),
                ThreadProcessorException::ERROR_WRONG_EMAIL
            );
        }

        // Verify group id
        $group_id = '';
        if (Settings::get('enablegroups') == '1') {
            if (preg_match("/^\d{1,8}$/", $args['groupId']) != 0) {
                $group = group_by_id($args['groupId']);
                if ($group) {
                    $group_id = $args['groupId'];
                }
            }
        }

        // Create thread for left message
        $remote_host = get_remote_host();
        $user_browser = $_SERVER['HTTP_USER_AGENT'];
        $visitor = visitor_from_request();

        // Get message locale
        $message_locale = Settings::get('left_messages_locale');
        if (!locale_is_available($message_locale)) {
            $message_locale = get_home_locale();
        }

        // Create thread
        $thread = new Thread();
        $thread->groupId = $group_id;
        $thread->userName = $name;
        $thread->remote = $remote_host;
        $thread->referer = $referrer;
        $thread->locale = get_current_locale();
        $thread->userId = $visitor['id'];
        $thread->userAgent = $user_browser;
        $thread->state = Thread::STATE_LEFT;
        $thread->closed = time();
        $thread->save();

        // Send some messages
        if ($referrer) {
            $thread->postMessage(
                Thread::KIND_FOR_AGENT,
                getlocal('Vistor came from page {0}', array($referrer), get_current_locale(), true)
            );
        }
        if ($email) {
            $thread->postMessage(
                Thread::KIND_FOR_AGENT,
                getlocal('E-Mail: {0}', array($email), get_current_locale(), true)
            );
        }
        if ($info) {
            $thread->postMessage(
                Thread::KIND_FOR_AGENT,
                getlocal('Info: {0}', array($info), get_current_locale(), true)
            );
        }
        $thread->postMessage(Thread::KIND_USER, $message, array('name' => $name));

        // Get email for message
        $inbox_mail = get_group_email($group_id);

        if (empty($inbox_mail)) {
            $inbox_mail = Settings::get('email');
        }

        // Send email
        if ($inbox_mail) {
            // Prepare message to send by email
            $mail_template = MailTemplate::loadByName('leave_message', $message_locale);
            if (!$mail_template) {
                trigger_error(
                    'Cannot send e-mail because "leave_message" mail template cannot be loaded.',
                    E_USER_WARNING
                );

                return;
            }

            $subject = $mail_template->buildSubject(array($args['name']));
            $body = $mail_template->buildBody(array(
                $args['name'],
                $email,
                $message,
                ($info ? $info . "\n" : ""),
            ));

            // Send
            $this->getMailerFactory()->getMailer()->send(
                MailUtils::buildMessage($inbox_mail, $email, $subject, $body)
            );
        }
    }
Esempio n. 8
0
/**
 * Update operators of specific group
 *
 * Triggers {@link \Mibew\EventDispatcher\Events::GROUP_UPDATE_OPERATORS} event.
 *
 * @param int $group_id ID of the group.
 * @param array $new_value list of all operators of specified group.
 */
function update_group_members($group_id, $new_value)
{
    // Get the unchanged set of operators related with the group to trigger
    // "update" event later
    $original_operators = get_group_members($group_id);

    $db = Database::getInstance();
    $db->query(
        "DELETE FROM {operatortoopgroup} WHERE groupid = ?",
        array($group_id)
    );

    foreach ($new_value as $operator_id) {
        $db->query(
            "INSERT INTO {operatortoopgroup} (groupid, operatorid) VALUES (?, ?)",
            array($group_id, $operator_id)
        );
    }
    if ($original_operators != $new_value) {
        // Trigger the "update" event only if operators set is changed.
        $args = array(
            'group' => group_by_id($group_id),
            'original_operators' => $original_operators,
            'operators' => $new_value,
        );
        EventDispatcher::getInstance()->triggerEvent(Events::GROUP_UPDATE_OPERATORS, $args);
    }
}
Esempio n. 9
0
/**
 * Updates set of groups the operator belongs to.
 *
 * Triggers {@link \Mibew\EventDispatcher\Events::GROUP_UPDATE_OPERATORS} event.
 *
 * @param int $operator_id ID of the operator.
 * @param array $new_value List of operator's groups IDs.
 */
function update_operator_groups($operator_id, $new_value)
{
    // Get difference of groups the operator belongs to before and after the
    // update.
    $original_groups = get_operator_group_ids($operator_id);
    $groups_union = array_unique(array_merge($original_groups, $new_value));
    $groups_intersect = array_intersect($original_groups, $new_value);
    $updated_groups = array_diff($groups_union, $groups_intersect);

    // Get members of all updated groups. It will be used to trigger the
    // "update" event later.
    $original_relations = array();
    foreach ($updated_groups as $group_id) {
        $original_relations[$group_id] = get_group_members($group_id);
    }

    // Update group members
    $db = Database::getInstance();
    $db->query(
        "DELETE FROM {operatortoopgroup} WHERE operatorid = ?",
        array($operator_id)
    );

    foreach ($new_value as $group_id) {
        $db->query(
            "INSERT INTO {operatortoopgroup} (groupid, operatorid) VALUES (?,?)",
            array($group_id, $operator_id)
        );
    }

    // Trigger the "update" event
    foreach ($original_relations as $group_id => $operators) {
        $args = array(
            'group' => group_by_id($group_id),
            'original_operators' => $operators,
            'operators' => get_group_members($group_id),
        );
        EventDispatcher::getInstance()->triggerEvent(Events::GROUP_UPDATE_OPERATORS, $args);
    }
}
Esempio n. 10
0
$all_locales = get_available_locales();
$locales_with_label = array();
foreach ($all_locales as $id) {
    $locales_with_label[] = array('id' => $id, 'name' => getlocal_($id, "names"));
}
$page['locales'] = $locales_with_label;
$lang = verifyparam("lang", "/^[\\w-]{2,5}\$/", "");
if (!$lang || !in_array($lang, $all_locales)) {
    $lang = in_array($current_locale, $all_locales) ? $current_locale : $all_locales[0];
}
# groups
$groupid = "";
if ($settings['enablegroups'] == '1') {
    $groupid = verifyparam("group", "/^\\d{0,8}\$/", "");
    if ($groupid) {
        $group = group_by_id($groupid);
        if (!$group) {
            $errors[] = getlocal("page.group.no_such");
            $groupid = "";
        }
    }
    $link = connect();
    $allgroups = get_all_groups($link);
    mysql_close($link);
    $page['groups'] = array();
    $page['groups'][] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group"));
    foreach ($allgroups as $g) {
        $page['groups'][] = $g;
    }
}
# delete
Esempio n. 11
0
require_once '../libs/operator.php';
require_once '../libs/chat.php';
require_once '../libs/expand.php';
require_once '../libs/groups.php';
$operator = check_login();
$threadid = verifyparam("thread", "/^\\d{1,10}\$/");
$token = verifyparam("token", "/^\\d{1,10}\$/");
$thread = thread_by_id($threadid);
if (!$thread || !isset($thread['ltoken']) || $token != $thread['ltoken']) {
    die("wrong thread");
}
$page = array();
$errors = array();
if (isset($_GET['nextGroup'])) {
    $nextid = verifyparam("nextGroup", "/^\\d{1,10}\$/");
    $nextGroup = group_by_id($nextid);
    if ($nextGroup) {
        $page['message'] = getlocal2("chat.redirected.group.content", array(safe_htmlspecialchars(topage(get_group_name($nextGroup)))));
        if ($thread['istate'] == $state_chatting) {
            $link = connect();
            commit_thread($threadid, array("istate" => intval($state_waiting), "nextagent" => 0, "groupid" => intval($nextid), "agentId" => 0, "agentName" => "''"), $link);
            post_message_($thread['threadid'], $kind_events, getstring2_("chat.status.operator.redirect", array(get_operator_name($operator)), $thread['locale'], true), $link);
            mysql_close($link);
        } else {
            $errors[] = getlocal("chat.redirect.cannot");
        }
    } else {
        $errors[] = getlocal("chat.redirect.unknown_group");
    }
} else {
    $nextid = verifyparam("nextAgent", "/^\\d{1,10}\$/");
Esempio n. 12
0
/**
 * Prepare some data for chat for both user and operator
 *
 * @param Thread $thread thread object
 * @return array Array of chat view data
 */
function setup_chatview(Thread $thread)
{
    $data = prepare_chat_app_data();
    // Get group info
    if (!empty($thread->groupId)) {
        $group = group_by_id($thread->groupId);
        $group = get_top_level_group($group);
    } else {
        $group = array();
    }
    // Create some empty arrays
    $data['chat'] = array('messageForm' => array(), 'links' => array(), 'windowsParams' => array());
    // Set thread params
    $data['chat']['thread'] = array('id' => $thread->id, 'token' => $thread->lastToken, 'agentId' => $thread->agentId, 'userId' => $thread->userId);
    $data['page.title'] = empty($group['vcchattitle']) ? Settings::get('chattitle') : $group['vcchattitle'];
    $data['chat']['page'] = array('title' => $data['page.title']);
    // Setup logo
    $data = array_merge_recursive($data, setup_logo($group));
    // Set enter key shortcut
    if (Settings::get('sendmessagekey') == 'enter') {
        $data['chat']['messageForm']['ignoreCtrl'] = true;
    } else {
        $data['chat']['messageForm']['ignoreCtrl'] = false;
    }
    // Load dialogs style options
    $chat_style = new ChatStyle(ChatStyle::getCurrentStyle());
    $style_config = $chat_style->getConfigurations();
    $data['chat']['windowsParams']['mail'] = $style_config['mail']['window'];
    // Load core style options
    $page_style = new PageStyle(PageStyle::getCurrentStyle());
    $style_config = $page_style->getConfigurations();
    $data['chat']['windowsParams']['history'] = $style_config['history']['window'];
    $data['startFrom'] = 'chat';
    return $data;
}
Esempio n. 13
0
 /**
  * Returns content of the chat button.
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function indexAction(Request $request)
 {
     $referer = $request->server->get('HTTP_REFERER', '');
     // We need to display message about visited page only if the visitor
     // really change it.
     $new_page = empty($_SESSION[SESSION_PREFIX . 'last_visited_page']) || $_SESSION[SESSION_PREFIX . 'last_visited_page'] != $referer;
     // Display message about page change
     if ($referer && isset($_SESSION[SESSION_PREFIX . 'threadid']) && $new_page) {
         $thread = Thread::load($_SESSION[SESSION_PREFIX . 'threadid']);
         if ($thread && $thread->state != Thread::STATE_CLOSED) {
             $msg = getlocal("Visitor navigated to {0}", array($referer), $thread->locale, true);
             $thread->postMessage(Thread::KIND_FOR_AGENT, $msg);
         }
     }
     $_SESSION[SESSION_PREFIX . 'last_visited_page'] = $referer;
     $image = $request->query->get('i', '');
     if (!preg_match("/^\\w+\$/", $image)) {
         $image = 'mibew';
     }
     $lang = $request->query->get('lang', '');
     if (!preg_match("/^[\\w-]{2,5}\$/", $lang)) {
         $lang = '';
     }
     if (!$lang || !locale_is_available($lang)) {
         $lang = get_current_locale();
     }
     $group_id = $request->query->get('group', '');
     if (!preg_match("/^\\d{1,8}\$/", $group_id)) {
         $group_id = false;
     }
     if ($group_id) {
         if (Settings::get('enablegroups') == '1') {
             $group = group_by_id($group_id);
             if (!$group) {
                 $group_id = false;
             }
         } else {
             $group_id = false;
         }
     }
     // Get image file content
     $image_postfix = has_online_operators($group_id) ? "on" : "off";
     $file_name = "locales/{$lang}/button/{$image}_{$image_postfix}.png";
     $content_type = 'image/png';
     if (!is_readable($file_name)) {
         // Fall back to .gif image
         $file_name = "locales/{$lang}/button/{$image}_{$image_postfix}.gif";
         $content_type = 'image/gif';
     }
     $fh = fopen($file_name, 'rb');
     if ($fh) {
         // Create response with image in body
         $file_size = filesize($file_name);
         $content = fread($fh, $file_size);
         fclose($fh);
         $response = new Response($content, 200);
         // Set correct content info
         $response->headers->set('Content-Type', $content_type);
         $response->headers->set('Content-Length', $file_size);
     } else {
         $response = new Response('Not found', 404);
     }
     // Disable caching
     $response->headers->addCacheControlDirective('no-cache', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->setExpires(new \DateTime('yesterday noon'));
     $response->headers->set('Pragma', 'no-cache');
     return $response;
 }
 /**
  * Generates a page with thread history (thread log).
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function threadAction(Request $request)
 {
     $operator = $this->getOperator();
     $page = array();
     // Load thread info
     $thread = Thread::load($request->attributes->get('thread_id'));
     $group = group_by_id($thread->groupId);
     $thread_info = array('userName' => $thread->userName, 'userAddress' => get_user_addr($thread->remote), 'userAgentVersion' => get_user_agent_version($thread->userAgent), 'agentName' => $thread->agentName, 'chatTime' => $thread->modified - $thread->created, 'chatStarted' => $thread->created, 'groupName' => get_group_name($group));
     $page['threadInfo'] = $thread_info;
     // Build messages list
     $last_id = -1;
     $messages = array_map('sanitize_message', $thread->getMessages(false, $last_id));
     $page['title'] = getlocal("Chat log");
     $page = array_merge($page, prepare_menu($operator, false));
     $this->getAssetManager()->attachJs('js/compiled/thread_log_app.js');
     $this->getAssetManager()->attachJs(sprintf('jQuery(document).ready(function(){Mibew.Application.start(%s);});', json_encode(array('messages' => $messages))), \Mibew\Asset\AssetManagerInterface::INLINE, 1000);
     return $this->render('history_thread', $page);
 }
Esempio n. 15
0
 /**
  * Process chat thread redirection.
  *
  * @param Request $request Incoming request.
  * @return string|\Symfony\Component\HttpFoundation\RedirectResponse Rendered
  *   page content or a redirect response.
  * @throws NotFoundException If the thread with specified ID and token is
  * not found.
  * @throws BadRequestException If one or more arguments have a wrong format.
  */
 public function redirectAction(Request $request)
 {
     $thread_id = $request->attributes->get('thread_id');
     $token = $request->attributes->get('token');
     $thread = Thread::load($thread_id, $token);
     if (!$thread) {
         throw new NotFoundException('The thread is not found.');
     }
     $page = array('errors' => array());
     if ($request->query->has('nextGroup')) {
         // The thread was redirected to a group.
         $next_id = $request->query->get('nextGroup');
         if (!preg_match("/^\\d{1,10}\$/", $next_id)) {
             throw new BadRequestException('Wrong value of "nextGroup" argument.');
         }
         $next_group = group_by_id($next_id);
         if ($next_group) {
             $page['message'] = getlocal('The visitor has been placed in a priorty queue of the group {0}.', array(get_group_name($next_group)));
             if (!$this->redirectToGroup($thread, (int) $next_id)) {
                 $page['errors'][] = getlocal('You are not chatting with the visitor.');
             }
         } else {
             $page['errors'][] = 'Unknown group';
         }
     } else {
         // The thread was redirected to an operator.
         $next_id = $request->query->get('nextAgent');
         if (!preg_match("/^\\d{1,10}\$/", $next_id)) {
             throw new BadRequestException('Wrong value of "nextAgent" argument.');
         }
         $next_operator = operator_by_id($next_id);
         if ($next_operator) {
             $page['message'] = getlocal('The visitor has been placed in the priorty queue of the operator {0}.', array(get_operator_name($next_operator)));
             if (!$this->redirectToOperator($thread, $next_id)) {
                 $page['errors'][] = getlocal('You are not chatting with the visitor.');
             }
         } else {
             $page['errors'][] = 'Unknown operator';
         }
     }
     $page = array_merge_recursive($page, setup_logo());
     if (count($page['errors']) > 0) {
         return $this->render('error', $page);
     } else {
         return $this->render('redirected', $page);
     }
 }
Esempio n. 16
0
 /**
  * Generates a page with Mibew button code form.
  *
  * @param Request $request Incoming request
  * @return Response Rendered content of the page.
  */
 public function generateAction(Request $request)
 {
     $operator = $this->getOperator();
     $page = array('errors' => array());
     $image_locales_map = $this->getImageLocalesMap(MIBEW_FS_ROOT . '/locales');
     $image = $request->query->get('i', 'mibew');
     if (!isset($image_locales_map[$image])) {
         $page['errors'][] = 'Unknown image: ' . $image;
         $avail = array_keys($image_locales_map);
         $image = $avail[0];
     }
     $image_locales = $image_locales_map[$image];
     $style_list = ChatStyle::getAvailableStyles();
     $style_list[''] = getlocal('-from general settings-');
     $style = $request->query->get('style', '');
     if ($style && !in_array($style, $style_list)) {
         $style = '';
     }
     $invitation_style_list = InvitationStyle::getAvailableStyles();
     $invitation_style_list[''] = getlocal('-from general settings-');
     $invitation_style = $request->query->get('invitationstyle', '');
     if ($invitation_style && !in_array($invitation_style, $invitation_style_list)) {
         $invitation_style = '';
     }
     $locales_list = get_available_locales();
     $group_id = $request->query->getInt('group');
     if ($group_id && !group_by_id($group_id)) {
         $page['errors'][] = getlocal("No such group");
         $group_id = false;
     }
     $show_host = $request->query->get('hostname') == 'on';
     $force_secure = $request->query->get('secure') == 'on';
     $mod_security = $request->query->get('modsecurity') == 'on';
     $force_windows = $request->query->get('forcewindows') == 'on';
     $code_type = $request->query->get('codetype', 'button');
     if (!in_array($code_type, array('button', 'operator_code', 'text_link'))) {
         throw new BadRequestException('Wrong value of "codetype" param.');
     }
     $lang = $request->query->get('lang', '');
     if (!preg_match("/^[\\w-]{2,5}\$/", $lang)) {
         $lang = '';
     }
     $operator_code = $code_type == 'operator_code';
     $generate_button = $code_type == 'button';
     $button_generator_options = array('chat_style' => $style, 'group_id' => $group_id, 'show_host' => $show_host, 'force_secure' => $force_secure, 'mod_security' => $mod_security, 'prefer_iframe' => !$force_windows);
     if ($operator_code) {
         $button_generator = new OperatorCodeFieldGenerator($this->getRouter(), $this->getAssetManager()->getUrlGenerator(), $button_generator_options);
     } elseif ($generate_button) {
         // Make sure locale exists
         if (!$lang || !in_array($lang, $image_locales)) {
             $lang = in_array(get_current_locale(), $image_locales) ? get_current_locale() : $image_locales[0];
         }
         $button_generator = new ImageButtonGenerator($this->getRouter(), $this->getAssetManager()->getUrlGenerator(), $button_generator_options);
         // Set generator-specific options
         $button_generator->setOption('image', $image);
     } else {
         // Make sure locale exists
         if (!$lang || !in_array($lang, $locales_list)) {
             $lang = in_array(get_current_locale(), $locales_list) ? get_current_locale() : $locales_list[0];
         }
         $button_generator = new TextButtonGenerator($this->getRouter(), $this->getAssetManager()->getUrlGenerator(), $button_generator_options);
         // Set generator-specific options
         $button_generator->setOption('caption', getlocal('Click to chat'));
     }
     // Set verified locale code to a button generator
     $button_generator->setOption('locale', $lang);
     $page['buttonCode'] = $button_generator->generate();
     $page['availableImages'] = array_keys($image_locales_map);
     $page['availableLocales'] = $generate_button ? $image_locales : $locales_list;
     $page['availableChatStyles'] = $style_list;
     $page['availableInvitationStyles'] = $invitation_style_list;
     $page['groups'] = $this->getGroupsList();
     $page['availableCodeTypes'] = array('button' => getlocal('button'), 'operator_code' => getlocal('operator code field'), 'text_link' => getlocal('text link'));
     $page['formgroup'] = $group_id;
     $page['formstyle'] = $style;
     $page['forminvitationstyle'] = $invitation_style;
     $page['formimage'] = $image;
     $page['formlang'] = $lang;
     $page['formhostname'] = $show_host;
     $page['formsecure'] = $force_secure;
     $page['formmodsecurity'] = $mod_security;
     $page['formcodetype'] = $code_type;
     $page['formforcewindows'] = $force_windows;
     $page['enabletracking'] = Settings::get('enabletracking');
     $page['operator_code'] = $operator_code;
     $page['generateButton'] = $generate_button;
     $page['title'] = getlocal("Button HTML code generation");
     $page['menuid'] = "getcode";
     $page = array_merge($page, prepare_menu($operator));
     return $this->render('button_code', $page);
 }