Ejemplo n.º 1
0
 /**
  * Renders template file to HTML.
  *
  * @param string $template_name Name of the template file with neither path
  *   nor extension.
  * @param array $data Associative array of values that should be used for
  *   substitutions in a template.
  * @return string Rendered template.
  */
 public function render($template_name, $data = array())
 {
     // Pass additional variables to template
     $data['mibewVersion'] = MIBEW_VERSION;
     $data['currentLocale'] = get_current_locale();
     $locale_info = get_locale_info(get_current_locale());
     $data['rtl'] = $locale_info && $locale_info['rtl'];
     $data['stylePath'] = $this->getFilesPath();
     $data['styleName'] = $this->getName();
     return $this->getHandlebars()->render($template_name, $data);
 }
Ejemplo n.º 2
0
 /**
  * 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);
 }
 /**
  * Generates a page for the first step of password recovery process.
  *
  * @param Request $request
  * @return string Rendered page content
  */
 public function indexAction(Request $request)
 {
     if ($this->getOperator()) {
         // If the operator is logged in just redirect him to the home page.
         return $this->redirect($request->getUriForPath('/operator'));
     }
     $page = array('version' => MIBEW_VERSION, 'title' => getlocal('Trouble Accessing Your Account?'), 'headertitle' => getlocal('Mibew Messenger'), 'show_small_login' => true, 'fixedwrap' => true, 'errors' => array());
     $login_or_email = '';
     if ($request->isMethod('POST')) {
         // When HTTP GET method is used the form is just rendered but the
         // user does not pass any data. Thus we need to prevent CSRF attacks
         // only for POST requests
         csrf_check_token($request);
     }
     if ($request->isMethod('POST') && $request->request->has('loginoremail')) {
         $login_or_email = $request->request->get('loginoremail');
         $to_restore = MailUtils::isValidAddress($login_or_email) ? operator_by_email($login_or_email) : operator_by_login($login_or_email);
         if (!$to_restore) {
             $page['errors'][] = getlocal('No such Operator');
         }
         $email = $to_restore['vcemail'];
         if (count($page['errors']) == 0 && !MailUtils::isValidAddress($email)) {
             $page['errors'][] = "Operator hasn't set his e-mail";
         }
         if (count($page['errors']) == 0) {
             $token = sha1($to_restore['vclogin'] . (function_exists('openssl_random_pseudo_bytes') ? openssl_random_pseudo_bytes(32) : time() + microtime() . mt_rand(0, 99999999)));
             // Update the operator
             $to_restore['dtmrestore'] = time();
             $to_restore['vcrestoretoken'] = $token;
             update_operator($to_restore);
             $href = $this->getRouter()->generate('password_recovery_reset', array('id' => $to_restore['operatorid'], 'token' => $token), UrlGeneratorInterface::ABSOLUTE_URL);
             // Load mail templates and substitute placeholders there.
             $mail_template = MailTemplate::loadByName('password_recovery', get_current_locale());
             if (!$mail_template) {
                 throw new \RuntimeException('Cannot load "password_recovery" mail template');
             }
             $this->sendMail(MailUtils::buildMessage($email, $email, $mail_template->buildSubject(), $mail_template->buildBody(array(get_operator_name($to_restore), $href))));
             $page['isdone'] = true;
             return $this->render('password_recovery', $page);
         }
     }
     $page['formloginoremail'] = $login_or_email;
     $page['localeLinks'] = get_locale_links();
     $page['isdone'] = false;
     return $this->render('password_recovery', $page);
 }
Ejemplo n.º 4
0
 /**
  * Generates list of all localization constants in the system.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  */
 public function indexAction(Request $request)
 {
     $operator = $this->getOperator();
     $target = $request->query->get('target');
     if (!preg_match("/^[\\w-]{2,5}\$/", $target)) {
         $target = get_current_locale();
     }
     $page = array('localeName' => $this->getLocaleName($target), 'errors' => array());
     // Load list of all available locales.
     $locales_list = array();
     $all_locales = get_available_locales();
     foreach ($all_locales as $loc) {
         $locales_list[] = array('id' => $loc, 'name' => $this->getLocaleName($loc));
     }
     // Prepare localization constants to display.
     $strings = $this->loadStrings($target);
     foreach ($strings as $key => $item) {
         $strings[$key] = array('id' => $item['translationid'], 'source' => htmlentities($item['source']), 'translation' => empty($item['translation']) ? "<font color=\"#c13030\"><b>absent</b></font>" : htmlspecialchars($item['translation']));
     }
     // Sort localization constants in the specified order.
     $order = $request->query->get('sort');
     if (!in_array($order, array('source', 'translation'))) {
         $order = 'source';
     }
     if ($order == 'source') {
         usort($strings, function ($a, $b) {
             return strcmp($a['source'], $b['source']);
         });
     } elseif ($order == 'translation') {
         usort($strings, function ($a, $b) {
             return strcmp($a['translation'], $b['translation']);
         });
     }
     $pagination = setup_pagination($strings, 100);
     $page['pagination'] = $pagination['info'];
     $page['pagination.items'] = $pagination['items'];
     $page['formtarget'] = $target;
     $page['availableLocales'] = $locales_list;
     $page['availableOrders'] = array(array('id' => 'source', 'name' => getlocal('Source string')), array('id' => 'translation', 'name' => getlocal('Translation')));
     $page['formsort'] = $order;
     $page['title'] = getlocal('Translations');
     $page['menuid'] = 'translation';
     $page = array_merge($page, prepare_menu($operator));
     $page['tabs'] = $this->buildTabs($request);
     return $this->render('translations', $page);
 }
 /**
  * Processes submitting of the form which is generated in
  * {@link \Mibew\Controller\TranslationImportController::showFormAction()}
  * method.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  */
 public function submitFormAction(Request $request)
 {
     csrf_check_token($request);
     $errors = array();
     $target = $request->request->get('target');
     if (!preg_match("/^[\\w-]{2,5}\$/", $target)) {
         $target = get_current_locale();
     }
     $override = (bool) $request->request->get('override', false);
     // Validate uploaded file
     $file = $request->files->get('translation_file');
     if ($file) {
         // Process uploaded file.
         $orig_filename = $file->getClientOriginalName();
         $file_size = $file->getSize();
         if ($file_size == 0 || $file_size > Settings::get('max_uploaded_file_size')) {
             $errors[] = failed_uploading_file($orig_filename, "Uploaded file size exceeded");
         } elseif ($file->getClientOriginalExtension() != 'po') {
             $errors[] = failed_uploading_file($orig_filename, "Invalid file type");
         }
     } else {
         $errors[] = getlocal("No file selected");
     }
     // Try to process uploaded file
     if (count($errors) == 0) {
         try {
             // Try to import new messages.
             import_messages($target, $file->getRealPath(), $override);
             // Remove cached client side translations.
             $this->getCache()->getItem('translation/js/' . $target)->clear();
             // The file is not needed any more. Remove it.
             unlink($file->getRealPath());
         } catch (\Exception $e) {
             $errors[] = $e->getMessage();
         }
     }
     if (count($errors) != 0) {
         $request->attributes->set('errors', $errors);
         // The form should be rebuild. Invoke appropriate action.
         return $this->showFormAction($request);
     }
     // Redirect the operator to the same page using GET method.
     $redirect_to = $this->generateUrl('translation_import', array('stored' => true));
     return $this->redirect($redirect_to);
 }
 /**
  * Processes submitting of the form which is generated in
  * {@link \Mibew\Controller\TranslationExportController::showFormAction()}
  * method.
  *
  * @param Request $request Incoming request.
  * @return string Rendered page content.
  */
 public function submitFormAction(Request $request)
 {
     csrf_check_token($request);
     $target = $request->request->get('target');
     if (!preg_match("/^[\\w-]{2,5}\$/", $target)) {
         $target = get_current_locale();
     }
     $messages = load_messages($target);
     ksort($messages);
     $catalogue = new MessageCatalogue($target, array('messages' => $messages));
     $dumper = new PoFileDumper();
     $output = $dumper->format($catalogue);
     $response = new Response();
     $response->headers->set('Content-type', 'application/octet-stream');
     $response->headers->set('Content-Disposition', sprintf('attachment; filename=translation-%s.po', $target));
     $response->headers->set('Content-Length', strlen($output));
     $response->headers->set('Content-Transfer-Encoding', 'binary');
     $response->setContent($output);
     return $response;
 }
Ejemplo n.º 7
0
/**
 * Returns name of the operator. Choose between vclocalname and vccommonname
 *
 * @param array $operator Operator's array
 * @return string Operator's name
 */
function get_operator_name($operator)
{
    if (get_home_locale() == get_current_locale()) {
        return $operator['vclocalename'];
    } else {
        return $operator['vccommonname'];
    }
}
Ejemplo n.º 8
0
Archivo: _nav.php Proyecto: Nynnii/syn
			        	<ul class="nav navbar-nav navbar-right">
			        		<li class="<?php 
    echo set_active('accueil');
    ?>
">
			        			<a href="#"><?php 
    echo $trad['accueil'][get_current_locale()];
    ?>
</a>
			        		</li>
			        		<li class="<?php 
    echo set_active('timetable');
    ?>
">
			        			<a href="#"><?php 
    echo $trad['emploi_du_temps'][get_current_locale()];
    ?>
</a>
			        		</li>
			        		<li class="<?php 
    echo set_active('cours');
    ?>
 <?php 
    echo set_active('cours');
    ?>
">
			        			<a href="cours.php?id=<?php 
    echo get_session('user_id');
    ?>
">Cours</a>
			        		</li>
Ejemplo n.º 9
0
/**
 * Start chat thread for user
 *
 * @param int $group_id Id of group related to thread
 * @param array $requested_operator Array of requested operator info
 * @param string $visitor_id Id of the visitor
 * @param string $visitor_name Name of the visitor
 * @param string $referrer Page user came from
 * @param string $info User info
 *
 * @return Thread thread object
 */
function chat_start_for_user($group_id, $requested_operator, $visitor_id, $visitor_name, $referrer, $info)
{
    // Get user info
    $remote_host = get_remote_host();
    $user_browser = $_SERVER['HTTP_USER_AGENT'];
    // Check connection limit
    if (Thread::connectionLimitReached($remote_host)) {
        die("number of connections from your IP is exceeded, try again later");
    }
    // Check if visitor was invited to chat
    $is_invited = false;
    if (Settings::get('enabletracking')) {
        $invitation_state = invitation_state($_SESSION[SESSION_PREFIX . 'visitorid']);
        if ($invitation_state['invited']) {
            $is_invited = true;
        }
    }
    // Get info about requested operator
    $requested_operator_online = false;
    if ($requested_operator) {
        $requested_operator_online = is_operator_online($requested_operator['operatorid']);
    }
    // Get thread object
    if ($is_invited) {
        // Get thread from invitation
        $thread = invitation_accept($_SESSION[SESSION_PREFIX . 'visitorid']);
        if (!$thread) {
            die("Cannot start thread");
        }
    } else {
        // Create thread
        $thread = new Thread();
        $thread->state = Thread::STATE_LOADING;
        $thread->agentId = 0;
        if ($requested_operator && $requested_operator_online) {
            $thread->nextAgent = $requested_operator['operatorid'];
        }
    }
    // Update thread fields
    $thread->groupId = $group_id;
    $thread->userName = $visitor_name;
    $thread->remote = $remote_host;
    $thread->referer = $referrer;
    $thread->locale = get_current_locale();
    $thread->userId = $visitor_id;
    $thread->userAgent = $user_browser;
    $thread->save();
    $_SESSION[SESSION_PREFIX . 'threadid'] = $thread->id;
    // Store own thread ids to restrict access for other people
    if (!isset($_SESSION[SESSION_PREFIX . 'own_threads'])) {
        $_SESSION[SESSION_PREFIX . 'own_threads'] = array();
    }
    $_SESSION[SESSION_PREFIX . 'own_threads'][] = $thread->id;
    // Bind thread to the visitor
    if (Settings::get('enabletracking')) {
        track_visitor_bind_thread($visitor_id, $thread);
    }
    // Send several messages
    if ($is_invited) {
        $operator = operator_by_id($thread->agentId);
        $operator_name = get_operator_name($operator);
        $thread->postMessage(Thread::KIND_FOR_AGENT, getlocal('Visitor accepted invitation from operator {0}', array($operator_name), get_current_locale(), true));
    } else {
        if ($referrer) {
            $thread->postMessage(Thread::KIND_FOR_AGENT, getlocal('Vistor came from page {0}', array($referrer), get_current_locale(), true));
        }
        if ($requested_operator && !$requested_operator_online) {
            $thread->postMessage(Thread::KIND_INFO, getlocal('Thank you for contacting us. We are sorry, but requested operator <strong>{0}</strong> is offline. Another operator will be with you shortly.', array(get_operator_name($requested_operator)), get_current_locale(), true));
        } else {
            $thread->postMessage(Thread::KIND_INFO, getlocal('Thank you for contacting us. An operator will be with you shortly.', null, get_current_locale(), true));
        }
    }
    // TODO: May be move sending this message somewhere else?
    if ($info) {
        $thread->postMessage(Thread::KIND_FOR_AGENT, getlocal('Info: {0}', array($info), get_current_locale(), true));
    }
    // Let plugins know that user is ready to chat.
    $dispatcher = EventDispatcher::getInstance();
    $event_args = array('thread' => $thread);
    $dispatcher->triggerEvent(Events::THREAD_USER_IS_READY, $event_args);
    return $thread;
}
Ejemplo n.º 10
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;
 }
Ejemplo n.º 11
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);
 }
Ejemplo n.º 12
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);
 }
Ejemplo n.º 13
0
 /**
  * Finalize the request and make sure that the response is in compliance
  * with it.
  *
  * @param Request $request The processed request.
  * @param Response $response The response which should be set to the client.
  */
 protected function finalizeRequest(Request $request, Response $response)
 {
     // Attach operator's authentication info to the response to distinguish
     // him in the next requests.
     $this->getAuthenticationManager()->attachOperatorToResponse($response);
     // Cache user's locale in the cookie. The code below should be treated
     // as a temporary workaround.
     // TODO: Move the following lines to Locales Manager when object
     // oriented approach for locales will be implemented.
     $response->headers->setCookie(CookieFactory::fromRequest($request)->createCookie(LOCALE_COOKIE_NAME, get_current_locale(), time() + 60 * 60 * 24 * 1000));
     $response->prepare($request);
 }
Ejemplo n.º 14
0
 /**
  * Extracts locale code from the request.
  *
  * @param Request $request
  * @return string Locale code for the selected locale.
  */
 protected function extractLocale(Request $request)
 {
     $lang = $request->isMethod('POST') ? $request->request->get('lang') : $request->query->get('lang');
     $all_locales = get_available_locales();
     $correct_locale = !empty($lang) && preg_match("/^[\\w-]{2,5}\$/", $lang) && in_array($lang, $all_locales);
     if (!$correct_locale) {
         $lang = in_array(get_current_locale(), $all_locales) ? get_current_locale() : $all_locales[0];
     }
     return $lang;
 }
Ejemplo n.º 15
0
/**
 * Return local or common group description depending on current locale.
 *
 * @param array $group Associative group array. Should contain following keys:
 *  - 'vccommondescription': string, contain common description of the group;
 *  - 'vclocaldescription': string, contain local description of the group.
 * @return string Group description
 */
function get_group_description($group)
{
    $use_local_description = (get_home_locale() == get_current_locale())
        || !isset($group['vccommondescription'])
        || !$group['vccommondescription'];

    if ($use_local_description) {
        return $group['vclocaldescription'];
    } else {
        return $group['vccommondescription'];
    }
}
Ejemplo n.º 16
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)
            );
        }
    }
Ejemplo n.º 17
0
 /**
  * Returns a rendered template.
  *
  * @param string $template Name of the template.
  * @param array $parameters An array of parameters to pass to the template.
  *
  * @return string The rendered template
  */
 public function render($template, array $parameters = array())
 {
     // Attach all default css files
     $this->getAssetManager()->attachCss('js/vendor/vex/css/vex.css', AssetManagerInterface::RELATIVE_URL, -1000);
     $this->getAssetManager()->attachCss('js/vendor/vex/css/vex-theme-default.css', AssetManagerInterface::RELATIVE_URL, -1000);
     // Attach all needed JavaScript files. This is done here to decouple
     // templates and JavaScript applications.
     $assets = array('js/vendor/jquery/dist/jquery.min.js', 'js/vendor/json/json2.min.js', 'js/vendor/underscore/underscore-min.js', 'js/vendor/backbone/backbone-min.js', 'js/vendor/marionette/lib/backbone.marionette.min.js', 'js/vendor/handlebars/handlebars.min.js', 'js/vendor/vex/js/vex.combined.min.js', 'js/vendor/validator-js/validator.min.js', $this->getStyle()->getFilesPath() . '/templates_compiled/client_side/templates.js', 'js/compiled/mibewapi.js', 'js/compiled/default_app.js');
     foreach ($assets as $asset) {
         $this->getAssetManager()->attachJs($asset, AssetManagerInterface::RELATIVE_URL, -1000);
     }
     // Localization file is added as absolute URL because URL Generator
     // already prepended base URL to its result.
     $this->getAssetManager()->attachJs($this->generateUrl('js_translation', array('locale' => get_current_locale())), AssetManagerInterface::ABSOLUTE_URL, -1000);
     return $this->getStyle()->render($template, $parameters);
 }
Ejemplo n.º 18
0
/**
 * Returns localized string.
 *
 * @param string $text A text which should be localized
 * @param array $params Indexed array with placeholders.
 * @param string|null $locale Target locale code. If null is passed in the
 *   current locale will be used.
 * @param boolean $raw Indicates if the result should be sanitized or not.
 * @return string Localized text.
 */
function getlocal($text, $params = null, $locale = null, $raw = false)
{
    if (is_null($locale)) {
        $locale = get_current_locale();
    }
    $string = get_localized_string($text, $locale);
    if ($params) {
        for ($i = 0; $i < count($params); $i++) {
            $string = str_replace("{" . $i . "}", $params[$i], $string);
        }
    }
    return $raw ? $string : sanitize_string($string, 'low', 'moderate');
}
Ejemplo n.º 19
0
<?php

$title = "Connexion ou inscription";
include 'partials/_header.php';
?>
<div id="main-content">
   	 <div class="container">
   	 	<div class="jumbotron">
	   	 	<div class="col-sm-6">
		    	<p class="font-size-15">
		    		<?php 
echo $trad['description_home'][get_current_locale()];
?>
		    	</p>
		    	<div id="myCarousel" class="carousel slide" data-ride="carousel">
				  <!-- Indicators -->
				  <ol class="carousel-indicators">
				    <li data-target="#myCarousel" data-slide-to="0"></li>
				    <li data-target="#myCarousel" data-slide-to="1"></li>
				    <li data-target="#myCarousel" data-slide-to="2"></li>
				    <li data-target="#myCarousel" data-slide-to="3"></li>
				  </ol>
				
				  <!-- Wrapper for slides -->
				  <div class="carousel-inner" role="listbox">
					    <div class="item active">
						      <img src="images/evlilly.jpg" alt="Evangeline Lilly">
						      <div class="carousel-caption"></div>
					    </div>
					
					    <div class="item">
Ejemplo n.º 20
0
/**
 * Inviation was rejected by visitor
 *
 * Triggers {@link \Mibew\EventDispatcher\Events::INVITATION_REJECT} event.
 *
 * @param int $visitor_id ID of the visitor
 */
function invitation_reject($visitor_id)
{
    $visitor = track_get_visitor_by_id($visitor_id);
    // Send message to operator
    $thread = Thread::load($visitor['threadid']);
    if ($thread) {
        $thread->postMessage(Thread::KIND_FOR_AGENT, getlocal('Visitor rejected invitation', null, get_current_locale(), true));
    }
    $db = Database::getInstance();
    $db->query("UPDATE {sitevisitor} v, {thread} t SET " . "v.threadid = NULL, " . "t.invitationstate = :invitation_rejected, " . "t.istate = :state_closed, " . "t.dtmclosed = :now " . "WHERE t.threadid = v.threadid " . "AND visitorid = :visitor_id", array(':invitation_rejected' => Thread::INVITATION_REJECTED, ':state_closed' => Thread::STATE_CLOSED, ':visitor_id' => $visitor_id, ':now' => time()));
    $args = array('invitation' => $thread);
    EventDispatcher::getInstance()->triggerEvent(Events::INVITATION_REJECT, $args);
}
Ejemplo n.º 21
0
/**
 * Format date according to passed in type and locale.
 *
 * @param int $timestamp Unix timestamp
 * @param string $format Format name. Can be one of "full", "date", "time".
 * @param string|null $locale Locale code. If null is passed in the current
 *   locale will be used.
 * @return string Formatted date.
 * @throws \InvalidArgumentException If $type argument has wrong value.
 */
function format_date($timestamp, $format, $locale = null)
{
    if (is_null($locale)) {
        $locale = get_current_locale();
    }
    // Get locale info
    $locale_info = get_locale_info($locale);
    $date_format = $locale_info['date_format'];
    if (!isset($date_format[$format])) {
        throw new \InvalidArgumentException('Wrong value of the $format argument.');
    }
    // Use correct months names and over translatable date/time strings.
    setlocale(LC_TIME, $locale_info['time_locale']);
    return strftime($date_format[$format], $timestamp);
}