Apply new codding style

This commit is contained in:
Dmitriy Simushev 2014-01-28 14:02:58 +00:00
parent 41f1e0a3bc
commit 42ff39f4d9
119 changed files with 10773 additions and 10241 deletions

View File

@ -20,55 +20,58 @@ use Mibew\Settings;
use Mibew\Thread; use Mibew\Thread;
// Initialize libraries // Initialize libraries
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ""; $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
if($referer && isset($_SESSION['threadid'])) { if ($referer && isset($_SESSION['threadid'])) {
$thread = Thread::load($_SESSION['threadid']); $thread = Thread::load($_SESSION['threadid']);
if ($thread && $thread->state != Thread::STATE_CLOSED) { if ($thread && $thread->state != Thread::STATE_CLOSED) {
$msg = getstring2_("chat.client.visited.page", array($referer), $thread->locale); $msg = getstring2_(
$thread->postMessage(Thread::KIND_FOR_AGENT, $msg); "chat.client.visited.page",
array($referer),
$thread->locale
);
$thread->postMessage(Thread::KIND_FOR_AGENT, $msg);
} }
} }
$image = verifyparam(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "mibew"); $image = verify_param(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "mibew");
$lang = verifyparam(isset($_GET['language']) ? "language" : "lang", "/^[\w-]{2,5}$/", ""); $lang = verify_param(isset($_GET['language']) ? "language" : "lang", "/^[\w-]{2,5}$/", "");
if(!$lang || !locale_exists($lang)) { if (!$lang || !locale_exists($lang)) {
$lang = CURRENT_LOCALE; $lang = CURRENT_LOCALE;
} }
$groupid = verifyparam( "group", "/^\d{1,8}$/", ""); $group_id = verify_param("group", "/^\d{1,8}$/", "");
if($groupid) { if ($group_id) {
if(Settings::get('enablegroups') == '1') { if (Settings::get('enablegroups') == '1') {
$group = group_by_id($groupid); $group = group_by_id($group_id);
if(!$group) { if (!$group) {
$groupid = ""; $group_id = "";
} }
} else { } else {
$groupid = ""; $group_id = "";
} }
} }
$image_postfix = has_online_operators($groupid) ? "on" : "off"; $image_postfix = has_online_operators($group_id) ? "on" : "off";
$filename = "locales/${lang}/button/${image}_${image_postfix}.gif"; $file_name = "locales/${lang}/button/${image}_${image_postfix}.gif";
$fp = fopen($filename, 'rb') or die("no image"); $fp = fopen($file_name, 'rb') or die("no image");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache"); header("Pragma: no-cache");
header("Content-Type: image/gif"); header("Content-Type: image/gif");
header("Content-Length: ".filesize($filename)); header("Content-Length: " . filesize($file_name));
if(function_exists('fpassthru')){ if (function_exists('fpassthru')) {
@fpassthru($fp); @fpassthru($fp);
} else { } else {
while( (!feof($fp)) && (connection_status()==0)){ while ((!feof($fp)) && (connection_status() == 0)) {
print(fread($fp, 1024*8)); print(fread($fp, 1024 * 8));
flush(); flush();
} }
fclose($fp); fclose($fp);
} }
exit;
?>

View File

@ -15,6 +15,4 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(dirname(__FILE__).'/b.php'); require_once(dirname(__FILE__) . '/b.php');
exit;
?>

View File

@ -15,12 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/captcha.php'); require_once(MIBEW_FS_ROOT . '/libs/captcha.php');
$captchaCode = gen_captcha(); $captcha_code = gen_captcha();
$_SESSION["mibew_captcha"] = $captchaCode; $_SESSION["mibew_captcha"] = $captcha_code;
draw_captcha($captchaCode); draw_captcha($captcha_code);
exit;
?>

View File

@ -21,24 +21,24 @@ use Mibew\Thread;
use Mibew\Style\ChatStyle; use Mibew\Style\ChatStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/captcha.php'); require_once(MIBEW_FS_ROOT . '/libs/captcha.php');
require_once(MIBEW_FS_ROOT.'/libs/invitation.php'); require_once(MIBEW_FS_ROOT . '/libs/invitation.php');
require_once(MIBEW_FS_ROOT.'/libs/track.php'); require_once(MIBEW_FS_ROOT . '/libs/track.php');
if(Settings::get('enablessl') == "1" && Settings::get('forcessl') == "1") { if (Settings::get('enablessl') == "1" && Settings::get('forcessl') == "1") {
if(!is_secure_request()) { if (!is_secure_request()) {
$requested = $_SERVER['PHP_SELF']; $requested = $_SERVER['PHP_SELF'];
if($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) { if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) {
header("Location: ".get_app_location(true,true)."/client.php?".$_SERVER['QUERY_STRING']); header("Location: " . get_app_location(true, true) . "/client.php?" . $_SERVER['QUERY_STRING']);
} else { } else {
die("only https connections are handled"); die("only https connections are handled");
} }
exit; exit;
} }
} }
// Initialize chat style which is currently used in system // Initialize chat style which is currently used in system
@ -46,155 +46,164 @@ $chat_style = new ChatStyle(ChatStyle::currentStyle());
// Do not support old browsers at all // Do not support old browsers at all
if (get_remote_level($_SERVER['HTTP_USER_AGENT']) == 'old') { if (get_remote_level($_SERVER['HTTP_USER_AGENT']) == 'old') {
// Create page array // Create page array
$page = array_merge_recursive( $page = array_merge_recursive(
setup_logo() setup_logo()
); );
$chat_style->render('nochat', $page); $chat_style->render('nochat', $page);
exit; exit;
} }
$action = verifyparam("act", "/^(invitation|mailthread)$/", "default"); $action = verify_param("act", "/^(invitation|mailthread)$/", "default");
if ($action == 'invitation' && Settings::get('enabletracking')) { if ($action == 'invitation' && Settings::get('enabletracking')) {
// Check if user invited to chat // Check if user invited to chat
$invitation_state = invitation_state($_SESSION['visitorid']); $invitation_state = invitation_state($_SESSION['visitorid']);
if ($invitation_state['invited'] && $invitation_state['threadid']) { if ($invitation_state['invited'] && $invitation_state['threadid']) {
$thread = Thread::load($invitation_state['threadid']); $thread = Thread::load($invitation_state['threadid']);
// Prepare page // Prepare page
$page = setup_invitation_view($thread); $page = setup_invitation_view($thread);
// Build js application options // Build js application options
$page['invitationOptions'] = json_encode($page['invitation']); $page['invitationOptions'] = json_encode($page['invitation']);
// Expand page // Expand page
$chat_style->render('chat', $page); $chat_style->render('chat', $page);
exit; exit;
} }
} }
if( !isset($_GET['token']) || !isset($_GET['thread']) ) { if (!isset($_GET['token']) || !isset($_GET['thread'])) {
$thread = NULL; $thread = null;
if( isset($_SESSION['threadid']) ) { if (isset($_SESSION['threadid'])) {
$thread = Thread::reopen($_SESSION['threadid']); $thread = Thread::reopen($_SESSION['threadid']);
} }
if( !$thread ) { if (!$thread) {
// Load group info // Load group info
$groupid = ""; $group_id = "";
$groupname = ""; $group_name = "";
$group = NULL; $group = null;
if(Settings::get('enablegroups') == '1') { if (Settings::get('enablegroups') == '1') {
$groupid = verifyparam( "group", "/^\d{1,8}$/", ""); $group_id = verify_param("group", "/^\d{1,8}$/", "");
if($groupid) { if ($group_id) {
$group = group_by_id($groupid); $group = group_by_id($group_id);
if(!$group) { if (!$group) {
$groupid = ""; $group_id = "";
} else { } else {
$groupname = get_group_name($group); $group_name = get_group_name($group);
} }
} }
} }
// Get operator code // Get operator code
$operator_code = empty($_GET['operator_code']) $operator_code = empty($_GET['operator_code']) ? '' : $_GET['operator_code'];
? '' if (!preg_match("/^[A-z0-9_]+$/", $operator_code)) {
: $_GET['operator_code']; $operator_code = false;
if (! preg_match("/^[A-z0-9_]+$/", $operator_code)) { }
$operator_code = false;
}
// Get visitor info // Get visitor info
$visitor = visitor_from_request(); $visitor = visitor_from_request();
$info = getgetparam('info'); $info = get_get_param('info');
$email = getgetparam('email'); $email = get_get_param('email');
// Get referrer // Get referrer
$referrer = isset($_GET['url']) $referrer = isset($_GET['url'])
? $_GET['url'] ? $_GET['url']
: (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ""); : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "");
if(isset($_GET['referrer']) && $_GET['referrer']) { if (isset($_GET['referrer']) && $_GET['referrer']) {
$referrer .= "\n".$_GET['referrer']; $referrer .= "\n" . $_GET['referrer'];
} }
// Check if there are online operators // Check if there are online operators
if(!has_online_operators($groupid)) { if (!has_online_operators($group_id)) {
// Display leave message page // Display leave message page
$page = array_merge_recursive( $page = array_merge_recursive(
setup_logo($group), setup_logo($group),
setup_leavemessage( setup_leavemessage(
$visitor['name'], $visitor['name'],
$email, $email,
$groupid, $group_id,
$info, $info,
$referrer $referrer
) )
); );
$page['leaveMessageOptions'] = json_encode($page['leaveMessage']); $page['leaveMessageOptions'] = json_encode($page['leaveMessage']);
$chat_style->render('chat', $page); $chat_style->render('chat', $page);
exit; exit;
} }
// Get invitation info // Get invitation info
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$invitation_state = invitation_state($_SESSION['visitorid']); $invitation_state = invitation_state($_SESSION['visitorid']);
$visitor_is_invited = $invitation_state['invited']; $visitor_is_invited = $invitation_state['invited'];
} else { } else {
$visitor_is_invited = false; $visitor_is_invited = false;
} }
// Get operator info // Get operator info
$requested_operator = false; $requested_operator = false;
if ($operator_code) { if ($operator_code) {
$requested_operator = operator_by_code($operator_code); $requested_operator = operator_by_code($operator_code);
} }
// Check if survey should be displayed // Check if survey should be displayed
if(Settings::get('enablepresurvey') == '1' if (Settings::get('enablepresurvey') == '1' && !$visitor_is_invited && !$requested_operator) {
&& !$visitor_is_invited // Display prechat survey
&& !$requested_operator $page = array_merge_recursive(
) { setup_logo($group),
// Display prechat survey setup_survey(
$page = array_merge_recursive( $visitor['name'],
setup_logo($group), $email,
setup_survey($visitor['name'], $email, $groupid, $info, $referrer) $group_id,
); $info,
$page['surveyOptions'] = json_encode($page['survey']); $referrer
$chat_style->render('chat', $page); )
exit; );
} $page['surveyOptions'] = json_encode($page['survey']);
$chat_style->render('chat', $page);
exit;
}
// Start chat thread // Start chat thread
$thread = chat_start_for_user($groupid, $requested_operator, $visitor['id'], $visitor['name'], $referrer, $info); $thread = chat_start_for_user(
} $group_id,
$threadid = $thread->id; $requested_operator,
$token = $thread->lastToken; $visitor['id'],
$chatstyle = verifyparam( "style", "/^\w+$/", ""); $visitor['name'],
header("Location: " . MIBEW_WEB_ROOT . "/client.php?thread=" . intval($threadid) . "&token=" . urlencode($token) . ($chatstyle ? "&style=" . urlencode($chatstyle) : "")); $referrer,
exit; $info
);
}
$thread_id = $thread->id;
$token = $thread->lastToken;
$chat_style_name = verify_param("style", "/^\w+$/", "");
$redirect_to = MIBEW_WEB_ROOT . "/client.php?thread=" . intval($thread_id)
. "&token=" . urlencode($token)
. ($chat_style_name ? "&style=" . urlencode($chat_style_name) : "");
header("Location: " . $redirect_to);
exit;
} }
$token = verifyparam( "token", "/^\d{1,8}$/"); $token = verify_param("token", "/^\d{1,8}$/");
$threadid = verifyparam( "thread", "/^\d{1,8}$/"); $thread_id = verify_param("thread", "/^\d{1,8}$/");
$thread = Thread::load($threadid, $token); $thread = Thread::load($thread_id, $token);
if (! $thread) { if (!$thread) {
die("wrong thread"); die("wrong thread");
} }
$page = setup_chatview_for_user($thread); $page = setup_chatview_for_user($thread);
if($action == "mailthread") { if ($action == "mailthread") {
$chat_style->render('mail', $page); $chat_style->render('mail', $page);
} else { } else {
// Build js application options // Build js application options
$page['chatOptions'] = json_encode($page['chat']); $page['chatOptions'] = json_encode($page['chat']);
// Expand page // Expand page
$chat_style->render('chat', $page); $chat_style->render('chat', $page);
} }
?>

View File

@ -20,16 +20,17 @@ use Mibew\EventDispatcher;
use Mibew\Settings; use Mibew\Settings;
// Initialize libraries // Initialize libraries
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/track.php'); require_once(MIBEW_FS_ROOT . '/libs/track.php');
require_once(MIBEW_FS_ROOT.'/libs/statistics.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/cron.php'); require_once(MIBEW_FS_ROOT . '/libs/statistics.php');
require_once(MIBEW_FS_ROOT . '/libs/cron.php');
$cron_key = empty($_GET['cron_key']) ? '' : $_GET['cron_key']; $cron_key = empty($_GET['cron_key']) ? '' : $_GET['cron_key'];
// Check cron security key // Check cron security key
if ($cron_key != Settings::get('cron_key')) { if ($cron_key != Settings::get('cron_key')) {
die(); die();
} }
// Determine use or not quiet mode // Determine use or not quiet mode
@ -50,9 +51,7 @@ $dispatcher->triggerEvent('cronRun');
Settings::set('_last_cron_run', time()); Settings::set('_last_cron_run', time());
Settings::update(); Settings::update();
if (! $quiet) { if (!$quiet) {
// TODO: May be localize it // TODO: May be localize it
echo('All cron jobs done.'); echo('All cron jobs done.');
} }
?>

View File

@ -16,6 +16,3 @@
*/ */
header("Location: operator/index.php"); header("Location: operator/index.php");
exit;
?>

View File

@ -36,6 +36,8 @@ define('MIBEW_WEB_ROOT', $mibewroot);
// Include common functions // Include common functions
require_once(MIBEW_FS_ROOT.'/libs/common/constants.php'); require_once(MIBEW_FS_ROOT.'/libs/common/constants.php');
require_once(MIBEW_FS_ROOT.'/libs/common/verification.php');
require_once(MIBEW_FS_ROOT.'/libs/common/converter.php');
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php'); require_once(MIBEW_FS_ROOT.'/libs/common/locale.php');
require_once(MIBEW_FS_ROOT.'/libs/common/misc.php'); require_once(MIBEW_FS_ROOT.'/libs/common/misc.php');
require_once(MIBEW_FS_ROOT.'/libs/common/response.php'); require_once(MIBEW_FS_ROOT.'/libs/common/response.php');
@ -48,7 +50,7 @@ function runsql($query, $link)
return $res; return $res;
} }
$act = verifyparam("act", "/^(silentcreateall|createdb|ct|dt|addcolumns)$/"); $act = verify_param("act", "/^(silentcreateall|createdb|ct|dt|addcolumns)$/");
$link = @mysql_connect($mysqlhost, $mysqllogin, $mysqlpass) $link = @mysql_connect($mysqlhost, $mysqllogin, $mysqlpass)
or show_install_err('Could not connect: ' . mysql_error()); or show_install_err('Could not connect: ' . mysql_error());

View File

@ -48,6 +48,8 @@ define('MIBEW_WEB_ROOT', $base_url);
// Include common functions // Include common functions
require_once(MIBEW_FS_ROOT.'/libs/common/constants.php'); require_once(MIBEW_FS_ROOT.'/libs/common/constants.php');
require_once(MIBEW_FS_ROOT.'/libs/common/verification.php');
require_once(MIBEW_FS_ROOT.'/libs/common/converter.php');
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php'); require_once(MIBEW_FS_ROOT.'/libs/common/locale.php');
require_once(MIBEW_FS_ROOT.'/libs/common/misc.php'); require_once(MIBEW_FS_ROOT.'/libs/common/misc.php');
require_once(MIBEW_FS_ROOT.'/libs/common/response.php'); require_once(MIBEW_FS_ROOT.'/libs/common/response.php');
@ -307,7 +309,7 @@ function add_canned_messages($link){
foreach (get_available_locales() as $locale) { foreach (get_available_locales() as $locale) {
if (! in_array($locale, $existlocales)) { if (! in_array($locale, $existlocales)) {
foreach (explode("\n", getstring_('chat.predefined_answers', $locale)) as $answer) { foreach (explode("\n", getstring_('chat.predefined_answers', $locale)) as $answer) {
$result[] = array('locale' => $locale, 'vctitle' => cutstring($answer, 97, '...'), 'vcvalue' => $answer); $result[] = array('locale' => $locale, 'vctitle' => cut_string($answer, 97, '...'), 'vcvalue' => $answer);
} }
} }
} }

View File

@ -18,56 +18,56 @@
// Import namespaces and classes of the core // Import namespaces and classes of the core
use Mibew\Database; use Mibew\Database;
function load_canned_messages($locale, $groupid) function load_canned_messages($locale, $group_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$values = array(':locale' => $locale); $values = array(':locale' => $locale);
if ($groupid) { if ($group_id) {
$values[':groupid'] = $groupid; $values[':groupid'] = $group_id;
} }
return $db->query(
"select id, vctitle, vcvalue from {chatresponses} " . return $db->query(
"where locale = :locale AND (" . ("SELECT id, vctitle, vcvalue FROM {chatresponses} "
($groupid ? "groupid = :groupid" : "groupid is NULL OR groupid = 0") . . "WHERE locale = :locale AND ("
") order by vcvalue", . ($group_id ? "groupid = :groupid" : "groupid is NULL OR groupid = 0")
$values, . ") ORDER BY vcvalue"),
array('return_rows' => Database::RETURN_ALL_ROWS) $values,
); array('return_rows' => Database::RETURN_ALL_ROWS)
);
} }
function load_canned_message($key) function load_canned_message($key)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$result = $db->query( $result = $db->query(
"select vctitle, vcvalue from {chatresponses} where id = ?", "SELECT vctitle, vcvalue FROM {chatresponses} WHERE id = ?",
array($key), array($key),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
return $result ? $result : null;
return $result ? $result : null;
} }
function save_canned_message($key, $title, $message) function save_canned_message($key, $title, $message)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"update {chatresponses} set vcvalue = ?, vctitle = ? where id = ?", "UPDATE {chatresponses} SET vcvalue = ?, vctitle = ? WHERE id = ?",
array($message, $title, $key) array($message, $title, $key)
); );
} }
function add_canned_message($locale, $groupid, $title, $message) function add_canned_message($locale, $group_id, $title, $message)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"insert into {chatresponses} (locale,groupid,vctitle,vcvalue) " . ("INSERT INTO {chatresponses} (locale,groupid,vctitle,vcvalue) "
"values (?, ?, ?, ?)", . "VALUES (?, ?, ?, ?)"),
array( array(
$locale, $locale,
($groupid ? $groupid : "null"), ($group_id ? $group_id : "null"),
$title, $title,
$message $message,
) )
); );
} }
?>

View File

@ -17,59 +17,57 @@
function can_show_captcha() function can_show_captcha()
{ {
return extension_loaded("gd"); return extension_loaded("gd");
} }
function gen_captcha() function gen_captcha()
{ {
$symbols = 'abcdefghijkmnpqrstuvwxyz123456789'; $symbols = 'abcdefghijkmnpqrstuvwxyz123456789';
$string = ''; $string = '';
for ($i = 0; $i < 5; $i++) { for ($i = 0; $i < 5; $i++) {
$string .= substr($symbols, mt_rand(0, strlen($symbols)), 1); $string .= substr($symbols, mt_rand(0, strlen($symbols)), 1);
} }
return $string;
return $string;
} }
function draw_captcha($security_code) function draw_captcha($security_code)
{ {
//Set the image width and height
$width = 100;
$height = 25;
//Set the image width and height //Create the image resource
$width = 100; $image = ImageCreate($width, $height);
$height = 25; if (function_exists('imageantialias')) {
imageantialias($image, true);
}
//Create the image resource //We are making three colors, white, black and gray
$image = ImageCreate($width, $height); $white = ImageColorAllocate($image, 255, 255, 255);
if (function_exists('imageantialias')) { $black = ImageColorAllocate($image, 15, 50, 15);
imageantialias($image, true); $grey = ImageColorAllocate($image, 204, 204, 204);
} $ellipsec = ImageColorAllocate($image, 0, 100, 60);
//We are making three colors, white, black and gray //Make the background black
$white = ImageColorAllocate($image, 255, 255, 255); ImageFill($image, 0, 0, $black);
$black = ImageColorAllocate($image, 15, 50, 15); imagefilledellipse($image, 56, 15, 30, 17, $ellipsec);
$grey = ImageColorAllocate($image, 204, 204, 204);
$ellipsec = ImageColorAllocate($image, 0, 100, 60);
//Make the background black //Add randomly generated string in white to the image
ImageFill($image, 0, 0, $black); ImageString($image, 5, 30, 4, $security_code, $white);
imagefilledellipse($image, 56, 15, 30, 17, $ellipsec);
//Add randomly generated string in white to the image //Throw in some lines to make it a little bit harder for any bots to break
ImageString($image, 5, 30, 4, $security_code, $white); ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);
imageline($image, 0, $height / 2 + 3, $width, $height / 2 + 5, $grey);
//Throw in some lines to make it a little bit harder for any bots to break imageline($image, $width / 2 - 14, 0, $width / 2 + 7, $height, $grey);
ImageRectangle($image, 0, 0, $width - 1, $height - 1, $grey);
imageline($image, 0, $height / 2 + 3, $width, $height / 2 + 5, $grey);
imageline($image, $width / 2 - 14, 0, $width / 2 + 7, $height, $grey);
//Tell the browser what kind of file is come in //Tell the browser what kind of file is come in
header("Content-Type: image/jpeg"); header("Content-Type: image/jpeg");
//Output the newly created image in jpeg format //Output the newly created image in jpeg format
ImageJpeg($image); ImageJpeg($image);
//Free up resources //Free up resources
ImageDestroy($image); ImageDestroy($image);
} }
?>

File diff suppressed because it is too large Load Diff

View File

@ -22,307 +22,319 @@ namespace Mibew\API;
* *
* @todo May be use regular methods instead of static one * @todo May be use regular methods instead of static one
*/ */
class API { class API
{
/**
* Version of the MIBEW API protocol implemented by the class
*/
const PROTOCOL_VERSION = '1.0';
/** /**
* Version of the MIBEW API protocol implemented by the class * Array of \Mibew\API\API objects
*/ *
const PROTOCOL_VERSION = '1.0'; * @var array
*/
protected static $interactions = array();
/** /**
* Array of \Mibew\API\API objects * An object that encapsulates type of the interaction
* @var array *
*/ * @var \Mibew\API\Interaction
protected static $interactions = array(); */
protected $interaction = null;
/** /**
* An object that encapsulates type of the interaction * Returns \Mibew\API\API object
* *
* @var \Mibew\API\Interaction * @param string $class_name A name of the interaction type class
*/ * @return MibeAPI object
protected $interaction = NULL; * @throws \Mibew\API\APIException
*/
public static function getAPI($class_name)
{
if (!class_exists($class_name)) {
throw new APIException(
"Wrong interaction type",
APIException::WRONG_INTERACTION_TYPE
);
}
if (empty(self::$interactions[$class_name])) {
self::$interactions[$class_name] = new self(new $class_name());
}
/** return self::$interactions[$class_name];
* Returns \Mibew\API\API object }
*
* @param string $class_name A name of the interaction type class
* @return MibeAPI object
* @throws \Mibew\API\APIException
*/
public static function getAPI($class_name) {
if (! class_exists($class_name)) {
throw new APIException(
"Wrong interaction type",
APIException::WRONG_INTERACTION_TYPE
);
}
if (empty(self::$interactions[$class_name])) {
self::$interactions[$class_name] = new self(new $class_name());
}
return self::$interactions[$class_name];
}
/** /**
* Class constructor * Validate package
* *
* @param \Mibew\API\Interaction $interaction Interaction type object * @param array $package Package array. See Mibew API for details.
*/ * @param array $trusted_signatures Array of trusted signatures.
protected function __construct(Interaction\Interaction $interaction) { * @throws \Mibew\API\APIException
$this->interaction = $interaction; */
} public function checkPackage($package, $trusted_signatures)
{
// Check signature
if (!isset($package['signature'])) {
throw new APIException(
"Package signature is empty",
APIException::EMPTY_SIGNATURE
);
}
if (!in_array($package['signature'], $trusted_signatures)) {
throw new APIException(
"Package signed with untrusted signature",
APIException::UNTRUSTED_SIGNATURE
);
}
/** // Check protocol
* Validate package if (empty($package['proto'])) {
* throw new APIException(
* @param array $package Package array. See Mibew API for details. "Package protocol is empty",
* @param array $trusted_signatures Array of trusted signatures. APIException::EMPTY_PROTOCOL
* @throws \Mibew\API\APIException );
*/ }
public function checkPackage($package, $trusted_signatures) { if ($package['proto'] != self::PROTOCOL_VERSION) {
// Check signature throw new APIException(
if (! isset($package['signature'])) { "Wrong package protocol version '{$package['proto']}'",
throw new APIException( APIException::WRONG_PROTOCOL_VERSION
"Package signature is empty", );
APIException::EMPTY_SIGNATURE }
);
}
if (! in_array($package['signature'], $trusted_signatures)) {
throw new APIException(
"Package signed with untrusted signature",
APIException::UNTRUSTED_SIGNATURE
);
}
// Check protocol // Check async flag
if (empty($package['proto'])) { if (!isset($package['async'])) {
throw new APIException( throw new APIException(
"Package protocol is empty", "'async' flag is missed",
APIException::EMPTY_PROTOCOL APIException::ASYNC_FLAG_MISSED
); );
} }
if ($package['proto'] != self::PROTOCOL_VERSION) { if (!is_bool($package['async'])) {
throw new APIException( throw new APIException(
"Wrong package protocol version '{$package['proto']}'", "Wrong 'async' flag value",
APIException::WRONG_PROTOCOL_VERSION APIException::WRONG_ASYNC_FLAG_VALUE
); );
} }
// Check async flag // Package must have at least one request
if (! isset($package['async'])) { if (empty($package['requests'])) {
throw new APIException( throw new APIException(
"'async' flag is missed", "Empty requests set",
APIException::ASYNC_FLAG_MISSED APIException::EMPTY_REQUESTS
); );
} }
if (! is_bool($package['async'])) { // Check requests in package
throw new APIException( foreach ($package['requests'] as $request) {
"Wrong 'async' flag value", $this->checkRequest($request);
APIException::WRONG_ASYNC_FLAG_VALUE }
); }
}
// Package must have at least one request /**
if (empty($package['requests'])) { * Validate request
throw new APIException( *
"Empty requests set", * @param array $request Request array. See Mibew API for details.
APIException::EMPTY_REQUESTS * @throws \Mibew\API\APIException
); */
} public function checkRequest($request)
// Check requests in package {
foreach ($package['requests'] as $request) { // Check token
$this->checkRequest($request); if (empty($request['token'])) {
} throw new APIException(
} "Empty request token",
APIException::EMPTY_TOKEN
);
}
// Request must have at least one function
if (empty($request['functions'])) {
throw new APIException(
"Empty functions set",
APIException::EMPTY_FUNCTIONS
);
}
// Check functions in request
foreach ($request['functions'] as $function) {
$this->checkFunction($function);
}
}
/** /**
* Validate request * Validate function
* *
* @param array $request Request array. See Mibew API for details. * @param array $function Function array. See Mibew API for details.
* @throws \Mibew\API\APIException * @param boolean $filter_reserved_functions Determine if function name must
*/ * not be in reserved list
public function checkRequest($request) { * @throws \Mibew\API\APIException
// Check token */
if (empty($request['token'])) { public function checkFunction($function, $filter_reserved_functions = false)
throw new APIException( {
"Empty request token", // Check function name
APIException::EMPTY_TOKEN if (empty($function['function'])) {
); throw new APIException(
} 'Cannot call for function with empty name',
// Request must have at least one function APIException::EMPTY_FUNCTION_NAME
if (empty($request['functions'])) { );
throw new APIException( }
"Empty functions set", if ($filter_reserved_functions) {
APIException::EMPTY_FUNCTIONS if (in_array($function['function'], $this->interaction->reservedFunctionNames)) {
); throw new APIException(
} "'{$function['function']}' is reserved function name",
// Check functions in request APIException::FUNCTION_NAME_RESERVED
foreach ($request['functions'] as $function) { );
$this->checkFunction($function); }
} }
} // Check function's arguments
if (empty($function['arguments'])) {
throw new APIException(
"There are no arguments in '{$function['function']}' function",
APIException::EMPTY_ARGUMENTS
);
}
if (!is_array($function['arguments'])) {
throw new APIException(
"Arguments must be an array",
APIException::WRONG_ARGUMENTS_TYPE
);
}
$unset_arguments = array_diff(
$this->interaction->getObligatoryArguments($function['function']),
array_keys($function['arguments'])
);
if (!empty($unset_arguments)) {
throw new APIException(
"Arguments '" . implode("', '", $unset_arguments) . "' must be set",
APIException::OBLIGATORY_ARGUMENTS_MISSED
);
}
}
/** /**
* Validate function * Encodes package
* *
* @param array $function Function array. See Mibew API for details. * @param array $requests Requests array. See Mibew API for details.
* @param boolean $filter_reserved_functions Determine if function name must not be in * @param string $signature Sender signature.
* reserved list * @param boolean $async true for asynchronous request and false for
* @throws \Mibew\API\APIException * synchronous request
*/ * @return string Ready for transfer encoded package
public function checkFunction($function, $filter_reserved_functions = false) { */
// Check function name public function encodePackage($requests, $signature, $async)
if (empty($function['function'])) { {
throw new APIException( $package = array();
'Cannot call for function with empty name', $package['signature'] = $signature;
APIException::EMPTY_FUNCTION_NAME $package['proto'] = self::PROTOCOL_VERSION;
); $package['async'] = $async;
} $package['requests'] = $requests;
if ($filter_reserved_functions) {
if (in_array(
$function['function'],
$this->interaction->reservedFunctionNames
)) {
throw new APIException(
"'{$function['function']}' is reserved function name",
APIException::FUNCTION_NAME_RESERVED
);
}
}
// Check function's arguments
if (empty($function['arguments'])) {
throw new APIException(
"There are no arguments in '{$function['function']}' function",
APIException::EMPTY_ARGUMENTS
);
}
if (! is_array($function['arguments'])) {
throw new APIException(
"Arguments must be an array",
APIException::WRONG_ARGUMENTS_TYPE
);
}
$unset_arguments = array_diff(
$this->interaction->getObligatoryArguments($function['function']),
array_keys($function['arguments'])
);
if (! empty($unset_arguments)) {
throw new APIException(
"Arguments '" . implode("', '", $unset_arguments) . "' must be set",
APIException::OBLIGATORY_ARGUMENTS_MISSED
);
}
}
/** return urlencode(json_encode($package));
* Encodes package }
*
* @param array $requests Requests array. See Mibew API for details.
* @param string $signature Sender signature.
* @param boolean $async true for asynchronous request and false for synchronous request
* @return string Ready for transfer encoded package
*/
public function encodePackage($requests, $signature, $async) {
$package = array();
$package['signature'] = $signature;
$package['proto'] = self::PROTOCOL_VERSION;
$package['async'] = $async;
$package['requests'] = $requests;
return urlencode(json_encode($package));
}
/** /**
* Decodes package and validate package structure * Decodes package and validate package structure
* *
* @param string $package Encoded package * @param string $package Encoded package
* @param array $trusted_signatures List of trusted signatures * @param array $trusted_signatures List of trusted signatures
* @return array Decoded package array. See Mibew API for details. * @return array Decoded package array. See Mibew API for details.
* @throws \Mibew\API\APIException * @throws \Mibew\API\APIException
*/ */
public function decodePackage($package, $trusted_signatures) { public function decodePackage($package, $trusted_signatures)
// Try to decode package {
$decoded_package = urldecode($package); // Try to decode package
$decoded_package = json_decode($decoded_package, true); $decoded_package = urldecode($package);
$decoded_package = json_decode($decoded_package, true);
// Check package // Check package
$json_error_code = json_last_error(); $json_error_code = json_last_error();
if ($json_error_code != JSON_ERROR_NONE) { if ($json_error_code != JSON_ERROR_NONE) {
// Not valid JSON // Not valid JSON
throw new APIException( throw new APIException(
"Package have invalid json structure. " . "Package have invalid json structure. JSON error code is '" . $json_error_code . "'",
"JSON error code is '" . $json_error_code . "'", APIException::NOT_VALID_JSON
APIException::NOT_VALID_JSON );
); }
} $this->checkPackage($decoded_package, $trusted_signatures);
$this->checkPackage($decoded_package, $trusted_signatures);
return $decoded_package; return $decoded_package;
} }
/** /**
* Builds result package * Builds result package
* *
* @param string $token Token of the result package * @param string $token Token of the result package
* @param array $result_arguments Arguments of result function * @param array $result_arguments Arguments of result function
* @return array Result package * @return array Result package
*/ */
public function buildResult($token, $result_arguments) { public function buildResult($token, $result_arguments)
$arguments = $result_arguments + $this->interaction->getObligatoryArgumentsDefaults('result'); {
$package = array( $arguments = $result_arguments + $this->interaction->getObligatoryArgumentsDefaults('result');
'token' => $token, $package = array(
'functions' => array( 'token' => $token,
array( 'functions' => array(
'function' => 'result', array(
'arguments' => $arguments 'function' => 'result',
) 'arguments' => $arguments,
) ),
); ),
return $package; );
}
/** return $package;
* Search 'result' function in $function_list. If request contains more than one result }
* functions throws an \Mibew\API\APIException
* /**
* @param array $functions_list Array of functions. See Mibew API specification * Search 'result' function in $function_list.
* for function structure details *
* @param mixed $existance Control existance of the 'result' function in request. * If request contains more than one result the functions throws
* Use boolean true if 'result' function must exists in request, boolean false if must not * an \Mibew\API\APIException.
* and null if it doesn't matter. *
* @return mixed Function array if 'result' function found and NULL otherwise * @param array $functions_list Array of functions. See Mibew API
* @throws \Mibew\API\APIException * specification for function structure details.
*/ * @param mixed $existance Control existance of the 'result' function in
public function getResultFunction ($functions_list, $existence = null) { * request. Use boolean true if 'result' function must exists in request,
$result_function = null; * boolean false if must not and null if it doesn't matter.
// Try to find 'result' function * @return mixed Function array if 'result' function found and NULL
foreach ($functions_list as $function) { * otherwise
if ($function['function'] == 'result') { * @throws \Mibew\API\APIException
if (! is_null($result_function)) { */
// Another 'result' function found public function getResultFunction($functions_list, $existence = null)
throw new APIException( {
"Function 'result' already exists in request", $result_function = null;
APIException::RESULT_FUNCTION_ALREADY_EXISTS // Try to find 'result' function
); foreach ($functions_list as $function) {
} if ($function['function'] == 'result') {
// First 'result' function found if (!is_null($result_function)) {
$result_function = $function; // Another 'result' function found
} throw new APIException(
} "Function 'result' already exists in request",
if ($existence === true && is_null($result_function)) { APIException::RESULT_FUNCTION_ALREADY_EXISTS
// 'result' function must present in request );
throw new APIException( }
"There is no 'result' function in request", // First 'result' function found
APIException::NO_RESULT_FUNCTION $result_function = $function;
); }
} }
if ($existence === false && !is_null($result_function)) { if ($existence === true && is_null($result_function)) {
// 'result' function must not present in request // 'result' function must present in request
throw new APIException( throw new APIException(
"There is 'result' function in request", "There is no 'result' function in request",
APIException::RESULT_FUNCTION_EXISTS APIException::NO_RESULT_FUNCTION
); );
} }
return $result_function; if ($existence === false && !is_null($result_function)) {
} // 'result' function must not present in request
throw new APIException(
"There is 'result' function in request",
APIException::RESULT_FUNCTION_EXISTS
);
}
return $result_function;
}
/**
* Class constructor
*
* @param \Mibew\API\Interaction $interaction Interaction type object
*/
protected function __construct(Interaction\Interaction $interaction)
{
$this->interaction = $interaction;
}
} }
?>

View File

@ -20,99 +20,98 @@ namespace Mibew\API;
/** /**
* Mibew API Exception class. * Mibew API Exception class.
*/ */
class APIException extends \Exception { class APIException extends \Exception
/** {
* Async flag is missed. /**
*/ * Async flag is missed.
const ASYNC_FLAG_MISSED = 1; */
/** const ASYNC_FLAG_MISSED = 1;
* There are no arguments in function /**
*/ * There are no arguments in function
const EMPTY_ARGUMENTS = 2; */
/** const EMPTY_ARGUMENTS = 2;
* Cannot call for function with empty name /**
*/ * Cannot call for function with empty name
const EMPTY_FUNCTION_NAME = 3; */
/** const EMPTY_FUNCTION_NAME = 3;
* Functions set is empty /**
*/ * Functions set is empty
const EMPTY_FUNCTIONS = 4; */
/** const EMPTY_FUNCTIONS = 4;
* Package protocol is empty /**
*/ * Package protocol is empty
const EMPTY_PROTOCOL = 5; */
/** const EMPTY_PROTOCOL = 5;
* Requests set is empty /**
*/ * Requests set is empty
const EMPTY_REQUESTS = 6; */
/** const EMPTY_REQUESTS = 6;
* Package signature is empty /**
*/ * Package signature is empty
const EMPTY_SIGNATURE = 7; */
/** const EMPTY_SIGNATURE = 7;
* Request token is empty /**
*/ * Request token is empty
const EMPTY_TOKEN = 8; */
/** const EMPTY_TOKEN = 8;
* Wrong reference. Reference variable is empty /**
*/ * Wrong reference. Reference variable is empty
const EMPTY_VARIABLE_IN_REFERENCE = 9; */
/** const EMPTY_VARIABLE_IN_REFERENCE = 9;
* This function name is reserved /**
*/ * This function name is reserved
const FUNCTION_NAME_RESERVED = 10; */
/** const FUNCTION_NAME_RESERVED = 10;
* There is no result function /**
*/ * There is no result function
const NO_RESULT_FUNCTION = 11; */
/** const NO_RESULT_FUNCTION = 11;
* Package have not valid JSON structure /**
*/ * Package have not valid JSON structure
const NOT_VALID_JSON = 12; */
/** const NOT_VALID_JSON = 12;
* Some of the function's obligatory arguments are missed /**
*/ * Some of the function's obligatory arguments are missed
const OBLIGATORY_ARGUMENTS_MISSED = 13; */
/** const OBLIGATORY_ARGUMENTS_MISSED = 13;
* Request contains more than one result functions /**
*/ * Request contains more than one result functions
const RESULT_FUNCTION_ALREADY_EXISTS = 14; */
/** const RESULT_FUNCTION_ALREADY_EXISTS = 14;
* There is 'result' function in request /**
*/ * There is 'result' function in request
const RESULT_FUNCTION_EXISTS = 15; */
/** const RESULT_FUNCTION_EXISTS = 15;
* Package signed with untrusted signature /**
*/ * Package signed with untrusted signature
const UNTRUSTED_SIGNATURE = 16; */
/** const UNTRUSTED_SIGNATURE = 16;
* Wrong reference. Variable is undefined in functions results /**
*/ * Wrong reference. Variable is undefined in functions results
const VARIABLE_IS_UNDEFINED_IN_REFERENCE = 17; */
/** const VARIABLE_IS_UNDEFINED_IN_REFERENCE = 17;
* Variable is undefined in function's results /**
*/ * Variable is undefined in function's results
const VARIABLE_IS_UNDEFINED_IN_RESULT = 18; */
/** const VARIABLE_IS_UNDEFINED_IN_RESULT = 18;
* Arguments must be an array /**
*/ * Arguments must be an array
const WRONG_ARGUMENTS_TYPE = 19; */
/** const WRONG_ARGUMENTS_TYPE = 19;
* Async flag value is wrong /**
*/ * Async flag value is wrong
const WRONG_ASYNC_FLAG_VALUE = 20; */
/** const WRONG_ASYNC_FLAG_VALUE = 20;
* Wrong reference. Function with this number does not call yet /**
*/ * Wrong reference. Function with this number does not call yet
const WRONG_FUNCTION_NUM_IN_REFERENCE = 21; */
/** const WRONG_FUNCTION_NUM_IN_REFERENCE = 21;
* Wrong interaction type /**
*/ * Wrong interaction type
const WRONG_INTERACTION_TYPE = 22; */
/** const WRONG_INTERACTION_TYPE = 22;
* Wrong package protocol version /**
*/ * Wrong package protocol version
const WRONG_PROTOCOL_VERSION = 23; */
const WRONG_PROTOCOL_VERSION = 23;
} }
?>

View File

@ -20,113 +20,137 @@ namespace Mibew\API;
/** /**
* Implements functions execution context * Implements functions execution context
*/ */
class ExecutionContext { class ExecutionContext
/** {
* Values which returns after execution of all functions in request /**
* @var array * Values which returns after execution of all functions in request
*/ *
protected $return = array(); * @var array
*/
protected $return = array();
/** /**
* Results of execution of all function in request * Results of execution of all function in request
* @var array *
*/ * @var array
protected $functions_results = array(); */
protected $functionsResults = array();
/** /**
* Returns requets results * Returns requets results
* *
* @return array Request results * @return array Request results
* @see \Mibew\API\ExecutionContext::$return * @see \Mibew\API\ExecutionContext::$return
*/ */
public function getResults () { public function getResults()
return $this->return; {
} return $this->return;
}
/** /**
* Build arguments list by replace all references by values of execution context * Build arguments list by replace all references by values of execution
* * context.
* @param array $function Function array. See MibewAPI for details. *
* @return array Arguments list * @param array $function Function array. See MibewAPI for details.
* @throws \Mibew\API\APIException * @return array Arguments list
*/ * @throws \Mibew\API\APIException
public function getArgumentsList ($function) { */
$arguments = $function['arguments']; public function getArgumentsList($function)
$references = $function['arguments']['references']; {
foreach ($references as $variable => $func_num) { $arguments = $function['arguments'];
// Check target function in context $references = $function['arguments']['references'];
if (! isset($this->functions_results[$func_num - 1])) { foreach ($references as $variable => $func_num) {
// Wrong function num // Check target function in context
throw new APIException( if (!isset($this->functionsResults[$func_num - 1])) {
"Wrong reference in '{$function['function']}' function. " . // Wrong function num
"Function #{$func_num} does not call yet.", $message = "Wrong reference in '%s' function. "
APIException::WRONG_FUNCTION_NUM_IN_REFERENCE . "Function #%s does not call yet.";
); throw new APIException(
} sprintf(
$message,
$function['function'],
$func_num
),
APIException::WRONG_FUNCTION_NUM_IN_REFERENCE
);
}
// Check reference // Check reference
if (empty($arguments[$variable])) { if (empty($arguments[$variable])) {
// Empty argument that should contains reference // Empty argument that should contains reference
throw new APIException( throw new APIException(
"Wrong reference in '{$function['function']}' function. " . sprintf(
"Empty {$variable} argument.", "Wrong reference in '%s' function. Empty %s argument.",
APIException::EMPTY_VARIABLE_IN_REFERENCE $function['function'],
); $variable
} ),
$reference_to = $arguments[$variable]; APIException::EMPTY_VARIABLE_IN_REFERENCE
);
}
$reference_to = $arguments[$variable];
// Check target value // Check target value
if (! isset($this->functions_results[$func_num - 1][$reference_to])) { if (!isset($this->functionsResults[$func_num - 1][$reference_to])) {
// Undefined target value // Undefined target value
throw new APIException( $message = "Wrong reference in '%s' function. "
"Wrong reference in '{$function['function']}' function. " . . "There is no '%s' argument in #%s function results";
"There is no '{$reference_to}' argument in #{$func_num} " . throw new APIException(
"function results", sprintf(
APIException::VARIABLE_IS_UNDEFINED_IN_REFERENCE $message,
); $function['function'],
} $reference_to,
$func_num
),
APIException::VARIABLE_IS_UNDEFINED_IN_REFERENCE
);
}
// Replace reference by target value // Replace reference by target value
$arguments[$variable] = $this->functions_results[$func_num - 1][$reference_to]; $arguments[$variable] = $this->functionsResults[$func_num - 1][$reference_to];
} }
return $arguments;
}
/** return $arguments;
* Stores functions results in execution context and add values to request result }
*
* @param array $function Function array. See MibewAPI for details.
* @param array $results Associative array of the function results.
* @throws \Mibew\API\APIException
*/
public function storeFunctionResults ($function, $results) {
// Check if function return correct results
if (empty($results['errorCode'])) {
// Add value to request results
foreach ($function['arguments']['return'] as $name => $alias) {
if (! isset($results[$name])) {
// Value that defined in 'return' argument is undefined
throw new APIException(
"Variable with name '{$name}' is undefined in the " .
"results of the '{$function['function']}' function",
APIException::VARIABLE_IS_UNDEFINED_IN_RESULT
);
}
$this->return[$alias] = $results[$name];
}
} else {
// Something went wrong during function execution
// Store error code and error message
$this->return['errorCode'] = $results['errorCode'];
$this->return['errorMessage'] = empty($results['errorMessage'])
? ''
: $results['errorMessage'];
}
// Store function results in execution context /**
$this->functions_results[] = $results; * Stores functions results in execution context and add values to request
} * result.
*
* @param array $function Function array. See MibewAPI for details.
* @param array $results Associative array of the function results.
* @throws \Mibew\API\APIException
*/
public function storeFunctionResults($function, $results)
{
// Check if function return correct results
if (empty($results['errorCode'])) {
// Add value to request results
foreach ($function['arguments']['return'] as $name => $alias) {
if (!isset($results[$name])) {
// Value that defined in 'return' argument is undefined
$message = "Variable with name '%s' is undefined "
. "in the results of the '%s' function";
throw new APIException(
sprintf(
$message,
$name,
$function['function']
),
APIException::VARIABLE_IS_UNDEFINED_IN_RESULT
);
}
$this->return[$alias] = $results[$name];
}
} else {
// Something went wrong during function execution
// Store error code and error message
$this->return['errorCode'] = $results['errorCode'];
$this->return['errorMessage'] = empty($results['errorMessage'])
? ''
: $results['errorMessage'];
}
// Store function results in execution context
$this->functionsResults[] = $results;
}
} }
?>

View File

@ -20,32 +20,31 @@ namespace Mibew\API\Interaction;
/** /**
* Implements Mibew Core - Mibew Chat Window interaction * Implements Mibew Core - Mibew Chat Window interaction
*/ */
class ChatInteraction extends Interaction { class ChatInteraction extends Interaction
/** {
* Defines obligatory arguments and default values for them /**
* @var array * Reserved function's names
* @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents * @var array
*/ * @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames
protected $obligatoryArguments = array( */
'*' => array( public $reservedFunctionNames = array(
'threadId' => null, 'result',
'token' => null, );
'references' => array(),
'return' => array()
),
'result' => array(
'errorCode' => 0
)
);
/** /**
* Reserved function's names * Defines obligatory arguments and default values for them
* @var array * @var array
* @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames * @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents
*/ */
public $reservedFunctionNames = array( protected $obligatoryArguments = array(
'result' '*' => array(
); 'threadId' => null,
'token' => null,
'references' => array(),
'return' => array(),
),
'result' => array(
'errorCode' => 0,
),
);
} }
?>

View File

@ -20,80 +20,94 @@ namespace Mibew\API\Interaction;
/** /**
* Encapsulates interaction type * Encapsulates interaction type
*/ */
abstract class Interaction { abstract class Interaction
/** {
* Defines obligatory arguments and default values for them /**
* * Reserved function's names
* @var array Keys of the array are function names ('*' for all functions). Values are arrays of obligatory *
* arguments with key for name of an argument and value for default value. * Defines reserved(system) function's names described in the Mibew API.
* * @var array
* For example: */
* <code> public $reservedFunctionNames = array();
* protected $obligatoryArguments = array(
* '*' => array( // Obligatory arguments for all functions are
* 'return' => array(), // 'return' with array() by default and
* 'references' => array() // 'references' with array() by default
* ),
* 'result' => array( // There is an additional argument for the result function
* 'errorCode' => 0 // This is 'error_code' with 0 by default
* )
* );
* </code>
*/
protected $obligatoryArguments = array();
/** /**
* Reserved function's names * Defines obligatory arguments and default values for them
* *
* Defines reserved(system) function's names described in the Mibew API. * @var array Keys of the array are function names ('*' for all functions).
* @var array * Values are arrays of obligatory arguments with key for name of an
*/ * argument and value for default value.
public $reservedFunctionNames = array(); *
* For example:
* <code>
* protected $obligatoryArguments = array(
* '*' => array(
* // Obligatory arguments for all functions are:
* 'return' => array(), // 'return' with array() by default and
* 'references' => array() // 'references' with array() by default
* ),
*
* 'result' => array(
* // There is an additional argument for the result function
* 'errorCode' => 0 // This is 'error_code' with 0 by default
* )
* );
* </code>
*/
protected $obligatoryArguments = array();
/** /**
* Returns obligatory arguments for the $function_name function * Returns obligatory arguments for the $function_name function
* *
* @param string $function_name Function name * @param string $function_name Function name
* @return array An array of obligatory arguments * @return array An array of obligatory arguments
*/ */
public function getObligatoryArguments($function_name) { public function getObligatoryArguments($function_name)
$obligatory_arguments = array(); {
// Add obligatory for all functions arguments $obligatory_arguments = array();
if (! empty($this->obligatoryArguments['*'])) { // Add obligatory for all functions arguments
$obligatory_arguments = array_merge( if (!empty($this->obligatoryArguments['*'])) {
$obligatory_arguments, $obligatory_arguments = array_merge(
array_keys($this->obligatoryArguments['*']) $obligatory_arguments,
); array_keys($this->obligatoryArguments['*'])
} );
// Add obligatory arguments for given function }
if (! empty($this->obligatoryArguments[$function_name])) { // Add obligatory arguments for given function
$obligatory_arguments = array_merge( if (!empty($this->obligatoryArguments[$function_name])) {
$obligatory_arguments, $obligatory_arguments = array_merge(
array_keys($this->obligatoryArguments[$function_name]) $obligatory_arguments,
); array_keys($this->obligatoryArguments[$function_name])
} );
return array_unique($obligatory_arguments); }
}
/** return array_unique($obligatory_arguments);
* Returns default values of obligatory arguments for the $function_name function }
*
* @param string $function_name Function name /**
* @return array Associative array with keys are obligatory arguments and values are default * Returns default values of obligatory arguments for the $function_name
* values of them * function
*/ *
public function getObligatoryArgumentsDefaults($function_name) { * @param string $function_name Function name
$obligatory_arguments = array(); * @return array Associative array with keys are obligatory arguments and
// Add obligatory for all functions arguments * values are default values of them
if (! empty($this->obligatoryArguments['*'])) { */
$obligatory_arguments = array_merge($obligatory_arguments, $this->obligatoryArguments['*']); public function getObligatoryArgumentsDefaults($function_name)
} {
// Add obligatory arguments for given function $obligatory_arguments = array();
if (! empty($this->obligatoryArguments[$function_name])) { // Add obligatory for all functions arguments
$obligatory_arguments = array_merge($obligatory_arguments, $this->obligatoryArguments[$function_name]); if (!empty($this->obligatoryArguments['*'])) {
} $obligatory_arguments = array_merge(
return $obligatory_arguments; $obligatory_arguments,
} $this->obligatoryArguments['*']
);
}
// Add obligatory arguments for given function
if (!empty($this->obligatoryArguments[$function_name])) {
$obligatory_arguments = array_merge(
$obligatory_arguments,
$this->obligatoryArguments[$function_name]
);
}
return $obligatory_arguments;
}
} }
?>

View File

@ -20,31 +20,30 @@ namespace Mibew\API\Interaction;
/** /**
* Implements Mibew Core - Mibew invitation waiting window interaction * Implements Mibew Core - Mibew invitation waiting window interaction
*/ */
class InviteInteraction extends Interaction { class InviteInteraction extends Interaction
/** {
* Defines obligatory arguments and default values for them /**
* @var array * Reserved function's names
* @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents * @var array
*/ * @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames
protected $obligatoryArguments = array( */
'*' => array( public $reservedFunctionNames = array(
'references' => array(), 'result',
'return' => array(), );
'visitorId' => null
),
'result' => array(
'errorCode' => 0
)
);
/** /**
* Reserved function's names * Defines obligatory arguments and default values for them
* @var array * @var array
* @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames * @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents
*/ */
public $reservedFunctionNames = array( protected $obligatoryArguments = array(
'result' '*' => array(
); 'references' => array(),
'return' => array(),
'visitorId' => null,
),
'result' => array(
'errorCode' => 0,
),
);
} }
?>

View File

@ -20,34 +20,33 @@ namespace Mibew\API\Interaction;
/** /**
* Implements Mibew Core - Mibew Users list interaction * Implements Mibew Core - Mibew Users list interaction
*/ */
class UsersInteraction extends Interaction { class UsersInteraction extends Interaction
/** {
* Defines obligatory arguments and default values for them /**
* @var array * Reserved function's names
* @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents * @var array
*/ * @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames
protected $obligatoryArguments = array( */
'*' => array( public $reservedFunctionNames = array(
'agentId' => null, 'result',
'references' => array(), );
'return' => array()
),
'updateThreads' => array(
'revision' => 0
),
'result' => array(
'errorCode' => 0
)
);
/** /**
* Reserved function's names * Defines obligatory arguments and default values for them
* @var array * @var array
* @see \Mibew\API\Interaction\Interaction::$reservedFunctionNames * @see \Mibew\API\Interaction\Interaction::$obligatoryArgumnents
*/ */
public $reservedFunctionNames = array( protected $obligatoryArguments = array(
'result' '*' => array(
); 'agentId' => null,
'references' => array(),
'return' => array(),
),
'updateThreads' => array(
'revision' => 0,
),
'result' => array(
'errorCode' => 0,
),
);
} }
?>

View File

@ -21,380 +21,406 @@ namespace Mibew;
* Encapsulates work with database. Implenets singleton pattern to provide only * Encapsulates work with database. Implenets singleton pattern to provide only
* one instance. * one instance.
*/ */
Class Database{ class Database
{
const FETCH_ASSOC = 1;
const FETCH_NUM = 2;
const FETCH_BOTH = 4;
const RETURN_ONE_ROW = 8;
const RETURN_ALL_ROWS = 16;
const FETCH_ASSOC = 1; /**
const FETCH_NUM = 2; * An instance of Database class
const FETCH_BOTH = 4; * @var Database
const RETURN_ONE_ROW = 8; */
const RETURN_ALL_ROWS = 16; protected static $instance = null;
/** /**
* An instance of Database class * PDO object
* @var Database * @var \PDO
*/ */
protected static $instance = NULL; protected $dbh = null;
/** /**
* PDO object * Database host
* @var \PDO * @var string
*/ */
protected $dbh = NULL; protected $dbHost = '';
/** /**
* Database host * Database user's login
* @var string * @var string
*/ */
protected $dbHost = ''; protected $dbLogin = '';
/** /**
* Database user's login * Database user's password
* @var string * @var string
*/ */
protected $dbLogin = ''; protected $dbPass = '';
/** /**
* Database user's password * Database name
* @var string * @var string
*/ */
protected $dbPass = ''; protected $dbName = '';
/** /**
* Database name * Tables prefix
* @var string * @var string
*/ */
protected $dbName = ''; protected $tablesPrefix = '';
/** /**
* Tables prefix * Database connection encoding. Is used only if
* @var string * Database::$forceCharsetInConnection is set to true.
*/ * @var string
protected $tablesPrefix = ''; *
* @see Database::$forceCharsetInConnection
*/
protected $dbEncoding = 'utf8';
/** /**
* Database connection encoding. Use only if Database::$forceCharsetInConnection set to true * Determine if connection must be forced to charset, specified in
* @var string * Database::$dbEncoding
* * @var boolean
* @see Database::$forceCharsetInConnection *
*/ * @see Database::$dbEncoding
protected $dbEncoding = 'utf8'; */
protected $forceCharsetInConnection = true;
/** /**
* Determine if connection must be forced to charset, specified in * Determine if connection to the database must be persistent
* Database::$dbEncoding * @var type
* @var boolean */
* protected $usePersistentConnection = false;
* @see Database::$dbEncoding
*/
protected $forceCharsetInConnection = true;
/** /**
* Determine if connection to the database must be persistent * Array of prepared SQL statements
* @var type * @var array
*/ */
protected $usePersistentConnection = false; protected $preparedStatements = array();
/** /**
* Array of prepared SQL statements * Id of the last query
* @var array * @var type
*/ */
protected $preparedStatements = array(); protected $lastQuery = null;
/** /**
* Id of the last query * Controls if exception must be processed into class or thrown
* @var type * @var boolean
*/ */
protected $lastQuery = NULL; protected $throwExceptions = false;
/** /**
* Controls if exception must be processed into class or thrown * Get instance of Database class.
* @var boolean *
*/ * If no instance exists, creates new instance.
protected $throwExceptions = false; * Use Database::initialize() before try to get an instance. If database
* was not initilize coorectly triggers an error with E_USER_ERROR level.
*
* @return Database
* @see Database::initialize()
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
trigger_error('Database was not initialized correctly', E_USER_ERROR);
}
/** return self::$instance;
* Get instance of Database class. }
*
* If no instance exists, creates new instance.
* Use Database::initialize() before try to get an instance. If database was not initilize coorectly triggers an
* error with E_USER_ERROR level.
*
* @return Database
* @see Database::initialize()
*/
public static function getInstance(){
if (is_null(self::$instance)) {
trigger_error('Database was not initialized correctly', E_USER_ERROR);
}
return self::$instance;
}
/** /**
* Destroy internal database object * Destroy internal database object
*/ */
public static function destroy(){ public static function destroy()
if (! is_null(self::$instance)) { {
self::$instance->__destruct(); if (!is_null(self::$instance)) {
self::$instance = NULL; self::$instance->__destruct();
} self::$instance = null;
} }
}
/** /**
* Initialize database. * Initialize database.
* *
* Set internal database and connectionproperties. Create Database object. Create PDO object and store it in the * Set internal database and connectionproperties. Create Database object.
* Database object. * Create PDO object and store it in the Database object.
* *
* @param string $host Database host. * @param string $host Database host.
* @param string $user Database user name. * @param string $user Database user name.
* @param string $pass Database for user with $name password. * @param string $pass Database for user with $name password.
* @param boolean $use_pconn Control use persistent connection to the database or not. * @param boolean $use_pconn Control use persistent connection to the
* @param string $db Database name. * database or not.
* @param string $prefix Database tables prefix * @param string $db Database name.
* @param boolean $force_charset Control force charset in conection or not. * @param string $prefix Database tables prefix
* @param string $encoding Contains connection encoding. Using only if $force_charset = true. * @param boolean $force_charset Control force charset in conection or not.
*/ * @param string $encoding Contains connection encoding. Is used only if
public static function initialize($host, $user, $pass, $use_pconn, $db, $prefix, $force_charset = false, $encoding = 'utf8') { * $force_charset is equals to TRUE.
// Check PDO */
if (! extension_loaded('PDO')) { public static function initialize(
throw new \Exception('PDO extension is not loaded'); $host,
} $user,
$pass,
$use_pconn,
$db,
$prefix,
$force_charset = false,
$encoding = 'utf8'
) {
// Check PDO
if (!extension_loaded('PDO')) {
throw new \Exception('PDO extension is not loaded');
}
if (! extension_loaded('pdo_mysql')) { if (!extension_loaded('pdo_mysql')) {
throw new \Exception('pdo_mysql extension is not loaded'); throw new \Exception('pdo_mysql extension is not loaded');
} }
// Check if initialization // Check if initialization
if (! is_null(self::$instance)) { if (!is_null(self::$instance)) {
throw new \Exception('Database already initialized'); throw new \Exception('Database already initialized');
} }
// Create database instance // Create database instance
$instance = new Database(); $instance = new Database();
// Set database and connection properties // Set database and connection properties
$instance->dbHost = $host; $instance->dbHost = $host;
$instance->dbLogin = $user; $instance->dbLogin = $user;
$instance->dbPass = $pass; $instance->dbPass = $pass;
$instance->dbName = $db; $instance->dbName = $db;
$instance->dbEncoding = $encoding; $instance->dbEncoding = $encoding;
$instance->tablesPrefix = preg_replace('/[^A-Za-z0-9_$]/', '', $prefix); $instance->tablesPrefix = preg_replace('/[^A-Za-z0-9_$]/', '', $prefix);
$instance->forceCharsetInConnection = $force_charset; $instance->forceCharsetInConnection = $force_charset;
$instance->usePersistentConnection = $use_pconn; $instance->usePersistentConnection = $use_pconn;
// Create PDO object // Create PDO object
$instance->dbh = new \PDO( $instance->dbh = new \PDO(
"mysql:host={$instance->dbHost};dbname={$instance->dbName}", "mysql:host={$instance->dbHost};dbname={$instance->dbName}",
$instance->dbLogin, $instance->dbLogin,
$instance->dbPass, $instance->dbPass,
array(\PDO::ATTR_PERSISTENT => $instance->usePersistentConnection) array(\PDO::ATTR_PERSISTENT => $instance->usePersistentConnection)
); );
if ($instance->forceCharsetInConnection) { if ($instance->forceCharsetInConnection) {
$instance->dbh->exec("SET NAMES ".$instance->dbh->quote($instance->dbEncoding)); $instance->dbh->exec("SET NAMES " . $instance->dbh->quote($instance->dbEncoding));
} }
// Store instance // Store instance
self::$instance = $instance; self::$instance = $instance;
} }
/** /**
* Forbid clone objects * Set if exceptions must be process into the class or thrown and return
*/ * previous value.
private final function __clone() {} *
* If called without arguments just return previous value without changing
* anything.
*
* @param boolean $value Value that should be set. This argument is optional
* @return bool Previous value
*/
public function throwExeptions()
{
$last_value = $this->throwExceptions;
if (func_num_args() > 0) {
$this->throwExceptions = func_get_arg(0);
}
/** return $last_value;
* Forbid external object creation }
*/
protected function __construct() {}
/** /**
* Handles errors * Database class destructor.
* @param \Exception $e */
*/ public function __destruct()
protected function handleError(\Exception $e){ {
if ($this->throwExceptions) { foreach ($this->preparedStatements as $key => $statement) {
throw $e; $this->preparedStatements[$key] = null;
} }
die($e->getMessage()); $this->dbh = null;
} self::$instance = null;
}
/** /**
* Set if exceptions must be process into the class or thrown and return * Executes SQL query.
* previous value. *
* * In SQL query can be used PDO style placeholders:
* If called without arguments just return previous value without changing * unnamed placeholders (question marks '?') and named placeholders (like
* anything. * ':name'). If unnamed placeholders are used, $values array must have
* * numeric indexes. If named placeholders are used, $values param must be an
* @param boolean $value Value that should be set. This argument is optional * associative array with keys corresponding to the placeholders names
* @return bool Previous value *
*/ * Table prefix automatically substitute if table name puts in curly braces
public function throwExeptions(){ *
$last_value = $this->throwExceptions; * @param string $query SQL query
if (func_num_args() > 0) { * @param array $values Values, that must be substitute instead of
$this->throwExceptions = func_get_arg(0); * placeholders in SQL query.
} * @param array $params Array of query parameters. It can contains values
return $last_value; * with following keys:
} * - 'return_rows' control if rows must be returned and how many rows must
* be returnd. The value can be Database::RETURN_ONE_ROW for olny one
* row or Database::RETURN_ALL_ROWS for all rows. If this key not
* specified, the function will not return any rows.
* - 'fetch_type' control indexes in resulting rows. The value can be
* Database::FETCH_ASSOC for associative array, Database::FETCH_NUM for
* array with numeric indexes and Database::FETCH_BOTH for both indexes.
* Default value is Database::FETCH_ASSOC.
* @return mixed If 'return_rows' key of the $params array is specified,
* returns one or several rows (depending on $params['return_rows'] value)
* or boolean false on fail.
* If 'return_rows' key of the $params array is not specified, returns
* boolean true on success or false on fail.
*
* @see Database::RETURN_ONE_ROW
* @see Database::RETURN_ALL_ROWS
* @see Database::FETCH_ASSOC
* @see Database::FETCH_NUM
* @see Database::FETCH_BOTH
*/
public function query($query, $values = null, $params = array())
{
try {
$query = preg_replace("/\{(\w+)\}/", $this->tablesPrefix . "$1", $query);
/** $query_key = md5($query);
* Database class destructor. if (!array_key_exists($query_key, $this->preparedStatements)) {
*/ $this->preparedStatements[$query_key] = $this->dbh->prepare($query);
public function __destruct(){ }
foreach($this->preparedStatements as $key => $statement) {
$this->preparedStatements[$key] = NULL;
}
$this->dbh = NULL;
self::$instance = NULL;
}
/** $this->lastQuery = $query_key;
* Executes SQL query.
* In SQL query can be used PDO style placeholders:
* unnamed placeholders (question marks '?') and named placeholders (like
* ':name').
* If unnamed placeholders are used, $values array must have numeric indexes.
* If named placeholders are used, $values param must be an associative array
* with keys corresponding to the placeholders names
*
* Table prefix automatically substitute if table name puts in curly braces
*
* @param string $query SQL query
* @param array $values Values, that must be substitute instead of
* placeholders in SQL query.
* @param array $params Array of query parameters. It can contains values with
* following keys:
* - 'return_rows' control if rows must be returned and how many rows must
* be returnd. The value can be Database::RETURN_ONE_ROW for olny one row
* or Database::RETURN_ALL_ROWS for all rows. If this key not specified,
* the function will not return any rows.
* - 'fetch_type' control indexes in resulting rows. The value can be
* Database::FETCH_ASSOC for associative array, Database::FETCH_NUM for
* array with numeric indexes and Database::FETCH_BOTH for both indexes.
* Default value is Database::FETCH_ASSOC.
* @return mixed If 'return_rows' key of the $params array is specified,
* returns one or several rows (depending on $params['return_rows'] value) or
* boolean false on fail.
* If 'return_rows' key of the $params array is not specified, returns
* boolean true on success or false on fail.
*
* @see Database::RETURN_ONE_ROW
* @see Database::RETURN_ALL_ROWS
* @see Database::FETCH_ASSOC
* @see Database::FETCH_NUM
* @see Database::FETCH_BOTH
*/
public function query($query, $values = NULL, $params = array()){
try{
$query = preg_replace("/\{(\w+)\}/", $this->tablesPrefix."$1", $query);
$query_key = md5($query); // Execute query
if (! array_key_exists($query_key, $this->preparedStatements)) { $this->preparedStatements[$query_key]->execute($values);
$this->preparedStatements[$query_key] = $this->dbh->prepare($query);
}
$this->lastQuery = $query_key; // Check if error occurs
if ($this->preparedStatements[$query_key]->errorCode() !== '00000') {
$errorInfo = $this->preparedStatements[$query_key]->errorInfo();
throw new \Exception(' Query failed: ' . $errorInfo[2]);
}
// Execute query // No need to return rows
$this->preparedStatements[$query_key]->execute($values); if (!array_key_exists('return_rows', $params)) {
return true;
}
// Check if error occurs // Some rows must be returned
if ($this->preparedStatements[$query_key]->errorCode() !== '00000') { // Get indexes type
$errorInfo = $this->preparedStatements[$query_key]->errorInfo(); if (!array_key_exists('fetch_type', $params)) {
throw new \Exception(' Query failed: ' . $errorInfo[2]); $params['fetch_type'] = Database::FETCH_ASSOC;
} }
switch ($params['fetch_type']) {
case Database::FETCH_NUM:
$fetch_type = \PDO::FETCH_NUM;
break;
case Database::FETCH_ASSOC:
$fetch_type = \PDO::FETCH_ASSOC;
break;
case Database::FETCH_BOTH:
$fetch_type = \PDO::FETCH_BOTH;
break;
default:
throw new \Exception("Unknown 'fetch_type' value!");
}
// No need to return rows // Get results
if (! array_key_exists('return_rows', $params)) { $rows = array();
return true; if ($params['return_rows'] == Database::RETURN_ONE_ROW) {
} $rows = $this->preparedStatements[$query_key]->fetch($fetch_type);
} elseif ($params['return_rows'] == Database::RETURN_ALL_ROWS) {
$rows = $this->preparedStatements[$query_key]->fetchAll($fetch_type);
} else {
throw new \Exception("Unknown 'return_rows' value!");
}
$this->preparedStatements[$query_key]->closeCursor();
// Some rows must be returned return $rows;
} catch (\Exception $e) {
$this->handleError($e);
}
}
// Get indexes type /**
if (! array_key_exists('fetch_type', $params)) { * Returns value of PDOStatement::$errorInfo property for last query.
$params['fetch_type'] = Database::FETCH_ASSOC; *
} * @return string Error info array
switch($params['fetch_type']){ * @see \PDOStatement::$erorrInfo
case Database::FETCH_NUM: */
$fetch_type = \PDO::FETCH_NUM; public function errorInfo()
break; {
case Database::FETCH_ASSOC: if (is_null($this->lastQuery)) {
$fetch_type = \PDO::FETCH_ASSOC; return false;
break; }
case Database::FETCH_BOTH: try {
$fetch_type = \PDO::FETCH_BOTH; $error_info = $this->preparedStatements[$this->lastQuery]->errorInfo();
break; } catch (\Exception $e) {
default: $this->handleError($e);
throw new \Exception("Unknown 'fetch_type' value!"); }
}
// Get results return $error_info;
$rows = array(); }
if ($params['return_rows'] == Database::RETURN_ONE_ROW) {
$rows = $this->preparedStatements[$query_key]->fetch($fetch_type);
} elseif ($params['return_rows'] == Database::RETURN_ALL_ROWS) {
$rows = $this->preparedStatements[$query_key]->fetchAll($fetch_type);
} else {
throw new \Exception("Unknown 'return_rows' value!");
}
$this->preparedStatements[$query_key]->closeCursor();
return $rows; /**
} catch(\Exception $e) { * Returns the ID of the last inserted row
$this->handleError($e); *
} * @return int The ID
} */
public function insertedId()
{
try {
$last_inserted_id = $this->dbh->lastInsertId();
} catch (\Exception $e) {
$this->handleError($e);
}
/** return $last_inserted_id;
* Returns value of PDOStatement::$errorInfo property for last query }
* @return string Error info array
*
* @see \PDOStatement::$erorrInfo
*/
public function errorInfo(){
if (is_null($this->lastQuery)) {
return false;
}
try{
$errorInfo = $this->preparedStatements[$this->lastQuery]->errorInfo();
} catch (\Exception $e) {
$this->handleError($e);
}
return $errorInfo;
}
/** /**
* Returns the ID of the last inserted row * Get count of affected rows in the last query
* *
* @return int The ID * @return int Affected rows count
*/ */
public function insertedId(){ public function affectedRows()
try{ {
$lastInsertedId = $this->dbh->lastInsertId(); if (is_null($this->lastQuery)) {
} catch(\Exception $e) { return false;
$this->handleError($e); }
} try {
return $lastInsertedId; $affected_rows = $this->preparedStatements[$this->lastQuery]->rowCount();
} } catch (\Exception $e) {
$this->handleError($e);
}
/** return $affected_rows;
* Get count of affected rows in the last query }
*
* @return int Affected rows count
*/
public function affectedRows(){
if (is_null($this->lastQuery)) {
return false;
}
try{
$affected_rows = $this->preparedStatements[$this->lastQuery]->rowCount();
} catch(\Exception $e) {
$this->handleError($e);
}
return $affected_rows;
}
/**
* Forbid external object creation
*/
protected function __construct()
{
}
/**
* Handles errors
* @param \Exception $e
*/
protected function handleError(\Exception $e)
{
if ($this->throwExceptions) {
throw $e;
}
die($e->getMessage());
}
/**
* Forbid clone objects
*/
final private function __clone()
{
}
} }
?>

View File

@ -21,128 +21,140 @@ namespace Mibew;
* Provide event-related functionality. * Provide event-related functionality.
* Implements singleton pattern. * Implements singleton pattern.
*/ */
Class EventDispatcher { class EventDispatcher
{
/**
* An instance of EventDispatcher class.
*
* @var EventDispatcher
*/
protected static $instance = null;
/** /**
* An instance of EventDispatcher class. * Events and listeners array.
* @var EventDispatcher *
*/ * @var array
protected static $instance = null; */
protected $events = array();
/** /**
* Events and listeners array. * Increments any time when plugin adds. Is used for determine plugins order
* @var array * for plugins with equal priority.
*/ *
protected $events = array(); * @var int
*/
protected $offset = 0;
/** /**
* Increments any time when plugin adds. Use for determine plugins order for plugins with * Returns an instance of EventDispatcher class.
* equal priority. *
* @var int * @return EventDispatcher
*/ */
protected $offset = 0; public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
/** return self::$instance;
* Returns an instance of EventDispatcher class. }
*
* @return EventDispatcher
*/
public static function getInstance(){
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/** /**
* Make constructor unavailable for client code * Attaches listener function to event.
*/ *
protected function __constructor() {} * All event listeners must receive one argument of array type by reference.
*
* @param string $event_name Event's name
* @param \Mibew\Plugin $plugin Plugin object, that handles the event
* @param string $listener Plugins method, that handles the event
* @param int $priority Priority of listener. If $priority = null, the
* plugin weight will use instead.
* @return boolean true on success or false on failure.
*
* @see \Mibew\Plugin::getWeight()
*/
public function attachListener($event_name, Plugin $plugin, $listener, $priority = null)
{
// Check method is callable
if (!is_callable(array($plugin, $listener))) {
trigger_error("Method '{$listener}' is not callable!", E_USER_WARNING);
/** return false;
* Attaches listener function to event. }
* // Create empty array for event listener if it not exists
* All event listeners must receive one argument of array type by reference. if (!array_key_exists($event_name, $this->events)) {
* $this->events[$event_name] = array();
* @param string $event_name Event's name }
* @param \Mibew\Plugin $plugin Plugin object, that handles the event // Check priority
* @param string $listener Plugins method, that handles the event if (is_null($priority)) {
* @param int $priority Priority of listener. If $priority = null, the plugin weight will $priority = $plugin->getWeight();
* use instead. }
* @return boolean true on success or false on failure. // Attach listener
* $this->events[$event_name][$priority . "_" . $this->offset] = array(
* @see \Mibew\Plugin::getWeight() 'plugin' => $plugin,
*/ 'listener' => $listener,
public function attachListener($event_name, Plugin $plugin, $listener, $priority = null){ );
// Check method is callable $this->offset++;
if (! is_callable(array($plugin, $listener))) {
trigger_error("Method '{$listener}' is not callable!", E_USER_WARNING);
return false;
}
// Create empty array for event listener if it not exists
if (! array_key_exists($event_name, $this->events)) {
$this->events[$event_name] = array();
}
// Check priority
if (is_null($priority)) {
$priority = $plugin->getWeight();
}
// Attach listener
$this->events[$event_name][$priority . "_" . $this->offset] = array(
'plugin' => $plugin,
'listener' => $listener
);
$this->offset++;
return true;
}
/** return true;
* Detach listener function from event }
*
* @param string $event_name Event's name
* @param \Mibew\Plugin $plugin Plugin object, that handles the event
* @param string $listener Plugins method, that handles the event
* @return boolean true on success or false on failure.
*/
public function detachListener($event_name, Plugin $plugin, $listener){
// Check event exists
if (! array_key_exists($event_name, $this->events)) {
return false;
}
// Search event and $plugin->$listener
foreach ($this->events[$event_name] as $index => $event) {
if ($event['plugin'] === $plugin && $event['listener'] == $listener) {
// Detach listener
unset($this->events[$event_name][$index]);
return true;
}
}
return false;
}
/** /**
* Triggers the event * Detach listener function from event
* *
* @param string $event_name Event's name * @param string $event_name Event's name
* @param array &$arguments Arguments passed to listener * @param \Mibew\Plugin $plugin Plugin object, that handles the event
* @return boolean true on success or false on failure * @param string $listener Plugins method, that handles the event
*/ * @return boolean true on success or false on failure.
public function triggerEvent($event_name, &$arguments = array()){ */
// Check event listeners exists public function detachListener($event_name, Plugin $plugin, $listener)
if (! array_key_exists($event_name, $this->events)) { {
return true; // Check event exists
} if (!array_key_exists($event_name, $this->events)) {
// Sorting listeners by priority return false;
uksort($this->events[$event_name], 'strnatcmp'); }
// Invoke listeners // Search event and $plugin->$listener
foreach ($this->events[$event_name] as $event) { foreach ($this->events[$event_name] as $index => $event) {
$plugin = $event['plugin']; if ($event['plugin'] === $plugin && $event['listener'] == $listener) {
$listener = $event['listener']; // Detach listener
$plugin->$listener($arguments); unset($this->events[$event_name][$index]);
}
return true;
}
return true;
}
}
return false;
}
/**
* Triggers the event
*
* @param string $event_name Event's name
* @param array &$arguments Arguments passed to listener
* @return boolean true on success or false on failure
*/
public function triggerEvent($event_name, &$arguments = array())
{
// Check event listeners exists
if (!array_key_exists($event_name, $this->events)) {
return true;
}
// Sorting listeners by priority
uksort($this->events[$event_name], 'strnatcmp');
// Invoke listeners
foreach ($this->events[$event_name] as $event) {
$plugin = $event['plugin'];
$listener = $event['listener'];
$plugin->$listener($arguments);
}
return true;
}
/**
* Make constructor unavailable for client code
*/
protected function __constructor()
{
}
} }
?>

View File

@ -20,52 +20,51 @@ namespace Mibew;
/** /**
* Base plugin class * Base plugin class
*/ */
abstract Class Plugin { abstract class Plugin
{
/**
* Constructor must set this value to true after successful initialization
* failures
* @var boolean
*/
public $initialized = false;
/** /**
* Constructor must set this value to true after successful initialization * An array of plugin configuration
* failures * @var array
* @var boolean */
*/ protected $config = array();
public $initialized = false;
/** /**
* An array of plugin configuration * Returns plugin weight. Weight is used for determine loading order and as
* @var array * default listner priority.
*/ *
protected $config = array(); * @return int Plugin weight
*/
abstract public function getWeight();
/** /**
* Returns plugin weight. Weight is used for determine loading order and as default * Register listeners
* listner priority. *
* * Event listener take one argument by reference. For example:
* @return int Plugin weight * <code>
*/ * public function testListener(&$arguments) {
abstract public function getWeight(); * $arguments['result'] = 'Test string';
* }
* </code>
*/
abstract public function registerListeners();
/** /**
* Register listeners * Returns list of plugin's dependences.
* *
* Event listener take one argument by reference. For example: * Each element of dependenses list is a string with a plugin name.
* <code> * If plugin have no dependenses do not override this method.
* public function testListener(&$arguments) { *
* $arguments['result'] = 'Test string'; * @return array List of plugin's dependences.
* } */
* </code> public static function getDependences()
*/ {
abstract public function registerListeners(); return array();
}
/**
* Returns list of plugin's dependences.
*
* Each element of dependenses list is a string with a plugin name.
* If plugin have no dependenses do not override this method.
*
* @return array List of plugin's dependences.
*/
public static function getDependences() {
return array();
}
} }
?>

View File

@ -20,143 +20,142 @@ namespace Mibew;
/** /**
* Manage plugins * Manage plugins
*/ */
Class PluginManager { class PluginManager
{
/**
* Contains all loaded plugins
*
* @var array
*/
protected static $loadedPlugins = array();
/** /**
* Contains all loaded plugins * Returns plugin object
* @var array *
*/ * @param string $plugin_name
protected static $loaded_plugins = array(); * @return \Mibew\Plugin
*/
public static function getPlugin($plugin_name)
{
if (empty(self::$loadedPlugins[$plugin_name])) {
trigger_error(
"Plugin '{$plugin_name}' does not initialized!",
E_USER_WARNING
);
}
/** return self::$loadedPlugins[$plugin_name];
* Returns plugin object }
*
* @param string $plugin_name
* @return \Mibew\Plugin
*/
public static function getPlugin($plugin_name) {
if (empty(self::$loaded_plugins[$plugin_name])) {
trigger_error(
"Plugin '{$plugin_name}' does not initialized!",
E_USER_WARNING
);
}
return self::$loaded_plugins[$plugin_name];
}
/** /**
* Returns associative array of loaded plugins. * Returns associative array of loaded plugins.
* *
* Key represents plugin's name and value contains Plugin object * Key represents plugin's name and value contains Plugin object
* *
* @return array * @return array
*/ */
public static function getAllPlugins() { public static function getAllPlugins()
return self::$loaded_plugins; {
} return self::$loadedPlugins;
}
/** /**
* Loads plugins. * Loads plugins.
* *
* The method checks dependences and plugin avaiulability before loading and * The method checks dependences and plugin avaiulability before loading and
* invokes Plugin::registerListeners() after loading. * invokes Plugin::registerListeners() after loading.
* *
* @param array $plugins_list List of plugins' names and configurations. * @param array $plugins_list List of plugins' names and configurations.
* For example: * For example:
* <code> * <code>
* $plugins_list = array(); * $plugins_list = array();
* $plugins_list[] = array( * $plugins_list[] = array(
* 'name' => 'plugin_name', // Obligatory value * 'name' => 'plugin_name', // Obligatory value
* 'config' => array( // Pass to plugin constructor * 'config' => array( // Pass to plugin constructor
* 'weight' => 100, * 'weight' => 100,
* 'some_configurable_value' => 'value' * 'some_configurable_value' => 'value'
* ) * )
* ) * )
* </code> * </code>
* *
* @see Plugin::registerListeners() * @see Plugin::registerListeners()
*/ */
public static function loadPlugins($plugins_list){ public static function loadPlugins($plugins_list)
// Add include path {
$include_path = get_include_path(); // Add include path
$include_path .= empty($include_path) ? '' : PATH_SEPARATOR ; $include_path = get_include_path();
set_include_path($include_path . realpath(MIBEW_FS_ROOT . "/plugins/")); $include_path .= empty($include_path) ? '' : PATH_SEPARATOR;
set_include_path($include_path . realpath(MIBEW_FS_ROOT . "/plugins/"));
// Load plugins // Load plugins
$loading_queue = array(); $loading_queue = array();
$offset = 0; $offset = 0;
foreach ($plugins_list as $plugin) { foreach ($plugins_list as $plugin) {
if (empty($plugin['name'])) { if (empty($plugin['name'])) {
trigger_error("Plugin name undefined!", E_USER_WARNING); trigger_error("Plugin name undefined!", E_USER_WARNING);
continue; continue;
} }
$plugin_name = $plugin['name']; $plugin_name = $plugin['name'];
$plugin_config = isset($plugin['config']) ? $plugin['config'] : array(); $plugin_config = isset($plugin['config']) ? $plugin['config'] : array();
// Build name of the plugin class // Build name of the plugin class
$plugin_name_parts = explode('_', $plugin_name); $plugin_name_parts = explode('_', $plugin_name);
$plugin_name_parts = array_map('ucfirst', $plugin_name_parts); $plugin_name_parts = array_map('ucfirst', $plugin_name_parts);
$plugin_classname = '\\Mibew\\Plugin\\' . implode('', $plugin_name_parts); $plugin_classname = '\\Mibew\\Plugin\\' . implode('', $plugin_name_parts);
// Try to load plugin file // Try to load plugin file
if (! (include_once $plugin_name."/".$plugin_name."_plugin.php")) { if (!(include_once $plugin_name . "/" . $plugin_name . "_plugin.php")) {
trigger_error("Cannot load plugin file!", E_USER_ERROR); trigger_error("Cannot load plugin file!", E_USER_ERROR);
} }
// Check plugin class name // Check plugin class name
if (! class_exists($plugin_classname)) { if (!class_exists($plugin_classname)) {
trigger_error( trigger_error(
"Plugin class '{$plugin_classname}' is undefined!", "Plugin class '{$plugin_classname}' is undefined!",
E_USER_WARNING E_USER_WARNING
); );
continue; continue;
} }
// Check if plugin extends abstract 'Plugin' class // Check if plugin extends abstract 'Plugin' class
if ('Mibew\\Plugin' != get_parent_class($plugin_classname)) { if ('Mibew\\Plugin' != get_parent_class($plugin_classname)) {
trigger_error( $error_essage = "Plugin class '{$plugin_classname}' does not "
"Plugin class '{$plugin_classname}' does not extend " . . "extend abstract '\\Mibew\\Plugin' class!";
"abstract '\\Mibew\\Plugin' class!", trigger_error($error_essage, E_USER_WARNING);
E_USER_WARNING continue;
); }
continue;
}
// Check plugin dependences // Check plugin dependences
$plugin_dependences = call_user_func(array( $plugin_dependences = call_user_func(array(
$plugin_classname, $plugin_classname,
'getDependences' 'getDependences',
)); ));
foreach ($plugin_dependences as $dependence) { foreach ($plugin_dependences as $dependence) {
if (empty(self::$loaded_plugins[$dependence])) { if (empty(self::$loadedPlugins[$dependence])) {
trigger_error( $error_essage = "Plugin '{$dependence}' was not loaded "
"Plugin '{$dependence}' was not loaded yet, but " . . "yet, but exists in '{$plugin_name}' dependences list!";
"exists in '{$plugin_name}' dependences list!", trigger_error($error_essage, E_USER_WARNING);
E_USER_WARNING continue 2;
); }
continue 2; }
}
}
// Add plugin to loading queue // Add plugin to loading queue
$plugin_instance = new $plugin_classname($plugin_config); $plugin_instance = new $plugin_classname($plugin_config);
if ($plugin_instance->initialized) { if ($plugin_instance->initialized) {
// Store plugin instance // Store plugin instance
self::$loaded_plugins[$plugin_name] = $plugin_instance; self::$loadedPlugins[$plugin_name] = $plugin_instance;
$loading_queue[$plugin_instance->getWeight() . "_" . $offset] = $plugin_instance; $loading_queue[$plugin_instance->getWeight() . "_" . $offset] = $plugin_instance;
$offset++; $offset++;
} else { } else {
trigger_error( trigger_error(
"Plugin '{$plugin_name}' was not initialized correctly!", "Plugin '{$plugin_name}' was not initialized correctly!",
E_USER_WARNING E_USER_WARNING
); );
} }
} }
// Sort queue in order to plugins' weights // Sort queue in order to plugins' weights
uksort($loading_queue, 'strnatcmp'); uksort($loading_queue, 'strnatcmp');
// Add events and listeners // Add events and listeners
foreach ($loading_queue as $plugin) { foreach ($loading_queue as $plugin) {
$plugin->registerListeners(); $plugin->registerListeners();
} }
} }
} }
?>

View File

@ -24,81 +24,84 @@ use Mibew\Database;
* Base class for all request processors that interact with JavaScript * Base class for all request processors that interact with JavaScript
* applications at the client side. * applications at the client side.
*/ */
abstract class ClientSideProcessor extends Processor { abstract class ClientSideProcessor extends Processor
{
/** /**
* Call function at client side * Call function at client side
* *
* @param array $functions Array of functions to call. See Mibew API for * @param array $functions Array of functions to call. See Mibew API for
* details. * details.
* @param array|null $callback callback array for synchronous requests. * @param array|null $callback callback array for synchronous requests.
* @return mixed request result or boolean false on failure. * @return mixed request result or boolean false on failure.
*/ */
public function call($functions, $callback = null) { public function call($functions, $callback = null)
return parent::call($functions, true, $callback); {
} return parent::call($functions, true, $callback);
}
/** /**
* Sends asynchronous responses * Sends asynchronous responses
* *
* @param array $responses An array of the 'Request' arrays. See Mibew API * @param array $responses An array of the 'Request' arrays. See Mibew API
* for details * for details
*/ */
protected function sendAsyncResponses($responses) { protected function sendAsyncResponses($responses)
header("Content-type: text/plain; charset=UTF-8"); {
echo($this->mibewAPI->encodePackage( header("Content-type: text/plain; charset=UTF-8");
$responses, echo($this->mibewAPI->encodePackage(
$this->config['signature'], $responses,
true $this->config['signature'],
)); true
} ));
}
/** /**
* Add request to client side to the buffer. Use database as storage. * Add request to client side to the buffer. Use database as storage.
* Override this method if you want to use another storage and/or save logic. * Override this method if you want to use another storage and/or save logic.
* *
* @param String $key Request key. Use to load request from buffer. * @param String $key Request key. Use to load request from buffer.
* @param $request Request array. * @param $request Request array.
*/ */
protected function addRequestToBuffer($key, $request) { protected function addRequestToBuffer($key, $request)
// Save request to database {
$db = Database::getInstance(); // Save request to database
$db->query( $db = Database::getInstance();
"INSERT INTO {requestbuffer} (request, requestkey) VALUES (:request, :key)", $db->query(
array(':request' => serialize($request), ':key' => md5($key)) "INSERT INTO {requestbuffer} (request, requestkey) VALUES (:request, :key)",
); array(':request' => serialize($request), ':key' => md5($key))
} );
}
/** /**
* Load stored requests to the client side * Load stored requests to the client side
* *
* @param String $key Request key * @param String $key Request key
* @return array Array of requests with given key * @return array Array of requests with given key
*/ */
protected function getRequestsFromBuffer($key) { protected function getRequestsFromBuffer($key)
$db = Database::getInstance(); {
$db = Database::getInstance();
$key = md5($key); $key = md5($key);
// Get requests from database // Get requests from database
$requests = $db->query( $requests = $db->query(
"SELECT request FROM {requestbuffer} WHERE requestkey = :key", "SELECT request FROM {requestbuffer} WHERE requestkey = :key",
array(':key' => $key), array(':key' => $key),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
// Remove got requests from database // Remove got requests from database
$db->query( $db->query(
"DELETE FROM {requestbuffer} WHERE requestkey = :key", "DELETE FROM {requestbuffer} WHERE requestkey = :key",
array(':key' => $key) array(':key' => $key)
); );
// Unserialize requests // Unserialize requests
$result = array(); $result = array();
foreach($requests as $request_info) { foreach ($requests as $request_info) {
$result[] = unserialize($request_info['request']); $result[] = unserialize($request_info['request']);
} }
return $result;
}
return $result;
}
} }
?>

View File

@ -20,11 +20,10 @@ namespace Mibew\RequestProcessor\Exception;
/** /**
* Class for {@link \Mibew\RequestProcessor\InviteRequestProcessor} exceptions * Class for {@link \Mibew\RequestProcessor\InviteRequestProcessor} exceptions
*/ */
class InviteProcessorException extends ProcessorException { class InviteProcessorException extends ProcessorException
/** {
* Operator is not logged in /**
*/ * Operator is not logged in
const ERROR_AGENT_NOT_LOGGED_IN = 1; */
const ERROR_AGENT_NOT_LOGGED_IN = 1;
} }
?>

View File

@ -20,11 +20,10 @@ namespace Mibew\RequestProcessor\Exception;
/** /**
* Class for {@link \Mibew\RequestProcessor\Processor} exceptions. * Class for {@link \Mibew\RequestProcessor\Processor} exceptions.
*/ */
class ProcessorException extends \Exception { class ProcessorException extends \Exception
/** {
* Wrong function arguments /**
*/ * Wrong function arguments
const WRONG_ARGUMENTS = 1; */
const WRONG_ARGUMENTS = 1;
} }
?>

View File

@ -20,51 +20,50 @@ namespace Mibew\RequestProcessor\Exception;
/** /**
* Class for {@link \Mibew\RequestProcessor\ThreadProcessor} exceptions. * Class for {@link \Mibew\RequestProcessor\ThreadProcessor} exceptions.
*/ */
class ThreadProcessorException extends ProcessorException { class ThreadProcessorException extends ProcessorException
/** {
* 'recipient' argument is not set /**
*/ * 'recipient' argument is not set
const EMPTY_RECIPIENT = 1; */
/** const EMPTY_RECIPIENT = 1;
* Operator is not logged in /**
*/ * Operator is not logged in
const ERROR_AGENT_NOT_LOGGED_IN = 2; */
/** const ERROR_AGENT_NOT_LOGGED_IN = 2;
* Wrong arguments set for an API function /**
*/ * Wrong arguments set for an API function
const ERROR_WRONG_ARGUMENTS = 3; */
/** const ERROR_WRONG_ARGUMENTS = 3;
* Thread cannot be loaded /**
*/ * Thread cannot be loaded
const ERROR_WRONG_THREAD = 4; */
/** const ERROR_WRONG_THREAD = 4;
* Message cannot be send /**
*/ * Message cannot be send
const ERROR_CANNOT_SEND = 5; */
/** const ERROR_CANNOT_SEND = 5;
* User rename forbidden by system configurations /**
*/ * User rename forbidden by system configurations
const ERROR_FORBIDDEN_RENAME = 6; */
/** const ERROR_FORBIDDEN_RENAME = 6;
* Various recipient in different functions in one package /**
*/ * Various recipient in different functions in one package
const VARIOUS_RECIPIENT = 7; */
/** const VARIOUS_RECIPIENT = 7;
* Various thread ids or thread tokens in different functions in one package /**
*/ * Various thread ids or thread tokens in different functions in one package
const VARIOUS_THREAD_ID = 8; */
/** const VARIOUS_THREAD_ID = 8;
* Wrong recipient value /**
*/ * Wrong recipient value
const WRONG_RECIPIENT_VALUE = 9; */
/** const WRONG_RECIPIENT_VALUE = 9;
* Wrong captcha value /**
*/ * Wrong captcha value
const ERROR_WRONG_CAPTCHA = 10; */
/** const ERROR_WRONG_CAPTCHA = 10;
* Wrong email address /**
*/ * Wrong email address
const ERROR_WRONG_EMAIL = 11; */
const ERROR_WRONG_EMAIL = 11;
} }
?>

View File

@ -20,19 +20,18 @@ namespace Mibew\RequestProcessor\Exception;
/** /**
* Class for {@link \Mibew\RequestProcessor\UsersProcessor} exceptions * Class for {@link \Mibew\RequestProcessor\UsersProcessor} exceptions
*/ */
class UsersProcessorException extends ProcessorException { class UsersProcessorException extends ProcessorException
/** {
* Operator is not logged in /**
*/ * Operator is not logged in
const ERROR_AGENT_NOT_LOGGED_IN = 1; */
/** const ERROR_AGENT_NOT_LOGGED_IN = 1;
* Wrong agent id /**
*/ * Wrong agent id
const ERROR_WRONG_AGENT_ID = 2; */
/** const ERROR_WRONG_AGENT_ID = 2;
* Various agent ids in different functions in one package /**
*/ * Various agent ids in different functions in one package
const VARIOUS_AGENT_ID = 3; */
const VARIOUS_AGENT_ID = 3;
} }
?>

View File

@ -33,94 +33,106 @@ use Mibew\RequestProcessor\Exception\InviteProcessorException;
* *
* Implements Singleton pattern * Implements Singleton pattern
*/ */
class InviteProcessor extends ClientSideProcessor { class InviteProcessor extends ClientSideProcessor
{
/**
* An instance of the InviteProcessor class
*
* @var \Mibew\RequestProcessor\InviteProcessor
*/
protected static $instance = null;
/** /**
* An instance of the InviteProcessor class * Return an instance of the InviteProcessor class.
* @var \Mibew\RequestProcessor\InviteProcessor *
*/ * @return \Mibew\RequestProcessor\InviteProcessor
protected static $instance = null; */
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
/** return self::$instance;
* Return an instance of the InviteProcessor class. }
* @return \Mibew\RequestProcessor\InviteProcessor
*/
public static function getInstance() {
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/** /**
* Class constructor * Class constructor
* *
* Do not use directly __construct method! Use * Do not use directly __construct method! Use
* \Mibew\RequestProcessor\InviteProcessor::getInstance() instead! * \Mibew\RequestProcessor\InviteProcessor::getInstance() instead!
* @todo Think about why the method is not protected *
*/ * @todo Think about why the method is not protected
public function __construct() { */
parent::__construct(array( public function __construct()
'signature' => '', {
'trusted_signatures' => array(''), parent::__construct(array(
'event_prefix' => 'invite' 'signature' => '',
)); 'trusted_signatures' => array(''),
} 'event_prefix' => 'invite'
));
}
/** /**
* Creates and returns an instance of the \Mibew\API\API class. * Creates and returns an instance of the \Mibew\API\API class.
* *
* @return \Mibew\API\API * @return \Mibew\API\API
*/ */
protected function getMibewAPIInstance() { protected function getMibewAPIInstance()
return MibewAPI::getAPI('\\Mibew\\API\\Interaction\\InviteInteraction'); {
} return MibewAPI::getAPI('\\Mibew\\API\\Interaction\\InviteInteraction');
}
/** /**
* Stub for sendAsyncRequest method. * Stub for sendAsyncRequest method.
* *
* Actually request not send to client side. This method is ONLY STUB. * Actually request not send to client side. This method is ONLY STUB.
* @return boolean Always true *
*/ * @return boolean Always true
protected function sendAsyncRequest() { */
return true; protected function sendAsyncRequest()
} {
return true;
}
/** /**
* Stub for call method. * Stub for call method.
* *
* Actually nothing can be called at client side. This method is ONLY STUB. * Actually nothing can be called at client side. This method is ONLY STUB.
* @return boolean Always false. *
*/ * @return boolean Always false.
public function call() { */
return false; public function call()
} {
return false;
}
/** /**
* Returns visitor invitation state. API function * Returns visitor invitation state. API function
* *
* @param array $args Associative array of arguments. It must contains * @param array $args Associative array of arguments. It must contains
* following keys: * following keys:
* - 'visitorId': Id of the invited visitor * - 'visitorId': Id of the invited visitor
* @return array Array of results. It contains following keys: * @return array Array of results. It contains following keys:
* - 'invited': boolean, indicates if visitor is invited * - 'invited': boolean, indicates if visitor is invited
* - 'threadId': thread id related to visitor or false if there is no thread * - 'threadId': thread id related to visitor or false if there is no
*/ * thread
protected function apiInvitationState($args) { */
$operator = get_logged_in(); protected function apiInvitationState($args)
if (!$operator) { {
throw new InviteProcessorException( $operator = get_logged_in();
"Operator not logged in!", if (!$operator) {
InviteProcessorException::ERROR_AGENT_NOT_LOGGED_IN throw new InviteProcessorException(
); "Operator not logged in!",
} InviteProcessorException::ERROR_AGENT_NOT_LOGGED_IN
);
}
$invitation = invitation_state($args['visitorId']); $invitation = invitation_state($args['visitorId']);
return array(
'invited' => (bool)$invitation['invited'], return array(
'threadId' => ($invitation['threadid'] ? $invitation['threadid'] : false) 'invited' => (bool) $invitation['invited'],
); 'threadId' => ($invitation['threadid'] ? $invitation['threadid'] : false),
} );
}
} }
?>

View File

@ -81,452 +81,488 @@ use Mibew\RequestProcessor\Exception\ProcessorException;
* Example of the event handler: * Example of the event handler:
* <code> * <code>
* public function callHandler(&$function) { * public function callHandler(&$function) {
* if ($function['function'] == 'microtime') { * if ($function['function'] == 'microtime') {
* $as_float = empty($function['arguments']['as_float']) * $as_float = empty($function['arguments']['as_float'])
* ? false * ? false
* : $function['arguments']['as_float']; * : $function['arguments']['as_float'];
* $function['results']['time'] = microtime($as_float); * $function['results']['time'] = microtime($as_float);
* } * }
* } * }
* </code> * </code>
* *
* @see \Mibew\RequestProcessor\Processor::__construct() * @see \Mibew\RequestProcessor\Processor::__construct()
*/ */
abstract class Processor { abstract class Processor
{
/**
* Instance of the MibewAPI class
*
* @var \Mibew\API\API
*/
protected $mibewAPI = null;
/** /**
* Instance of the MibewAPI class * Prefix that uses for all events triggered by the class.
* @var \Mibew\API\API *
*/ * @var string
protected $mibewAPI = null; */
protected $eventPrefix = '';
/** /**
* Prefix that uses for all events triggered by the class. * Array of the responses packages
* @var string *
*/ * @var array
protected $eventPrefix = ''; */
protected $responses = array();
/** /**
* Array of the responses packages * Array of configurations
* @var array *
*/ * @var array
protected $responses = array(); */
protected $config = array();
/** /**
* Array of configurations * Class constructor
* @var array *
*/ * @param type $config Configuration data.
protected $config = array(); * It must contains following keys:
* - 'signature': Use for verification sender
* - 'trusted_signatures': array of trusted signatures. Uses for identify
* another side of interaction.
* And may contains following (if not default values will be used)
* - 'event_prefix': prefix that uses for all events triggered by the
* class. The default value is the class name with first character in
* lower case
*/
public function __construct($config)
{
// Check signature
if (!isset($config['signature'])) {
trigger_error("Signature is not specified", E_USER_ERROR);
}
/** // Check trusted signatures
* Class constructor if (!isset($config['trusted_signatures'])) {
* trigger_error("Trusted signatures is not specified", E_USER_ERROR);
* @param type $config Configuration data. }
* It must contains following keys:
* - 'signature': Use for verification sender
* - 'trusted_signatures': array of trusted signatures. Uses for identify another
* side of interaction.
* And may contains following (if not default values will be used)
* - 'event_prefix': prefix that uses for all events triggered by the
* class. The default value is the class name with first character in
* lower case
*/
public function __construct($config) {
// Check signature
if (! isset($config['signature'])) {
trigger_error("Signature is not specified", E_USER_ERROR);
}
// Check trusted signatures // Get an instance of the MibewAPI class
if (! isset($config['trusted_signatures'])) { $this->mibewAPI = $this->getMibewAPIInstance();
trigger_error("Trusted signatures is not specified", E_USER_ERROR);
}
// Get an instance of the MibewAPI class // Get class name and prefix for events and etc.
$this->mibewAPI = $this->getMibewAPIInstance(); $class_name_parts = explode('\\', get_class($this));
$class_name = array_pop($class_name_parts);
$this->eventPrefix = empty($config['event_prefix'])
? strtolower(substr($class_name, 0, 1)) . substr($class_name, 1)
: $config['event_prefix'];
// Get class name and prefix for events and etc. // Store config
$class_name_parts = explode('\\', get_class($this)); $this->config = $config;
$class_name = array_pop($class_name_parts); }
$this->eventPrefix = empty($config['event_prefix'])
? strtolower(substr($class_name, 0, 1)) . substr($class_name, 1)
: $config['event_prefix'];
// Store config /**
$this->config = $config; * Proccess received packages
} *
* On any error function returns only boolean false. To handle error add
* listener to the "<eventPrefix>RequestError" event.
*
* @param string $package Encoded package
* @return boolean true if request processed succussfully or false on
* failure
*/
public function receiveRequest($package)
{
$dispatcher = EventDispatcher::getInstance();
// Try to handle request
try {
// Decode package
$request_package = $this->mibewAPI->decodePackage(
$package,
$this->config['trusted_signatures']
);
/** // Trigger request received event
* Proccess received packages $vars = array('package' => $request_package);
* $dispatcher->triggerEvent(
* On any error function returns only boolean false. To handle error add listener to the $this->eventPrefix . 'RequestReceived',
* "<eventPrefix>RequestError" event. $vars
* );
* @param string $package Encoded package $package = $vars['package'];
* @return boolean true if request processed succussfully or false on failure
*/
public function receiveRequest($package){
$dispatcher = EventDispatcher::getInstance();
// Try to handle request
try {
// Decode package
$request_package = $this->mibewAPI->decodePackage(
$package,
$this->config['trusted_signatures']
);
// Trigger request received event // Process requests in package
$vars = array('package' => $request_package); // Clear responses
$dispatcher->triggerEvent( $this->responses = array();
$this->eventPrefix . 'RequestReceived', foreach ($package['requests'] as $request) {
$vars if ($package['async']) {
); // Asynchronous request
$package = $vars['package']; // Try to load callback function for this token
$callback = $this->loadCallback($request['token']);
// Process requests in package if (!is_null($callback)) {
// Clear responses // There is callback function. Try to get result arguments
$this->responses = array(); $arguments = $this->processRequest($request, true);
foreach ($package['requests'] as $request) { $function = $callback['function'];
if ($package['async']) { $arguments += empty($callback['arguments'])
// Asynchronous request ? array()
// Try to load callback function for this token : $callback['arguments'];
$callback = $this->loadCallback($request['token']); call_user_func_array($function, array($arguments));
continue;
} else {
// Try to get result function
$result_function = $this->mibewAPI->getResultFunction($request['functions']);
if (! is_null($callback)) { if (!is_null($result_function)) {
// There is callback function. Try to get result arguments // There is result function but no callback
$arguments = $this->processRequest($request, true); continue;
$function = $callback['function']; }
$arguments += empty($callback['arguments'])
? array()
: $callback['arguments'];
call_user_func_array($function, array($arguments));
continue;
} else {
// Try to get result function
$result_function = $this->mibewAPI->getResultFunction($request['functions']);
if (! is_null($result_function)) { // There is no result function
// There is result function but no callback // Process request
continue; $arguments = $this->processRequest($request, false);
} // Send response
$this->responses[] = $this->mibewAPI->buildResult(
$request['token'],
$arguments
);
}
} else {
// Synchronous request
// Process request
$arguments = $this->processRequest($request, false);
// Send response
$this->responses[] = $this->mibewAPI->buildResult(
$request['token'],
$arguments
);
}
}
// There is no result function if (count($this->responses) != 0) {
// Process request // Send responses
$arguments = $this->processRequest($request, false); if ($request_package['async']) {
// Send response $this->sendAsyncResponses($this->responses);
$this->responses[] = $this->mibewAPI->buildResult( } else {
$request['token'], $this->sendSyncResponses($this->responses);
$arguments }
); }
}
} else {
// Synchronous request
// Process request
$arguments = $this->processRequest($request, false);
// Send response
$this->responses[] = $this->mibewAPI->buildResult(
$request['token'],
$arguments
);
}
}
if (count($this->responses) != 0) { // Output response
// Send responses } catch (\Exception $e) {
if ($request_package['async']) { // Something went wrong. Trigger error event
$this->sendAsyncResponses($this->responses); $vars = array('exception' => $e);
} else { $dispatcher->triggerEvent($this->eventPrefix . 'RequestError', $vars);
$this->sendSyncResponses($this->responses);
}
}
// Output response return false;
} catch (\Exception $e) { }
// Something went wrong. Trigger error event
$vars = array('exception' => $e);
$dispatcher->triggerEvent($this->eventPrefix . 'RequestError', $vars);
return false;
}
return true;
}
/** return true;
* Call functions at the other side }
*
* On any error function returns only boolean false. To handle error add listener to the
* "<eventPrefix>CallError" event.
*
* @param array $functions Array of functions. See Mibew API for details.
* @param boolean $async True for asynchronous requests and false for synchronous request
* @param mixed $callback callback array or null for synchronous requests.
* @return mixed request result or boolean false on failure.
*/
public function call($functions, $async, $callback = null) {
// Get an instance of the \Mibew\EventDispatcher class
$dispatcher = EventDispatcher::getInstance();
// Try to call function at Other side
try {
// Check functions to call
if (! is_array($functions)) {
throw new ProcessorException(
'#1 argument must be an array!',
ProcessorException::WRONG_ARGUMENTS
);
}
foreach ($functions as $function) {
$this->mibewAPI->checkFunction($function, true);
$this->checkFunction($function);
}
// Create request /**
// TODO: evaluate a possibility of using more secure method of the generation of token * Call functions at the other side
$token = md5(microtime() . rand()); *
$request = array( * On any error function returns only boolean false. To handle error add
'token' => $token, * listener to the "<eventPrefix>CallError" event.
'functions' => $functions *
); * @param array $functions Array of functions. See Mibew API for details.
* @param boolean $async True for asynchronous requests and false for
* synchronous request
* @param mixed $callback callback array or null for synchronous requests.
* @return mixed request result or boolean false on failure.
*/
public function call($functions, $async, $callback = null)
{
// Get an instance of the \Mibew\EventDispatcher class
$dispatcher = EventDispatcher::getInstance();
// Try to call function at Other side
try {
// Check functions to call
if (!is_array($functions)) {
throw new ProcessorException(
'#1 argument must be an array!',
ProcessorException::WRONG_ARGUMENTS
);
}
foreach ($functions as $function) {
$this->mibewAPI->checkFunction($function, true);
$this->checkFunction($function);
}
if ($async) { // Create request
// Store callback // TODO: evaluate a possibility of using more secure method of the
if (! is_null($callback)) { // generation of token
$this->saveCallback($token, $callback); $token = md5(microtime() . rand());
} $request = array(
'token' => $token,
'functions' => $functions
);
// Send asynchronous request if ($async) {
$this->sendAsyncRequest($request); // Store callback
return true; if (!is_null($callback)) {
} $this->saveCallback($token, $callback);
}
// Send synchronous request // Send asynchronous request
$response_package = $this->sendSyncRequest($request); $this->sendAsyncRequest($request);
return true;
}
// Trigger response received event // Send synchronous request
$vars = array('package' => $response_package); $response_package = $this->sendSyncRequest($request);
$dispatcher->triggerEvent($this->eventPrefix . 'ResponseReceived', $vars);
// Process requests in response // Trigger response received event
$result = null; $vars = array('package' => $response_package);
foreach ($response_package['requests'] as $request) { $dispatcher->triggerEvent($this->eventPrefix . 'ResponseReceived', $vars);
// Use only response with token equals to request token. Ignore other packages.
// TODO: May be not ignore other packages
if ($request['token'] == $token) {
$result = $this->processRequest($request, true);
}
}
} catch (\Exception $e) {
// Trigger error event
$vars = array('exception' => $e);
$dispatcher->triggerEvent($this->eventPrefix . "CallError", $vars);
return false;
}
return $result;
}
/** // Process requests in response
* Process request $result = null;
* foreach ($response_package['requests'] as $request) {
* @param array $request 'Requests' array. See Mibew API for details. // Use only response with token equals to request token. Ignore other packages.
* @param mixed $result_function Control existance of the 'result' function in request. // TODO: May be not ignore other packages
* Use boolean true if 'result' function must exists in request, boolean false if must not if ($request['token'] == $token) {
* and null if it doesn't matter. $result = $this->processRequest($request, true);
* @return array Array of requests results. }
*/ }
protected function processRequest($request, $result_function = null) { } catch (\Exception $e) {
$context = new \Mibew\API\ExecutionContext(); // Trigger error event
$vars = array('exception' => $e);
$dispatcher->triggerEvent($this->eventPrefix . "CallError", $vars);
// Get result functions return false;
$result_function = $this->mibewAPI->getResultFunction( }
$request['functions'],
$result_function
);
// Request contains not only result function return $result;
if (! is_null($result_function) && count($request['functions']) > 1) { }
trigger_error(
'Request contains not only result function',
E_USER_WARNING
);
}
if (is_null($result_function)) { /**
// Execute functions * Process request
foreach ($request['functions'] as $function) { *
if (! $this->processFunction($function, $context)) { * @param array $request 'Requests' array. See Mibew API for details.
// Stop if errorCode is set and not equals to 0 * @param mixed $result_function Control existance of the 'result' function
break; * in request. Use boolean true if 'result' function must exists in
} * request, boolean false if must not and null if it doesn't matter.
} * @return array Array of requests results.
return $context->getResults(); */
} else { protected function processRequest($request, $result_function = null)
// Return result {
return $result_function['arguments']; $context = new \Mibew\API\ExecutionContext();
}
}
/** // Get result functions
* Process function $result_function = $this->mibewAPI->getResultFunction(
* $request['functions'],
* @param array $function 'Function' array. See Mibew API for details $result_function
* @param \Mibew\API\ExecutionContext &$context Execution context );
* @return boolean lase if function returns errorCode and errorCode differs from 0.
*/
protected function processFunction($function, \Mibew\API\ExecutionContext &$context) {
// Get function arguments with replaced references
$arguments = $context->getArgumentsList($function);
$call_vars = array( // Request contains not only result function
'function' => $function['function'], if (!is_null($result_function) && count($request['functions']) > 1) {
'arguments' => $arguments, trigger_error(
'results' => array() 'Request contains not only result function',
); E_USER_WARNING
);
}
// Call processor function if (is_null($result_function)) {
$this->processorCall($call_vars); // Execute functions
foreach ($request['functions'] as $function) {
if (!$this->processFunction($function, $context)) {
// Stop if errorCode is set and not equals to 0
break;
}
}
// Trigger FunctionCall event return $context->getResults();
$dispatcher = EventDispatcher::getInstance(); } else {
$dispatcher->triggerEvent($this->eventPrefix . 'FunctionCall', $call_vars); // Return result
return $result_function['arguments'];
}
}
// Get results /**
$results = $call_vars['results']; * Process function
*
* @param array $function 'Function' array. See Mibew API for details
* @param \Mibew\API\ExecutionContext &$context Execution context
* @return boolean lase if function returns errorCode and errorCode differs
* from 0.
*/
protected function processFunction($function, \Mibew\API\ExecutionContext &$context)
{
// Get function arguments with replaced references
$arguments = $context->getArgumentsList($function);
// Add function results to execution context $call_vars = array(
$context->storeFunctionResults($function, $results); 'function' => $function['function'],
'arguments' => $arguments,
'results' => array(),
);
// Check errorCode // Call processor function
return empty($results['errorCode']); $this->processorCall($call_vars);
}
/** // Trigger FunctionCall event
* Stores callback function $dispatcher = EventDispatcher::getInstance();
* $dispatcher->triggerEvent($this->eventPrefix . 'FunctionCall', $call_vars);
* Callback is an associative array with following keys
* - 'function': function name to call
* - 'arguments': additional arguments, that passed to the callback function
*
* @param string $token Request token
* @param array $callback Callback function array
* @todo Create some unit tests
*/
protected function saveCallback($token, $callback) {
$db = Database::getInstance();
$db->query(
"INSERT INTO {requestcallback} ( ".
"token, function, arguments ".
") VALUES ( " .
":token, :function, :arguments" .
")",
array(
':token' => $token,
':function' => $callback['function'],
':arguments' => serialize($callback['arguments'])
)
);
}
/** // Get results
* Loads callback function $results = $call_vars['results'];
*
* Callback is an associative array with following keys
* - 'function': function name to call
* - 'arguments': additional arguments, that passed to the callback function
*
* @param string $token Token of the request related to callback function
* @return mixed callback function array or null if callback function not exists
* @todo Create some unit tests
*/
protected function loadCallback($token) {
$db = Database::getInstance();
$callback = $db->query(
"SELECT * FROM {requestcallback} WHERE token = :token",
array(':token' => $token),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if (! $callback) {
return null;
}
return array(
'function' => $callback['function'],
'arguments' => unserialize($callback['arguments'])
);
}
/** // Add function results to execution context
* Dispatcher of the functions, provided by the RequestProcessor (or inherited) classes as an external API. $context->storeFunctionResults($function, $results);
*
* All API methods names starts with 'api' prefix.
* It calls before '<eventPrefix>FunctionCall' event triggers.
*
* @param array &$func Function array equals to array, passed to the '<eventPrefix>FunctionCall' event.
* @todo Create some unit tests
*/
protected function processorCall(&$func) {
$method_name = 'api' . ucfirst($func['function']);
if (is_callable(array($this, $method_name))) {
try {
$func['results'] = $this->$method_name($func['arguments']);
} catch(ProcessorException $e) {
$func['results'] = array(
'errorCode' => $e->getCode(),
'errorMessage' => $e->getMessage()
);
}
}
}
/** // Check errorCode
* Sends synchronous request return empty($results['errorCode']);
* }
* @param array $request The 'request' array. See Mibew API for details
* @return mixed response array or boolean false on failure
*/
protected function sendSyncRequest($request) {
trigger_error('Method sendSyncRequest does not implement!', E_USER_WARNING);
}
/** /**
* Sends asynchronous request * Stores callback function
* *
* @param array $request The 'request' array. See Mibew API for details * Callback is an associative array with following keys
* @return boolean true on success or false on failure * - 'function': function name to call.
*/ * - 'arguments': additional arguments, that passed to the callback
protected function sendAsyncRequest($request) { * function.
trigger_error('Method sendAsyncRequest does not implement!', E_USER_WARNING); *
} * @param string $token Request token
* @param array $callback Callback function array
* @todo Create some unit tests
*/
protected function saveCallback($token, $callback)
{
$db = Database::getInstance();
/** $query = "INSERT INTO {requestcallback} ( "
* Sends synchronous responses . "token, function, arguments "
* . ") VALUES ( "
* @param array $responses An array of the 'Request' arrays. See Mibew API for details . ":token, :function, :arguments"
*/ . ")";
protected function sendSyncResponses($responses) {
trigger_error('Method sendSyncResponses does not implement!', E_USER_WARNING);
}
/** $db->query(
* Sends asynchronous responses $query,
* array(
* @param array $responses An array of the 'Request' arrays. See Mibew API for details ':token' => $token,
*/ ':function' => $callback['function'],
protected function sendAsyncResponses($responses) { ':arguments' => serialize($callback['arguments']),
trigger_error('Method sendAsyncResponses does not implement!', E_USER_WARNING); )
} );
}
/** /**
* Additional validation for functions that called via call method * Loads callback function
* *
* If something wrong function should throw an Exception. * Callback is an associative array with following keys
* * - 'function': function name to call.
* @param Array $function A Function array * - 'arguments': additional arguments, that passed to the callback
*/ * function.
protected function checkFunction($function) {} *
* @param string $token Token of the request related to callback function
* @return mixed callback function array or null if callback function not
* exists
* @todo Create some unit tests
*/
protected function loadCallback($token)
{
$db = Database::getInstance();
$callback = $db->query(
"SELECT * FROM {requestcallback} WHERE token = :token",
array(':token' => $token),
array('return_rows' => Database::RETURN_ONE_ROW)
);
if (!$callback) {
return null;
}
/** return array(
* Creates and returns an instance of the \Mibew\API\API class. 'function' => $callback['function'],
* 'arguments' => unserialize($callback['arguments']),
* @return \Mibew\API\API );
*/ }
protected abstract function getMibewAPIInstance();
/**
* Dispatcher of the functions, provided by the RequestProcessor
* (or inherited) classes as an external API.
*
* All API methods names starts with 'api' prefix.
* It calls before '<eventPrefix>FunctionCall' event triggers.
*
* @param array &$func Function array equals to array, passed to the
* '<eventPrefix>FunctionCall' event.
* @todo Create some unit tests
*/
protected function processorCall(&$func)
{
$method_name = 'api' . ucfirst($func['function']);
if (is_callable(array($this, $method_name))) {
try {
$func['results'] = $this->$method_name($func['arguments']);
} catch (ProcessorException $e) {
$func['results'] = array(
'errorCode' => $e->getCode(),
'errorMessage' => $e->getMessage(),
);
}
}
}
/**
* Sends synchronous request
*
* @param array $request The 'request' array. See Mibew API for details
* @return mixed response array or boolean false on failure
*/
protected function sendSyncRequest($request)
{
trigger_error('Method sendSyncRequest does not implement!', E_USER_WARNING);
}
/**
* Sends asynchronous request
*
* @param array $request The 'request' array. See Mibew API for details
* @return boolean true on success or false on failure
*/
protected function sendAsyncRequest($request)
{
trigger_error('Method sendAsyncRequest does not implement!', E_USER_WARNING);
}
/**
* Sends synchronous responses
*
* @param array $responses An array of the 'Request' arrays. See Mibew API
* for details
*/
protected function sendSyncResponses($responses)
{
trigger_error('Method sendSyncResponses does not implement!', E_USER_WARNING);
}
/**
* Sends asynchronous responses
*
* @param array $responses An array of the 'Request' arrays. See Mibew API
* for details
*/
protected function sendAsyncResponses($responses)
{
trigger_error('Method sendAsyncResponses does not implement!', E_USER_WARNING);
}
/**
* Additional validation for functions that called via call method
*
* If something wrong function should throw an Exception.
*
* @param Array $function A Function array
*/
protected function checkFunction($function)
{
}
/**
* Creates and returns an instance of the \Mibew\API\API class.
*
* @return \Mibew\API\API
*/
abstract protected function getMibewAPIInstance();
} }
?>

View File

@ -20,161 +20,165 @@ namespace Mibew;
/** /**
* Encapsulates work with system settings. * Encapsulates work with system settings.
*/ */
Class Settings { class Settings
{
/**
* An instance of Settings class
*
* @var Settings
*/
protected static $instance = null;
/** /**
* An instance of Settings class * Array of settings
* @var Settings *
*/ * @var array
protected static $instance = null; */
protected $settings = array();
/** /**
* Array of settings * Array of settings stored in database
* @var array *
*/ * @var array
protected $settings = array(); */
protected $settingsInDb = array();
/** /**
* Array of settings stored in database * Returns an instance of Settings class
* @var array *
*/ * @return Settings
protected $settingsInDb = array(); */
protected static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
/** return self::$instance;
* Returns an instance of Settings class }
* @return Settings
*/
protected static function getInstance(){
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/** /**
* Settings class constructor. Set default values and load setting from database. * Settings class constructor. Set default values and load setting from
*/ * database.
protected function __construct() { */
// Set default values protected function __construct()
$this->settings = array( {
'dbversion' => 0, // Set default values
'featuresversion' => 0, $this->settings = array(
'title' => 'Your Company', 'dbversion' => 0,
'hosturl' => 'http://mibew.org', 'featuresversion' => 0,
'logo' => '', 'title' => 'Your Company',
'usernamepattern' => '{name}', 'hosturl' => 'http://mibew.org',
'chat_style' => 'default', 'logo' => '',
'invitation_style' => 'default', 'usernamepattern' => '{name}',
'page_style' => 'default', 'chat_style' => 'default',
'chattitle' => 'Live Support', 'invitation_style' => 'default',
'geolink' => 'http://api.hostip.info/get_html.php?ip={ip}', 'page_style' => 'default',
'geolinkparams' => 'width=440,height=100,toolbar=0,scrollbars=0,location=0,status=1,menubar=0,resizable=1', 'chattitle' => 'Live Support',
'max_uploaded_file_size' => 100000, 'geolink' => 'http://api.hostip.info/get_html.php?ip={ip}',
'max_connections_from_one_host' => 10, 'geolinkparams' => 'width=440,height=100,toolbar=0,scrollbars=0,location=0,status=1,menubar=0,resizable=1',
'thread_lifetime' => 600, 'max_uploaded_file_size' => 100000,
'max_connections_from_one_host' => 10,
'thread_lifetime' => 600,
'email' => '', /* inbox for left messages */
'left_messages_locale' => HOME_LOCALE,
'sendmessagekey' => 'center',
'enableban' => '0',
'enablessl' => '0',
'forcessl' => '0',
'usercanchangename' => '1',
'enablegroups' => '0',
'enablegroupsisolation' => '0',
'enablestatistics' => '1',
'enabletracking' => '0',
'enablepresurvey' => '1',
'surveyaskmail' => '0',
'surveyaskgroup' => '1',
'surveyaskmessage' => '0',
'enablepopupnotification' => '0',
'showonlineoperators' => '0',
'enablecaptcha' => '0',
'online_timeout' => 30, /* Timeout (in seconds) when online operator becomes offline */
'updatefrequency_operator' => 2,
'updatefrequency_chat' => 2,
'statistics_aggregation_interval' => 24 * 60 * 60,
'updatefrequency_tracking' => 10,
'visitors_limit' => 20, /* Number of visitors to look over */
'invitation_lifetime' => 60, /* Lifetime for invitation to chat */
'tracking_lifetime' => 600, /* Time to store tracked old visitors' data */
'cron_key' => DEFAULT_CRON_KEY,
// System values are listed below. They cannot be changed via
// administrative interface. Start names for these values from
// underscore sign(_).
// Unix timestamp when cron job ran last time.
'_last_cron_run' => 0,
);
'email' => '', /* inbox for left messages */ // Load values from database
'left_messages_locale' => HOME_LOCALE, $db = Database::getInstance();
'sendmessagekey' => 'center', $rows = $db->query(
"SELECT vckey, vcvalue FROM {chatconfig}",
null,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
'enableban' => '0', foreach ($rows as $row) {
'enablessl' => '0', $name = $row['vckey'];
'forcessl' => '0', $this->settings[$name] = $row['vcvalue'];
'usercanchangename' => '1', $this->settingsInDb[$name] = true;
'enablegroups' => '0', }
'enablegroupsisolation' => '0', }
'enablestatistics' => '1',
'enabletracking' => '0',
'enablepresurvey' => '1',
'surveyaskmail' => '0',
'surveyaskgroup' => '1',
'surveyaskmessage' => '0',
'enablepopupnotification' => '0',
'showonlineoperators' => '0',
'enablecaptcha' => '0',
'online_timeout' => 30, /* Timeout (in seconds) when online operator becomes offline */ /**
'updatefrequency_operator' => 2, * Get setting value.
'updatefrequency_chat' => 2, *
* @param string $name Variable's name
* @return mixed
*/
public static function get($name)
{
$instance = self::getInstance();
'statistics_aggregation_interval' => 24*60*60, return $instance->settings[$name];
}
'updatefrequency_tracking' => 10, /**
'visitors_limit' => 20, /* Number of visitors to look over */ * Set setting value.
'invitation_lifetime' => 60, /* Lifetime for invitation to chat */ *
'tracking_lifetime' => 600, /* Time to store tracked old visitors' data */ * @param string $name Variables's name
* @param mixed $value Variable's value
*/
public static function set($name, $value)
{
$instance = self::getInstance();
$instance->settings[$name] = $value;
}
'cron_key' => DEFAULT_CRON_KEY, /**
* Updates settings in database.
*/
public static function update()
{
$instance = self::getInstance();
$db = Database::getInstance();
foreach ($instance->settings as $key => $value) {
if (!isset($instance->settingsInDb[$key])) {
$db->query(
"INSERT INTO {chatconfig} (vckey) VALUES (?)",
array($key)
);
}
$db->query(
"UPDATE {chatconfig} SET vcvalue=? WHERE vckey=?",
array($value, $key)
);
}
}
// System values are listed below. They cannot be changed via /**
// administrative interface. Start names for these values from * Implementation of destructor
// underscore sign(_). */
public function __destruct()
// Unix timestamp when cron job ran last time. {
'_last_cron_run' => 0 }
);
// Load values from database
$db = Database::getInstance();
$rows = $db->query(
"select vckey,vcvalue from {chatconfig}",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
foreach ($rows as $row) {
$name = $row['vckey'];
$this->settings[$name] = $row['vcvalue'];
$this->settingsInDb[$name] = true;
}
}
/**
* Get setting value.
*
* @param string $name Variable's name
* @return mixed
*/
public static function get($name) {
$instance = self::getInstance();
return $instance->settings[$name];
}
/**
* Set setting value.
*
* @param string $name Variables's name
* @param mixed $value Variable's value
*/
public static function set($name, $value) {
$instance = self::getInstance();
$instance->settings[$name] = $value;
}
/**
* Updates settings in database.
*/
public static function update() {
$instance = self::getInstance();
$db = Database::getInstance();
foreach ($instance->settings as $key => $value) {
if (!isset($instance->settingsInDb[$key])) {
$db->query(
"insert into {chatconfig} (vckey) values (?)",
array($key)
);
}
$db->query(
"update {chatconfig} set vcvalue=? where vckey=?",
array($value, $key)
);
}
}
/**
* Implementation of destructor
*/
public function __destruct() {}
} }
?>

View File

@ -24,146 +24,152 @@ use Mibew\TemplateEngine\ChatTemplateEngine;
/** /**
* Represents a chat style * Represents a chat style
*/ */
class ChatStyle extends Style implements StyleInterface { class ChatStyle extends Style implements StyleInterface
{
/**
* Template engine for chat templates.
*
* @var \Mibew\TemplateEngine\ChatTemplateEngine
*/
protected $templateEngine;
/** /**
* Template engine for chat templates. * Object constructor
* @var \Mibew\TemplateEngine\ChatTemplateEngine *
*/ * @param string $style_name Name of the style
protected $templateEngine; */
public function __construct($style_name)
{
parent::__construct($style_name);
/** $this->templateEngine = new ChatTemplateEngine(
* Object constructor $this->filesPath(),
* $this->name()
* @param string $style_name Name of the style );
*/ }
public function __construct($style_name) {
parent::__construct($style_name);
$this->templateEngine = new ChatTemplateEngine( /**
$this->filesPath(), * Builds base path for style files. This path is relative Mibew root and
$this->name() * does not contain neither leading nor trailing slash.
); *
} * @return string Base path for style files
*/
public function filesPath()
{
return 'styles/dialogs/' . $this->name();
}
/**
* Renders template file to HTML and send it to the output
*
* @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.
*/
public function render($template_name, $data = array())
{
start_html_output();
echo($this->templateEngine->render($template_name, $data));
}
/** /**
* Builds base path for style files. This path is relative Mibew root and * Returns name of the style which shoud be used for the current request.
* does not contain neither leading nor trailing slash. *
* * Result of the method can depends on user role, requested page or any
* @return string Base path for style files * other criteria.
*/ *
public function filesPath() { * @return string Name of a style
return 'styles/dialogs/' . $this->name(); * @throws \RuntimeException
} */
public static function currentStyle()
{
// Ceck if request contains chat style
$style_name = verify_param("style", "/^\w+$/", "");
if (!$style_name) {
// Use the default style
$style_name = self::defaultStyle();
}
/** // Get all style list and make sure that in has at least one style.
* Renders template file to HTML and send it to the output $available_styles = self::availableStyles();
* if (empty($available_styles)) {
* @param string $template_name Name of the template file with neither path throw new \RuntimeException('There are no dialog styles in the system');
* nor extension. }
* @param array $data Associative array of values that should be used for
* substitutions in a template.
*/
public function render($template_name, $data = array()) {
start_html_output();
echo($this->templateEngine->render($template_name, $data));
}
/** // Check if selected style exists. If it does not exist try to fall back
* Returns name of the style which shoud be used for the current request. // to "default". Finally, if there is no appropriate style in the system
* // throw an exception.
* Result of the method can depends on user role, requested page or any if (in_array($style_name, $available_styles)) {
* other criteria. return $style_name;
* } elseif (in_array('default', $available_styles)) {
* @return string Name of a style return 'default';
* @throws \RuntimeException } else {
*/ throw new \RuntimeException('There is no appropriate dialog style in the system');
public static function currentStyle() { }
// Ceck if request contains chat style }
$style_name = verifyparam("style", "/^\w+$/", "");
if (!$style_name) {
// Use the default style
$style_name = self::defaultStyle();
}
// Get all style list and make sure that in has at least one style. /**
$available_styles = self::availableStyles(); * Returns name of the style which is used in the system by default.
if (empty($available_styles)) { *
throw new \RuntimeException('There are no dialog styles in the system'); * @return string Name of a style
} */
public static function defaultStyle()
{
// Load value from system settings
return Settings::get('chat_style');
}
// Check if selected style exists. If it does not exist try to fall back /**
// to "default". Finally, if there is no appropriate style in the system * Sets style which is used in the system by default
// throw an exception. *
if (in_array($style_name, $available_styles)) { * @param string $style_name Name of a style
return $style_name; */
} elseif (in_array('default', $available_styles)) { public static function setDefaultStyle($style_name)
return 'default'; {
} else { Settings::set('chat_style', $style_name);
throw new \RuntimeException('There is no appropriate dialog style in the system'); Settings::update();
} }
}
/** /**
* Returns name of the style which is used in the system by default. * Returns an array which contains names of available styles.
* *
* @return string Name of a style * @param array List of styles names
*/ */
public static function defaultStyle() { public static function availableStyles()
// Load value from system settings {
return Settings::get('chat_style'); $styles_root = MIBEW_FS_ROOT . '/styles/dialogs';
}
/** return self::getStyleList($styles_root);
* Sets style which is used in the system by default }
*
* @param string $style_name Name of a style
*/
public static function setDefaultStyle($style_name) {
Settings::set('chat_style', $style_name);
Settings::update();
}
/** /**
* Returns an array which contains names of available styles. * Returns array of default configurations for concrete style object. This
* * method uses "Template method" design pattern.
* @param array List of styles names *
*/ * @return array Default configurations of the style
public static function availableStyles() { */
$styles_root = MIBEW_FS_ROOT . '/styles/dialogs'; protected function defaultConfigurations()
{
return self::getStyleList($styles_root); return array(
} 'history' => array(
'window_params' => '',
/** ),
* Returns array of default configurations for concrete style object. This 'users' => array(
* method uses "Template method" design pattern. 'thread_tag' => 'div',
* 'visitor_tag' => 'div',
* @return array Default configurations of the style ),
*/ 'tracked' => array(
protected function defaultConfigurations() { 'user_window_params' => '',
return array( 'visitor_window_params' => '',
'history' => array( ),
'window_params' => '' 'invitation' => array(
), 'window_params' => '',
'users' => array( ),
'thread_tag' => 'div', 'ban' => array(
'visitor_tag' => 'div' 'window_params' => '',
), ),
'tracked' => array( 'screenshots' => array(),
'user_window_params' => '', );
'visitor_window_params' => '' }
),
'invitation' => array(
'window_params' => ''
),
'ban' => array(
'window_params' => ''
),
'screenshots' => array()
);
}
} }
?>

View File

@ -23,89 +23,96 @@ use Mibew\Settings;
/** /**
* Represents a style for invitations * Represents a style for invitations
*/ */
class InvitationStyle extends Style implements StyleInterface { class InvitationStyle extends Style implements StyleInterface
/** {
* Builds base path for style files. This path is relative Mibew root and /**
* does not contain neither leading nor trailing slash. * Builds base path for style files. This path is relative Mibew root and
* * does not contain neither leading nor trailing slash.
* @return string Base path for style files *
*/ * @return string Base path for style files
public function filesPath() { */
return 'styles/invitations/' . $this->name(); public function filesPath()
} {
return 'styles/invitations/' . $this->name();
}
/** /**
* Loads configurations of the style. * Loads configurations of the style.
* *
* @return array Style configurations * @return array Style configurations
*/ */
public function configurations() { public function configurations()
return array(); {
} return array();
}
/** /**
* Stub for StyleInterface::render method. * Stub for StyleInterface::render method.
* *
* The method does not contain actual code because inviation styles are not * The method does not contain actual code because inviation styles are not
* renderable now. * renderable now.
*/ */
public function render($template_name, $data = array()) { public function render($template_name, $data = array())
return FALSE; {
} return false;
}
/** /**
* Returns name of the style which shoud be used for the current request. * Returns name of the style which shoud be used for the current request.
* *
* Result of the method can depends on user role, requested page or any * Result of the method can depends on user role, requested page or any
* other criteria. * other criteria.
* *
* @return string Name of a style * @return string Name of a style
*/ */
public static function currentStyle() { public static function currentStyle()
// Just use the default style {
return self::defaultStyle(); // Just use the default style
} return self::defaultStyle();
}
/** /**
* Returns name of the style which is used in the system by default. * Returns name of the style which is used in the system by default.
* *
* @return string Name of a style * @return string Name of a style
*/ */
public static function defaultStyle() { public static function defaultStyle()
// Load value from system settings {
return Settings::get('invitation_style'); // Load value from system settings
} return Settings::get('invitation_style');
}
/** /**
* Sets style which is used in the system by default * Sets style which is used in the system by default
* *
* @param string $style_name Name of a style * @param string $style_name Name of a style
*/ */
public static function setDefaultStyle($style_name) { public static function setDefaultStyle($style_name)
Settings::set('invitation_style', $style_name); {
Settings::update(); Settings::set('invitation_style', $style_name);
} Settings::update();
}
/** /**
* Returns an array which contains names of available styles. * Returns an array which contains names of available styles.
* *
* @param array List of styles names * @param array List of styles names
*/ */
public static function availableStyles() { public static function availableStyles()
$styles_root = MIBEW_FS_ROOT . '/styles/invitations'; {
$styles_root = MIBEW_FS_ROOT . '/styles/invitations';
return self::getStyleList($styles_root); return self::getStyleList($styles_root);
} }
/** /**
* Returns array of default configurations for concrete style object. This * Returns array of default configurations for concrete style object. This
* method uses "Template method" design pattern. * method uses "Template method" design pattern.
* *
* @return array Default configurations of the style * @return array Default configurations of the style
*/ */
protected function defaultConfigurations() { protected function defaultConfigurations()
return array(); {
} return array();
}
} }
?>

View File

@ -23,106 +23,112 @@ use Mibew\Settings;
/** /**
* Represents a style for operator pages * Represents a style for operator pages
*/ */
class PageStyle extends Style implements StyleInterface { class PageStyle extends Style implements StyleInterface
/** {
* Builds base path for style files. This path is relative Mibew root and /**
* does not contain neither leading nor trailing slash. * Builds base path for style files. This path is relative Mibew root and
* * does not contain neither leading nor trailing slash.
* @return string Base path for style files *
*/ * @return string Base path for style files
public function filesPath() { */
return 'styles/pages/' . $this->name(); public function filesPath()
} {
return 'styles/pages/' . $this->name();
}
/** /**
* Renders template file to HTML and send it to the output * Renders template file to HTML and send it to the output
* *
* @param string $template_name Name of the template file with neither path * @param string $template_name Name of the template file with neither path
* nor extension. * nor extension.
* @param array $data Associative array of values that should be used for * @param array $data Associative array of values that should be used for
* substitutions in a template. * substitutions in a template.
*/ */
public function render($template_name, $data = array()) { public function render($template_name, $data = array())
// Add template root value to page variables {
$page['stylepath'] = MIBEW_WEB_ROOT . '/' . $this->filesPath(); // Add template root value to page variables
$page['stylepath'] = MIBEW_WEB_ROOT . '/' . $this->filesPath();
// Prepare to output html // Prepare to output html
start_html_output(); start_html_output();
// Build full view name. Remove '\' and '/' characters form the // Build full view name. Remove '\' and '/' characters form the
// specified view name // specified view name
$full_view_name = MIBEW_FS_ROOT . '/' . $this->filesPath() . '/views/' . $full_view_name = MIBEW_FS_ROOT . '/' . $this->filesPath() . '/views/'
str_replace("/\\", '', $template_name) . '.php'; . str_replace("/\\", '', $template_name) . '.php';
// $page variable is used in included views files, so we need to create // $page variable is used in included views files, so we need to create
// it as an alias of $data argument. // it as an alias of $data argument.
$page = $data; $page = $data;
// Load and execute the view // Load and execute the view
require($full_view_name); require($full_view_name);
} }
/** /**
* Returns name of the style which shoud be used for the current request. * Returns name of the style which shoud be used for the current request.
* *
* Result of the method can depends on user role, requested page or any * Result of the method can depends on user role, requested page or any
* other criteria. * other criteria.
* *
* @return string Name of a style * @return string Name of a style
*/ */
public static function currentStyle() { public static function currentStyle()
// Just use the default style {
return self::defaultStyle(); // Just use the default style
} return self::defaultStyle();
}
/** /**
* Returns name of the style which is used in the system by default. * Returns name of the style which is used in the system by default.
* *
* @return string Name of a style * @return string Name of a style
*/ */
public static function defaultStyle() { public static function defaultStyle()
// Load value from system settings {
return Settings::get('page_style'); // Load value from system settings
} return Settings::get('page_style');
}
/** /**
* Sets style which is used in the system by default * Sets style which is used in the system by default
* *
* @param string $style_name Name of a style * @param string $style_name Name of a style
*/ */
public static function setDefaultStyle($style_name) { public static function setDefaultStyle($style_name)
Settings::set('page_style', $style_name); {
Settings::update(); Settings::set('page_style', $style_name);
} Settings::update();
}
/** /**
* Returns an array which contains names of available styles. * Returns an array which contains names of available styles.
* *
* @param array List of styles names * @param array List of styles names
*/ */
public static function availableStyles() { public static function availableStyles()
$styles_root = MIBEW_FS_ROOT . '/styles/pages'; {
$styles_root = MIBEW_FS_ROOT . '/styles/pages';
return self::getStyleList($styles_root); return self::getStyleList($styles_root);
} }
/** /**
* Returns array of default configurations for concrete style object. This * Returns array of default configurations for concrete style object. This
* method uses "Template method" design pattern. * method uses "Template method" design pattern.
* *
* @return array Default configurations of the style * @return array Default configurations of the style
*/ */
protected function defaultConfigurations() { protected function defaultConfigurations()
return array( {
'chat' => array( return array(
'window_params' => '' 'chat' => array(
), 'window_params' => ''
'mail' => array( ),
'window_params' => '' 'mail' => array(
), 'window_params' => ''
'screenshots' => array() ),
); 'screenshots' => array(),
} );
}
} }
?>

View File

@ -20,117 +20,123 @@ namespace Mibew\Style;
/** /**
* Base class for styles * Base class for styles
*/ */
abstract class Style { abstract class Style
/** {
* Styles configuration array or NULL by default /**
* @var array|NULL * Styles configuration array or NULL by default
*/ *
protected $cachedConfigurations = NULL; * @var array|NULL
*/
protected $cachedConfigurations = null;
/** /**
* This value is used to store name of a style * This value is used to store name of a style
* @var string *
*/ * @var string
protected $styleName; */
protected $styleName;
/** /**
* Contains cached results of the \Mibew\Style\StyleInterface::getStyleList * Contains cached results of the \Mibew\Style\StyleInterface::getStyleList
* method. The lists are keyed by the $root_dir argument of the method. * method. The lists are keyed by the $root_dir argument of the method.
* @var array *
* @see \Mibew\Style\StyleInterface::getStyleList * @var array
*/ * @see \Mibew\Style\StyleInterface::getStyleList
protected static $cachedStyleLists = array(); */
protected static $cachedStyleLists = array();
/** /**
* Object constructor * Object constructor
* *
* @param string $style_name Name of the style * @param string $style_name Name of the style
*/ */
public function __construct($style_name) { public function __construct($style_name)
$this->styleName = $style_name; {
} $this->styleName = $style_name;
}
/** /**
* Returns name of the style related with the object * Returns name of the style related with the object
* *
* @return string Name of the style * @return string Name of the style
*/ */
public function name() { public function name()
return $this->styleName; {
} return $this->styleName;
}
/** /**
* Loads configurations of the style. The results is cached in the class * Loads configurations of the style. The results is cached in the class
* instance. * instance.
* *
* @return array Style configurations * @return array Style configurations
* @throws \RuntimeException * @throws \RuntimeException
*/ */
public function configurations() { public function configurations()
$config_file = MIBEW_FS_ROOT . '/' . $this->filesPath() . '/config.ini'; {
$config_file = MIBEW_FS_ROOT . '/' . $this->filesPath() . '/config.ini';
// Check if configurations already loaded. Do not do the job twice. // Check if configurations already loaded. Do not do the job twice.
if (is_null($this->cachedConfigurations)) { if (is_null($this->cachedConfigurations)) {
// Set empty value for configuration array // Set empty value for configuration array
$this->cachedConfigurations = array(); $this->cachedConfigurations = array();
// Try to read configuration file // Try to read configuration file
if (!is_readable($config_file)) { if (!is_readable($config_file)) {
throw new \RuntimeException('Cannot read configuration file'); throw new \RuntimeException('Cannot read configuration file');
} }
// Load configurations from file, merge it with default configs and // Load configurations from file, merge it with default configs and
// cache the result. // cache the result.
$loaded_config = parse_ini_file($config_file, true); $loaded_config = parse_ini_file($config_file, true);
$default_config = $this->defaultConfigurations(); $default_config = $this->defaultConfigurations();
$this->cachedConfigurations = $loaded_config + $default_config; $this->cachedConfigurations = $loaded_config + $default_config;
} }
return $this->cachedConfigurations; return $this->cachedConfigurations;
} }
/** /**
* Gets names of styles which are located in the $root_dir. * Builds base path for style files. This path is relative Mibew root and
* * does not contain neither leading nor trailing slash.
* @param string $root_dir Root styles directory *
* @return array List of styles' names * @return string Base path for style files
*/ */
protected static function getStyleList($root_dir) { abstract public function filesPath();
// Check if styles list is already stored in the cache
if (!isset(self::$cachedStyleLists[$root_dir])) {
// Build list of styles for the specified root directory.
$style_list = array();
if ($handle = opendir($root_dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/^\w+$/", $file) && is_dir("$root_dir/$file")) {
$style_list[$file] = $file;
}
}
closedir($handle);
}
// Cache the list /**
self::$cachedStyleLists[$root_dir] = $style_list; * Gets names of styles which are located in the $root_dir.
} *
* @param string $root_dir Root styles directory
* @return array List of styles' names
*/
protected static function getStyleList($root_dir)
{
// Check if styles list is already stored in the cache
if (!isset(self::$cachedStyleLists[$root_dir])) {
// Build list of styles for the specified root directory.
$style_list = array();
if ($handle = opendir($root_dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/^\w+$/", $file) && is_dir("$root_dir/$file")) {
$style_list[$file] = $file;
}
}
closedir($handle);
}
return self::$cachedStyleLists[$root_dir]; // Cache the list
} self::$cachedStyleLists[$root_dir] = $style_list;
}
/** return self::$cachedStyleLists[$root_dir];
* Builds base path for style files. This path is relative Mibew root and }
* does not contain neither leading nor trailing slash.
*
* @return string Base path for style files
*/
public abstract function filesPath();
/** /**
* Returns array of default configurations for concrete style object. This * Returns array of default configurations for concrete style object. This
* method uses "Template method" design pattern. * method uses "Template method" design pattern.
* *
* @return array Default configurations of the style * @return array Default configurations of the style
*/ */
protected abstract function defaultConfigurations(); abstract protected function defaultConfigurations();
} }
?>

View File

@ -20,69 +20,69 @@ namespace Mibew\Style;
/** /**
* Determine interface for specific style class. * Determine interface for specific style class.
*/ */
interface StyleInterface { interface StyleInterface
/** {
* Returns name of the style which shoud be used for the current request.
*
* Result of the method can depends on user role, requested page or any
* other criteria.
*
* @return string Name of a style
*/
public static function currentStyle();
/** /**
* Returns name of the style which is used in the system by default. * Returns name of the style which shoud be used for the current request.
* *
* @return string Name of a style * Result of the method can depends on user role, requested page or any
*/ * other criteria.
public static function defaultStyle(); *
* @return string Name of a style
*/
public static function currentStyle();
/** /**
* Sets style which is used in the system by default * Returns name of the style which is used in the system by default.
* *
* @param string $style_name Name of a style * @return string Name of a style
*/ */
public static function setDefaultStyle($style_name); public static function defaultStyle();
/** /**
* Returns an array which contains names of available styles. * Sets style which is used in the system by default
* *
* @param array List of styles names * @param string $style_name Name of a style
*/ */
public static function availableStyles(); public static function setDefaultStyle($style_name);
/** /**
* Builds base path for style files. This URL is relative Mibew root and * Returns an array which contains names of available styles.
* does not contain neither leading nor trailing slash. *
* * @param array List of styles names
* @return string Base path for style files */
*/ public static function availableStyles();
public function filesPath();
/** /**
* Loads and returns configurations of the style. * Builds base path for style files. This URL is relative Mibew root and
* * does not contain neither leading nor trailing slash.
* @param array $name Style's configuration params *
*/ * @return string Base path for style files
public function configurations(); */
public function filesPath();
/** /**
* Returns name of the style related with the object * Loads and returns configurations of the style.
* *
* @return string Name of the style * @param array $name Style's configuration params
*/ */
public function name(); public function configurations();
/** /**
* Renders template file to HTML and send it to the output * Returns name of the style related with the object
* *
* @param string $template_name Name of the template file with neither path * @return string Name of the style
* nor extension. */
* @param array $data Associative array of values that should be used for public function name();
* substitutions in a template.
*/ /**
public function render($template_name, $data = array()); * Renders template file to HTML and send it to the output
*
* @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.
*/
public function render($template_name, $data = array());
} }
?>

View File

@ -20,235 +20,243 @@ namespace Mibew\TemplateEngine;
/** /**
* Simple template engine for chat templates * Simple template engine for chat templates
*/ */
class ChatTemplateEngine { class ChatTemplateEngine
{
/**
* Regular expression for conditional blocks in templates
*/
const IF_REGEXP = "/\\\${(if|ifnot):([\w\.]+)}(.*?)(\\\${else:\\2}.*?)?\\\${endif:\\2}/s";
/**
* Path to teplates relative to MIBEW_FS_ROOT.
* @var string
*/
protected $stylePath;
/** /**
* Regular expression for conditional blocks in templates * Machine name of the templates style.
*/ * @var string
const IF_REGEXP = "/\\\${(if|ifnot):([\w\.]+)}(.*?)(\\\${else:\\2}.*?)?\\\${endif:\\2}/s"; */
protected $styleName;
/** /**
* Path to teplates relative to MIBEW_FS_ROOT. * Data for the currently rendering template. Unfortunately there is no
* @var string * another place to store these data for used chat templates logic.
*/ * @var array
protected $stylePath; */
protected $templateData;
/** /**
* Machine name of the templates style. * Flatten data for the currently rendering template.
* @var string * @var array
*/ */
protected $styleName; protected $flattenTemplateData;
/** /**
* Data for the currently rendering template. Unfortunately there is no * Constructs an instance of the template engine.
* another place to store these data for used chat templates logic. *
* @var array * @param string $style_path Path to the style relative to MIBEW_FS_ROOT.
*/ * @param string $style_name Machine name of the templates style.
protected $templateData; */
public function __construct($style_path, $style_name)
{
$this->stylePath = $style_path;
$this->styleName = $style_name;
}
/** /**
* Flatten data for the currently rendering template. * Renders template and returns HTML for it.
* @var array *
*/ * @param string $template_name Name of a template with neither path nor
protected $flattenTemplateData; * extension.
* @param array $data Data for substitutions.
* @return string Rendered HTML markup.
*/
public function render($template_name, $data)
{
$this->flattenTemplateData = array_flatten_recursive($data);
$this->templateData = $data;
$contents = $this->getTemplateFileContent($template_name);
/** return $this->expandText($contents);
* Constructs an instance of the template engine. }
*
* @param string $style_path Path to the style relative to MIBEW_FS_ROOT.
* @param string $style_name Machine name of the templates style.
*/
public function __construct($style_path, $style_name) {
$this->stylePath = $style_path;
$this->styleName = $style_name;
}
/** /**
* Renders template and returns HTML for it. * Check if condition form conditional construction is true.
* *
* @param string $template_name Name of a template with neither path nor * @param string $condition Condition name. Can be any element name of the
* extension. * template data array.
* @param array $data Data for substitutions. */
* @return string Rendered HTML markup. public function checkCondition($condition)
*/ {
public function render($template_name, $data) { if ($condition == 'errors') {
$this->flattenTemplateData = array_flatten_recursive($data); return !empty($this->templateData['errors'])
$this->templateData = $data; && is_array($this->templateData['errors']);
$contents = $this->getTemplateFileContent($template_name); }
return $this->expandText($contents);
}
/** return !empty($this->flattenTemplateData[$condition]);
* Check if condition form conditional construction is true. }
*
* @param string $condition Condition name. Can be any element name of the
* template data array.
*/
public function checkCondition($condition) {
if ($condition == 'errors') {
return !empty($this->templateData['errors'])
&& is_array($this->templateData['errors']);
}
return !empty($this->flattenTemplateData[$condition]);
}
/** /**
* Process conditional construction. This function is a callback for * Process conditional construction. This function is a callback for
* "preg_replace_callback" function. * "preg_replace_callback" function.
* *
* @param array $matches matches passed from "preg_replace_callback" * @param array $matches matches passed from "preg_replace_callback"
* function. * function.
* @return string One of conditional blocks depending of conditional value. * @return string One of conditional blocks depending of conditional value.
*/ */
public function expandCondition($matches) { public function expandCondition($matches)
$value = $this->checkCondition($matches[2]) ^ ($matches[1] != 'if'); {
$value = $this->checkCondition($matches[2]) ^ ($matches[1] != 'if');
if ($value) { if ($value) {
return preg_replace_callback( return preg_replace_callback(
self::IF_REGEXP, self::IF_REGEXP,
array($this, "expandCondition"), array($this, "expandCondition"),
$matches[3] $matches[3]
); );
} else if (isset($matches[4])) { } elseif (isset($matches[4])) {
return preg_replace_callback( return preg_replace_callback(
self::IF_REGEXP, self::IF_REGEXP,
array($this, "expandCondition"), array($this, "expandCondition"),
substr($matches[4], strpos($matches[4], "}") + 1) substr($matches[4], strpos($matches[4], "}") + 1)
); );
} }
return ""; return "";
} }
/** /**
* Replace variables in template with its values. This function is a * Replace variables in template with its values. This function is a
* callback for "preg_replace_callback" function. * callback for "preg_replace_callback" function.
* *
* @param array $matches matches passed from "preg_replace_callback" * @param array $matches matches passed from "preg_replace_callback"
* function. * function.
* @return string Value of the variable or empty string if the value was not * @return string Value of the variable or empty string if the value was not
* passed in with template data. * passed in with template data.
*/ */
public function expandVar($matches) { public function expandVar($matches)
$prefix = $matches[1]; {
$var = $matches[2]; $prefix = $matches[1];
$var = $matches[2];
if (!$prefix) { if (!$prefix) {
if ($var == 'mibewroot') { if ($var == 'mibewroot') {
return MIBEW_WEB_ROOT; return MIBEW_WEB_ROOT;
} elseif ($var == 'tplroot') { } elseif ($var == 'tplroot') {
return MIBEW_WEB_ROOT . "/" . $this->stylePath; return MIBEW_WEB_ROOT . "/" . $this->stylePath;
} elseif ($var == 'styleid') { } elseif ($var == 'styleid') {
return $this->styleName; return $this->styleName;
} elseif ($var == 'pagination') { } elseif ($var == 'pagination') {
return generate_pagination( return generate_pagination(
MIBEW_WEB_ROOT . '/' . $this->stylePath, MIBEW_WEB_ROOT . '/' . $this->stylePath,
$this->templateData['pagination'] $this->templateData['pagination']
); );
} elseif ($var == 'errors' || $var == 'harderrors') { } elseif ($var == 'errors' || $var == 'harderrors') {
if ( $errors_data_exists = !empty($this->templateData['errors'])
!empty($this->templateData['errors']) && is_array($this->templateData['errors']);
&& is_array($this->templateData['errors']) if ($errors_data_exists) {
) { $result = getlocal("$var.header");
$result = getlocal("$var.header"); foreach ($this->templateData['errors'] as $e) {
foreach ($this->templateData['errors'] as $e) { $result .= getlocal("errors.prefix")
$result .= getlocal("errors.prefix") . $e
. $e . getlocal("errors.suffix");
. getlocal("errors.suffix"); }
} $result .= getlocal("errors.footer");
$result .= getlocal("errors.footer");
return $result;
}
}
} elseif ($prefix == 'msg:' || $prefix == 'msgjs:' || $prefix == 'url:') { return $result;
$message = ''; }
if (strpos($var, ",") !== false) { }
$pos = strpos($var, ","); } elseif ($prefix == 'msg:' || $prefix == 'msgjs:' || $prefix == 'url:') {
$param = substr($var, $pos + 1); $message = '';
$var = substr($var, 0, $pos); if (strpos($var, ",") !== false) {
$message = getlocal2($var, array($this->flattenTemplateData[$param])); $pos = strpos($var, ",");
} else { $param = substr($var, $pos + 1);
$message = getlocal($var); $var = substr($var, 0, $pos);
} $message = getlocal2($var, array($this->flattenTemplateData[$param]));
if ($prefix == 'msgjs:') { } else {
return json_encode($message); $message = getlocal($var);
} }
return $message; if ($prefix == 'msgjs:') {
} else if ($prefix == 'form:') { return json_encode($message);
return form_value($this->templateData, $var); }
} else if ($prefix == 'page:' || $prefix == 'pagejs:') { return $message;
$message = isset($this->flattenTemplateData[$var]) } elseif ($prefix == 'form:') {
? $this->flattenTemplateData[$var] return form_value($this->templateData, $var);
: ""; } elseif ($prefix == 'page:' || $prefix == 'pagejs:') {
return ($prefix == 'pagejs:') ? json_encode($message) : $message; $message = isset($this->flattenTemplateData[$var])
} else if ($prefix == 'if:' || $prefix == 'else:' || $prefix == 'endif:' || $prefix == 'ifnot:') { ? $this->flattenTemplateData[$var]
return "<!-- wrong $prefix:$var -->"; : "";
}
return ""; return ($prefix == 'pagejs:') ? json_encode($message) : $message;
} } elseif ($prefix == 'if:' || $prefix == 'else:' || $prefix == 'endif:' || $prefix == 'ifnot:') {
return "<!-- wrong $prefix:$var -->";
}
/** return "";
* Process "include" control structure. This function is a callback for }
* "preg_replace_callback" function.
*
* @param array $matches matches passed from "preg_replace_callback"
* function.
* @return string Contents of including file
*/
public function expandInclude($matches) {
$template_name = $matches[1];
return $this->getTemplateFileContent($template_name);
}
/** /**
* Converts all control structures to markup. * Process "include" control structure. This function is a callback for
* * "preg_replace_callback" function.
* @param string $text Source text *
* @return string Markup with no control structures * @param array $matches matches passed from "preg_replace_callback"
*/ * function.
public function expandText($text) { * @return string Contents of including file
$text = preg_replace_callback( */
"/\\\${include:([\w\.]+)}/", public function expandInclude($matches)
array($this, "expandInclude"), {
$text $template_name = $matches[1];
);
$text = preg_replace_callback( return $this->getTemplateFileContent($template_name);
self::IF_REGEXP, }
array($this, "expandCondition"),
$text
);
return preg_replace_callback( /**
"/\\\${(\w+:)?([\w\.,]+)}/", * Converts all control structures to markup.
array($this, "expandVar"), *
$text * @param string $text Source text
); * @return string Markup with no control structures
} */
public function expandText($text)
{
$text = preg_replace_callback(
"/\\\${include:([\w\.]+)}/",
array($this, "expandInclude"),
$text
);
/** $text = preg_replace_callback(
* Loads content of a template file. self::IF_REGEXP,
* array($this, "expandCondition"),
* @param string $template_name Name of a template file to load. $text
* @return string Template file's content. );
*
* @throws \RuntimeException If there is no such template file or the file
* is not readable.
*/
protected function getTemplateFileContent($template_name) {
$full_file_path = MIBEW_FS_ROOT . '/' . $this->stylePath .
'/templates/' . $template_name . '.tpl';
if (!is_readable($full_file_path)) { return preg_replace_callback(
throw new \RuntimeException( "/\\\${(\w+:)?([\w\.,]+)}/",
'Cannot load template file: "' . $full_file_path . '"' array($this, "expandVar"),
); $text
} );
}
return file_get_contents($full_file_path); /**
} * Loads content of a template file.
*
* @param string $template_name Name of a template file to load.
* @return string Template file's content.
*
* @throws \RuntimeException If there is no such template file or the file
* is not readable.
*/
protected function getTemplateFileContent($template_name)
{
$full_file_path = MIBEW_FS_ROOT . '/' . $this->stylePath
. '/templates/' . $template_name . '.tpl';
if (!is_readable($full_file_path)) {
throw new \RuntimeException(
'Cannot load template file: "' . $full_file_path . '"'
);
}
return file_get_contents($full_file_path);
}
} }
?>

File diff suppressed because it is too large Load Diff

View File

@ -17,23 +17,23 @@
/** /**
* Autoloader for classes which implements PSR-0 standard. * Autoloader for classes which implements PSR-0 standard.
*
* @param string $class_name Fully qualified name of the class * @param string $class_name Fully qualified name of the class
*/ */
function class_autoload($class_name) { function class_autoload($class_name)
$base_dir = MIBEW_FS_ROOT . DIRECTORY_SEPARATOR . 'libs' . {
DIRECTORY_SEPARATOR . 'classes'; $base_dir = MIBEW_FS_ROOT . DIRECTORY_SEPARATOR . 'libs' .
DIRECTORY_SEPARATOR . 'classes';
$class_name = ltrim($class_name, '\\'); $class_name = ltrim($class_name, '\\');
$file_name = ''; $file_name = '';
$namespace = ''; $namespace = '';
if ($last_ns_pos = strrpos($class_name, '\\')) { if ($last_ns_pos = strrpos($class_name, '\\')) {
$namespace = substr($class_name, 0, $last_ns_pos); $namespace = substr($class_name, 0, $last_ns_pos);
$class_name = substr($class_name, $last_ns_pos + 1); $class_name = substr($class_name, $last_ns_pos + 1);
$file_name = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; $file_name = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
} }
$file_name .= str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php'; $file_name .= str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
require $base_dir . DIRECTORY_SEPARATOR . $file_name; require $base_dir . DIRECTORY_SEPARATOR . $file_name;
} }
?>

View File

@ -20,13 +20,13 @@
* *
* @param string $file Path to Configuration file * @param string $file Path to Configuration file
* @return boolean|array Array of configurations or boolean false if file can * @return boolean|array Array of configurations or boolean false if file can
* not be read. * not be read.
*/ */
function read_config_file($file) { function read_config_file($file)
if (! is_readable($file)) { {
return false; if (!is_readable($file)) {
} return false;
return parse_ini_file($file, true); }
}
?> return parse_ini_file($file, true);
}

View File

@ -34,15 +34,15 @@ define('FEATURES_VERSION', '2.0');
* Prefix for session variables. * Prefix for session variables.
* Provide an ability to instal several mibew instances on one server. * Provide an ability to instal several mibew instances on one server.
*/ */
define('SESSION_PREFIX', md5($mysqlhost.'##'.$mysqldb.'##'.$mysqlprefix) . '_'); define('SESSION_PREFIX', md5($mysqlhost . '##' . $mysqldb . '##' . $mysqlprefix) . '_');
/** /**
* Default value for cron security key. * Default value for cron security key.
* Another value can be set at operator/settings.php page. * Another value can be set at operator/settings.php page.
*/ */
define('DEFAULT_CRON_KEY', md5( define('DEFAULT_CRON_KEY', md5(
$mysqlhost . '##' . $mysqldb . '##' . $mysqllogin. '##' . $mysqlhost . '##' . $mysqldb . '##' . $mysqllogin . '##'
$mysqlpass . '##' . $mysqlprefix . '##' . $mysqlpass . '##' . $mysqlprefix . '##'
)); ));
/** /**
@ -54,5 +54,3 @@ define('VISITOR_COOKIE_NAME', 'MIBEW_VisitorID');
* Internal system encoding * Internal system encoding
*/ */
define('MIBEW_ENCODING', $mibew_encoding); define('MIBEW_ENCODING', $mibew_encoding);
?>

View File

@ -16,36 +16,34 @@
*/ */
$_utf8win1251 = array( $_utf8win1251 = array(
"\xD0\x90" => "\xC0", "\xD0\x91" => "\xC1", "\xD0\x92" => "\xC2", "\xD0\x93" => "\xC3", "\xD0\x94" => "\xC4", "\xD0\x90" => "\xC0", "\xD0\x91" => "\xC1", "\xD0\x92" => "\xC2", "\xD0\x93" => "\xC3", "\xD0\x94" => "\xC4",
"\xD0\x95" => "\xC5", "\xD0\x81" => "\xA8", "\xD0\x96" => "\xC6", "\xD0\x97" => "\xC7", "\xD0\x98" => "\xC8", "\xD0\x95" => "\xC5", "\xD0\x81" => "\xA8", "\xD0\x96" => "\xC6", "\xD0\x97" => "\xC7", "\xD0\x98" => "\xC8",
"\xD0\x99" => "\xC9", "\xD0\x9A" => "\xCA", "\xD0\x9B" => "\xCB", "\xD0\x9C" => "\xCC", "\xD0\x9D" => "\xCD", "\xD0\x99" => "\xC9", "\xD0\x9A" => "\xCA", "\xD0\x9B" => "\xCB", "\xD0\x9C" => "\xCC", "\xD0\x9D" => "\xCD",
"\xD0\x9E" => "\xCE", "\xD0\x9F" => "\xCF", "\xD0\xA0" => "\xD0", "\xD0\xA1" => "\xD1", "\xD0\xA2" => "\xD2", "\xD0\x9E" => "\xCE", "\xD0\x9F" => "\xCF", "\xD0\xA0" => "\xD0", "\xD0\xA1" => "\xD1", "\xD0\xA2" => "\xD2",
"\xD0\xA3" => "\xD3", "\xD0\xA4" => "\xD4", "\xD0\xA5" => "\xD5", "\xD0\xA6" => "\xD6", "\xD0\xA7" => "\xD7", "\xD0\xA3" => "\xD3", "\xD0\xA4" => "\xD4", "\xD0\xA5" => "\xD5", "\xD0\xA6" => "\xD6", "\xD0\xA7" => "\xD7",
"\xD0\xA8" => "\xD8", "\xD0\xA9" => "\xD9", "\xD0\xAA" => "\xDA", "\xD0\xAB" => "\xDB", "\xD0\xAC" => "\xDC", "\xD0\xA8" => "\xD8", "\xD0\xA9" => "\xD9", "\xD0\xAA" => "\xDA", "\xD0\xAB" => "\xDB", "\xD0\xAC" => "\xDC",
"\xD0\xAD" => "\xDD", "\xD0\xAE" => "\xDE", "\xD0\xAF" => "\xDF", "\xD0\x87" => "\xAF", "\xD0\x86" => "\xB2", "\xD0\xAD" => "\xDD", "\xD0\xAE" => "\xDE", "\xD0\xAF" => "\xDF", "\xD0\x87" => "\xAF", "\xD0\x86" => "\xB2",
"\xD0\x84" => "\xAA", "\xD0\x8E" => "\xA1", "\xD0\xB0" => "\xE0", "\xD0\xB1" => "\xE1", "\xD0\xB2" => "\xE2", "\xD0\x84" => "\xAA", "\xD0\x8E" => "\xA1", "\xD0\xB0" => "\xE0", "\xD0\xB1" => "\xE1", "\xD0\xB2" => "\xE2",
"\xD0\xB3" => "\xE3", "\xD0\xB4" => "\xE4", "\xD0\xB5" => "\xE5", "\xD1\x91" => "\xB8", "\xD0\xB6" => "\xE6", "\xD0\xB3" => "\xE3", "\xD0\xB4" => "\xE4", "\xD0\xB5" => "\xE5", "\xD1\x91" => "\xB8", "\xD0\xB6" => "\xE6",
"\xD0\xB7" => "\xE7", "\xD0\xB8" => "\xE8", "\xD0\xB9" => "\xE9", "\xD0\xBA" => "\xEA", "\xD0\xBB" => "\xEB", "\xD0\xB7" => "\xE7", "\xD0\xB8" => "\xE8", "\xD0\xB9" => "\xE9", "\xD0\xBA" => "\xEA", "\xD0\xBB" => "\xEB",
"\xD0\xBC" => "\xEC", "\xD0\xBD" => "\xED", "\xD0\xBE" => "\xEE", "\xD0\xBF" => "\xEF", "\xD1\x80" => "\xF0", "\xD0\xBC" => "\xEC", "\xD0\xBD" => "\xED", "\xD0\xBE" => "\xEE", "\xD0\xBF" => "\xEF", "\xD1\x80" => "\xF0",
"\xD1\x81" => "\xF1", "\xD1\x82" => "\xF2", "\xD1\x83" => "\xF3", "\xD1\x84" => "\xF4", "\xD1\x85" => "\xF5", "\xD1\x81" => "\xF1", "\xD1\x82" => "\xF2", "\xD1\x83" => "\xF3", "\xD1\x84" => "\xF4", "\xD1\x85" => "\xF5",
"\xD1\x86" => "\xF6", "\xD1\x87" => "\xF7", "\xD1\x88" => "\xF8", "\xD1\x89" => "\xF9", "\xD1\x8A" => "\xFA", "\xD1\x86" => "\xF6", "\xD1\x87" => "\xF7", "\xD1\x88" => "\xF8", "\xD1\x89" => "\xF9", "\xD1\x8A" => "\xFA",
"\xD1\x8B" => "\xFB", "\xD1\x8C" => "\xFC", "\xD1\x8D" => "\xFD", "\xD1\x8E" => "\xFE", "\xD1\x8F" => "\xFF", "\xD1\x8B" => "\xFB", "\xD1\x8C" => "\xFC", "\xD1\x8D" => "\xFD", "\xD1\x8E" => "\xFE", "\xD1\x8F" => "\xFF",
"\xD1\x96" => "\xB3", "\xD1\x97" => "\xBF", "\xD1\x94" => "\xBA", "\xD1\x9E" => "\xA2"); "\xD1\x96" => "\xB3", "\xD1\x97" => "\xBF", "\xD1\x94" => "\xBA", "\xD1\x9E" => "\xA2");
$_win1251utf8 = array( $_win1251utf8 = array(
"\xC0" => "\xD0\x90", "\xC1" => "\xD0\x91", "\xC2" => "\xD0\x92", "\xC3" => "\xD0\x93", "\xC4" => "\xD0\x94", "\xC0" => "\xD0\x90", "\xC1" => "\xD0\x91", "\xC2" => "\xD0\x92", "\xC3" => "\xD0\x93", "\xC4" => "\xD0\x94",
"\xC5" => "\xD0\x95", "\xA8" => "\xD0\x81", "\xC6" => "\xD0\x96", "\xC7" => "\xD0\x97", "\xC8" => "\xD0\x98", "\xC5" => "\xD0\x95", "\xA8" => "\xD0\x81", "\xC6" => "\xD0\x96", "\xC7" => "\xD0\x97", "\xC8" => "\xD0\x98",
"\xC9" => "\xD0\x99", "\xCA" => "\xD0\x9A", "\xCB" => "\xD0\x9B", "\xCC" => "\xD0\x9C", "\xCD" => "\xD0\x9D", "\xC9" => "\xD0\x99", "\xCA" => "\xD0\x9A", "\xCB" => "\xD0\x9B", "\xCC" => "\xD0\x9C", "\xCD" => "\xD0\x9D",
"\xCE" => "\xD0\x9E", "\xCF" => "\xD0\x9F", "\xD0" => "\xD0\xA0", "\xD1" => "\xD0\xA1", "\xD2" => "\xD0\xA2", "\xCE" => "\xD0\x9E", "\xCF" => "\xD0\x9F", "\xD0" => "\xD0\xA0", "\xD1" => "\xD0\xA1", "\xD2" => "\xD0\xA2",
"\xD3" => "\xD0\xA3", "\xD4" => "\xD0\xA4", "\xD5" => "\xD0\xA5", "\xD6" => "\xD0\xA6", "\xD7" => "\xD0\xA7", "\xD3" => "\xD0\xA3", "\xD4" => "\xD0\xA4", "\xD5" => "\xD0\xA5", "\xD6" => "\xD0\xA6", "\xD7" => "\xD0\xA7",
"\xD8" => "\xD0\xA8", "\xD9" => "\xD0\xA9", "\xDA" => "\xD0\xAA", "\xDB" => "\xD0\xAB", "\xDC" => "\xD0\xAC", "\xD8" => "\xD0\xA8", "\xD9" => "\xD0\xA9", "\xDA" => "\xD0\xAA", "\xDB" => "\xD0\xAB", "\xDC" => "\xD0\xAC",
"\xDD" => "\xD0\xAD", "\xDE" => "\xD0\xAE", "\xDF" => "\xD0\xAF", "\xAF" => "\xD0\x87", "\xB2" => "\xD0\x86", "\xDD" => "\xD0\xAD", "\xDE" => "\xD0\xAE", "\xDF" => "\xD0\xAF", "\xAF" => "\xD0\x87", "\xB2" => "\xD0\x86",
"\xAA" => "\xD0\x84", "\xA1" => "\xD0\x8E", "\xE0" => "\xD0\xB0", "\xE1" => "\xD0\xB1", "\xE2" => "\xD0\xB2", "\xAA" => "\xD0\x84", "\xA1" => "\xD0\x8E", "\xE0" => "\xD0\xB0", "\xE1" => "\xD0\xB1", "\xE2" => "\xD0\xB2",
"\xE3" => "\xD0\xB3", "\xE4" => "\xD0\xB4", "\xE5" => "\xD0\xB5", "\xB8" => "\xD1\x91", "\xE6" => "\xD0\xB6", "\xE3" => "\xD0\xB3", "\xE4" => "\xD0\xB4", "\xE5" => "\xD0\xB5", "\xB8" => "\xD1\x91", "\xE6" => "\xD0\xB6",
"\xE7" => "\xD0\xB7", "\xE8" => "\xD0\xB8", "\xE9" => "\xD0\xB9", "\xEA" => "\xD0\xBA", "\xEB" => "\xD0\xBB", "\xE7" => "\xD0\xB7", "\xE8" => "\xD0\xB8", "\xE9" => "\xD0\xB9", "\xEA" => "\xD0\xBA", "\xEB" => "\xD0\xBB",
"\xEC" => "\xD0\xBC", "\xED" => "\xD0\xBD", "\xEE" => "\xD0\xBE", "\xEF" => "\xD0\xBF", "\xF0" => "\xD1\x80", "\xEC" => "\xD0\xBC", "\xED" => "\xD0\xBD", "\xEE" => "\xD0\xBE", "\xEF" => "\xD0\xBF", "\xF0" => "\xD1\x80",
"\xF1" => "\xD1\x81", "\xF2" => "\xD1\x82", "\xF3" => "\xD1\x83", "\xF4" => "\xD1\x84", "\xF5" => "\xD1\x85", "\xF1" => "\xD1\x81", "\xF2" => "\xD1\x82", "\xF3" => "\xD1\x83", "\xF4" => "\xD1\x84", "\xF5" => "\xD1\x85",
"\xF6" => "\xD1\x86", "\xF7" => "\xD1\x87", "\xF8" => "\xD1\x88", "\xF9" => "\xD1\x89", "\xFA" => "\xD1\x8A", "\xF6" => "\xD1\x86", "\xF7" => "\xD1\x87", "\xF8" => "\xD1\x88", "\xF9" => "\xD1\x89", "\xFA" => "\xD1\x8A",
"\xFB" => "\xD1\x8B", "\xFC" => "\xD1\x8C", "\xFD" => "\xD1\x8D", "\xFE" => "\xD1\x8E", "\xFF" => "\xD1\x8F", "\xFB" => "\xD1\x8B", "\xFC" => "\xD1\x8C", "\xFD" => "\xD1\x8D", "\xFE" => "\xD1\x8E", "\xFF" => "\xD1\x8F",
"\xB3" => "\xD1\x96", "\xBF" => "\xD1\x97", "\xBA" => "\xD1\x94", "\xA2" => "\xD1\x9E"); "\xB3" => "\xD1\x96", "\xBF" => "\xD1\x97", "\xBA" => "\xD1\x94", "\xA2" => "\xD1\x9E");
?>

View File

@ -16,47 +16,45 @@
*/ */
/* authorization token check for CSRF attack */ /* authorization token check for CSRF attack */
function csrfchecktoken() function csrf_check_token()
{ {
setcsrftoken(); set_csrf_token();
// check the turing code for post requests and del requests // Check the turing code for post requests and del requests
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if token match // If token match
if (!isset($_POST['csrf_token']) || ($_POST['csrf_token'] != $_SESSION['csrf_token'])) { if (!isset($_POST['csrf_token']) || ($_POST['csrf_token'] != $_SESSION['csrf_token'])) {
die("CSRF failure");
die("CSRF failure"); }
} } elseif (isset($_GET['act'])) {
} else if (isset($_GET['act'])) { if (($_GET['act'] == 'del' || $_GET['act'] == 'delete') && $_GET['csrf_token'] != $_SESSION['csrf_token']) {
if (($_GET['act'] == 'del' || $_GET['act'] == 'delete') && $_GET['csrf_token'] != $_SESSION['csrf_token']) { die("CSRF failure");
}
die("CSRF failure"); }
}
}
} }
/* print csrf token as a hidden field*/ /* print csrf token as a hidden field */
function print_csrf_token_input() function print_csrf_token_input()
{ {
setcsrftoken(); set_csrf_token();
echo "<input name='csrf_token' type='hidden' value='" . $_SESSION['csrf_token'] . "' />"; echo "<input name='csrf_token' type='hidden' value='" . $_SESSION['csrf_token'] . "' />";
} }
/* print csrf token in url format */ /* print csrf token in url format */
function print_csrf_token_in_url() function print_csrf_token_in_url()
{ {
setcsrftoken(); set_csrf_token();
echo "&amp;csrf_token=" . $_SESSION['csrf_token']; echo "&amp;csrf_token=" . $_SESSION['csrf_token'];
} }
/* set csrf token */ /* set csrf token */
function setcsrftoken() function set_csrf_token()
{ {
if (!isset($_SESSION['csrf_token'])) { if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = sha1(session_id() . (function_exists('openssl_random_pseudo_bytes') ? openssl_random_pseudo_bytes(32) : (time() + microtime()) . mt_rand(0, 99999999))); $_SESSION['csrf_token'] = sha1(session_id() . (function_exists('openssl_random_pseudo_bytes')
} ? openssl_random_pseudo_bytes(32)
: (time() + microtime()) . mt_rand(0, 99999999)));
}
} }
?>

View File

@ -15,71 +15,72 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php');
function date_diff_to_text($seconds) function date_diff_to_text($seconds)
{ {
$minutes = div($seconds, 60); $minutes = div($seconds, 60);
$seconds = $seconds % 60; $seconds = $seconds % 60;
if ($minutes < 60) { if ($minutes < 60) {
return sprintf("%02d:%02d", $minutes, $seconds); return sprintf("%02d:%02d", $minutes, $seconds);
} else { } else {
$hours = div($minutes, 60); $hours = div($minutes, 60);
$minutes = $minutes % 60; $minutes = $minutes % 60;
return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
} return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
}
} }
function get_month_selection($fromtime, $totime) function get_month_selection($from_time, $to_time)
{ {
$start = getdate($fromtime); $start = getdate($from_time);
$month = $start['mon']; $month = $start['mon'];
$year = $start['year']; $year = $start['year'];
$result = array(); $result = array();
do { do {
$current = mktime(0, 0, 0, $month, 1, $year); $current = mktime(0, 0, 0, $month, 1, $year);
$result[date("m.y", $current)] = strftime("%B, %Y", $current); $result[date("m.y", $current)] = strftime("%B, %Y", $current);
$month++; $month++;
if ($month > 12) { if ($month > 12) {
$month = 1; $month = 1;
$year++; $year++;
} }
} while ($current < $totime); } while ($current < $to_time);
return $result;
return $result;
} }
function get_form_date($day, $month) function get_form_date($day, $month)
{ {
if (preg_match('/^(\d{2}).(\d{2})$/', $month, $matches)) { if (preg_match('/^(\d{2}).(\d{2})$/', $month, $matches)) {
return mktime(0, 0, 0, $matches[1], $day, $matches[2]); return mktime(0, 0, 0, $matches[1], $day, $matches[2]);
} }
return 0;
return 0;
} }
function set_form_date($utime, $prefix) { function set_form_date($utime, $prefix)
return array( {
"form${prefix}day" => date("d", $utime), return array(
"form${prefix}month" => date("m.y", $utime) "form${prefix}day" => date("d", $utime),
); "form${prefix}month" => date("m.y", $utime),
);
} }
function date_to_text($unixtime) function date_to_text($unixtime)
{ {
if ($unixtime < 60 * 60 * 24 * 30) if ($unixtime < 60 * 60 * 24 * 30) {
return getlocal("time.never"); return getlocal("time.never");
}
$then = getdate($unixtime); $then = getdate($unixtime);
$now = getdate(); $now = getdate();
if ($then['yday'] == $now['yday'] && $then['year'] == $now['year']) { if ($then['yday'] == $now['yday'] && $then['year'] == $now['year']) {
$date_format = getlocal("time.today.at"); $date_format = getlocal("time.today.at");
} else if (($then['yday'] + 1) == $now['yday'] && $then['year'] == $now['year']) { } elseif (($then['yday'] + 1) == $now['yday'] && $then['year'] == $now['year']) {
$date_format = getlocal("time.yesterday.at"); $date_format = getlocal("time.yesterday.at");
} else { } else {
$date_format = getlocal("time.dateformat"); $date_format = getlocal("time.dateformat");
} }
return strftime($date_format . " " . getlocal("time.timeformat"), $unixtime); return strftime($date_format . " " . getlocal("time.timeformat"), $unixtime);
} }
?>

View File

@ -19,47 +19,52 @@
* Returns properly prepared value of a form variable. * Returns properly prepared value of a form variable.
* *
* @param array $page The page array. All form variables are prefixed with * @param array $page The page array. All form variables are prefixed with
* "form" string. * "form" string.
* @param string $name Form variable name. * @param string $name Form variable name.
* @return string Value of a form variable. * @return string Value of a form variable.
*/ */
function form_value($page, $name) { function form_value($page, $name)
if (!empty($page) && isset($page["form$name"])) {
return htmlspecialchars($page["form$name"]); if (!empty($page) && isset($page["form$name"])) {
return ""; return htmlspecialchars($page["form$name"]);
}
return "";
} }
/** /**
* Checks if a form variable is true. * Checks if a form variable is true.
* *
* @param array $page The page array. All form variables are prefixed with * @param array $page The page array. All form variables are prefixed with
* "form" string. * "form" string.
* @param string $name Form variable name. * @param string $name Form variable name.
* @return boolean Returns TRUE only if specified form variable is set, has boolean type * @return boolean Returns TRUE only if specified form variable is set, has
* and equals to TRUE. In all other cases returns FALSE. * boolean type and equals to TRUE. In all other cases returns FALSE.
*/ */
function form_value_cb($page, $name) { function form_value_cb($page, $name)
if (!empty($page) && isset($page["form$name"])) {
return $page["form$name"] === true; if (!empty($page) && isset($page["form$name"])) {
return false; return $page["form$name"] === true;
} }
return false;
}
/** /**
* Checks if form variable is array and has element with specified key. * Checks if form variable is array and has element with specified key.
* *
* @param array $page The page array. All form variables are prefixed with * @param array $page The page array. All form variables are prefixed with
* "form" string. * "form" string.
* @param string $name Form variable name. * @param string $name Form variable name.
* @param string $key Key of the element to check. * @param string $key Key of the element to check.
* @return boolean Returns TRUE only if specified form variable is set, is an * @return boolean Returns TRUE only if specified form variable is set, is an
* array has element with the specified key. In all other cases returns FALSE. * array has element with the specified key. In all other cases returns FALSE.
*/ */
function form_value_mb($page, $name, $key) { function form_value_mb($page, $name, $key)
if (!empty($page) && isset($page["form$name"]) && is_array($page["form$name"])) { {
return in_array($key, $page["form$name"]); if (!empty($page) && isset($page["form$name"]) && is_array($page["form$name"])) {
} return in_array($key, $page["form$name"]);
return false; }
}
?> return false;
}

View File

@ -18,10 +18,6 @@
// Import namespaces and classes of the core // Import namespaces and classes of the core
use Mibew\PluginManager; use Mibew\PluginManager;
// Initialize libraries
require_once(MIBEW_FS_ROOT.'/libs/common/converter.php');
require_once(MIBEW_FS_ROOT.'/libs/common/verification.php');
/** /**
* Name for the cookie to store locale code in use * Name for the cookie to store locale code in use
*/ */
@ -33,13 +29,19 @@ define('LOCALE_COOKIE_NAME', 'mibew_locale');
* Verified value of the $default_locale configuration parameter (see * Verified value of the $default_locale configuration parameter (see
* "libs/default_config.php" for details) * "libs/default_config.php" for details)
*/ */
define('DEFAULT_LOCALE', locale_pattern_check($default_locale) && locale_exists($default_locale) ? $default_locale : 'en'); define(
'DEFAULT_LOCALE',
locale_pattern_check($default_locale) && locale_exists($default_locale) ? $default_locale : 'en'
);
/** /**
* Verified value of the $home_locale configuration parameter (see * Verified value of the $home_locale configuration parameter (see
* "libs/default_config.php" for details) * "libs/default_config.php" for details)
*/ */
define('HOME_LOCALE', locale_pattern_check($home_locale) && locale_exists($home_locale) ? $home_locale : 'en'); define(
'HOME_LOCALE',
locale_pattern_check($home_locale) && locale_exists($home_locale) ? $home_locale : 'en'
);
/** /**
* Code of the current system locale * Code of the current system locale
@ -48,105 +50,123 @@ define('CURRENT_LOCALE', get_locale());
function myiconv($in_enc, $out_enc, $string) function myiconv($in_enc, $out_enc, $string)
{ {
global $_utf8win1251, $_win1251utf8; global $_utf8win1251, $_win1251utf8;
if ($in_enc == $out_enc) { if ($in_enc == $out_enc) {
return $string; return $string;
} }
if (function_exists('iconv')) { if (function_exists('iconv')) {
$converted = @iconv($in_enc, $out_enc, $string); $converted = @iconv($in_enc, $out_enc, $string);
if ($converted !== FALSE) { if ($converted !== false) {
return $converted; return $converted;
} }
} }
if ($in_enc == "cp1251" && $out_enc == "utf-8") if ($in_enc == "cp1251" && $out_enc == "utf-8") {
return strtr($string, $_win1251utf8); return strtr($string, $_win1251utf8);
if ($in_enc == "utf-8" && $out_enc == "cp1251") }
return strtr($string, $_utf8win1251); if ($in_enc == "utf-8" && $out_enc == "cp1251") {
return strtr($string, $_utf8win1251);
}
return $string; // do not know how to convert return $string; // do not know how to convert
} }
function locale_exists($locale) function locale_exists($locale)
{ {
return file_exists(MIBEW_FS_ROOT."/locales/$locale/properties"); return file_exists(MIBEW_FS_ROOT . "/locales/$locale/properties");
} }
function locale_pattern_check($locale) function locale_pattern_check($locale)
{ {
$locale_pattern = "/^[\w-]{2,5}$/"; $locale_pattern = "/^[\w-]{2,5}$/";
return preg_match($locale_pattern, $locale) && $locale != 'names';
return preg_match($locale_pattern, $locale) && $locale != 'names';
} }
function get_available_locales() function get_available_locales()
{ {
$list = array(); $list = array();
$folder = MIBEW_FS_ROOT.'/locales'; $folder = MIBEW_FS_ROOT . '/locales';
if ($handle = opendir($folder)) { if ($handle = opendir($folder)) {
while (false !== ($file = readdir($handle))) { while (false !== ($file = readdir($handle))) {
if (locale_pattern_check($file) && is_dir("$folder/$file")) { if (locale_pattern_check($file) && is_dir("$folder/$file")) {
$list[] = $file; $list[] = $file;
} }
} }
closedir($handle); closedir($handle);
} }
sort($list); sort($list);
return $list;
return $list;
} }
function get_user_locale() function get_user_locale()
{ {
if (isset($_COOKIE[LOCALE_COOKIE_NAME])) { if (isset($_COOKIE[LOCALE_COOKIE_NAME])) {
$requested_lang = $_COOKIE[LOCALE_COOKIE_NAME]; $requested_lang = $_COOKIE[LOCALE_COOKIE_NAME];
if (locale_pattern_check($requested_lang) && locale_exists($requested_lang)) if (locale_pattern_check($requested_lang) && locale_exists($requested_lang)) {
return $requested_lang; return $requested_lang;
} }
}
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$requested_langs = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']); $requested_langs = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($requested_langs as $requested_lang) { foreach ($requested_langs as $requested_lang) {
if (strlen($requested_lang) > 2) if (strlen($requested_lang) > 2) {
$requested_lang = substr($requested_lang, 0, 2); $requested_lang = substr($requested_lang, 0, 2);
}
if (locale_pattern_check($requested_lang) && locale_exists($requested_lang)) if (locale_pattern_check($requested_lang) && locale_exists($requested_lang)) {
return $requested_lang; return $requested_lang;
} }
} }
}
if (locale_pattern_check(DEFAULT_LOCALE) && locale_exists(DEFAULT_LOCALE)) if (locale_pattern_check(DEFAULT_LOCALE) && locale_exists(DEFAULT_LOCALE)) {
return DEFAULT_LOCALE; return DEFAULT_LOCALE;
}
return 'en'; return 'en';
} }
function get_locale() function get_locale()
{ {
$locale = verifyparam("locale", "/./", ""); $locale = verify_param("locale", "/./", "");
if ($locale && locale_pattern_check($locale) && locale_exists($locale)) { // Check if locale code passed in as a param is valid
$_SESSION['locale'] = $locale; $locale_param_valid = $locale
} && locale_pattern_check($locale)
else if (isset($_SESSION['locale']) && locale_pattern_check($_SESSION['locale']) && locale_exists($_SESSION['locale'])) { && locale_exists($locale);
$locale = $_SESSION['locale'];
}
else {
$locale = get_user_locale();
}
setcookie(LOCALE_COOKIE_NAME, $locale, time() + 60 * 60 * 24 * 1000, MIBEW_WEB_ROOT . "/"); // Check if locale code stored in session data is valid
return $locale; $session_locale_valid = isset($_SESSION['locale'])
&& locale_pattern_check($_SESSION['locale'])
&& locale_exists($_SESSION['locale']);
if ($locale_param_valid) {
$_SESSION['locale'] = $locale;
} elseif ($session_locale_valid) {
$locale = $_SESSION['locale'];
} else {
$locale = get_user_locale();
}
setcookie(LOCALE_COOKIE_NAME, $locale, time() + 60 * 60 * 24 * 1000, MIBEW_WEB_ROOT . "/");
return $locale;
} }
function get_locale_links($href) function get_locale_links($href)
{ {
$localeLinks = array(); $locale_links = array();
$allLocales = get_available_locales(); $all_locales = get_available_locales();
if (count($allLocales) < 2) { if (count($all_locales) < 2) {
return null; return null;
} }
foreach ($allLocales as $k) { foreach ($all_locales as $k) {
$localeLinks[$k] = getlocal_($k, "names"); $locale_links[$k] = getlocal_($k, "names");
} }
return $localeLinks;
return $locale_links;
} }
/** /**
@ -157,38 +177,39 @@ function get_locale_links($href)
* *
* @param string $locale Name of a locale whose messages should be loaded. * @param string $locale Name of a locale whose messages should be loaded.
*/ */
function load_messages($locale) { function load_messages($locale)
global $messages, $output_encoding; {
global $messages, $output_encoding;
// Load core localization // Load core localization
$locale_file = MIBEW_FS_ROOT . "/locales/{$locale}/properties"; $locale_file = MIBEW_FS_ROOT . "/locales/{$locale}/properties";
$locale_data = read_locale_file($locale_file); $locale_data = read_locale_file($locale_file);
if (! is_null($locale_data['output_encoding'])) { if (!is_null($locale_data['output_encoding'])) {
$output_encoding[$locale] = $locale_data['output_encoding']; $output_encoding[$locale] = $locale_data['output_encoding'];
} }
$messages[$locale] = $locale_data['messages']; $messages[$locale] = $locale_data['messages'];
// Plugins are unavailable on system installation // Plugins are unavailable on system installation
if (!installation_in_progress()) { if (!installation_in_progress()) {
// Load active plugins localization // Load active plugins localization
$plugins_list = array_keys(PluginManager::getAllPlugins()); $plugins_list = array_keys(PluginManager::getAllPlugins());
foreach($plugins_list as $plugin_name) { foreach ($plugins_list as $plugin_name) {
$locale_file = MIBEW_FS_ROOT . $locale_file = MIBEW_FS_ROOT .
"/plugins/{$plugin_name}/locales/{$locale}/properties"; "/plugins/{$plugin_name}/locales/{$locale}/properties";
if (is_readable($locale_file)) { if (is_readable($locale_file)) {
$locale_data = read_locale_file($locale_file); $locale_data = read_locale_file($locale_file);
// array_merge used to provide an ability for plugins to override // array_merge used to provide an ability for plugins to override
// localized strings // localized strings
$messages[$locale] = array_merge( $messages[$locale] = array_merge(
$messages[$locale], $messages[$locale],
$locale_data['messages'] $locale_data['messages']
); );
} }
} }
} }
} }
/** /**
@ -210,188 +231,216 @@ function load_messages($locale) {
* All localized strings have internal Mibew encoding(see $mibew_encoding * All localized strings have internal Mibew encoding(see $mibew_encoding
* value in libs/config.php). * value in libs/config.php).
*/ */
function read_locale_file($path) { function read_locale_file($path)
// Set default values {
$current_encoding = MIBEW_ENCODING; // Set default values
$output_encoding = null; $current_encoding = MIBEW_ENCODING;
$messages = array(); $output_encoding = null;
$messages = array();
$fp = fopen($path, "r"); $fp = fopen($path, "r");
if ($fp === FALSE) { if ($fp === false) {
die("unable to read locale file $path"); die("unable to read locale file $path");
} }
while (!feof($fp)) { while (!feof($fp)) {
$line = fgets($fp, 4096); $line = fgets($fp, 4096);
// Try to get key and value from locale file line // Try to get key and value from locale file line
$line_parts = preg_split("/=/", $line, 2); $line_parts = preg_split("/=/", $line, 2);
if (count($line_parts) == 2) { if (count($line_parts) == 2) {
$key = $line_parts[0]; $key = $line_parts[0];
$value = $line_parts[1]; $value = $line_parts[1];
// Check if key is service field and treat it as // Check if key is service field and treat it as
// localized string otherwise // localized string otherwise
if ($key == 'encoding') { if ($key == 'encoding') {
$current_encoding = trim($value); $current_encoding = trim($value);
} else if ($key == 'output_encoding') { } elseif ($key == 'output_encoding') {
$output_encoding = trim($value); $output_encoding = trim($value);
} else if ($current_encoding == MIBEW_ENCODING) { } elseif ($current_encoding == MIBEW_ENCODING) {
$messages[$key] = str_replace("\\n", "\n", trim($value)); $messages[$key] = str_replace("\\n", "\n", trim($value));
} else { } else {
$messages[$key] = myiconv( $messages[$key] = myiconv(
$current_encoding, $current_encoding,
MIBEW_ENCODING, MIBEW_ENCODING,
str_replace("\\n", "\n", trim($value)) str_replace("\\n", "\n", trim($value))
); );
} }
} }
} }
fclose($fp); fclose($fp);
return array( return array(
'encoding' => $current_encoding, 'encoding' => $current_encoding,
'output_encoding' => $output_encoding, 'output_encoding' => $output_encoding,
'messages' => $messages 'messages' => $messages
); );
} }
function getoutputenc() function getoutputenc()
{ {
global $output_encoding, $messages; global $output_encoding, $messages;
if (!isset($messages[CURRENT_LOCALE])) if (!isset($messages[CURRENT_LOCALE])) {
load_messages(CURRENT_LOCALE); load_messages(CURRENT_LOCALE);
return isset($output_encoding[CURRENT_LOCALE]) ? $output_encoding[CURRENT_LOCALE] : MIBEW_ENCODING; }
return isset($output_encoding[CURRENT_LOCALE])
? $output_encoding[CURRENT_LOCALE]
: MIBEW_ENCODING;
} }
function getstring_($text, $locale) function getstring_($text, $locale)
{ {
global $messages; global $messages;
if (!isset($messages[$locale])) if (!isset($messages[$locale])) {
load_messages($locale); load_messages($locale);
}
$localized = $messages[$locale]; $localized = $messages[$locale];
if (isset($localized[$text])) if (isset($localized[$text])) {
return $localized[$text]; return $localized[$text];
if ($locale != 'en') { }
return getstring_($text, 'en'); if ($locale != 'en') {
} return getstring_($text, 'en');
}
return "!" . $text; return "!" . $text;
} }
function getstring($text) function getstring($text)
{ {
return getstring_($text, CURRENT_LOCALE); return getstring_($text, CURRENT_LOCALE);
} }
function getlocal($text) function getlocal($text)
{ {
return myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE)); return myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE));
} }
function getlocal_($text, $locale) function getlocal_($text, $locale)
{ {
return myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, $locale)); return myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, $locale));
} }
function getstring2_($text, $params, $locale) function getstring2_($text, $params, $locale)
{ {
$string = getstring_($text, $locale); $string = getstring_($text, $locale);
for ($i = 0; $i < count($params); $i++) { for ($i = 0; $i < count($params); $i++) {
$string = str_replace("{" . $i . "}", $params[$i], $string); $string = str_replace("{" . $i . "}", $params[$i], $string);
} }
return $string;
return $string;
} }
function getstring2($text, $params) function getstring2($text, $params)
{ {
return getstring2_($text, $params, CURRENT_LOCALE); return getstring2_($text, $params, CURRENT_LOCALE);
} }
function getlocal2($text, $params) function getlocal2($text, $params)
{ {
$string = myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE)); $string = myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE));
for ($i = 0; $i < count($params); $i++) { for ($i = 0; $i < count($params); $i++) {
$string = str_replace("{" . $i . "}", $params[$i], $string); $string = str_replace("{" . $i . "}", $params[$i], $string);
} }
return $string;
return $string;
} }
/* prepares for Javascript string */ /* prepares for Javascript string */
function getlocalforJS($text, $params) function get_local_for_js($text, $params)
{ {
$string = myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE)); $string = myiconv(MIBEW_ENCODING, getoutputenc(), getstring_($text, CURRENT_LOCALE));
$string = str_replace("\"", "\\\"", str_replace("\n", "\\n", $string)); $string = str_replace("\"", "\\\"", str_replace("\n", "\\n", $string));
for ($i = 0; $i < count($params); $i++) { for ($i = 0; $i < count($params); $i++) {
$string = str_replace("{" . $i . "}", $params[$i], $string); $string = str_replace("{" . $i . "}", $params[$i], $string);
} }
return $string;
return $string;
} }
function locale_load_idlist($name) function locale_load_id_list($name)
{ {
$result = array(); $result = array();
$fp = @fopen(MIBEW_FS_ROOT."/locales/names/$name", "r"); $fp = @fopen(MIBEW_FS_ROOT . "/locales/names/$name", "r");
if ($fp !== FALSE) { if ($fp !== false) {
while (!feof($fp)) { while (!feof($fp)) {
$line = trim(fgets($fp, 4096)); $line = trim(fgets($fp, 4096));
if ($line && preg_match("/^[\w_\.]+$/", $line)) { if ($line && preg_match("/^[\w_\.]+$/", $line)) {
$result[] = $line; $result[] = $line;
} }
} }
fclose($fp); fclose($fp);
} }
return $result;
return $result;
} }
function save_message($locale, $key, $value) function save_message($locale, $key, $value)
{ {
$result = ""; $result = "";
$added = false; $added = false;
$current_encoding = MIBEW_ENCODING; $current_encoding = MIBEW_ENCODING;
$fp = fopen(MIBEW_FS_ROOT."/locales/$locale/properties", "r"); $fp = fopen(MIBEW_FS_ROOT . "/locales/$locale/properties", "r");
if ($fp === FALSE) { if ($fp === false) {
die("unable to open properties for locale $locale"); die("unable to open properties for locale $locale");
} }
while (!feof($fp)) { while (!feof($fp)) {
$line = fgets($fp, 4096); $line = fgets($fp, 4096);
$keyval = preg_split("/=/", $line, 2); $key_val = preg_split("/=/", $line, 2);
if (isset($keyval[1])) { if (isset($key_val[1])) {
if ($keyval[0] == 'encoding') { if ($key_val[0] == 'encoding') {
$current_encoding = trim($keyval[1]); $current_encoding = trim($key_val[1]);
} else if (!$added && $keyval[0] == $key) { } elseif (!$added && $key_val[0] == $key) {
$line = "$key=" . myiconv(MIBEW_ENCODING, $current_encoding, str_replace("\r", "", str_replace("\n", "\\n", trim($value)))) . "\n"; $line = "$key="
$added = true; . myiconv(
} MIBEW_ENCODING,
} $current_encoding,
$result .= $line; str_replace("\r", "", str_replace("\n", "\\n", trim($value)))
} ) . "\n";
fclose($fp); $added = true;
if (!$added) { }
$result .= "$key=" . myiconv(MIBEW_ENCODING, $current_encoding, str_replace("\r", "", str_replace("\n", "\\n", trim($value)))) . "\n"; }
} $result .= $line;
$fp = @fopen(MIBEW_FS_ROOT."/locales/$locale/properties", "w"); }
if ($fp !== FALSE) { fclose($fp);
fwrite($fp, $result); if (!$added) {
fclose($fp); $result .= "$key="
} else { . myiconv(
die("cannot write /locales/$locale/properties, please check file permissions on your server"); MIBEW_ENCODING,
} $current_encoding,
$fp = @fopen(MIBEW_FS_ROOT."/locales/$locale/properties.log", "a"); str_replace("\r", "", str_replace("\n", "\\n", trim($value)))
if ($fp !== FALSE) { ) . "\n";
$extAddr = $_SERVER['REMOTE_ADDR']; }
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $fp = @fopen(MIBEW_FS_ROOT . "/locales/$locale/properties", "w");
$_SERVER['HTTP_X_FORWARDED_FOR'] != $_SERVER['REMOTE_ADDR']) { if ($fp !== false) {
$extAddr = $_SERVER['REMOTE_ADDR'] . ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')'; fwrite($fp, $result);
} fclose($fp);
$userbrowser = $_SERVER['HTTP_USER_AGENT']; } else {
$remoteHost = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : $extAddr; die("cannot write /locales/$locale/properties, please check file permissions on your server");
}
$fp = @fopen(MIBEW_FS_ROOT . "/locales/$locale/properties.log", "a");
if ($fp !== false) {
$ext_addr = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) &&
$_SERVER['HTTP_X_FORWARDED_FOR'] != $_SERVER['REMOTE_ADDR']) {
$ext_addr = $_SERVER['REMOTE_ADDR'] . ' (' . $_SERVER['HTTP_X_FORWARDED_FOR'] . ')';
}
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$remote_host = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : $ext_addr;
fwrite($fp, "# " . date(DATE_RFC822) . " by $remoteHost using $userbrowser\n"); fwrite($fp, "# " . date(DATE_RFC822) . " by $remote_host using $user_browser\n");
fwrite($fp, "$key=" . myiconv(MIBEW_ENCODING, $current_encoding, str_replace("\r", "", str_replace("\n", "\\n", trim($value)))) . "\n"); fwrite(
fclose($fp); $fp,
} ("$key="
. myiconv(
MIBEW_ENCODING,
$current_encoding,
str_replace("\r", "", str_replace("\n", "\\n", trim($value)))
)
. "\n")
);
fclose($fp);
}
} }
$messages = array(); $messages = array();
$output_encoding = array(); $output_encoding = array();
?>

View File

@ -15,42 +15,41 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(MIBEW_FS_ROOT.'/libs/common/constants.php');
function debugexit_print($var) function debugexit_print($var)
{ {
echo "<html><body><pre>"; echo "<html><body><pre>";
print_r($var); print_r($var);
echo "</pre></body></html>"; echo "</pre></body></html>";
exit; exit;
} }
function get_gifimage_size($filename) function get_gifimage_size($filename)
{ {
if (function_exists('gd_info')) { if (function_exists('gd_info')) {
$info = gd_info(); $info = gd_info();
if (isset($info['GIF Read Support']) && $info['GIF Read Support']) { if (isset($info['GIF Read Support']) && $info['GIF Read Support']) {
$img = @imagecreatefromgif($filename); $img = @imagecreatefromgif($filename);
if ($img) { if ($img) {
$height = imagesy($img); $height = imagesy($img);
$width = imagesx($img); $width = imagesx($img);
imagedestroy($img); imagedestroy($img);
return array($width, $height);
} return array($width, $height);
} }
} }
return array(0, 0); }
return array(0, 0);
} }
function js_path()
function jspath()
{ {
return "js/compiled"; return "js/compiled";
} }
function div($a, $b) function div($a, $b)
{ {
return ($a - ($a % $b)) / $b; return ($a - ($a % $b)) / $b;
} }
/** /**
@ -88,21 +87,23 @@ function div($a, $b)
* @param array $arr Array to flatten * @param array $arr Array to flatten
* @return array * @return array
*/ */
function array_flatten_recursive($arr) { function array_flatten_recursive($arr)
$result = array(); {
foreach($arr as $key => $value) { $result = array();
if (is_array($value)) { foreach ($arr as $key => $value) {
// Flatten nested arrays if (is_array($value)) {
$value = array_flatten_recursive($value); // Flatten nested arrays
foreach($value as $inner_key => $inner_value) { $value = array_flatten_recursive($value);
$result[$key.".".$inner_key] = $inner_value; foreach ($value as $inner_key => $inner_value) {
} $result[$key . "." . $inner_key] = $inner_value;
} else { }
// Leave scalar values 'as is' } else {
$result[$key] = $value; // Leave scalar values 'as is'
} $result[$key] = $value;
} }
return $result; }
return $result;
} }
/** /**
@ -110,12 +111,11 @@ function array_flatten_recursive($arr) {
* *
* @return boolean * @return boolean
*/ */
function installation_in_progress() { function installation_in_progress()
if (!defined('INSTALLATION_IN_PROGRESS')) { {
return FALSE; if (!defined('INSTALLATION_IN_PROGRESS')) {
} return false;
}
return INSTALLATION_IN_PROGRESS; return INSTALLATION_IN_PROGRESS;
} }
?>

View File

@ -18,62 +18,61 @@
// Import namespaces and classes of the core // Import namespaces and classes of the core
use Mibew\Settings; use Mibew\Settings;
// Initialize libraries
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php');
/* ajax server actions use utf-8 */ /* ajax server actions use utf-8 */
function getrawparam($name) function get_raw_param($name)
{ {
if (isset($_POST[$name])) { if (isset($_POST[$name])) {
$value = myiconv("utf-8", MIBEW_ENCODING, $_POST[$name]); $value = myiconv("utf-8", MIBEW_ENCODING, $_POST[$name]);
if (get_magic_quotes_gpc()) { if (get_magic_quotes_gpc()) {
$value = stripslashes($value); $value = stripslashes($value);
} }
return $value;
}
die("no " . $name . " parameter");
}
return $value;
}
die("no " . $name . " parameter");
}
/* form processors use current Output encoding */ /* form processors use current Output encoding */
function getparam($name)
function get_param($name)
{ {
if (isset($_POST[$name])) { if (isset($_POST[$name])) {
$value = myiconv(getoutputenc(), MIBEW_ENCODING, $_POST[$name]); $value = myiconv(getoutputenc(), MIBEW_ENCODING, $_POST[$name]);
if (get_magic_quotes_gpc()) { if (get_magic_quotes_gpc()) {
$value = stripslashes($value); $value = stripslashes($value);
} }
return $value;
} return $value;
die("no " . $name . " parameter"); }
die("no " . $name . " parameter");
} }
function getgetparam($name, $default = '') function get_get_param($name, $default = '')
{ {
if (!isset($_GET[$name]) || !$_GET[$name]) { if (!isset($_GET[$name]) || !$_GET[$name]) {
return $default; return $default;
} }
$value = myiconv("utf-8", MIBEW_ENCODING, unicode_urldecode($_GET[$name])); $value = myiconv("utf-8", MIBEW_ENCODING, unicode_urldecode($_GET[$name]));
if (get_magic_quotes_gpc()) { if (get_magic_quotes_gpc()) {
$value = stripslashes($value); $value = stripslashes($value);
} }
return $value;
return $value;
} }
function get_app_location($showhost, $issecure) function get_app_location($show_host, $is_secure)
{ {
if ($showhost) { if ($show_host) {
return ($issecure ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . MIBEW_WEB_ROOT; return ($is_secure ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . MIBEW_WEB_ROOT;
} else { } else {
return MIBEW_WEB_ROOT; return MIBEW_WEB_ROOT;
} }
} }
function is_secure_request() function is_secure_request()
{ {
return return (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443')
isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")
|| isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on" || (isset($_SERVER["HTTP_HTTPS"]) && $_SERVER["HTTP_HTTPS"] == "on");
|| isset($_SERVER["HTTP_HTTPS"]) && $_SERVER["HTTP_HTTPS"] == "on";
} }
/** /**
@ -81,8 +80,7 @@ function is_secure_request()
* *
* @return string * @return string
*/ */
function get_page_style() { function get_page_style()
return Settings::get('page_style'); {
return Settings::get('page_style');
} }
?>

View File

@ -15,57 +15,61 @@
* limitations under the License. * limitations under the License.
*/ */
// Import namespaces and classes of the core // Import namespaces and classes of the core
use Mibew\EventDispatcher; use Mibew\EventDispatcher;
// Initialize libraries function get_popup($href, $js_href, $message, $title, $wnd_name, $options)
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php');
function get_popup($href, $jshref, $message, $title, $wndName, $options)
{ {
if (!$jshref) { if (!$js_href) {
$jshref = "'$href'"; $js_href = "'$href'";
} }
return "<a href=\"$href\" target=\"_blank\" " . ($title ? "title=\"$title\" " : "") . "onclick=\"if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 &amp;&amp; window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open($jshref, '$wndName', '$options');this.newWindow.focus();this.newWindow.opener=window;return false;\">$message</a>"; return "<a href=\"$href\" target=\"_blank\" "
. ($title ? "title=\"$title\" " : "")
. "onclick=\"if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 "
. "&amp;&amp; window.event.preventDefault) window.event.preventDefault();"
. "this.newWindow = window.open($js_href, '$wnd_name', '$options');"
. "this.newWindow.focus();this.newWindow.opener=window;return false;\">$message</a>";
} }
function get_image($href, $width, $height) function get_image($href, $width, $height)
{ {
if ($width != 0 && $height != 0) if ($width != 0 && $height != 0) {
return "<img src=\"$href\" border=\"0\" width=\"$width\" height=\"$height\" alt=\"\"/>"; return "<img src=\"$href\" border=\"0\" width=\"$width\" height=\"$height\" alt=\"\"/>";
return "<img src=\"$href\" border=\"0\" alt=\"\"/>"; }
return "<img src=\"$href\" border=\"0\" alt=\"\"/>";
} }
function start_xml_output() function start_xml_output()
{ {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache"); header("Pragma: no-cache");
header("Content-type: text/xml; charset=utf-8"); header("Content-type: text/xml; charset=utf-8");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
} }
function start_html_output() function start_html_output()
{ {
$charset = getstring("output_charset"); $charset = getstring("output_charset");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache"); header("Pragma: no-cache");
header("Content-type: text/html" . (isset($charset) ? "; charset=" . $charset : "")); header("Content-type: text/html" . (isset($charset) ? "; charset=" . $charset : ""));
} }
function start_js_output(){ function start_js_output()
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/javascript; charset=utf-8");
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
function topage($text)
{ {
return myiconv(MIBEW_ENCODING, getoutputenc(), $text); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/javascript; charset=utf-8");
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
}
function to_page($text)
{
return myiconv(MIBEW_ENCODING, getoutputenc(), $text);
} }
/** /**
@ -81,24 +85,25 @@ function topage($text)
* @param string $page_name CSS files load to this page * @param string $page_name CSS files load to this page
* @return string HTML block of 'link' tags * @return string HTML block of 'link' tags
*/ */
function get_additional_css($page_name) { function get_additional_css($page_name)
// Prepare event arguments array {
$args = array( // Prepare event arguments array
'page' => $page_name, $args = array(
'css' => array() 'page' => $page_name,
); 'css' => array(),
);
// Trigger event // Trigger event
$dispatcher = EventDispatcher::getInstance(); $dispatcher = EventDispatcher::getInstance();
$dispatcher->triggerEvent('pageAddCSS', $args); $dispatcher->triggerEvent('pageAddCSS', $args);
// Build resulting css list // Build resulting css list
$result = array(); $result = array();
foreach($args['css'] as $css) { foreach ($args['css'] as $css) {
$result[] = '<link rel="stylesheet" type="text/css" href="'.$css.'">'; $result[] = '<link rel="stylesheet" type="text/css" href="' . $css . '">';
} }
return implode("\n", $result); return implode("\n", $result);
} }
/** /**
@ -114,24 +119,25 @@ function get_additional_css($page_name) {
* @param string $page_name JavaScript files load to this page * @param string $page_name JavaScript files load to this page
* @return string HTML block of 'script' tags * @return string HTML block of 'script' tags
*/ */
function get_additional_js($page_name) { function get_additional_js($page_name)
// Prepare event arguments array {
$args = array( // Prepare event arguments array
'page' => $page_name, $args = array(
'js' => array() 'page' => $page_name,
); 'js' => array()
);
// Trigger event // Trigger event
$dispatcher = EventDispatcher::getInstance(); $dispatcher = EventDispatcher::getInstance();
$dispatcher->triggerEvent('pageAddJS', $args); $dispatcher->triggerEvent('pageAddJS', $args);
// Build resulting css list // Build resulting css list
$result = array(); $result = array();
foreach($args['js'] as $js) { foreach ($args['js'] as $js) {
$result[] = '<script type="text/javascript" src="'.$js.'"></script>'; $result[] = '<script type="text/javascript" src="' . $js . '"></script>';
} }
return implode("\n", $result); return implode("\n", $result);
} }
/** /**
@ -145,25 +151,25 @@ function get_additional_js($page_name) {
* @param string $page_name Localized strings add to this page * @param string $page_name Localized strings add to this page
* @return string JSON encoded localized strings * @return string JSON encoded localized strings
*/ */
function get_additional_localized_strings($page_name) { function get_additional_localized_strings($page_name)
// Prepare event arguments array {
$args = array( // Prepare event arguments array
'page' => $page_name, $args = array(
'localized_strings' => array() 'page' => $page_name,
); 'localized_strings' => array(),
);
// Trigger event // Trigger event
$dispatcher = EventDispatcher::getInstance(); $dispatcher = EventDispatcher::getInstance();
$dispatcher->triggerEvent('pageAddLocalizedStrings', $args); $dispatcher->triggerEvent('pageAddLocalizedStrings', $args);
// Build result // Build result
$result = array(); $result = array();
if (! empty($args['localized_strings']) if (!empty($args['localized_strings']) && is_array($args['localized_strings'])) {
&& is_array($args['localized_strings'])) { $result = $args['localized_strings'];
$result = $args['localized_strings']; }
}
return json_encode($result); return json_encode($result);
} }
/** /**
@ -179,19 +185,20 @@ function get_additional_localized_strings($page_name) {
* @param string $page_name Plugins initialize at this page * @param string $page_name Plugins initialize at this page
* @return string JavaScript options block * @return string JavaScript options block
*/ */
function get_js_plugin_options($page_name) { function get_js_plugin_options($page_name)
// Prepare event arguments array {
$args = array( // Prepare event arguments array
'page' => $page_name, $args = array(
'plugins' => array() 'page' => $page_name,
); 'plugins' => array()
);
// Trigger event // Trigger event
$dispatcher = EventDispatcher::getInstance(); $dispatcher = EventDispatcher::getInstance();
$dispatcher->triggerEvent('pageAddJSPluginOptions', $args); $dispatcher->triggerEvent('pageAddJSPluginOptions', $args);
// Return encoded options // Return encoded options
return json_encode($args['plugins']); return json_encode($args['plugins']);
} }
/** /**
@ -199,74 +206,76 @@ function get_js_plugin_options($page_name) {
* *
* @param string $page_name Plugins initialize at this page * @param string $page_name Plugins initialize at this page
* @return array Associative array of plugins data. It contains following keys: * @return array Associative array of plugins data. It contains following keys:
* - 'additional_css': contains results of the 'get_additional_css function * - 'additional_css': contains results of the 'get_additional_css function
* - 'additional_js': contains results of the 'get_additional_js' function * - 'additional_js': contains results of the 'get_additional_js' function
* - 'additional_localized_strings': contains results of the * - 'additional_localized_strings': contains results of the
* 'get_additional_localized_strings' function * 'get_additional_localized_strings' function
* - 'js_plugin_options': contains results of the 'get_js_plugin_options' * - 'js_plugin_options': contains results of the 'get_js_plugin_options'
* function * function
*/ */
function get_plugins_data($page_name) { function get_plugins_data($page_name)
return array( {
'additional_css' => get_additional_css($page_name), return array(
'additional_js' => get_additional_js($page_name), 'additional_css' => get_additional_css($page_name),
'additional_localized_strings' => get_additional_localized_strings($page_name), 'additional_js' => get_additional_js($page_name),
'js_plugin_options' => get_js_plugin_options($page_name) 'additional_localized_strings' => get_additional_localized_strings($page_name),
); 'js_plugin_options' => get_js_plugin_options($page_name)
);
} }
function no_field($key) function no_field($key)
{ {
return getlocal2("errors.required", array(getlocal($key))); return getlocal2("errors.required", array(getlocal($key)));
} }
function failed_uploading_file($filename, $key) function failed_uploading_file($filename, $key)
{ {
return getlocal2("errors.failed.uploading.file", return getlocal2("errors.failed.uploading.file", array($filename, getlocal($key)));
array($filename, getlocal($key)));
} }
function wrong_field($key) function wrong_field($key)
{ {
return getlocal2("errors.wrong_field", array(getlocal($key))); return getlocal2("errors.wrong_field", array(getlocal($key)));
} }
function add_params($servlet, $params) function add_params($servlet, $params)
{ {
$infix = '?'; $infix = '?';
if (strstr($servlet, $infix) !== FALSE) if (strstr($servlet, $infix) !== false) {
$infix = '&amp;'; $infix = '&amp;';
foreach ($params as $k => $v) { }
$servlet .= $infix . $k . "=" . $v; foreach ($params as $k => $v) {
$infix = '&amp;'; $servlet .= $infix . $k . "=" . $v;
} $infix = '&amp;';
return $servlet; }
return $servlet;
} }
/** /**
* Builds JSONP response to the Mibew widget * Builds JSONP response to the Mibew widget
* *
* @param array $response Response data. It can contain following items: * @param array $response Response data. It can contain following items:
* - 'load': associative array, specify files which must be loaded. Array keys * - 'load': associative array, specify files which must be loaded. Array keys
* are file aliases and values are URLs. One can use file alias to specify * are file aliases and values are URLs. One can use file alias to specify
* dependences (described below). * dependences (described below).
* - 'handlers': array, handlers which must be called (described below). * - 'handlers': array, handlers which must be called (described below).
* - 'dependences': array, specify dependences between handlers and loaded * - 'dependences': array, specify dependences between handlers and loaded
* files. Array keys are handlers names and values are arrays of file aliases * files. Array keys are handlers names and values are arrays of file aliases
* from load item. Handler function will call only after all specified files * from load item. Handler function will call only after all specified files
* loaded. * loaded.
* - 'data': associative array, arbitrary structure which will be passed to all * - 'data': associative array, arbitrary structure which will be passed to all
* functions, specified in 'handlers' item. * functions, specified in 'handlers' item.
* @return string JSONP response that ready to send to the widget * @return string JSONP response that ready to send to the widget
*/ */
function build_widget_response($response) { function build_widget_response($response)
$result = $response + array( {
'load' => array(), $result = $response + array(
'handlers' => array(), 'load' => array(),
'dependences' => array(), 'handlers' => array(),
'data' => array() 'dependences' => array(),
); 'data' => array(),
return "Mibew.Objects.widget.onResponse(" . json_encode($result) . ");"; );
}
?> return "Mibew.Objects.widget.onResponse(" . json_encode($result) . ");";
}

View File

@ -17,42 +17,40 @@
function unicode_urldecode($url) function unicode_urldecode($url)
{ {
preg_match_all('/%u([[:alnum:]]{4})/', $url, $a); preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);
foreach ($a[1] as $uniord) { foreach ($a[1] as $uniord) {
$dec = hexdec($uniord); $dec = hexdec($uniord);
$utf = ''; $utf = '';
if ($dec < 128) { if ($dec < 128) {
$utf = chr($dec); $utf = chr($dec);
} else if ($dec < 2048) { } elseif ($dec < 2048) {
$utf = chr(192 + (($dec - ($dec % 64)) / 64)); $utf = chr(192 + (($dec - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64)); $utf .= chr(128 + ($dec % 64));
} else { } else {
$utf = chr(224 + (($dec - ($dec % 4096)) / 4096)); $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64)); $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64)); $utf .= chr(128 + ($dec % 64));
} }
$url = str_replace('%u' . $uniord, $utf, $url); $url = str_replace('%u' . $uniord, $utf, $url);
} }
return urldecode($url); return urldecode($url);
} }
function cutstring($string, $length = 75, $ellipsis = '') function cut_string($string, $length = 75, $ellipsis = '')
{ {
$result = ''; $result = '';
if (strlen($string) > $length) { if (strlen($string) > $length) {
$splitstring = explode("[__cut__]", wordwrap($string, $length, "[__cut__]", true)); $splitstring = explode("[__cut__]", wordwrap($string, $length, "[__cut__]", true));
$result = $splitstring[0] . $ellipsis; $result = $splitstring[0] . $ellipsis;
}else{ } else {
$result = $string; $result = $string;
} }
return $result; return $result;
} }
function escape_with_cdata($text) function escape_with_cdata($text)
{ {
return "<![CDATA[" . str_replace("]]>", "]]>]]&gt;<![CDATA[", $text) . "]]>"; return "<![CDATA[" . str_replace("]]>", "]]>]]&gt;<![CDATA[", $text) . "]]>";
} }
?>

View File

@ -15,29 +15,28 @@
* limitations under the License. * limitations under the License.
*/ */
function verifyparam($name, $regexp, $default = null) function verify_param($name, $reg_exp, $default = null)
{ {
if (isset($_GET[$name]) && is_scalar($_GET[$name])) { if (isset($_GET[$name]) && is_scalar($_GET[$name])) {
$val = $_GET[$name]; $val = $_GET[$name];
if (preg_match($regexp, $val)) if (preg_match($reg_exp, $val)) {
return $val; return $val;
}
} else if (isset($_POST[$name]) && is_scalar($_POST[$name])) { } elseif (isset($_POST[$name]) && is_scalar($_POST[$name])) {
$val = $_POST[$name]; $val = $_POST[$name];
if (preg_match($regexp, $val)) if (preg_match($reg_exp, $val)) {
return $val; return $val;
}
} else { } else {
if (isset($default)) if (isset($default)) {
return $default; return $default;
} }
echo "<html><head></head><body>Wrong parameter used or absent: " . $name . "</body></html>"; }
exit; echo "<html><head></head><body>Wrong parameter used or absent: " . $name . "</body></html>";
exit;
} }
function is_valid_email($email) function is_valid_email($email)
{ {
return preg_match("/^[^@]+@[^\.]+(\.[^\.]+)*$/", $email); return preg_match("/^[^@]+@[^\.]+(\.[^\.]+)*$/", $email);
} }
?>

View File

@ -21,12 +21,10 @@
* @param string $cron_key Cron security key * @param string $cron_key Cron security key
* @return string Cron URI * @return string Cron URI
*/ */
function cron_get_uri($cron_key) { function cron_get_uri($cron_key)
$path = get_app_location(true, is_secure_request()) . '/cron.php'; {
$path .= empty($cron_key) $path = get_app_location(true, is_secure_request()) . '/cron.php';
? '' $path .= empty($cron_key) ? '' : '?cron_key=' . $cron_key;
: '?cron_key='.$cron_key;
return $path;
}
?> return $path;
}

View File

@ -62,14 +62,13 @@ $default_locale = "en"; /* if user does not provide known lang */
* Plugins * Plugins
*/ */
$plugins_list = array(); $plugins_list = array();
/* Exapmle of plugins configuration /* Exapmle of plugins configuration
$plugins_list[] = array( $plugins_list[] = array(
'name' => 'plugin_name', 'name' => 'plugin_name',
'config' => array( 'config' => array(
'weight' => 100, 'weight' => 100,
'some_configurable_value' => 'value' 'some_configurable_value' => 'value'
) )
) )
*/ */
?>

View File

@ -19,121 +19,143 @@
use Mibew\Settings; use Mibew\Settings;
use Mibew\Style\InvitationStyle; use Mibew\Style\InvitationStyle;
function generate_button($title, $locale, $style, $invitation_style_name, $group, $inner, $showhost, $forcesecure, $modsecurity, $operator_code) function generate_button(
{ $title,
$app_location = get_app_location($showhost, $forcesecure); $locale,
$link = $app_location . "/client.php"; $style,
if ($locale) $invitation_style_name,
$link = append_query($link, "locale=$locale"); $group,
if ($style) $inner,
$link = append_query($link, "style=$style"); $show_host,
if ($group) $force_secure,
$link = append_query($link, "group=$group"); $mod_security,
$operator_code
) {
$app_location = get_app_location($show_host, $force_secure);
$link = $app_location . "/client.php";
if ($locale) {
$link = append_query($link, "locale=$locale");
}
if ($style) {
$link = append_query($link, "style=$style");
}
if ($group) {
$link = append_query($link, "group=$group");
}
$modsecfix = $modsecurity ? ".replace('http://','').replace('https://','')" : ""; $modsecfix = $mod_security ? ".replace('http://','').replace('https://','')" : "";
$jslink = append_query("'" . $link, "url='+escape(document.location.href$modsecfix)+'&amp;referrer='+escape(document.referrer$modsecfix)"); $js_link = append_query(
$popup_options = "toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1"; "'" . $link,
"url='+escape(document.location.href$modsecfix)+'&amp;referrer='+escape(document.referrer$modsecfix)"
);
$popup_options = "toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1";
// Generate operator code field // Generate operator code field
if ($operator_code) { if ($operator_code) {
$form_on_submit = "if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 " . $form_on_submit = "if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 "
"&amp;&amp; window.event.preventDefault) window.event.preventDefault();" . . "&amp;&amp; window.event.preventDefault) window.event.preventDefault();"
"this.newWindow = window.open({$jslink} + '&amp;operator_code=' + document.getElementById('mibewOperatorCodeField').value, 'mibew', '{$popup_options}');" . . "this.newWindow = window.open({$js_link} + '&amp;operator_code=' "
"this.newWindow.focus();this.newWindow.opener=window;return false;"; . "+ document.getElementById('mibewOperatorCodeField').value, 'mibew', '{$popup_options}');"
$temp = '<form action="" onsubmit="' . $form_on_submit . '" id="mibewOperatorCodeForm">' . . "this.newWindow.focus();this.newWindow.opener=window;return false;";
'<input type="text" id="mibewOperatorCodeField" />' . $temp = '<form action="" onsubmit="' . $form_on_submit . '" id="mibewOperatorCodeForm">'
'</form>'; . '<input type="text" id="mibewOperatorCodeField" />'
return "<!-- mibew operator code field -->" . $temp . "<!-- / mibew operator code field -->"; . '</form>';
} return "<!-- mibew operator code field -->" . $temp . "<!-- / mibew operator code field -->";
}
// Generate button // Generate button
$temp = get_popup($link, "$jslink", $temp = get_popup($link, "$js_link", $inner, $title, "mibew", $popup_options);
$inner, $title, "mibew", $popup_options); if (Settings::get('enabletracking')) {
if (Settings::get('enabletracking')) { $widget_data = array();
$widget_data = array();
// Get actual invitation style instance // Get actual invitation style instance
if (!$invitation_style_name) { if (!$invitation_style_name) {
$invitation_style_name = InvitationStyle::currentStyle(); $invitation_style_name = InvitationStyle::currentStyle();
} }
$invitation_style = new InvitationStyle($invitation_style_name); $invitation_style = new InvitationStyle($invitation_style_name);
// URL of file with additional CSS rules for invitation popup // URL of file with additional CSS rules for invitation popup
$widget_data['inviteStyle'] = $app_location . '/' . $widget_data['inviteStyle'] = $app_location . '/' .
$invitation_style->filesPath() . $invitation_style->filesPath() .
'/invite.css'; '/invite.css';
// Time between requests to the server in milliseconds // Time between requests to the server in milliseconds
$widget_data['requestTimeout'] = Settings::get('updatefrequency_tracking') $widget_data['requestTimeout'] = Settings::get('updatefrequency_tracking') * 1000;
* 1000;
// URL for requests // URL for requests
$widget_data['requestURL'] = $app_location . '/widget.php'; $widget_data['requestURL'] = $app_location . '/widget.php';
// Locale for invitation // Locale for invitation
$widget_data['locale'] = $locale; $widget_data['locale'] = $locale;
// Name of the cookie to track user. Use if third-party cookie blocked // Name of the cookie to track user. Use if third-party cookie blocked
$widget_data['visitorCookieName'] = VISITOR_COOKIE_NAME; $widget_data['visitorCookieName'] = VISITOR_COOKIE_NAME;
// Build additional button code // Build additional button code
$temp = preg_replace('/^(<a )/', '\1id="mibewAgentButton" ', $temp) . $temp = preg_replace('/^(<a )/', '\1id="mibewAgentButton" ', $temp)
'<div id="mibewinvitation"></div>' . . '<div id="mibewinvitation"></div>'
'<script type="text/javascript" src="' . . '<script type="text/javascript" src="'
$app_location . '/js/compiled/widget.js' . . $app_location . '/js/compiled/widget.js'
'"></script>' . . '"></script>'
'<script type="text/javascript">' . . '<script type="text/javascript">'
'Mibew.Widget.init('.json_encode($widget_data).')' . . 'Mibew.Widget.init(' . json_encode($widget_data) . ')'
'</script>'; . '</script>';
} }
return "<!-- mibew button -->" . $temp . "<!-- / mibew button -->";
return "<!-- mibew button -->" . $temp . "<!-- / mibew button -->";
} }
function verifyparam_groupid($paramid, &$errors) { function verifyparam_groupid($param_id, &$errors)
$groupid = ""; {
$groupid = verifyparam($paramid, "/^\d{0,8}$/", ""); $group_id = verify_param($param_id, "/^\d{0,8}$/", "");
if ($groupid) { if ($group_id) {
$group = group_by_id($groupid); $group = group_by_id($group_id);
if (!$group) { if (!$group) {
$errors[] = getlocal("page.group.no_such"); $errors[] = getlocal("page.group.no_such");
$groupid = ""; $group_id = "";
} }
} }
return $groupid;
return $group_id;
} }
function get_groups_list() function get_groups_list()
{ {
$result = array(); $result = array();
$allgroups = get_all_groups(); $all_groups = get_all_groups();
$result[] = array('groupid' => '', 'vclocalname' => getlocal("page.gen_button.default_group"), 'level' => 0); $result[] = array(
foreach ($allgroups as $g) { 'groupid' => '',
$result[] = $g; 'vclocalname' => getlocal("page.gen_button.default_group"),
} 'level' => 0,
return $result; );
foreach ($all_groups as $g) {
$result[] = $g;
}
return $result;
} }
function get_image_locales_map($localesdir) function get_image_locales_map($locales_dir)
{ {
$imageLocales = array(); $image_locales = array();
$allLocales = get_available_locales(); $all_locales = get_available_locales();
foreach ($allLocales as $curr) { foreach ($all_locales as $curr) {
$imagesDir = "$localesdir/$curr/button"; $images_dir = "$locales_dir/$curr/button";
if ($handle = @opendir($imagesDir)) { if ($handle = @opendir($images_dir)) {
while (false !== ($file = readdir($handle))) { while (false !== ($file = readdir($handle))) {
if (preg_match("/^(\w+)_on.gif$/", $file, $matches) $both_files_exist = preg_match("/^(\w+)_on.gif$/", $file, $matches)
&& is_file("$imagesDir/" . $matches[1] . "_off.gif")) { && is_file("$images_dir/" . $matches[1] . "_off.gif");
$image = $matches[1]; if ($both_files_exist) {
if (!isset($imageLocales[$image])) { $image = $matches[1];
$imageLocales[$image] = array(); if (!isset($image_locales[$image])) {
} $image_locales[$image] = array();
$imageLocales[$image][] = $curr; }
} $image_locales[$image][] = $curr;
} }
closedir($handle); }
} closedir($handle);
} }
return $imageLocales; }
}
?> return $image_locales;
}

View File

@ -21,32 +21,35 @@ use Mibew\Settings;
function group_by_id($id) function group_by_id($id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$group = $db->query( $group = $db->query(
"select * from {chatgroup} where groupid = ?", "SELECT * FROM {chatgroup} WHERE groupid = ?",
array($id), array($id),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
return $group;
return $group;
} }
function group_by_name($name) function group_by_name($name)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$group = $db->query( $group = $db->query(
"select * from {chatgroup} where vclocalname = ?", "SELECT * FROM {chatgroup} WHERE vclocalname = ?",
array($name), array($name),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
return $group;
return $group;
} }
function get_group_name($group) function get_group_name($group)
{ {
if (HOME_LOCALE == CURRENT_LOCALE || !isset($group['vccommonname']) || !$group['vccommonname']) if (HOME_LOCALE == CURRENT_LOCALE || !isset($group['vccommonname']) || !$group['vccommonname']) {
return $group['vclocalname']; return $group['vclocalname'];
else } else {
return $group['vccommonname']; return $group['vccommonname'];
}
} }
/** /**
@ -57,97 +60,114 @@ function get_group_name($group)
* @param int $active Number of the active tab. The count starts from 0. * @param int $active Number of the active tab. The count starts from 0.
* @return array Tabs list * @return array Tabs list
*/ */
function setup_group_settings_tabs($gid, $active) { function setup_group_settings_tabs($gid, $active)
$tabs = array(); {
$tabs = array();
if ($gid) { if ($gid) {
$tabs = array( $tabs = array(
getlocal("page_group.tab.main") => $active != 0 ? (MIBEW_WEB_ROOT . "/operator/group.php?gid=$gid") : "", getlocal("page_group.tab.main") => ($active != 0
getlocal("page_group.tab.members") => $active != 1 ? (MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=$gid") : "", ? (MIBEW_WEB_ROOT . "/operator/group.php?gid=$gid")
); : ""),
} getlocal("page_group.tab.members") => ($active != 1
? (MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=$gid")
: ""),
);
}
return $tabs; return $tabs;
} }
function get_operator_groupslist($operatorid) function get_operator_groups_list($operator_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
if (Settings::get('enablegroups') == '1') { if (Settings::get('enablegroups') == '1') {
$groupids = array(0); $group_ids = array(0);
$allgroups = $db->query( $all_groups = $db->query(
"select groupid from {chatgroupoperator} where operatorid = ? order by groupid", "SELECT groupid FROM {chatgroupoperator} WHERE operatorid = ? ORDER BY groupid",
array($operatorid), array($operator_id),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
foreach ($allgroups as $g) { foreach ($all_groups as $g) {
$groupids[] = $g['groupid']; $group_ids[] = $g['groupid'];
} }
return implode(",", $groupids);
} else { return implode(",", $group_ids);
return ""; } else {
} return "";
}
} }
function get_available_parent_groups($skipgroup) function get_available_parent_groups($skip_group)
{ {
$db = Database::getInstance(); $result = array();
$groupslist = $db->query(
"select {chatgroup}.groupid as groupid, parent, vclocalname " .
"from {chatgroup} order by vclocalname",
NULL,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$result = array(array('groupid' => '', 'level' => '', 'vclocalname' => getlocal("form.field.groupparent.root")));
if ($skipgroup) { $result[] = array(
$skipgroup = (array)$skipgroup; 'groupid' => '',
} else { 'level' => '',
$skipgroup = array(); 'vclocalname' => getlocal("form.field.groupparent.root"),
} );
$result = array_merge($result, get_sorted_child_groups_($groupslist, $skipgroup, 0) ); $db = Database::getInstance();
return $result; $groups_list = $db->query(
("SELECT {chatgroup}.groupid AS groupid, parent, vclocalname "
. "FROM {chatgroup} ORDER BY vclocalname"),
null,
array('return_rows' => Database::RETURN_ALL_ROWS)
);
if ($skip_group) {
$skip_group = (array) $skip_group;
} else {
$skip_group = array();
}
$result = array_merge($result, get_sorted_child_groups_($groups_list, $skip_group, 0));
return $result;
} }
function group_has_children($groupid) function group_has_children($group_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$children = $db->query( $children = $db->query(
"select COUNT(*) as count from {chatgroup} where parent = ?", "SELECT COUNT(*) AS count FROM {chatgroup} WHERE parent = ?",
array($groupid), array($group_id),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
return ($children['count'] > 0);
return ($children['count'] > 0);
} }
function get_top_level_group($group) function get_top_level_group($group)
{ {
return is_null($group['parent'])?$group:group_by_id($group['parent']); return is_null($group['parent']) ? $group : group_by_id($group['parent']);
} }
/** /**
* Try to load email for specified group or for its parent. * Try to load email for specified group or for its parent.
*
* @param int $group_id Group id * @param int $group_id Group id
* @return string|boolean Email address or false if there is no email * @return string|boolean Email address or false if there is no email
*/ */
function get_group_email($group_id) { function get_group_email($group_id)
// Try to get group email {
$group = group_by_id($group_id); // Try to get group email
if ($group && !empty($group['vcemail'])) { $group = group_by_id($group_id);
return $group['vcemail']; if ($group && !empty($group['vcemail'])) {
} return $group['vcemail'];
}
// Try to get parent group email // Try to get parent group email
if (! is_null($group['parent'])) { if (!is_null($group['parent'])) {
$group = group_by_id($group['parent']); $group = group_by_id($group['parent']);
if ($group && !empty($group['vcemail'])) { if ($group && !empty($group['vcemail'])) {
return $group['vcemail']; return $group['vcemail'];
} }
} }
// There is no email // There is no email
return false; return false;
} }
/** /**
@ -156,9 +176,10 @@ function get_group_email($group_id) {
* @param array $group Associative group array. Should contain 'ilastseen' key. * @param array $group Associative group array. Should contain 'ilastseen' key.
* @return bool * @return bool
*/ */
function group_is_online($group) { function group_is_online($group)
return ($group['ilastseen'] !== NULL {
&& $group['ilastseen'] < Settings::get('online_timeout')); return $group['ilastseen'] !== null
&& $group['ilastseen'] < Settings::get('online_timeout');
} }
/** /**
@ -168,9 +189,10 @@ function group_is_online($group) {
* key. * key.
* @return bool * @return bool
*/ */
function group_is_away($group) { function group_is_away($group)
return $group['ilastseenaway'] !== NULL {
&& $group['ilastseenaway'] < Settings::get('online_timeout'); return $group['ilastseenaway'] !== null
&& $group['ilastseenaway'] < Settings::get('online_timeout');
} }
/** /**
@ -181,137 +203,173 @@ function group_is_away($group) {
* - 'vclocaldescription': string, contain local description of the group. * - 'vclocaldescription': string, contain local description of the group.
* @return string Group description * @return string Group description
*/ */
function get_group_description($group) { function get_group_description($group)
if (HOME_LOCALE == CURRENT_LOCALE {
|| !isset($group['vccommondescription']) $use_local_description = HOME_LOCALE == CURRENT_LOCALE
|| !$group['vccommondescription']) { || !isset($group['vccommondescription'])
return $group['vclocaldescription']; || !$group['vccommondescription'];
} else {
return $group['vccommondescription']; if ($use_local_description) {
} return $group['vclocaldescription'];
} else {
return $group['vccommondescription'];
}
} }
function check_group_params($group, $extra_params = NULL) function check_group_params($group, $extra_params = null)
{ {
$obligatory_params = array( $obligatory_params = array(
'name', 'name',
'description', 'description',
'commonname', 'commonname',
'commondescription', 'commondescription',
'email', 'email',
'weight', 'weight',
'parent', 'parent',
'chattitle', 'chattitle',
'hosturl', 'hosturl',
'logo'); 'logo',
$params = is_null($extra_params)?$obligatory_params:array_merge($obligatory_params,$extra_params); );
if(count(array_diff($params, array_keys($group))) != 0){
die('Wrong parameters set!'); $params = is_null($extra_params)
} ? $obligatory_params
: array_merge($obligatory_params, $extra_params);
if (count(array_diff($params, array_keys($group))) != 0) {
die('Wrong parameters set!');
}
} }
/** /**
* Creates group * Creates group
* *
* @param array $group Operators' group. * @param array $group Operators' group. The $group array must contains the
* The $group array must contains following keys: * following keys:
* name, description, commonname, commondescription, * - name,
* email, weight, parent, title, chattitle, hosturl, logo * - description,
* - commonname,
* - commondescription,
* - email,
* - weight,
* - parent,
* - title,
* - chattitle,
* - hosturl,
* - logo
* @return array Created group * @return array Created group
*/ */
function create_group($group) function create_group($group)
{ {
$db = Database::getInstance(); check_group_params($group);
check_group_params($group);
$db->query(
"insert into {chatgroup} (parent, vclocalname,vclocaldescription,vccommonname, " .
"vccommondescription,vcemail,vctitle,vcchattitle,vchosturl,vclogo,iweight) " .
"values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
array(
($group['parent'] ? (int)$group['parent'] : NULL),
$group['name'],
$group['description'],
$group['commonname'],
$group['commondescription'],
$group['email'],
$group['title'],
$group['chattitle'],
$group['hosturl'],
$group['logo'],
$group['weight']
)
);
$id = $db->insertedId();
$newdep = $db->query( $db = Database::getInstance();
"select * from {chatgroup} where groupid = ?", $db->query(
array($id), ("INSERT INTO {chatgroup} ("
array('return_rows' => Database::RETURN_ONE_ROW) . "parent, vclocalname, vclocaldescription, vccommonname, "
); . "vccommondescription, vcemail, vctitle, vcchattitle, vchosturl, "
return $newdep; . "vclogo, iweight"
. ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),
array(
($group['parent'] ? (int) $group['parent'] : null),
$group['name'],
$group['description'],
$group['commonname'],
$group['commondescription'],
$group['email'],
$group['title'],
$group['chattitle'],
$group['hosturl'],
$group['logo'],
$group['weight'],
)
);
$id = $db->insertedId();
$new_group = $db->query(
"SELECT * FROM {chatgroup} WHERE groupid = ?",
array($id),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return $new_group;
} }
/** /**
* Updates group info * Updates group info
* *
* @param array $group Operators' group. * @param array $group Operators' group. The $group array must contains the
* The $group array must contains following keys: * following keys:
* id, name, description, commonname, commondescription, * - id,
* email, weight, parent, title, chattitle, hosturl, logo * - name,
* - description,
* - commonname,
* - commondescription,
* - email,
* - weight,
* - parent,
* - title,
* - chattitle,
* - hosturl,
* - logo
*/ */
function update_group($group) function update_group($group)
{ {
$db = Database::getInstance(); check_group_params($group, array('id'));
check_group_params($group, array('id'));
$db->query(
"update {chatgroup} set parent = ?, vclocalname = ?, vclocaldescription = ?, " .
"vccommonname = ?, vccommondescription = ?, vcemail = ?, vctitle = ?, " .
"vcchattitle = ?, vchosturl = ?, vclogo = ?, iweight = ? where groupid = ?",
array(
($group['parent'] ? (int)$group['parent'] : NULL),
$group['name'],
$group['description'],
$group['commonname'],
$group['commondescription'],
$group['email'],
$group['title'],
$group['chattitle'],
$group['hosturl'],
$group['logo'],
$group['weight'],
$group['id']
)
);
if ($group['parent']) { $db = Database::getInstance();
$db->query( $db->query(
"update {chatgroup} set parent = NULL where parent = ?", ("UPDATE {chatgroup} SET "
array($group['id']) . "parent = ?, vclocalname = ?, vclocaldescription = ?, "
); . "vccommonname = ?, vccommondescription = ?, "
} . "vcemail = ?, vctitle = ?, vcchattitle = ?, "
. "vchosturl = ?, vclogo = ?, iweight = ? "
. "where groupid = ?"),
array(
($group['parent'] ? (int) $group['parent'] : null),
$group['name'],
$group['description'],
$group['commonname'],
$group['commondescription'],
$group['email'],
$group['title'],
$group['chattitle'],
$group['hosturl'],
$group['logo'],
$group['weight'],
$group['id']
)
);
if ($group['parent']) {
$db->query(
"UPDATE {chatgroup} SET parent = NULL WHERE parent = ?",
array($group['id'])
);
}
} }
function get_group_members($groupid) function get_group_members($group_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
return $db->query( return $db->query(
"select operatorid from {chatgroupoperator} where groupid = ?", "SELECT operatorid FROM {chatgroupoperator} WHERE groupid = ?",
array($groupid), array($group_id),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
} }
function update_group_members($groupid, $newvalue) function update_group_members($group_id, $new_value)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query("delete from {chatgroupoperator} where groupid = ?", array($groupid)); $db->query(
"DELETE FROM {chatgroupoperator} WHERE groupid = ?",
array($group_id)
);
foreach ($newvalue as $opid) { foreach ($new_value as $operator_id) {
$db->query( $db->query(
"insert into {chatgroupoperator} (groupid, operatorid) values (?, ?)", "INSERT INTO {chatgroupoperator} (groupid, operatorid) VALUES (?, ?)",
array($groupid,$opid) array($group_id, $operator_id)
); );
} }
} }
?>

View File

@ -24,10 +24,16 @@ define('MIBEW_FS_ROOT', dirname(dirname(__FILE__)));
@ini_set('open_basedir', MIBEW_FS_ROOT); @ini_set('open_basedir', MIBEW_FS_ROOT);
// Include configuration file // Include configuration file
require_once(MIBEW_FS_ROOT.'/libs/config.php'); require_once(MIBEW_FS_ROOT . '/libs/config.php');
// Sanitize path to application and remove extra slashes // Sanitize path to application and remove extra slashes
$mibewroot = join("/", array_map("urlencode", preg_split('/\//', preg_replace('/\/+$/', '', preg_replace('/\/{2,}/', '/', '/' . $mibewroot))))); $mibewroot = join(
"/",
array_map(
"urlencode",
preg_split('/\//', preg_replace('/\/+$/', '', preg_replace('/\/{2,}/', '/', '/' . $mibewroot)))
)
);
/** /**
* Base URL of the Mibew installation * Base URL of the Mibew installation
@ -35,28 +41,29 @@ $mibewroot = join("/", array_map("urlencode", preg_split('/\//', preg_replace('/
define('MIBEW_WEB_ROOT', $mibewroot); define('MIBEW_WEB_ROOT', $mibewroot);
// Include system constants file // Include system constants file
require_once(MIBEW_FS_ROOT.'/libs/common/constants.php'); require_once(MIBEW_FS_ROOT . '/libs/common/constants.php');
// Initialize classes autoloading // Initialize classes autoloading
require_once(MIBEW_FS_ROOT.'/libs/common/autoload.php'); require_once(MIBEW_FS_ROOT . '/libs/common/autoload.php');
spl_autoload_register('class_autoload'); spl_autoload_register('class_autoload');
// Include common libs // Include common libs
require_once(MIBEW_FS_ROOT.'/libs/common/configurations.php'); require_once(MIBEW_FS_ROOT . '/libs/common/configurations.php');
require_once(MIBEW_FS_ROOT.'/libs/common/csrf.php'); require_once(MIBEW_FS_ROOT . '/libs/common/verification.php');
require_once(MIBEW_FS_ROOT.'/libs/common/datetime.php'); require_once(MIBEW_FS_ROOT . '/libs/common/converter.php');
require_once(MIBEW_FS_ROOT.'/libs/common/forms.php'); require_once(MIBEW_FS_ROOT . '/libs/common/locale.php');
require_once(MIBEW_FS_ROOT.'/libs/common/verification.php'); require_once(MIBEW_FS_ROOT . '/libs/common/csrf.php');
require_once(MIBEW_FS_ROOT.'/libs/common/locale.php'); require_once(MIBEW_FS_ROOT . '/libs/common/datetime.php');
require_once(MIBEW_FS_ROOT.'/libs/common/misc.php'); require_once(MIBEW_FS_ROOT . '/libs/common/forms.php');
require_once(MIBEW_FS_ROOT.'/libs/common/request.php'); require_once(MIBEW_FS_ROOT . '/libs/common/misc.php');
require_once(MIBEW_FS_ROOT.'/libs/common/response.php'); require_once(MIBEW_FS_ROOT . '/libs/common/request.php');
require_once(MIBEW_FS_ROOT.'/libs/common/string.php'); require_once(MIBEW_FS_ROOT . '/libs/common/response.php');
require_once(MIBEW_FS_ROOT . '/libs/common/string.php');
// Make session cookie more secure // Make session cookie more secure
@ini_set('session.cookie_httponly', TRUE); @ini_set('session.cookie_httponly', true);
if (is_secure_request()) { if (is_secure_request()) {
@ini_set('session.cookie_secure', TRUE); @ini_set('session.cookie_secure', true);
} }
@ini_set('session.cookie_path', MIBEW_WEB_ROOT . "/"); @ini_set('session.cookie_path', MIBEW_WEB_ROOT . "/");
@ini_set('session.name', 'MibewSessionID'); @ini_set('session.name', 'MibewSessionID');
@ -66,25 +73,23 @@ session_start();
// Initialize the database // Initialize the database
\Mibew\Database::initialize( \Mibew\Database::initialize(
$mysqlhost, $mysqlhost,
$mysqllogin, $mysqllogin,
$mysqlpass, $mysqlpass,
$use_persistent_connection, $use_persistent_connection,
$mysqldb, $mysqldb,
$mysqlprefix, $mysqlprefix,
$force_charset_in_connection, $force_charset_in_connection,
$dbencoding $dbencoding
); );
if (function_exists("date_default_timezone_set")) { if (function_exists("date_default_timezone_set")) {
// TODO try to get timezone from config.php/session etc. // TODO try to get timezone from config.php/session etc.
// autodetect timezone // autodetect timezone
@date_default_timezone_set(function_exists("date_default_timezone_get") ? @date_default_timezone_get() : "GMT"); @date_default_timezone_set(function_exists("date_default_timezone_get") ? @date_default_timezone_get() : "GMT");
} }
if (! empty($plugins_list)) { if (!empty($plugins_list)) {
// Variable $plugins_config defined in libs/config.php // Variable $plugins_config defined in libs/config.php
\Mibew\PluginManager::loadPlugins($plugins_list); \Mibew\PluginManager::loadPlugins($plugins_list);
} }
?>

View File

@ -29,27 +29,29 @@ use Mibew\Thread;
* - 'threadid': int, ID of the thread, related with visitor or boolean false * - 'threadid': int, ID of the thread, related with visitor or boolean false
* if visitor with specfied ID does not exist. * if visitor with specfied ID does not exist.
*/ */
function invitation_state($visitor_id) { function invitation_state($visitor_id)
$db = Database::getInstance(); {
$db_result = $db->query( $db = Database::getInstance();
"SELECT t.threadid, t.invitationstate, t.istate " . $db_result = $db->query(
"FROM {chatsitevisitor} v, {chatthread} t " . ("SELECT t.threadid, t.invitationstate, t.istate "
"WHERE visitorid = ? " . . "FROM {chatsitevisitor} v, {chatthread} t "
"AND t.threadid = v.threadid", . "WHERE visitorid = ? "
array($visitor_id), . "AND t.threadid = v.threadid"),
array('return_rows' => Database::RETURN_ONE_ROW) array($visitor_id),
); array('return_rows' => Database::RETURN_ONE_ROW)
);
$ret = array(); $ret = array();
if (!$db_result) { if (!$db_result) {
$ret['invited'] = false; $ret['invited'] = false;
$ret['threadid'] = false; $ret['threadid'] = false;
} else { } else {
$ret['invited'] = ($db_result['istate'] == Thread::STATE_INVITED) $ret['invited'] = ($db_result['istate'] == Thread::STATE_INVITED)
&& ($db_result['invitationstate'] == Thread::INVITATION_WAIT); && ($db_result['invitationstate'] == Thread::INVITATION_WAIT);
$ret['threadid'] = $db_result['threadid']; $ret['threadid'] = $db_result['threadid'];
} }
return $ret;
return $ret;
} }
/** /**
@ -58,79 +60,80 @@ function invitation_state($visitor_id) {
* @param int $visitor_id ID of the visitor, who must be invited. * @param int $visitor_id ID of the visitor, who must be invited.
* @param array $operator Info for operator who invite the visitor * @param array $operator Info for operator who invite the visitor
* @return Thread|boolean Thread object related with invitation or boolean * @return Thread|boolean Thread object related with invitation or boolean
* false on failure * false on failure
*/ */
function invitation_invite($visitor_id, $operator) { function invitation_invite($visitor_id, $operator)
// Check if visitor already invited {
$invitation_state = invitation_state($visitor_id); // Check if visitor already invited
if ($invitation_state['invited']) { $invitation_state = invitation_state($visitor_id);
return false; if ($invitation_state['invited']) {
} return false;
}
// Get visitor info // Get visitor info
$visitor = track_get_visitor_by_id($visitor_id); $visitor = track_get_visitor_by_id($visitor_id);
// Get last page visited by the visitor // Get last page visited by the visitor
$visitor_path = track_get_path($visitor); $visitor_path = track_get_path($visitor);
ksort($visitor_path); ksort($visitor_path);
$last_visited_page = array_pop($visitor_path); $last_visited_page = array_pop($visitor_path);
// Get visitor details // Get visitor details
$visitor_details = track_retrieve_details($visitor); $visitor_details = track_retrieve_details($visitor);
// Get some operator's info // Get some operator's info
$operator_name = get_operator_name($operator); $operator_name = get_operator_name($operator);
// Create thread for invitation // Create thread for invitation
$thread = Thread::create(); $thread = Thread::create();
if (! $thread) { if (!$thread) {
// Something went wrong // Something went wrong
return false; return false;
} }
// Populate thread and save it // Populate thread and save it
$thread->agentId = $operator['operatorid']; $thread->agentId = $operator['operatorid'];
$thread->agentName = $operator_name; $thread->agentName = $operator_name;
$thread->userName = $visitor['username']; $thread->userName = $visitor['username'];
$thread->remote = $visitor_details['remote_host']; $thread->remote = $visitor_details['remote_host'];
$thread->referer = $last_visited_page; $thread->referer = $last_visited_page;
// User's locale is unknown, set operator locale to the thread // User's locale is unknown, set operator locale to the thread
$thread->locale = CURRENT_LOCALE; $thread->locale = CURRENT_LOCALE;
$thread->userId = $visitor['userid']; $thread->userId = $visitor['userid'];
$thread->userAgent = $visitor_details['user_agent']; $thread->userAgent = $visitor_details['user_agent'];
$thread->state = Thread::STATE_INVITED; $thread->state = Thread::STATE_INVITED;
$thread->invitationState = Thread::INVITATION_WAIT; $thread->invitationState = Thread::INVITATION_WAIT;
$thread->save(); $thread->save();
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"UPDATE {chatsitevisitor} set " . ("UPDATE {chatsitevisitor} set "
"invitations = invitations + 1, " . . "invitations = invitations + 1, "
"threadid = :thread_id " . . "threadid = :thread_id "
"WHERE visitorid = :visitor_id", . "WHERE visitorid = :visitor_id"),
array( array(
':thread_id' => $thread->id, ':thread_id' => $thread->id,
':visitor_id' => $visitor_id ':visitor_id' => $visitor_id,
) )
); );
// Send some messages // Send some messages
$thread->postMessage( $thread->postMessage(
Thread::KIND_FOR_AGENT, Thread::KIND_FOR_AGENT,
getlocal2( getlocal2(
'chat.visitor.invitation.sent', 'chat.visitor.invitation.sent',
array($operator_name, $last_visited_page) array($operator_name, $last_visited_page)
) )
); );
$thread->postMessage( $thread->postMessage(
Thread::KIND_AGENT, Thread::KIND_AGENT,
getlocal("invitation.message"), getlocal("invitation.message"),
array( array(
'name' => $operator_name, 'name' => $operator_name,
'operator_id' => $operator['operatorid'] 'operator_id' => $operator['operatorid'],
) )
); );
return $thread; return $thread;
} }
/** /**
@ -139,47 +142,48 @@ function invitation_invite($visitor_id, $operator) {
* @param int $visitor_id ID of the visitor who accept invitation * @param int $visitor_id ID of the visitor who accept invitation
* @return Thread|boolean Thread object or boolean false on failure * @return Thread|boolean Thread object or boolean false on failure
*/ */
function invitation_accept($visitor_id) { function invitation_accept($visitor_id)
// Check if visitor was invited {
$invitation_state = invitation_state($visitor_id); // Check if visitor was invited
if (! $invitation_state['invited']) { $invitation_state = invitation_state($visitor_id);
// Visitor was not invited if (!$invitation_state['invited']) {
return false; // Visitor was not invited
} return false;
}
// Get thread related with the visitor // Get thread related with the visitor
$db = Database::getInstance(); $db = Database::getInstance();
$result = $db->query( $result = $db->query(
"SELECT threadid FROM {chatsitevisitor} WHERE visitorid = :visitor_id", "SELECT threadid FROM {chatsitevisitor} WHERE visitorid = :visitor_id",
array(':visitor_id' => $visitor_id), array(':visitor_id' => $visitor_id),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
if (empty($result['threadid'])) { if (empty($result['threadid'])) {
// Something went wrong. There is no thread related with the visitor. // Something went wrong. There is no thread related with the visitor.
return false; return false;
} }
$thread = Thread::load($result['threadid']); $thread = Thread::load($result['threadid']);
if (! $thread) { if (!$thread) {
// Something went wrong. Cannot load thread. // Something went wrong. Cannot load thread.
return false; return false;
} }
// Update thread info // Update thread info
$thread->state = Thread::STATE_LOADING; $thread->state = Thread::STATE_LOADING;
$thread->invitationState = Thread::INVITATION_ACCEPTED; $thread->invitationState = Thread::INVITATION_ACCEPTED;
$thread->chatStarted = time(); $thread->chatStarted = time();
$thread->save(); $thread->save();
// Update visitor info // Update visitor info
$db->query( $db->query(
"UPDATE {chatsitevisitor} SET chats = chats + 1 " . ("UPDATE {chatsitevisitor} SET chats = chats + 1 "
"WHERE visitorid = :visitor_id", . "WHERE visitorid = :visitor_id"),
array(':visitor_id' => $visitor_id) array(':visitor_id' => $visitor_id)
); );
return $thread; return $thread;
} }
/** /**
@ -187,87 +191,89 @@ function invitation_accept($visitor_id) {
* *
* @param int $visitor_id ID of the visitor * @param int $visitor_id ID of the visitor
*/ */
function invitation_reject($visitor_id) { function invitation_reject($visitor_id)
$visitor = track_get_visitor_by_id($visitor_id); {
$visitor = track_get_visitor_by_id($visitor_id);
// Send message to operator // Send message to operator
$thread = Thread::load($visitor['threadid']); $thread = Thread::load($visitor['threadid']);
if ($thread) { if ($thread) {
$thread->postMessage( $thread->postMessage(
Thread::KIND_FOR_AGENT, Thread::KIND_FOR_AGENT,
getlocal('chat.visitor.invitation.rejected') getlocal('chat.visitor.invitation.rejected')
); );
} }
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"UPDATE {chatsitevisitor} v, {chatthread} t SET " . ("UPDATE {chatsitevisitor} v, {chatthread} t SET "
"v.threadid = NULL, " . . "v.threadid = NULL, "
"t.invitationstate = :invitation_rejected, " . . "t.invitationstate = :invitation_rejected, "
"t.istate = :state_closed, " . . "t.istate = :state_closed, "
"t.dtmclosed = :now " . . "t.dtmclosed = :now "
"WHERE t.threadid = v.threadid " . . "WHERE t.threadid = v.threadid "
"AND visitorid = :visitor_id", . "AND visitorid = :visitor_id"),
array( array(
':invitation_rejected' => Thread::INVITATION_REJECTED, ':invitation_rejected' => Thread::INVITATION_REJECTED,
':state_closed' => Thread::STATE_CLOSED, ':state_closed' => Thread::STATE_CLOSED,
':visitor_id' => $visitor_id, ':visitor_id' => $visitor_id,
':now' => time() ':now' => time(),
) )
); );
} }
/** /**
* Close old invitations * Close old invitations
*/ */
function invitation_close_old() { function invitation_close_old()
$db = Database::getInstance(); {
$db = Database::getInstance();
// Get all threads to close // Get all threads to close
$threads = $db->query( $threads = $db->query(
"SELECT * FROM {chatthread} " . ("SELECT * FROM {chatthread} "
"WHERE istate = :state_invited " . . "WHERE istate = :state_invited "
"AND invitationstate = :invitation_wait " . . "AND invitationstate = :invitation_wait "
"AND (:now - dtmcreated) > :lifetime", . "AND (:now - dtmcreated) > :lifetime"),
array( array(
':invitation_wait' => Thread::INVITATION_WAIT, ':invitation_wait' => Thread::INVITATION_WAIT,
':state_invited' => Thread::STATE_INVITED, ':state_invited' => Thread::STATE_INVITED,
':lifetime' => Settings::get('invitation_lifetime'), ':lifetime' => Settings::get('invitation_lifetime'),
':now' => time() ':now' => time(),
), ),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
// Remove old invitations // Remove old invitations
$db->query( $db->query(
"UPDATE {chatsitevisitor} v, {chatthread} t SET " . ("UPDATE {chatsitevisitor} v, {chatthread} t SET "
"t.invitationstate = :invitation_ignored, " . . "t.invitationstate = :invitation_ignored, "
"t.istate = :state_closed, " . . "t.istate = :state_closed, "
"t.dtmclosed = :now, " . . "t.dtmclosed = :now, "
"v.threadid = NULL " . . "v.threadid = NULL "
"WHERE t.istate = :state_invited " . . "WHERE t.istate = :state_invited "
"AND t.invitationstate = :invitation_wait " . . "AND t.invitationstate = :invitation_wait "
"AND (:now - t.dtmcreated) > :lifetime", . "AND (:now - t.dtmcreated) > :lifetime"),
array( array(
':invitation_ignored' => Thread::INVITATION_IGNORED, ':invitation_ignored' => Thread::INVITATION_IGNORED,
':invitation_wait' => Thread::INVITATION_WAIT, ':invitation_wait' => Thread::INVITATION_WAIT,
':state_closed' => Thread::STATE_CLOSED, ':state_closed' => Thread::STATE_CLOSED,
':state_invited' => Thread::STATE_INVITED, ':state_invited' => Thread::STATE_INVITED,
':lifetime' => Settings::get('invitation_lifetime'), ':lifetime' => Settings::get('invitation_lifetime'),
':now' => time() ':now' => time(),
) )
); );
// Iterate over all threads and send messages to operator about close by // Iterate over all threads and send messages to operator about close by
// timeout // timeout
foreach($threads as $thread_info) { foreach ($threads as $thread_info) {
$thread = Thread::createFromDbInfo($thread_info); $thread = Thread::createFromDbInfo($thread_info);
$thread->postMessage( $thread->postMessage(
Thread::KIND_FOR_AGENT, Thread::KIND_FOR_AGENT,
getstring_('chat.visitor.invitation.ignored', $thread->locale) getstring_('chat.visitor.invitation.ignored', $thread->locale)
); );
unset($thread); unset($thread);
} }
} }
/** /**
@ -276,32 +282,31 @@ function invitation_close_old() {
* @param Thread $thread Thread object related with invitation * @param Thread $thread Thread object related with invitation
* @return array Array of invitation data * @return array Array of invitation data
*/ */
function setup_invitation_view(Thread $thread) { function setup_invitation_view(Thread $thread)
$data = prepare_chat_app_data(); {
$data = prepare_chat_app_data();
// Set refresh frequency // Set refresh frequency
$data['frequency'] = Settings::get('updatefrequency_chat'); $data['frequency'] = Settings::get('updatefrequency_chat');
// Load JavaScript plugins and JavaScripts, CSS files required by them // Load JavaScript plugins and JavaScripts, CSS files required by them
$data = array_merge_recursive($data, get_plugins_data('client_chat_window')); $data = array_merge_recursive($data, get_plugins_data('client_chat_window'));
// Create some empty arrays // Create some empty arrays
$data['invitation'] = array(); $data['invitation'] = array();
$data['invitation']['thread'] = array( $data['invitation']['thread'] = array(
'id' => $thread->id, 'id' => $thread->id,
'token' => $thread->lastToken 'token' => $thread->lastToken,
); );
$data['invitation']['user'] = array( $data['invitation']['user'] = array(
'name' => htmlspecialchars(topage($thread->userName)), 'name' => htmlspecialchars(to_page($thread->userName)),
'canChangeName' => false, 'canChangeName' => false,
'isAgent' => false 'isAgent' => false,
); );
$data['startFrom'] = 'invitation'; $data['startFrom'] = 'invitation';
return $data; return $data;
} }
?>

View File

@ -15,25 +15,29 @@
* limitations under the License. * limitations under the License.
*/ */
function mibew_mail($toaddr, $reply_to, $subject, $body) function mibew_mail($to_addr, $reply_to, $subject, $body)
{ {
global $mibew_mailbox, $mail_encoding; global $mibew_mailbox, $mail_encoding;
$headers = "From: $mibew_mailbox\r\n" $headers = "From: $mibew_mailbox\r\n"
. "Reply-To: " . myiconv(MIBEW_ENCODING, $mail_encoding, $reply_to) . "\r\n" . "Reply-To: " . myiconv(MIBEW_ENCODING, $mail_encoding, $reply_to) . "\r\n"
. "Content-Type: text/plain; charset=$mail_encoding\r\n" . "Content-Type: text/plain; charset=$mail_encoding\r\n"
. 'X-Mailer: PHP/' . phpversion(); . 'X-Mailer: PHP/' . phpversion();
$real_subject = "=?" . $mail_encoding . "?B?" . base64_encode(myiconv(MIBEW_ENCODING, $mail_encoding, $subject)) . "?="; $real_subject = "=?" . $mail_encoding . "?B?"
. base64_encode(myiconv(MIBEW_ENCODING, $mail_encoding, $subject)) . "?=";
$body = preg_replace("/\n/", "\r\n", $body); $body = preg_replace("/\n/", "\r\n", $body);
$old_from = ini_get('sendmail_from'); $old_from = ini_get('sendmail_from');
@ini_set('sendmail_from', $mibew_mailbox); @ini_set('sendmail_from', $mibew_mailbox);
@mail($toaddr, $real_subject, wordwrap(myiconv(MIBEW_ENCODING, $mail_encoding, $body), 70), $headers); @mail(
if (isset($old_from)) { $to_addr,
@ini_set('sendmail_from', $old_from); $real_subject,
} wordwrap(myiconv(MIBEW_ENCODING, $mail_encoding, $body), 70),
$headers
);
if (isset($old_from)) {
@ini_set('sendmail_from', $old_from);
}
} }
?>

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,6 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* Builds list of operator settings tabs. The keys of the resulting array are * Builds list of operator settings tabs. The keys of the resulting array are
* tabs titles and the values are tabs URLs. * tabs titles and the values are tabs URLs.
@ -24,19 +23,26 @@
* @param int $active Number of the active tab. The count starts from 0. * @param int $active Number of the active tab. The count starts from 0.
* @return array Tabs list * @return array Tabs list
*/ */
function setup_operator_settings_tabs($operator_id, $active) { function setup_operator_settings_tabs($operator_id, $active)
$tabs = array(); {
$tabs = array();
if ($operator_id) { if ($operator_id) {
$tabs = array( $tabs = array(
getlocal("page_agent.tab.main") => $active != 0 ? (MIBEW_WEB_ROOT . "/operator/operator.php?op=" . $operator_id) : "", getlocal("page_agent.tab.main") => ($active != 0
getlocal("page_agent.tab.avatar") => $active != 1 ? (MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . $operator_id) : "", ? (MIBEW_WEB_ROOT . "/operator/operator.php?op=" . $operator_id)
getlocal("page_agent.tab.groups") => $active != 2 ? (MIBEW_WEB_ROOT . "/operator/opgroups.php?op=" . $operator_id) : "", : ""),
getlocal("page_agent.tab.permissions") => $active != 3 ? (MIBEW_WEB_ROOT . "/operator/permissions.php?op=" . $operator_id) : "" getlocal("page_agent.tab.avatar") => ($active != 1
); ? (MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . $operator_id)
} : ""),
getlocal("page_agent.tab.groups") => ($active != 2
? (MIBEW_WEB_ROOT . "/operator/opgroups.php?op=" . $operator_id)
: ""),
getlocal("page_agent.tab.permissions") => ($active != 3
? (MIBEW_WEB_ROOT . "/operator/permissions.php?op=" . $operator_id)
: ""),
);
}
return $tabs; return $tabs;
} }
?>

View File

@ -32,11 +32,13 @@ define('PAGINATION_LINKS_ON_PAGE', 5);
* @param string $title Link title * @param string $title Link title
* @return string HTML markup * @return string HTML markup
*/ */
function generate_pagination_link($page, $title) { function generate_pagination_link($page, $title)
$lnk = $_SERVER['REQUEST_URI']; {
$href = preg_replace("/\?page=\d+\&/", "?", preg_replace("/\&page=\d+/", "", $lnk)); $lnk = $_SERVER['REQUEST_URI'];
$href .= strstr($href, "?") ? "&page=$page" : "?page=$page"; $href = preg_replace("/\?page=\d+\&/", "?", preg_replace("/\&page=\d+/", "", $lnk));
return "<a href=\"" . htmlspecialchars($href) . "\" class=\"pagelink\">$title</a>"; $href .= strstr($href, "?") ? "&page=$page" : "?page=$page";
return "<a href=\"" . htmlspecialchars($href) . "\" class=\"pagelink\">$title</a>";
} }
/** /**
@ -47,8 +49,9 @@ function generate_pagination_link($page, $title) {
* @param string $alt Value of an 'alt' atribute of the image tag. * @param string $alt Value of an 'alt' atribute of the image tag.
* @return string HTML markup * @return string HTML markup
*/ */
function generate_pagination_image($style_path, $id, $alt) { function generate_pagination_image($style_path, $id, $alt)
return "<img src=\"" . $style_path . "/images/$id.gif\" border=\"0\" alt=\"" . htmlspecialchars($alt) . "\"/>"; {
return "<img src=\"" . $style_path . "/images/$id.gif\" border=\"0\" alt=\"" . htmlspecialchars($alt) . "\"/>";
} }
/** /**
@ -65,37 +68,38 @@ function generate_pagination_image($style_path, $id, $alt) {
* - start: int, index of item to start from. * - start: int, index of item to start from.
* - end: int, index of item to end at. * - end: int, index of item to end at.
*/ */
function pagination_info($items_count, $default_items_per_page = 15) { function pagination_info($items_count, $default_items_per_page = 15)
if ($items_count) { {
$items_per_page = verifyparam("items", "/^\d{1,3}$/", $default_items_per_page); if ($items_count) {
if ($items_per_page < 2) { $items_per_page = verify_param("items", "/^\d{1,3}$/", $default_items_per_page);
$items_per_page = 2; if ($items_per_page < 2) {
} $items_per_page = 2;
}
$total_pages = div($items_count + $items_per_page - 1, $items_per_page); $total_pages = div($items_count + $items_per_page - 1, $items_per_page);
$curr_page = verifyparam("page", "/^\d{1,6}$/", 1); $curr_page = verify_param("page", "/^\d{1,6}$/", 1);
if ($curr_page < 1) { if ($curr_page < 1) {
$curr_page = 1; $curr_page = 1;
} }
if ($curr_page > $total_pages) { if ($curr_page > $total_pages) {
$curr_page = $total_pages; $curr_page = $total_pages;
} }
$start_index = ($curr_page - 1) * $items_per_page; $start_index = ($curr_page - 1) * $items_per_page;
$end_index = min($start_index + $items_per_page, $items_count); $end_index = min($start_index + $items_per_page, $items_count);
return array( return array(
"page" => $curr_page, "page" => $curr_page,
"items" => $items_per_page, "items" => $items_per_page,
"total" => $total_pages, "total" => $total_pages,
"count" => $items_count, "count" => $items_count,
"start" => $start_index, "start" => $start_index,
"end" => $end_index, "end" => $end_index,
); );
} else { } else {
return false; return false;
} }
} }
/** /**
@ -108,26 +112,28 @@ function pagination_info($items_count, $default_items_per_page = 15) {
* pagination_info function for details. * pagination_info function for details.
* - items: slice of items to display. * - items: slice of items to display.
*/ */
function setup_pagination($items, $default_items_per_page = 15) { function setup_pagination($items, $default_items_per_page = 15)
if (count($items) > 0) { {
$info = pagination_info(count($items), $default_items_per_page); if (count($items) > 0) {
if ($info) { $info = pagination_info(count($items), $default_items_per_page);
$items_slice = array_slice( if ($info) {
$items, $items_slice = array_slice(
$info['start'], $items,
$info['end'] - $info['start'] $info['start'],
); $info['end'] - $info['start']
return array( );
'info' => $info,
'items' => $items_slice,
);
}
}
return array( return array(
'info' => false, 'info' => $info,
'items' => false, 'items' => $items_slice,
); );
}
}
return array(
'info' => false,
'items' => false,
);
} }
/** /**
@ -140,64 +146,66 @@ function setup_pagination($items, $default_items_per_page = 15) {
* page. * page.
* @return string HTML markup * @return string HTML markup
*/ */
function generate_pagination($style_path, $pagination, $bottom = true) { function generate_pagination($style_path, $pagination, $bottom = true)
$result = getlocal2( {
"tag.pagination.info", $result = getlocal2(
array( "tag.pagination.info",
$pagination['page'], array(
$pagination['total'], $pagination['page'],
$pagination['start'] + 1, $pagination['total'],
$pagination['end'], $pagination['start'] + 1,
$pagination['count'] $pagination['end'],
) $pagination['count'],
) . "<br/>"; )
) . "<br/>";
if ($pagination['total'] > 1) { if ($pagination['total'] > 1) {
if (!$bottom) { if (!$bottom) {
$result = ""; $result = "";
} else { } else {
$result .= "<br/>"; $result .= "<br/>";
} }
$result .= "<div class='pagination'>"; $result .= "<div class='pagination'>";
$curr_page = $pagination['page']; $curr_page = $pagination['page'];
$minPage = max($curr_page - PAGINATION_LINKS_ON_PAGE, 1); $min_page = max($curr_page - PAGINATION_LINKS_ON_PAGE, 1);
$maxPage = min($curr_page + PAGINATION_LINKS_ON_PAGE, $pagination['total']); $max_page = min($curr_page + PAGINATION_LINKS_ON_PAGE, $pagination['total']);
if ($curr_page > 1) { if ($curr_page > 1) {
$result .= generate_pagination_link( $result .= generate_pagination_link(
$curr_page - 1, $curr_page - 1,
generate_pagination_image( generate_pagination_image(
$style_path, $style_path,
"prevpage", "prevpage",
getlocal("tag.pagination.previous") getlocal("tag.pagination.previous")
) )
) . PAGINATION_SPACING; ) . PAGINATION_SPACING;
} }
for ($i = $minPage; $i <= $maxPage; $i++) { for ($i = $min_page; $i <= $max_page; $i++) {
$title = abs($curr_page - $i) >= PAGINATION_LINKS_ON_PAGE && $i != 1 ? "..." : $i; $title = (abs($curr_page - $i) >= PAGINATION_LINKS_ON_PAGE && $i != 1) ? "..." : $i;
if ($i != $curr_page) if ($i != $curr_page) {
$result .= generate_pagination_link($i, $title); $result .= generate_pagination_link($i, $title);
else } else {
$result .= "<span class=\"pagecurrent\">$title</span>"; $result .= "<span class=\"pagecurrent\">$title</span>";
if ($i < $maxPage) }
$result .= PAGINATION_SPACING; if ($i < $max_page) {
} $result .= PAGINATION_SPACING;
}
}
if ($curr_page < $pagination['total']) { if ($curr_page < $pagination['total']) {
$result .= PAGINATION_SPACING . generate_pagination_link( $result .= PAGINATION_SPACING . generate_pagination_link(
$curr_page + 1, $curr_page + 1,
generate_pagination_image( generate_pagination_image(
$style_path, $style_path,
"nextpage", "nextpage",
getlocal("tag.pagination.next") getlocal("tag.pagination.next")
) )
); );
} }
$result .= "</div>"; $result .= "</div>";
} }
return $result;
return $result;
} }
?>

View File

@ -25,20 +25,31 @@ use Mibew\Settings;
* @param int $active Number of the active tab. The count starts from 0. * @param int $active Number of the active tab. The count starts from 0.
* @return array Tabs list * @return array Tabs list
*/ */
function setup_settings_tabs($active) { function setup_settings_tabs($active)
$tabs = array( {
getlocal("page_settings.tab.main") => $active != 0 ? (MIBEW_WEB_ROOT . "/operator/settings.php") : "", $tabs = array(
getlocal("page_settings.tab.features") => $active != 1 ? (MIBEW_WEB_ROOT . "/operator/features.php") : "", getlocal("page_settings.tab.main") => ($active != 0
getlocal("page_settings.tab.performance") => $active != 2 ? (MIBEW_WEB_ROOT . "/operator/performance.php") : "", ? (MIBEW_WEB_ROOT . "/operator/settings.php")
getlocal("page_settings.tab.page_themes") => $active != 3 ? (MIBEW_WEB_ROOT . "/operator/page_themes.php") : "", : ""),
getlocal("page_settings.tab.themes") => $active != 4 ? (MIBEW_WEB_ROOT . "/operator/themes.php") : "", getlocal("page_settings.tab.features") => ($active != 1
); ? (MIBEW_WEB_ROOT . "/operator/features.php")
: ""),
getlocal("page_settings.tab.performance") => ($active != 2
? (MIBEW_WEB_ROOT . "/operator/performance.php")
: ""),
getlocal("page_settings.tab.page_themes") => ($active != 3
? (MIBEW_WEB_ROOT . "/operator/page_themes.php")
: ""),
getlocal("page_settings.tab.themes") => ($active != 4
? (MIBEW_WEB_ROOT . "/operator/themes.php")
: ""),
);
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$tabs[getlocal("page_settings.tab.invitationthemes")] = ($active != 5 ? (MIBEW_WEB_ROOT . "/operator/invitationthemes.php") : ""); $tabs[getlocal("page_settings.tab.invitationthemes")] = ($active != 5
} ? (MIBEW_WEB_ROOT . "/operator/invitationthemes.php")
: "");
}
return $tabs; return $tabs;
} }
?>

File diff suppressed because it is too large Load Diff

View File

@ -20,75 +20,78 @@ use Mibew\Database;
use Mibew\Settings; use Mibew\Settings;
use Mibew\Thread; use Mibew\Thread;
// Initialize libraries function track_visitor($visitor_id, $entry, $referer)
require_once(MIBEW_FS_ROOT.'/libs/chat.php');
function track_visitor($visitorid, $entry, $referer)
{ {
$visitor = track_get_visitor_by_id($visitorid); $visitor = track_get_visitor_by_id($visitor_id);
if (FALSE === $visitor) { if (false === $visitor) {
$visitor = track_visitor_start($entry, $referer); $visitor = track_visitor_start($entry, $referer);
return $visitor;
} else { return $visitor;
$db = Database::getInstance(); } else {
$db->query( $db = Database::getInstance();
"update {chatsitevisitor} set lasttime = :now " . $db->query(
"where visitorid = :visitorid", "UPDATE {chatsitevisitor} SET lasttime = :now WHERE visitorid = :visitorid",
array( array(
':visitorid' => $visitor['visitorid'], ':visitorid' => $visitor['visitorid'],
':now' => time() ':now' => time(),
) )
); );
track_visit_page($visitor['visitorid'], $referer); track_visit_page($visitor['visitorid'], $referer);
return $visitor['visitorid'];
} return $visitor['visitorid'];
}
} }
function track_visitor_start($entry, $referer) function track_visitor_start($entry, $referer)
{ {
$visitor = visitor_from_request(); $visitor = visitor_from_request();
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"insert into {chatsitevisitor} (userid,username,firsttime,lasttime,entry,details) ". ("INSERT INTO {chatsitevisitor} ( "
"values (:userid, :username, :now, :now, :entry, :details)", . "userid, username, firsttime, lasttime, entry,details "
array( . ") VALUES ( "
':userid' => $visitor['id'], . ":userid, :username, :now, :now, :entry, :details "
':username' => $visitor['name'], . ")"),
':now' => time(), array(
':entry' => $entry, ':userid' => $visitor['id'],
':details' => track_build_details() ':username' => $visitor['name'],
) ':now' => time(),
); ':entry' => $entry,
':details' => track_build_details(),
)
);
$id = $db->insertedId(); $id = $db->insertedId();
if ($id) { if ($id) {
track_visit_page($id, $referer); track_visit_page($id, $referer);
} }
return $id ? $id : 0; return $id ? $id : 0;
} }
function track_get_visitor_by_id($visitorid) function track_get_visitor_by_id($visitor_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
return $db->query(
"select * from {chatsitevisitor} where visitorid = ?", return $db->query(
array($visitorid), "SELECT * FROM {chatsitevisitor} WHERE visitorid = ?",
array('return_rows' => Database::RETURN_ONE_ROW) array($visitor_id),
); array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
function track_get_visitor_by_threadid($threadid) function track_get_visitor_by_thread_id($thread_id)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
return $db->query(
"select * from {chatsitevisitor} where threadid = ?", return $db->query(
array($threadid), "SELECT * FROM {chatsitevisitor} WHERE threadid = ?",
array('return_rows' => Database::RETURN_ONE_ROW) array($thread_id),
); array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
/** /**
@ -97,66 +100,73 @@ function track_get_visitor_by_threadid($threadid)
* @param string $user_id User id * @param string $user_id User id
* @return boolean|array Visitor array or boolean false if visitor not exists * @return boolean|array Visitor array or boolean false if visitor not exists
*/ */
function track_get_visitor_by_user_id($user_id) { function track_get_visitor_by_user_id($user_id)
$db = Database::getInstance(); {
return $db->query( $db = Database::getInstance();
"select * from {chatsitevisitor} where userid = ?",
array($user_id), return $db->query(
array('return_rows' => Database::RETURN_ONE_ROW) "SELECT * FROM {chatsitevisitor} WHERE userid = ?",
); array($user_id),
array('return_rows' => Database::RETURN_ONE_ROW)
);
} }
function track_visit_page($visitorid, $page) function track_visit_page($visitor_id, $page)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
if (empty($page)) { if (empty($page)) {
return; return;
} }
$lastpage = $db->query( $last_page = $db->query(
"select address from {visitedpage} where visitorid = ? " . ("SELECT address "
"order by visittime desc limit 1", . "FROM {visitedpage} "
array($visitorid), . "WHERE visitorid = ? "
array('return_rows' => Database::RETURN_ONE_ROW) . "ORDER BY visittime DESC "
); . "LIMIT 1"),
if ( $lastpage['address'] != $page ) { array($visitor_id),
$db->query( array('return_rows' => Database::RETURN_ONE_ROW)
"insert into {visitedpage} (visitorid, address, visittime) " . );
"values (:visitorid, :page, :now)", if ($last_page['address'] != $page) {
array( $db->query(
':visitorid' => $visitorid, ("INSERT INTO {visitedpage} ("
':page' => $page, . "visitorid, address, visittime "
':now' => time() . ") VALUES ( "
) . ":visitorid, :page, :now "
); .")"),
} array(
':visitorid' => $visitor_id,
':page' => $page,
':now' => time(),
)
);
}
} }
function track_get_path($visitor) function track_get_path($visitor)
{ {
$db = Database::getInstance(); $db = Database::getInstance();
$query_result = $db->query( $query_result = $db->query(
"select address, visittime from {visitedpage} " . "SELECT address, visittime FROM {visitedpage} WHERE visitorid = ?",
"where visitorid = ?", array($visitor['visitorid']),
array($visitor['visitorid']), array('return_rows' => Database::RETURN_ALL_ROWS)
array('return_rows' => Database::RETURN_ALL_ROWS) );
); $result = array();
$result = array(); foreach ($query_result as $page) {
foreach ($query_result as $page) { $result[$page['visittime']] = $page['address'];
$result[$page['visittime']] = $page['address']; }
}
return $result; return $result;
} }
function track_build_details() function track_build_details()
{ {
$result = array( $result = array(
'user_agent' => $_SERVER['HTTP_USER_AGENT'], 'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'remote_host' => get_remote_host() 'remote_host' => get_remote_host(),
); );
return serialize($result); return serialize($result);
} }
function track_retrieve_details($visitor) function track_retrieve_details($visitor)
@ -167,64 +177,68 @@ function track_retrieve_details($visitor)
/** /**
* Remove old visitors * Remove old visitors
*/ */
function track_remove_old_visitors() { function track_remove_old_visitors()
$db = Database::getInstance(); {
$db = Database::getInstance();
// Remove associations of visitors with closed threads // Remove associations of visitors with closed threads
$db->query( $db->query(
"UPDATE {chatsitevisitor} SET threadid = NULL " . "UPDATE {chatsitevisitor} SET threadid = NULL "
"WHERE threadid IS NOT NULL AND " . . "WHERE threadid IS NOT NULL AND "
" (SELECT count(*) FROM {chatthread} " . . "(SELECT count(*) FROM {chatthread} "
"WHERE threadid = {chatsitevisitor}.threadid" . . "WHERE threadid = {chatsitevisitor}.threadid "
" AND istate <> " . Thread::STATE_CLOSED . " " . . "AND istate <> " . Thread::STATE_CLOSED . " "
" AND istate <> " . Thread::STATE_LEFT . ") = 0" . "AND istate <> " . Thread::STATE_LEFT . ") = 0 "
); );
// Remove old visitors // Remove old visitors
$db->query( $db->query(
"DELETE FROM {chatsitevisitor} " . ("DELETE FROM {chatsitevisitor} "
"WHERE (:now - lasttime) > :lifetime ". . "WHERE (:now - lasttime) > :lifetime "
"AND threadid IS NULL", . "AND threadid IS NULL"),
array( array(
':lifetime' => Settings::get('tracking_lifetime'), ':lifetime' => Settings::get('tracking_lifetime'),
':now' => time() ':now' => time(),
) )
); );
} }
/** /**
* Remove old tracks * Remove old tracks
*/ */
function track_remove_old_tracks() { function track_remove_old_tracks()
$db = Database::getInstance(); {
$db = Database::getInstance();
// Remove old visitors' tracks // Remove old visitors' tracks
$db->query( $db->query(
"DELETE FROM {visitedpage} " . ("DELETE FROM {visitedpage} "
"WHERE (:now - visittime) > :lifetime " . . "WHERE (:now - visittime) > :lifetime "
// Remove only tracks that are included in statistics // Remove only tracks that are included in statistics
"AND calculated = 1 " . . "AND calculated = 1 "
"AND visitorid NOT IN (SELECT visitorid FROM {chatsitevisitor}) ", . "AND visitorid NOT IN (SELECT visitorid FROM {chatsitevisitor}) "),
array( array(
':lifetime' => Settings::get('tracking_lifetime'), ':lifetime' => Settings::get('tracking_lifetime'),
':now' => time() ':now' => time(),
) )
); );
} }
/** /**
* Return user id by visitor id. * Return user id by visitor id.
* *
* @param int $visitorid Id of the visitor * @param int $visitor_id Id of the visitor
* @return string|boolean user id or boolean false if there is no visitor with * @return string|boolean user id or boolean false if there is no visitor with
* specified visitor id * specified visitor id
*/ */
function track_get_user_id($visitorid) { function track_get_user_id($visitor_id)
$visitor = track_get_visitor_by_id($visitorid); {
if (! $visitor) { $visitor = track_get_visitor_by_id($visitor_id);
return false; if (!$visitor) {
} return false;
return $visitor['userid']; }
return $visitor['userid'];
} }
/** /**
@ -234,17 +248,16 @@ function track_get_user_id($visitorid) {
* visitor. * visitor.
* @param Thread $thread Chat thread object * @param Thread $thread Chat thread object
*/ */
function track_visitor_bind_thread($user_id, $thread) { function track_visitor_bind_thread($user_id, $thread)
$db = Database::getInstance(); {
$db->query( $db = Database::getInstance();
'UPDATE {chatsitevisitor} ' . $db->query(
'SET threadid = :thread_id ' . ('UPDATE {chatsitevisitor} '
'WHERE userid = :user_id', . 'SET threadid = :thread_id '
array( . 'WHERE userid = :user_id'),
':thread_id' => $thread->id, array(
':user_id' => $user_id ':thread_id' => $thread->id,
) ':user_id' => $user_id,
); )
);
} }
?>

View File

@ -18,50 +18,50 @@
// Import namespaces and classes of the core // Import namespaces and classes of the core
use Mibew\Settings; use Mibew\Settings;
function get_useragent_version($userAgent) function get_user_agent_version($user_agent)
{ {
$known_agents = get_known_user_agents(); $known_agents = get_known_user_agents();
if (is_array($known_agents)) { if (is_array($known_agents)) {
$userAgent = strtolower($userAgent); $user_agent = strtolower($user_agent);
foreach ($known_agents as $agent) { foreach ($known_agents as $agent) {
if (strstr($userAgent, $agent)) { if (strstr($user_agent, $agent)) {
if (preg_match("/" . $agent . "[\\s\/]?(\\d+(\\.\\d+(\\.\\d+(\\.\\d+)?)?)?)/", $userAgent, $matches)) { if (preg_match("/" . $agent . "[\\s\/]?(\\d+(\\.\\d+(\\.\\d+(\\.\\d+)?)?)?)/", $user_agent, $matches)) {
$ver = $matches[1]; $ver = $matches[1];
if ($agent == 'safari') { if ($agent == 'safari') {
if (preg_match("/version\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) { if (preg_match("/version\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $user_agent, $matches)) {
$ver = $matches[1]; $ver = $matches[1];
} else { } else {
$ver = "1 or 2 (build " . $ver . ")"; $ver = "1 or 2 (build " . $ver . ")";
} }
if (preg_match("/mobile\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $userAgent, $matches)) { if (preg_match("/mobile\/(\\d+(\\.\\d+(\\.\\d+)?)?)/", $user_agent, $matches)) {
$userAgent = "iPhone " . $matches[1] . " ($agent $ver)"; $user_agent = "iPhone " . $matches[1] . " ($agent $ver)";
break; break;
} }
} }
$userAgent = ucfirst($agent) . " " . $ver; $user_agent = ucfirst($agent) . " " . $ver;
break; break;
} }
} }
} }
} }
return $userAgent;
return $user_agent;
} }
function get_user_addr($addr) function get_user_addr($addr)
{ {
if (Settings::get('geolink') && preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $addr, $matches)) { if (Settings::get('geolink') && preg_match("/(\\d+\\.\\d+\\.\\d+\\.\\d+)/", $addr, $matches)) {
$userip = $matches[1]; $user_ip = $matches[1];
return get_popup( return get_popup(
str_replace("{ip}", $userip, Settings::get('geolink')), str_replace("{ip}", $user_ip, Settings::get('geolink')),
'', '',
htmlspecialchars($addr), htmlspecialchars($addr),
"GeoLocation", "GeoLocation",
"ip$userip", "ip$user_ip",
Settings::get('geolinkparams') Settings::get('geolinkparams')
); );
} }
return htmlspecialchars($addr);
}
?> return htmlspecialchars($addr);
}

View File

@ -19,7 +19,7 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
$page = array(); $page = array();
$page['title'] = getlocal("license.title"); $page['title'] = getlocal("license.title");
@ -28,5 +28,3 @@ $page['fixedwrap'] = true;
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('license', $page); $page_style->render('license', $page);
?>

View File

@ -21,68 +21,68 @@ use Mibew\Thread;
use Mibew\Style\ChatStyle; use Mibew\Style\ChatStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(__FILE__).'/libs/init.php'); require_once(dirname(__FILE__) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/notify.php'); require_once(MIBEW_FS_ROOT . '/libs/notify.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$page = array( $page = array(
'errors' =>array() 'errors' => array(),
); );
$token = verifyparam( "token", "/^\d{1,8}$/"); $token = verify_param("token", "/^\d{1,8}$/");
$threadid = verifyparam( "thread", "/^\d{1,8}$/"); $thread_id = verify_param("thread", "/^\d{1,8}$/");
$thread = Thread::load($threadid, $token); $thread = Thread::load($thread_id, $token);
if (! $thread) { if (!$thread) {
die("wrong thread"); die("wrong thread");
} }
// Initialize chat style which is currently used in system // Initialize chat style which is currently used in system
$chat_style = new ChatStyle(ChatStyle::currentStyle()); $chat_style = new ChatStyle(ChatStyle::currentStyle());
$email = getparam('email'); $email = get_param('email');
$page['email'] = $email; $page['email'] = $email;
$group = is_null($thread->groupId)?NULL:group_by_id($thread->groupId); $group = is_null($thread->groupId) ? null : group_by_id($thread->groupId);
if( !$email ) { if (!$email) {
$page['errors'][] = no_field("form.field.email"); $page['errors'][] = no_field("form.field.email");
} else if( !is_valid_email($email)) { } elseif (!is_valid_email($email)) {
$page['errors'][] = wrong_field("form.field.email"); $page['errors'][] = wrong_field("form.field.email");
} }
if( count($page['errors']) > 0 ) { if (count($page['errors']) > 0) {
$page['formemail'] = $email; $page['formemail'] = $email;
$page['chat.thread.id'] = $thread->id; $page['chat.thread.id'] = $thread->id;
$page['chat.thread.token'] = $thread->lastToken; $page['chat.thread.token'] = $thread->lastToken;
$page['level'] = ""; $page['level'] = "";
$page = array_merge_recursive( $page = array_merge_recursive(
$page, $page,
setup_logo($group) setup_logo($group)
); );
$chat_style->render('mail', $page); $chat_style->render('mail', $page);
exit; exit;
} }
$history = ""; $history = "";
$last_id = -1; $last_id = -1;
$messages = $thread->getMessages(true, $last_id); $messages = $thread->getMessages(true, $last_id);
foreach ($messages as $msg) { foreach ($messages as $msg) {
$history .= message_to_text($msg); $history .= message_to_text($msg);
} }
$subject = getstring("mail.user.history.subject"); $subject = getstring("mail.user.history.subject");
$body = getstring2( $body = getstring2(
"mail.user.history.body", "mail.user.history.body",
array($thread->userName, $history, Settings::get('title'), Settings::get('hosturl')) array($thread->userName,
$history,
Settings::get('title'),
Settings::get('hosturl')
)
); );
mibew_mail($email, $mibew_mailbox, $subject, $body); mibew_mail($email, $mibew_mailbox, $subject, $body);
$page = array_merge_recursive( $page = array_merge_recursive($page, setup_logo($group));
$page,
setup_logo($group)
);
$chat_style->render('mailsent', $page); $chat_style->render('mailsent', $page);
exit;
?>

View File

@ -22,30 +22,31 @@ use Mibew\Style\ChatStyle;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/canned.php'); require_once(MIBEW_FS_ROOT . '/libs/canned.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
if (Settings::get('enablessl') == "1" && Settings::get('forcessl') == "1") { if (Settings::get('enablessl') == "1" && Settings::get('forcessl') == "1") {
if (!is_secure_request()) { if (!is_secure_request()) {
$requested = $_SERVER['PHP_SELF']; $requested = $_SERVER['PHP_SELF'];
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) { if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_SERVER['QUERY_STRING']) {
header("Location: " . get_app_location(true, true) . "/operator/agent.php?" . $_SERVER['QUERY_STRING']); header("Location: " . get_app_location(true, true) . "/operator/agent.php?" . $_SERVER['QUERY_STRING']);
} else { } else {
die("only https connections are handled"); die("only https connections are handled");
} }
exit; exit;
} }
} }
$threadid = verifyparam("thread", "/^\d{1,8}$/"); $thread_id = verify_param("thread", "/^\d{1,8}$/");
$page = array( $page = array(
'errors' => array() 'errors' => array(),
); );
// Initialize chat style which is currently used in system // Initialize chat style which is currently used in system
@ -55,92 +56,92 @@ $page_style = new PageStyle(PageStyle::currentStyle());
if (!isset($_GET['token'])) { if (!isset($_GET['token'])) {
$remote_level = get_remote_level($_SERVER['HTTP_USER_AGENT']); $remote_level = get_remote_level($_SERVER['HTTP_USER_AGENT']);
if ($remote_level != "ajaxed") { if ($remote_level != "ajaxed") {
$page['errors'][] = getlocal("thread.error.old_browser"); $page['errors'][] = getlocal("thread.error.old_browser");
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
$thread = Thread::load($threadid); $thread = Thread::load($thread_id);
if (!$thread || !isset($thread->lastToken)) { if (!$thread || !isset($thread->lastToken)) {
$page['errors'][] = getlocal("thread.error.wrong_thread"); $page['errors'][] = getlocal("thread.error.wrong_thread");
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
$viewonly = verifyparam("viewonly", "/^true$/", false); $view_only = verify_param("viewonly", "/^true$/", false);
$forcetake = verifyparam("force", "/^true$/", false); $force_take = verify_param("force", "/^true$/", false);
if (!$viewonly && $thread->state == Thread::STATE_CHATTING && $operator['operatorid'] != $thread->agentId) { if (!$view_only && $thread->state == Thread::STATE_CHATTING && $operator['operatorid'] != $thread->agentId) {
if (!is_capable(CAN_TAKEOVER, $operator)) { if (!is_capable(CAN_TAKEOVER, $operator)) {
$page['errors'][] = getlocal("thread.error.cannot_take_over"); $page['errors'][] = getlocal("thread.error.cannot_take_over");
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
if ($forcetake == false) { if ($force_take == false) {
$page = array( $page = array(
'user' => topage($thread->userName), 'user' => to_page($thread->userName),
'agent' => topage($thread->agentName), 'agent' => to_page($thread->agentName),
'link' => $_SERVER['PHP_SELF'] . "?thread=$threadid&amp;force=true", 'link' => $_SERVER['PHP_SELF'] . "?thread=$thread_id&amp;force=true",
'title' => getlocal("confirm.take.head"), 'title' => getlocal("confirm.take.head"),
); );
$page_style->render('confirm', $page); $page_style->render('confirm', $page);
exit; exit;
} }
} }
if (!$viewonly) { if (!$view_only) {
if(! $thread->take($operator)){ if (!$thread->take($operator)) {
$page['errors'][] = getlocal("thread.error.cannot_take"); $page['errors'][] = getlocal("thread.error.cannot_take");
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
} else if (!is_capable(CAN_VIEWTHREADS, $operator)) { } elseif (!is_capable(CAN_VIEWTHREADS, $operator)) {
$page['errors'][] = getlocal("thread.error.cannot_view"); $page['errors'][] = getlocal("thread.error.cannot_view");
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
$token = $thread->lastToken; $token = $thread->lastToken;
header("Location: " . MIBEW_WEB_ROOT . "/operator/agent.php?thread=" . intval($threadid) . "&token=" . urlencode($token)); $redirect_to = MIBEW_WEB_ROOT . "/operator/agent.php?thread="
exit; . intval($thread_id) . "&token=" . urlencode($token);
header("Location: " . $redirect_to);
exit;
} }
$token = verifyparam("token", "/^\d{1,8}$/"); $token = verify_param("token", "/^\d{1,8}$/");
$thread = Thread::load($threadid, $token); $thread = Thread::load($thread_id, $token);
if (!$thread) { if (!$thread) {
die("wrong thread"); die("wrong thread");
} }
if ($thread->agentId != $operator['operatorid'] && !is_capable(CAN_VIEWTHREADS, $operator)) { if ($thread->agentId != $operator['operatorid'] && !is_capable(CAN_VIEWTHREADS, $operator)) {
$page['errors'][] = "Cannot view threads"; $page['errors'][] = "Cannot view threads";
$chat_style->render('error', $page); $chat_style->render('error', $page);
exit; exit;
} }
$page = array_merge_recursive( $page = array_merge_recursive(
$page, $page,
setup_chatview_for_operator($thread, $operator) setup_chatview_for_operator($thread, $operator)
); );
start_html_output(); start_html_output();
$pparam = verifyparam("act", "/^(redirect)$/", "default"); $pparam = verify_param("act", "/^(redirect)$/", "default");
if ($pparam == "redirect") { if ($pparam == "redirect") {
$page = array_merge_recursive( $page = array_merge_recursive(
$page, $page,
setup_redirect_links($threadid, $operator, $token) setup_redirect_links($thread_id, $operator, $token)
); );
$chat_style->render('redirect', $page); $chat_style->render('redirect', $page);
} else { } else {
// Build js application options // Build js application options
$page['chatOptions'] = json_encode($page['chat']); $page['chatOptions'] = json_encode($page['chat']);
// Render the page // Render the page
$chat_style->render('chat', $page); $chat_style->render('chat', $page);
} }
?>

View File

@ -20,97 +20,89 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/operator_settings.php'); require_once(MIBEW_FS_ROOT . '/libs/operator_settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$opId = verifyparam("op", "/^\d{1,9}$/"); $op_id = verify_param("op", "/^\d{1,9}$/");
$page = array( $page = array(
'opid' => $opId, 'opid' => $op_id,
'avatar' => '', 'avatar' => '',
'errors' => array(), 'errors' => array(),
); );
$canmodify = ($opId == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator)) $can_modify = ($op_id == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator))
|| is_capable(CAN_ADMINISTRATE, $operator); || is_capable(CAN_ADMINISTRATE, $operator);
$op = operator_by_id($opId); $op = operator_by_id($op_id);
if (!$op) { if (!$op) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} elseif (isset($_POST['op'])) {
$avatar = $op['vcavatar'];
} else if (isset($_POST['op'])) { if (!$can_modify) {
$avatar = $op['vcavatar']; $page['errors'][] = getlocal('page_agent.cannot_modify');
} elseif (isset($_FILES['avatarFile']) && $_FILES['avatarFile']['name']) {
$valid_types = array("gif", "jpg", "png", "tif", "jpeg");
if (!$canmodify) { $orig_filename = $_FILES['avatarFile']['name'];
$page['errors'][] = getlocal('page_agent.cannot_modify'); $tmp_file_name = $_FILES['avatarFile']['tmp_name'];
} else if (isset($_FILES['avatarFile']) && $_FILES['avatarFile']['name']) { $ext = preg_replace('/\//', '', strtolower(substr($orig_filename, 1 + strrpos($orig_filename, "."))));
$valid_types = array("gif", "jpg", "png", "tif", "jpeg"); $new_file_name = intval($op_id) . ".$ext";
$orig_filename = $_FILES['avatarFile']['name']; $file_size = $_FILES['avatarFile']['size'];
$tmp_file_name = $_FILES['avatarFile']['tmp_name']; if ($file_size == 0 || $file_size > Settings::get('max_uploaded_file_size')) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.file.size.exceeded");
} elseif (!in_array($ext, $valid_types)) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.invalid.file.type");
} else {
$avatar_local_dir = MIBEW_FS_ROOT . '/files/avatar/';
$full_file_path = $avatar_local_dir . $new_file_name;
if (file_exists($full_file_path)) {
unlink($full_file_path);
}
if (!@move_uploaded_file($_FILES['avatarFile']['tmp_name'], $full_file_path)) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.file.move.error");
} else {
$avatar = MIBEW_WEB_ROOT . "/files/avatar/$new_file_name";
}
}
} else {
$page['errors'][] = "No file selected";
}
$ext = preg_replace('/\//', '', strtolower(substr($orig_filename, 1 + strrpos($orig_filename, ".")))); if (count($page['errors']) == 0) {
$new_file_name = intval($opId). ".$ext"; update_operator_avatar($op['operatorid'], $avatar);
$file_size = $_FILES['avatarFile']['size'];
if ($file_size == 0 || $file_size > Settings::get('max_uploaded_file_size')) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.file.size.exceeded");
} elseif (!in_array($ext, $valid_types)) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.invalid.file.type");
} else {
$avatar_local_dir = MIBEW_FS_ROOT.'/files/avatar/';
$full_file_path = $avatar_local_dir . $new_file_name;
if (file_exists($full_file_path)) {
unlink($full_file_path);
}
if (!@move_uploaded_file($_FILES['avatarFile']['tmp_name'], $full_file_path)) {
$page['errors'][] = failed_uploading_file($orig_filename, "errors.file.move.error");
} else {
$avatar = MIBEW_WEB_ROOT . "/files/avatar/$new_file_name";
}
}
} else {
$page['errors'][] = "No file selected";
}
if (count($page['errors']) == 0) {
update_operator_avatar($op['operatorid'], $avatar);
if ($opId && $avatar && $_SESSION[SESSION_PREFIX."operator"] && $operator['operatorid'] == $opId) {
$_SESSION[SESSION_PREFIX."operator"]['vcavatar'] = $avatar;
}
header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($opId));
exit;
} else {
$page['avatar'] = topage($op['vcavatar']);
}
if ($op_id && $avatar && $_SESSION[SESSION_PREFIX . "operator"] && $operator['operatorid'] == $op_id) {
$_SESSION[SESSION_PREFIX . "operator"]['vcavatar'] = $avatar;
}
header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($op_id));
exit;
} else {
$page['avatar'] = to_page($op['vcavatar']);
}
} else { } else {
if (isset($_GET['delete']) && $_GET['delete'] == "true" && $canmodify) { if (isset($_GET['delete']) && $_GET['delete'] == "true" && $can_modify) {
update_operator_avatar($op['operatorid'], ''); update_operator_avatar($op['operatorid'], '');
header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($opId)); header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($op_id));
exit; exit;
} }
$page['avatar'] = topage($op['vcavatar']); $page['avatar'] = to_page($op['vcavatar']);
} }
$page['currentop'] = $op ? topage(get_operator_name($op)) . " (" . $op['vclogin'] . ")" : getlocal("not_found"); $page['currentop'] = $op ? to_page(get_operator_name($op)) . " (" . $op['vclogin'] . ")" : getlocal("not_found");
$page['canmodify'] = $canmodify ? "1" : ""; $page['canmodify'] = $can_modify ? "1" : "";
$page['title'] = getlocal("page_avatar.title"); $page['title'] = getlocal("page_avatar.title");
$page['menuid'] = ($operator['operatorid'] == $opId) ? "profile" : "operators"; $page['menuid'] = ($operator['operatorid'] == $op_id) ? "profile" : "operators";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page, $page['tabs'] = setup_operator_settings_tabs($op_id, 1);
prepare_menu($operator)
);
$page['tabs'] = setup_operator_settings_tabs($opId, 1);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('avatar', $page); $page_style->render('avatar', $page);
?>

View File

@ -21,13 +21,14 @@ use Mibew\Thread;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array('banId' => ''); $page = array('banId' => '');
$page['saved'] = false; $page['saved'] = false;
$page['thread'] = ''; $page['thread'] = '';
@ -35,109 +36,103 @@ $page['threadid'] = '';
$page['errors'] = array(); $page['errors'] = array();
if (isset($_POST['address'])) { if (isset($_POST['address'])) {
$banId = verifyparam("banId", "/^(\d{1,9})?$/", ""); $ban_id = verify_param("banId", "/^(\d{1,9})?$/", "");
$address = getparam("address"); $address = get_param("address");
$days = getparam("days"); $days = get_param("days");
$comment = getparam('comment'); $comment = get_param('comment');
$threadid = isset($_POST['threadid']) ? getparam('threadid') : ""; $thread_id = isset($_POST['threadid']) ? get_param('threadid') : "";
if (!$address) { if (!$address) {
$page['errors'][] = no_field("form.field.address"); $page['errors'][] = no_field("form.field.address");
} }
if (!preg_match("/^\d+$/", $days)) { if (!preg_match("/^\d+$/", $days)) {
$page['errors'][] = wrong_field("form.field.ban_days"); $page['errors'][] = wrong_field("form.field.ban_days");
} }
if (!$comment) { if (!$comment) {
$page['errors'][] = no_field("form.field.ban_comment"); $page['errors'][] = no_field("form.field.ban_comment");
} }
$existing_ban = ban_for_addr($address); $existing_ban = ban_for_addr($address);
if ((!$banId && $existing_ban) || if ((!$ban_id && $existing_ban) ||
($banId && $existing_ban && $banId != $existing_ban['banid'])) { ($ban_id && $existing_ban && $ban_id != $existing_ban['banid'])) {
$page['errors'][] = getlocal2("ban.error.duplicate", array($address, $existing_ban['banid'])); $page['errors'][] = getlocal2("ban.error.duplicate", array($address, $existing_ban['banid']));
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$db = Database::getInstance(); $db = Database::getInstance();
$now = time(); $now = time();
$till_time = $now + $days * 24 * 60 * 60; $till_time = $now + $days * 24 * 60 * 60;
if (!$banId) { if (!$ban_id) {
$db->query( $db->query(
"insert into {chatban} (dtmcreated,dtmtill,address,comment) " . ("INSERT INTO {chatban} (dtmcreated, dtmtill, address, comment) "
"values (:now,:till,:address,:comment)", . "VALUES (:now,:till,:address,:comment)"),
array( array(
':now' => $now, ':now' => $now,
':till' => $till_time, ':till' => $till_time,
':address' => $address, ':address' => $address,
':comment' => $comment ':comment' => $comment,
) )
); );
} else { } else {
$db->query( $db->query(
"update {chatban} set dtmtill = :till,address = :address, " . ("UPDATE {chatban} SET dtmtill = :till, address = :address, "
"comment = :comment where banid = :banid", . "comment = :comment WHERE banid = :banid"),
array( array(
':till' => $till_time, ':till' => $till_time,
':address' => $address, ':address' => $address,
':comment' => $comment, ':comment' => $comment,
':banid' => $banId ':banid' => $ban_id,
) )
); );
} }
$page['saved'] = true; $page['saved'] = true;
$page['address'] = $address; $page['address'] = $address;
} else {
$page['banId'] = to_page($ban_id);
$page['formaddress'] = to_page($address);
$page['formdays'] = to_page($days);
$page['formcomment'] = to_page($comment);
$page['threadid'] = $thread_id;
}
} elseif (isset($_GET['id'])) {
$ban_id = verify_param('id', "/^\d{1,9}$/");
$db = Database::getInstance();
$ban = $db->query(
("SELECT banid, (dtmtill - :now) AS days, address, comment "
. "FROM {chatban} WHERE banid = :banid"),
array(
':banid' => $ban_id,
':now' => time(),
),
array('return_rows' => Database::RETURN_ONE_ROW)
);
} else { if ($ban) {
$page['banId'] = topage($banId); $page['banId'] = to_page($ban['banid']);
$page['formaddress'] = topage($address); $page['formaddress'] = to_page($ban['address']);
$page['formdays'] = topage($days); $page['formdays'] = to_page(round($ban['days'] / 86400));
$page['formcomment'] = topage($comment); $page['formcomment'] = to_page($ban['comment']);
$page['threadid'] = $threadid; } else {
} $page['errors'][] = "Wrong id";
} else if (isset($_GET['id'])) { }
$banId = verifyparam('id', "/^\d{1,9}$/"); } elseif (isset($_GET['thread'])) {
$db = Database::getInstance(); $thread_id = verify_param('thread', "/^\d{1,9}$/");
$ban = $db->query( $thread = Thread::load($thread_id);
"select banid,(dtmtill - :now)" . if ($thread) {
" as days,address,comment from {chatban} where banid = :banid", $page['thread'] = to_page($thread->userName);
array( $page['threadid'] = $thread_id;
':banid' => $banId, $page['formaddress'] = to_page($thread->remote);
':now' => time() $page['formdays'] = 15;
), }
array('return_rows' => Database::RETURN_ONE_ROW)
);
if ($ban) {
$page['banId'] = topage($ban['banid']);
$page['formaddress'] = topage($ban['address']);
$page['formdays'] = topage(round($ban['days'] / 86400));
$page['formcomment'] = topage($ban['comment']);
} else {
$page['errors'][] = "Wrong id";
}
} else if (isset($_GET['thread'])) {
$threadid = verifyparam('thread', "/^\d{1,9}$/");
$thread = Thread::load($threadid);
if ($thread) {
$page['thread'] = topage($thread->userName);
$page['threadid'] = $threadid;
$page['formaddress'] = topage($thread->remote);
$page['formdays'] = 15;
}
} }
$page['title'] = getlocal("page_ban.title"); $page['title'] = getlocal("page_ban.title");
$page = array_merge( $page = array_merge($page, prepare_menu($operator, false));
$page,
prepare_menu($operator, false)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('ban', $page); $page_style->render('ban', $page);
?>

View File

@ -20,16 +20,17 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
setlocale(LC_TIME, getstring("time.locale")); setlocale(LC_TIME, getstring("time.locale"));
@ -37,38 +38,33 @@ setlocale(LC_TIME, getstring("time.locale"));
$db = Database::getInstance(); $db = Database::getInstance();
if (isset($_GET['act']) && $_GET['act'] == 'del') { if (isset($_GET['act']) && $_GET['act'] == 'del') {
$banId = isset($_GET['id']) ? $_GET['id'] : ""; $ban_id = isset($_GET['id']) ? $_GET['id'] : "";
if (!preg_match("/^\d+$/", $banId)) { if (!preg_match("/^\d+$/", $ban_id)) {
$page['errors'][] = "Cannot delete: wrong argument"; $page['errors'][] = "Cannot delete: wrong argument";
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$db->query("delete from {chatban} where banid = ?", array($banId)); $db->query("DELETE FROM {chatban} WHERE banid = ?", array($ban_id));
header("Location: " . MIBEW_WEB_ROOT . "/operator/blocked.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/blocked.php");
exit; exit;
} }
} }
$blockedList = $db->query( $blocked_list = $db->query(
"select banid, dtmtill as till,address,comment from {chatban}", "SELECT banid, dtmtill AS till,address,comment FROM {chatban}",
NULL, null,
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
$page['title'] = getlocal("page_bans.title"); $page['title'] = getlocal("page_bans.title");
$page['menuid'] = "blocked"; $page['menuid'] = "blocked";
$pagination = setup_pagination($blockedList); $pagination = setup_pagination($blocked_list);
$page['pagination'] = $pagination['info']; $page['pagination'] = $pagination['info'];
$page['pagination.items'] = $pagination['items']; $page['pagination.items'] = $pagination['items'];
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('blocked_visitors', $page); $page_style->render('blocked_visitors', $page);
?>

View File

@ -20,19 +20,19 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/canned.php'); require_once(MIBEW_FS_ROOT . '/libs/canned.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
# locales # locales
@ -40,58 +40,59 @@ $page = array(
$all_locales = get_available_locales(); $all_locales = get_available_locales();
$locales_with_label = array(); $locales_with_label = array();
foreach ($all_locales as $id) { foreach ($all_locales as $id) {
$locales_with_label[] = array('id' => $id, 'name' => getlocal_($id, "names")); $locales_with_label[] = array('id' => $id, 'name' => getlocal_($id, "names"));
} }
$page['locales'] = $locales_with_label; $page['locales'] = $locales_with_label;
$lang = verifyparam("lang", "/^[\w-]{2,5}$/", ""); $lang = verify_param("lang", "/^[\w-]{2,5}$/", "");
if (!$lang || !in_array($lang, $all_locales)) { if (!$lang || !in_array($lang, $all_locales)) {
$lang = in_array(CURRENT_LOCALE, $all_locales) ? CURRENT_LOCALE : $all_locales[0]; $lang = in_array(CURRENT_LOCALE, $all_locales) ? CURRENT_LOCALE : $all_locales[0];
} }
# groups # groups
$groupid = ""; $group_id = verify_param("group", "/^\d{0,8}$/", "");
$groupid = verifyparam("group", "/^\d{0,8}$/", ""); if ($group_id) {
if ($groupid) { $group = group_by_id($group_id);
$group = group_by_id($groupid); if (!$group) {
if (!$group) { $page['errors'][] = getlocal("page.group.no_such");
$page['errors'][] = getlocal("page.group.no_such"); $group_id = "";
$groupid = ""; }
}
} }
$allgroups = in_isolation($operator)?get_all_groups_for_operator($operator):get_all_groups(); $all_groups = in_isolation($operator) ? get_all_groups_for_operator($operator) : get_all_groups();
$page['groups'] = array(); $page['groups'] = array();
$page['groups'][] = array( $page['groups'][] = array(
'groupid' => '', 'groupid' => '',
'vclocalname' => getlocal("page.gen_button.default_group"), 'vclocalname' => getlocal("page.gen_button.default_group"),
'level' => 0 'level' => 0,
); );
foreach ($allgroups as $g) { foreach ($all_groups as $g) {
$page['groups'][] = $g; $page['groups'][] = $g;
} }
# delete # delete
if (isset($_GET['act']) && $_GET['act'] == 'delete') { if (isset($_GET['act']) && $_GET['act'] == 'delete') {
$key = isset($_GET['key']) ? $_GET['key'] : ""; $key = isset($_GET['key']) ? $_GET['key'] : "";
if (!preg_match("/^\d+$/", $key)) { if (!preg_match("/^\d+$/", $key)) {
$page['errors'][] = "Wrong key"; $page['errors'][] = "Wrong key";
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query("delete from {chatresponses} where id = ?", array($key)); $db->query("DELETE FROM {chatresponses} WHERE id = ?", array($key));
header("Location: " . MIBEW_WEB_ROOT . "/operator/canned.php?lang=" . urlencode($lang) . "&group=" . intval($groupid)); $redirect_to = MIBEW_WEB_ROOT . "/operator/canned.php?lang="
exit; . urlencode($lang) . "&group=" . intval($group_id);
} header("Location: " . $redirect_to);
exit;
}
} }
// Get messages and setup pagination // Get messages and setup pagination
$messages = load_canned_messages($lang, $groupid); $messages = load_canned_messages($lang, $group_id);
$pagination = setup_pagination($messages); $pagination = setup_pagination($messages);
$page['pagination'] = $pagination['info']; $page['pagination'] = $pagination['info'];
$page['pagination.items'] = $pagination['items']; $page['pagination.items'] = $pagination['items'];
@ -99,16 +100,11 @@ $page['pagination.items'] = $pagination['items'];
# form values # form values
$page['formlang'] = $lang; $page['formlang'] = $lang;
$page['formgroup'] = $groupid; $page['formgroup'] = $group_id;
$page['title'] = getlocal("canned.title"); $page['title'] = getlocal("canned.title");
$page['menuid'] = "canned"; $page['menuid'] = "canned";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('canned', $page); $page_style->render('canned', $page);
?>

View File

@ -19,77 +19,69 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/canned.php'); require_once(MIBEW_FS_ROOT . '/libs/canned.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$stringid = verifyparam("key", "/^\d{0,9}$/", ""); $string_id = verify_param("key", "/^\d{0,9}$/", "");
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
if ($stringid) { if ($string_id) {
$canned_message = load_canned_message($stringid); $canned_message = load_canned_message($string_id);
if (!$canned_message) { if (!$canned_message) {
$page['errors'][] = getlocal("cannededit.no_such"); $page['errors'][] = getlocal("cannededit.no_such");
$stringid = ""; $string_id = "";
}else{ } else {
$title = $canned_message['vctitle']; $title = $canned_message['vctitle'];
$message = $canned_message['vcvalue']; $message = $canned_message['vcvalue'];
} }
} else { } else {
$message = ''; $message = '';
$title = ''; $title = '';
$page['locale'] = verifyparam("lang", "/^[\w-]{2,5}$/", ""); $page['locale'] = verify_param("lang", "/^[\w-]{2,5}$/", "");
$page['groupid'] = ""; $page['groupid'] = "";
$page['groupid'] = verifyparam("group", "/^\d{0,8}$/"); $page['groupid'] = verify_param("group", "/^\d{0,8}$/");
} }
if (isset($_POST['message']) && isset($_POST['title'])) { if (isset($_POST['message']) && isset($_POST['title'])) {
$title = getparam('title'); $title = get_param('title');
if (!$title) { if (!$title) {
$page['errors'][] = no_field("form.field.title"); $page['errors'][] = no_field("form.field.title");
} }
$message = getparam('message'); $message = get_param('message');
if (!$message) { if (!$message) {
$page['errors'][] = no_field("form.field.message"); $page['errors'][] = no_field("form.field.message");
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
if ($stringid) { if ($string_id) {
save_canned_message($stringid, $title, $message); save_canned_message($string_id, $title, $message);
} else { } else {
add_canned_message($page['locale'], $page['groupid'], $title, $message); add_canned_message($page['locale'], $page['groupid'], $title, $message);
} }
$page['saved'] = true; $page['saved'] = true;
$page = array_merge( $page = array_merge($page, prepare_menu($operator, false));
$page, $page_style->render('cannededit', $page);
prepare_menu($operator, false) exit;
); }
$page_style->render('cannededit', $page);
exit;
}
} }
$page['saved'] = false; $page['saved'] = false;
$page['key'] = $stringid; $page['key'] = $string_id;
$page['formtitle'] = topage($title); $page['formtitle'] = to_page($title);
$page['formmessage'] = topage($message); $page['formmessage'] = to_page($message);
$page['title'] = empty($stringid) ? getlocal("cannednew.title") : getlocal("cannededit.title"); $page['title'] = empty($string_id) ? getlocal("cannednew.title") : getlocal("cannededit.title");
$page = array_merge( $page = array_merge($page, prepare_menu($operator, false));
$page,
prepare_menu($operator, false)
);
$page_style->render('cannededit', $page); $page_style->render('cannededit', $page);
?>

View File

@ -20,66 +20,70 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'agentId' => '', 'agentId' => '',
'errors' => array(), 'errors' => array(),
); );
$options = array( $options = array(
'enableban', 'usercanchangename', 'enableban',
'enablegroups', 'enablegroupsisolation', 'usercanchangename',
'enablestatistics', 'enabletracking', 'enablegroups',
'enablessl', 'forcessl', 'enablegroupsisolation',
'enablepresurvey', 'surveyaskmail', 'surveyaskgroup', 'surveyaskmessage', 'enablestatistics',
'enablepopupnotification', 'showonlineoperators', 'enabletracking',
'enablecaptcha'); 'enablessl',
'forcessl',
'enablepresurvey',
'surveyaskmail',
'surveyaskgroup',
'surveyaskmessage',
'enablepopupnotification',
'showonlineoperators',
'enablecaptcha',
);
if (Settings::get('featuresversion') != FEATURES_VERSION) { if (Settings::get('featuresversion') != FEATURES_VERSION) {
Settings::set('featuresversion', FEATURES_VERSION); Settings::set('featuresversion', FEATURES_VERSION);
Settings::update(); Settings::update();
} }
$params = array(); $params = array();
foreach ($options as $opt) { foreach ($options as $opt) {
$params[$opt] = Settings::get($opt); $params[$opt] = Settings::get($opt);
} }
if (isset($_POST['sent'])) { if (isset($_POST['sent'])) {
if (is_capable(CAN_ADMINISTRATE, $operator)) { if (is_capable(CAN_ADMINISTRATE, $operator)) {
foreach ($options as $opt) { foreach ($options as $opt) {
Settings::set($opt,(verifyparam($opt, "/^on$/", "") == "on" ? "1" : "0")); Settings::set($opt, (verify_param($opt, "/^on$/", "") == "on" ? "1" : "0"));
} }
Settings::update(); Settings::update();
header("Location: " . MIBEW_WEB_ROOT . "/operator/features.php?stored"); header("Location: " . MIBEW_WEB_ROOT . "/operator/features.php?stored");
exit; exit;
} else { } else {
$page['errors'][] = "Not an administrator"; $page['errors'][] = "Not an administrator";
} }
} }
$page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator); $page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator);
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
foreach ($options as $opt) { foreach ($options as $opt) {
$page["form$opt"] = $params[$opt] == "1"; $page["form$opt"] = $params[$opt] == "1";
} }
$page['title'] = getlocal("settings.title"); $page['title'] = getlocal("settings.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(1); $page['tabs'] = setup_settings_tabs(1);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('features', $page); $page_style->render('features', $page);
?>

View File

@ -22,82 +22,94 @@ use Mibew\Style\InvitationStyle;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/getcode.php'); require_once(MIBEW_FS_ROOT . '/libs/getcode.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
$imageLocales = get_image_locales_map(MIBEW_FS_ROOT.'/locales'); $image_locales_map = get_image_locales_map(MIBEW_FS_ROOT . '/locales');
$image = verifyparam(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "mibew"); $image = verify_param(isset($_GET['image']) ? "image" : "i", "/^\w+$/", "mibew");
if (!isset($imageLocales[$image])) { if (!isset($image_locales_map[$image])) {
$page['errors'][] = "Unknown image: $image"; $page['errors'][] = "Unknown image: $image";
$avail = array_keys($imageLocales); $avail = array_keys($image_locales_map);
$image = $avail[0]; $image = $avail[0];
} }
$image_locales = $imageLocales[$image]; $image_locales = $image_locales_map[$image];
$stylelist = ChatStyle::availableStyles(); $style_list = ChatStyle::availableStyles();
$stylelist[""] = getlocal("page.preview.style_default"); $style_list[""] = getlocal("page.preview.style_default");
$style = verifyparam("style", "/^\w*$/", ""); $style = verify_param("style", "/^\w*$/", "");
if ($style && !in_array($style, $stylelist)) { if ($style && !in_array($style, $style_list)) {
$style = ""; $style = "";
} }
$invitationstylelist = InvitationStyle::availableStyles(); $invitation_style_list = InvitationStyle::availableStyles();
$invitationstylelist[""] = getlocal("page.preview.style_default"); $invitation_style_list[""] = getlocal("page.preview.style_default");
$invitationstyle = verifyparam("invitationstyle", "/^\w*$/", ""); $invitation_style = verify_param("invitationstyle", "/^\w*$/", "");
if ($invitationstyle && !in_array($invitationstyle, $invitationstylelist)) { if ($invitation_style && !in_array($invitation_style, $invitation_style_list)) {
$invitationstyle = ""; $invitation_style = "";
} }
$groupid = verifyparam_groupid("group", $page['errors']); $group_id = verifyparam_groupid("group", $page['errors']);
$showhost = verifyparam("hostname", "/^on$/", "") == "on"; $show_host = verify_param("hostname", "/^on$/", "") == "on";
$forcesecure = verifyparam("secure", "/^on$/", "") == "on"; $force_secure = verify_param("secure", "/^on$/", "") == "on";
$modsecurity = verifyparam("modsecurity", "/^on$/", "") == "on"; $mod_security = verify_param("modsecurity", "/^on$/", "") == "on";
$code_type = verifyparam("codetype", "/^(button|operator_code)$/", "button"); $code_type = verify_param("codetype", "/^(button|operator_code)$/", "button");
$operator_code = ($code_type == "operator_code"); $operator_code = ($code_type == "operator_code");
$lang = verifyparam("lang", "/^[\w-]{2,5}$/", ""); $lang = verify_param("lang", "/^[\w-]{2,5}$/", "");
if (!$lang || !in_array($lang, $image_locales)) if (!$lang || !in_array($lang, $image_locales)) {
$lang = in_array(CURRENT_LOCALE, $image_locales) ? CURRENT_LOCALE : $image_locales[0]; $lang = in_array(CURRENT_LOCALE, $image_locales) ? CURRENT_LOCALE : $image_locales[0];
}
$file = MIBEW_FS_ROOT.'/locales/${lang}/button/${image}_on.gif'; $file = MIBEW_FS_ROOT . '/locales/${lang}/button/${image}_on.gif';
$size = get_gifimage_size($file); $size = get_gifimage_size($file);
$imagehref = get_app_location($showhost, $forcesecure) . "/b.php?i=$image&amp;lang=$lang"; $image_href = get_app_location($show_host, $force_secure) . "/b.php?i=$image&amp;lang=$lang";
if ($groupid) { if ($group_id) {
$imagehref .= "&amp;group=$groupid"; $image_href .= "&amp;group=$group_id";
} }
$message = get_image($imagehref, $size[0], $size[1]); $message = get_image($image_href, $size[0], $size[1]);
$page['buttonCode'] = generate_button("", $lang, $style, $invitationstyle, $groupid, $message, $showhost, $forcesecure, $modsecurity, $operator_code); $page['buttonCode'] = generate_button(
$page['availableImages'] = array_keys($imageLocales); "",
$lang,
$style,
$invitation_style,
$group_id,
$message,
$show_host,
$force_secure,
$mod_security,
$operator_code
);
$page['availableImages'] = array_keys($image_locales_map);
$page['availableLocales'] = $image_locales; $page['availableLocales'] = $image_locales;
$page['availableChatStyles'] = $stylelist; $page['availableChatStyles'] = $style_list;
$page['availableInvitationStyles'] = $invitationstylelist; $page['availableInvitationStyles'] = $invitation_style_list;
$page['groups'] = get_groups_list(); $page['groups'] = get_groups_list();
$page['availableCodeTypes'] = array( $page['availableCodeTypes'] = array(
'button' => getlocal('page.gen_button.button'), 'button' => getlocal('page.gen_button.button'),
'operator_code' => getlocal('page.gen_button.operator_code') 'operator_code' => getlocal('page.gen_button.operator_code')
); );
$page['formgroup'] = $groupid; $page['formgroup'] = $group_id;
$page['formstyle'] = $style; $page['formstyle'] = $style;
$page['forminvitationstyle'] = $invitationstyle; $page['forminvitationstyle'] = $invitation_style;
$page['formimage'] = $image; $page['formimage'] = $image;
$page['formlang'] = $lang; $page['formlang'] = $lang;
$page['formhostname'] = $showhost; $page['formhostname'] = $show_host;
$page['formsecure'] = $forcesecure; $page['formsecure'] = $force_secure;
$page['formmodsecurity'] = $modsecurity; $page['formmodsecurity'] = $mod_security;
$page['formcodetype'] = $code_type; $page['formcodetype'] = $code_type;
$page['enabletracking'] = Settings::get('enabletracking'); $page['enabletracking'] = Settings::get('enabletracking');
@ -106,12 +118,7 @@ $page['operator_code'] = $operator_code;
$page['title'] = getlocal("page.gen_button.title"); $page['title'] = getlocal("page.gen_button.title");
$page['menuid'] = "getcode"; $page['menuid'] = "getcode";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('gen_button', $page); $page_style->render('gen_button', $page);
?>

View File

@ -19,138 +19,142 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'grid' => '', 'grid' => '',
'errors' => array(), 'errors' => array(),
); );
$groupid = ''; $group_id = '';
if (isset($_POST['name'])) { if (isset($_POST['name'])) {
$groupid = verifyparam("gid", "/^(\d{1,9})?$/", ""); $group_id = verify_param("gid", "/^(\d{1,9})?$/", "");
$name = getparam('name'); $name = get_param('name');
$description = getparam('description'); $description = get_param('description');
$commonname = getparam('commonname'); $common_name = get_param('commonname');
$commondescription = getparam('commondescription'); $common_description = get_param('commondescription');
$email = getparam('email'); $email = get_param('email');
$weight = getparam('weight'); $weight = get_param('weight');
$parentgroup = verifyparam("parentgroup", "/^(\d{1,9})?$/", ""); $parent_group = verify_param("parentgroup", "/^(\d{1,9})?$/", "");
$title = getparam('title'); $title = get_param('title');
$chattitle = getparam('chattitle'); $chat_title = get_param('chattitle');
$hosturl = getparam('hosturl'); $host_url = get_param('hosturl');
$logo = getparam('logo'); $logo = get_param('logo');
if (!$name) if (!$name) {
$page['errors'][] = no_field("form.field.groupname"); $page['errors'][] = no_field("form.field.groupname");
}
if ($email != '' && !is_valid_email($email)) if ($email != '' && !is_valid_email($email)) {
$page['errors'][] = wrong_field("form.field.mail"); $page['errors'][] = wrong_field("form.field.mail");
}
if (! preg_match("/^(\d{1,9})?$/", $weight)) if (!preg_match("/^(\d{1,9})?$/", $weight)) {
$page['errors'][] = wrong_field("form.field.groupweight"); $page['errors'][] = wrong_field("form.field.groupweight");
}
if ($weight == '') if ($weight == '') {
$weight = 0; $weight = 0;
}
if (! $parentgroup) if (!$parent_group) {
$parentgroup = NULL; $parent_group = null;
}
$existing_group = group_by_name($name); $existing_group = group_by_name($name);
if ((!$groupid && $existing_group) || $duplicate_name = (!$group_id && $existing_group)
($groupid && $existing_group && $groupid != $existing_group['groupid'])) || ($group_id
$page['errors'][] = getlocal("page.group.duplicate_name"); && $existing_group
&& $group_id != $existing_group['groupid']);
if (count($page['errors']) == 0) { if ($duplicate_name) {
if (!$groupid) { $page['errors'][] = getlocal("page.group.duplicate_name");
$newdep = create_group(array( }
'name' => $name,
'description' => $description,
'commonname' => $commonname,
'commondescription' => $commondescription,
'email' => $email,
'weight' => $weight,
'parent' => $parentgroup,
'title' => $title,
'chattitle' => $chattitle,
'hosturl' => $hosturl,
'logo' => $logo));
header("Location: " . MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=" . intval($newdep['groupid']));
exit;
} else {
update_group(array(
'id' => $groupid,
'name' => $name,
'description' => $description,
'commonname' => $commonname,
'commondescription' => $commondescription,
'email' => $email,
'weight' => $weight,
'parent' => $parentgroup,
'title' => $title,
'chattitle' => $chattitle,
'hosturl' => $hosturl,
'logo' => $logo));
header("Location: " . MIBEW_WEB_ROOT . "/operator/group.php?gid=" . intval($groupid) . "&stored");
exit;
}
} else {
$page['formname'] = topage($name);
$page['formdescription'] = topage($description);
$page['formcommonname'] = topage($commonname);
$page['formcommondescription'] = topage($commondescription);
$page['formemail'] = topage($email);
$page['formweight'] = topage($weight);
$page['formparentgroup'] = topage($parentgroup);
$page['grid'] = topage($groupid);
$page['formtitle'] = topage($title);
$page['formchattitle'] = topage($chattitle);
$page['formhosturl'] = topage($hosturl);
$page['formlogo'] = topage($logo);
}
} else if (isset($_GET['gid'])) { if (count($page['errors']) == 0) {
$groupid = verifyparam('gid', "/^\d{1,9}$/"); if (!$group_id) {
$group = group_by_id($groupid); $new_dep = create_group(array(
'name' => $name,
'description' => $description,
'commonname' => $common_name,
'commondescription' => $common_description,
'email' => $email,
'weight' => $weight,
'parent' => $parent_group,
'title' => $title,
'chattitle' => $chat_title,
'hosturl' => $host_url,
'logo' => $logo));
header("Location: " . MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=" . intval($new_dep['groupid']));
exit;
} else {
update_group(array(
'id' => $group_id,
'name' => $name,
'description' => $description,
'commonname' => $common_name,
'commondescription' => $common_description,
'email' => $email,
'weight' => $weight,
'parent' => $parent_group,
'title' => $title,
'chattitle' => $chat_title,
'hosturl' => $host_url,
'logo' => $logo));
header("Location: " . MIBEW_WEB_ROOT . "/operator/group.php?gid=" . intval($group_id) . "&stored");
exit;
}
} else {
$page['formname'] = to_page($name);
$page['formdescription'] = to_page($description);
$page['formcommonname'] = to_page($common_name);
$page['formcommondescription'] = to_page($common_description);
$page['formemail'] = to_page($email);
$page['formweight'] = to_page($weight);
$page['formparentgroup'] = to_page($parent_group);
$page['grid'] = to_page($group_id);
$page['formtitle'] = to_page($title);
$page['formchattitle'] = to_page($chat_title);
$page['formhosturl'] = to_page($host_url);
$page['formlogo'] = to_page($logo);
}
} elseif (isset($_GET['gid'])) {
$group_id = verify_param('gid', "/^\d{1,9}$/");
$group = group_by_id($group_id);
if (!$group) { if (!$group) {
$page['errors'][] = getlocal("page.group.no_such"); $page['errors'][] = getlocal("page.group.no_such");
$page['grid'] = topage($groupid); $page['grid'] = to_page($group_id);
} else { } else {
$page['formname'] = topage($group['vclocalname']); $page['formname'] = to_page($group['vclocalname']);
$page['formdescription'] = topage($group['vclocaldescription']); $page['formdescription'] = to_page($group['vclocaldescription']);
$page['formcommonname'] = topage($group['vccommonname']); $page['formcommonname'] = to_page($group['vccommonname']);
$page['formcommondescription'] = topage($group['vccommondescription']); $page['formcommondescription'] = to_page($group['vccommondescription']);
$page['formemail'] = topage($group['vcemail']); $page['formemail'] = to_page($group['vcemail']);
$page['formweight'] = topage($group['iweight']); $page['formweight'] = to_page($group['iweight']);
$page['formparentgroup'] = topage($group['parent']); $page['formparentgroup'] = to_page($group['parent']);
$page['grid'] = topage($group['groupid']); $page['grid'] = to_page($group['groupid']);
$page['formtitle'] = topage($group['vctitle']); $page['formtitle'] = to_page($group['vctitle']);
$page['formchattitle'] = topage($group['vcchattitle']); $page['formchattitle'] = to_page($group['vcchattitle']);
$page['formhosturl'] = topage($group['vchosturl']); $page['formhosturl'] = to_page($group['vchosturl']);
$page['formlogo'] = topage($group['vclogo']); $page['formlogo'] = to_page($group['vclogo']);
} }
} }
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
$page['availableParentGroups'] = get_available_parent_groups($groupid); $page['availableParentGroups'] = get_available_parent_groups($group_id);
$page['title'] = getlocal("page.group.title"); $page['title'] = getlocal("page.group.title");
$page['menuid'] = "groups"; $page['menuid'] = "groups";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_group_settings_tabs($groupid, 0); $page['tabs'] = setup_group_settings_tabs($group_id, 0);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('group', $page); $page_style->render('group', $page);
?>

View File

@ -19,56 +19,50 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$groupid = verifyparam("gid", "/^\d{1,9}$/"); $group_id = verify_param("gid", "/^\d{1,9}$/");
$page = array('groupid' => $groupid); $page = array('groupid' => $group_id);
$page['operators'] = get_operators_list(array()); $page['operators'] = get_operators_list(array());
$page['errors'] = array(); $page['errors'] = array();
$group = group_by_id($groupid); $group = group_by_id($group_id);
if (!$group) { if (!$group) {
$page['errors'][] = getlocal("page.group.no_such"); $page['errors'][] = getlocal("page.group.no_such");
} elseif (isset($_POST['gid'])) {
} else if (isset($_POST['gid'])) { $new_members = array();
foreach ($page['operators'] as $op) {
if (verify_param("op" . $op['operatorid'], "/^on$/", "") == "on") {
$new_members[] = $op['operatorid'];
}
}
$new_members = array(); update_group_members($group_id, $new_members);
foreach ($page['operators'] as $op) { header("Location: " . MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=" . intval($group_id) . "&stored");
if (verifyparam("op" . $op['operatorid'], "/^on$/", "") == "on") { exit;
$new_members[] = $op['operatorid'];
}
}
update_group_members($groupid, $new_members);
header("Location: " . MIBEW_WEB_ROOT . "/operator/groupmembers.php?gid=" . intval($groupid) . "&stored");
exit;
} }
$page['formop'] = array(); $page['formop'] = array();
$page['currentgroup'] = $group ? topage(htmlspecialchars($group['vclocalname'])) : ""; $page['currentgroup'] = $group ? to_page(htmlspecialchars($group['vclocalname'])) : "";
foreach (get_group_members($groupid) as $rel) { foreach (get_group_members($group_id) as $rel) {
$page['formop'][] = $rel['operatorid']; $page['formop'][] = $rel['operatorid'];
} }
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
$page['title'] = getlocal("page.groupmembers.title"); $page['title'] = getlocal("page.groupmembers.title");
$page['menuid'] = "groups"; $page['menuid'] = "groups";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_group_settings_tabs($groupid, 1); $page['tabs'] = setup_group_settings_tabs($group_id, 1);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('groupmembers', $page); $page_style->render('groupmembers', $page);
?>

View File

@ -20,61 +20,56 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
if (isset($_GET['act']) && $_GET['act'] == 'del') { if (isset($_GET['act']) && $_GET['act'] == 'del') {
$groupid = isset($_GET['gid']) ? $_GET['gid'] : ""; $group_id = isset($_GET['gid']) ? $_GET['gid'] : "";
if (!preg_match("/^\d+$/", $groupid)) { if (!preg_match("/^\d+$/", $group_id)) {
$page['errors'][] = getlocal("page.groups.error.cannot_delete"); $page['errors'][] = getlocal("page.groups.error.cannot_delete");
} }
if (!is_capable(CAN_ADMINISTRATE, $operator)) { if (!is_capable(CAN_ADMINISTRATE, $operator)) {
$page['errors'][] = getlocal("page.groups.error.forbidden_remove"); $page['errors'][] = getlocal("page.groups.error.forbidden_remove");
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query("delete from {chatgroup} where groupid = ?", array($groupid)); $db->query("delete from {chatgroup} where groupid = ?", array($group_id));
$db->query("delete from {chatgroupoperator} where groupid = ?", array($groupid)); $db->query("delete from {chatgroupoperator} where groupid = ?", array($group_id));
$db->query("update {chatthread} set groupid = 0 where groupid = ?",array($groupid)); $db->query("update {chatthread} set groupid = 0 where groupid = ?", array($group_id));
header("Location: " . MIBEW_WEB_ROOT . "/operator/groups.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/groups.php");
exit; exit;
} }
} }
$page = array(); $page = array();
$sort['by'] = verifyparam("sortby", "/^(name|lastseen|weight)$/", "name"); $sort['by'] = verify_param("sortby", "/^(name|lastseen|weight)$/", "name");
$sort['desc'] = (verifyparam("sortdirection", "/^(desc|asc)$/", "desc") == "desc"); $sort['desc'] = (verify_param("sortdirection", "/^(desc|asc)$/", "desc") == "desc");
$page['groups'] = get_sorted_groups($sort); $page['groups'] = get_sorted_groups($sort);
$page['formsortby'] = $sort['by']; $page['formsortby'] = $sort['by'];
$page['formsortdirection'] = $sort['desc']?'desc':'asc'; $page['formsortdirection'] = $sort['desc'] ? 'desc' : 'asc';
$page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator); $page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator);
$page['availableOrders'] = array( $page['availableOrders'] = array(
array('id' => 'name', 'name' => getlocal('form.field.groupname')), array('id' => 'name', 'name' => getlocal('form.field.groupname')),
array('id' => 'lastseen', 'name' => getlocal('page_agents.status')), array('id' => 'lastseen', 'name' => getlocal('page_agents.status')),
array('id' => 'weight', 'name' => getlocal('page.groups.weight')) array('id' => 'weight', 'name' => getlocal('page.groups.weight')),
); );
$page['availableDirections'] = array( $page['availableDirections'] = array(
array('id' => 'desc', 'name' => getlocal('page.groups.sortdirection.desc')), array('id' => 'desc', 'name' => getlocal('page.groups.sortdirection.desc')),
array('id' => 'asc', 'name' => getlocal('page.groups.sortdirection.asc')), array('id' => 'asc', 'name' => getlocal('page.groups.sortdirection.asc')),
); );
$page['title'] = getlocal("page.groups.title"); $page['title'] = getlocal("page.groups.title");
$page['menuid'] = "groups"; $page['menuid'] = "groups";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('groups', $page); $page_style->render('groups', $page);
?>

View File

@ -21,12 +21,13 @@ use Mibew\Thread;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/userinfo.php'); require_once(MIBEW_FS_ROOT . '/libs/userinfo.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT.'/libs/cron.php'); require_once(MIBEW_FS_ROOT . '/libs/cron.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
@ -36,109 +37,107 @@ setlocale(LC_TIME, getstring("time.locale"));
$page = array(); $page = array();
$query = isset($_GET['q']) ? myiconv(getoutputenc(), MIBEW_ENCODING, $_GET['q']) : false; $query = isset($_GET['q']) ? myiconv(getoutputenc(), MIBEW_ENCODING, $_GET['q']) : false;
$searchType = verifyparam('type', '/^(all|message|operator|visitor)$/', 'all'); $search_type = verify_param('type', '/^(all|message|operator|visitor)$/', 'all');
$searchInSystemMessages = (verifyparam('insystemmessages', '/^on$/', 'off') == 'on') || !$query; $search_in_system_messages = (verify_param('insystemmessages', '/^on$/', 'off') == 'on') || !$query;
if ($query !== false) { if ($query !== false) {
$db = Database::getInstance(); $db = Database::getInstance();
$groups = $db->query( $groups = $db->query(
"select {chatgroup}.groupid as groupid, vclocalname " . ("SELECT {chatgroup}.groupid AS groupid, vclocalname " .
"from {chatgroup} order by vclocalname", "FROM {chatgroup} " .
NULL, "ORDER BY vclocalname"),
array('return_rows' => Database::RETURN_ALL_ROWS) null,
); array('return_rows' => Database::RETURN_ALL_ROWS)
);
$groupName = array(); $group_name = array();
foreach ($groups as $group) { foreach ($groups as $group) {
$groupName[$group['groupid']] = $group['vclocalname']; $group_name[$group['groupid']] = $group['vclocalname'];
} }
$page['groupName'] = $groupName; $page['groupName'] = $group_name;
$values = array( $values = array(
':query' => "%{$query}%", ':query' => "%{$query}%",
':invitation_accepted' => Thread::INVITATION_ACCEPTED, ':invitation_accepted' => Thread::INVITATION_ACCEPTED,
':invitation_not_invited' => Thread::INVITATION_NOT_INVITED ':invitation_not_invited' => Thread::INVITATION_NOT_INVITED,
); );
$searchConditions = array(); $search_conditions = array();
if ($searchType == 'message' || $searchType == 'all') { if ($search_type == 'message' || $search_type == 'all') {
$searchConditions[] = "({chatmessage}.tmessage LIKE :query" . $search_conditions[] = "({chatmessage}.tmessage LIKE :query"
($searchInSystemMessages?'':" AND ({chatmessage}.ikind = :kind_user OR {chatmessage}.ikind = :kind_agent)") . . ($search_in_system_messages
")"; ? ''
if (! $searchInSystemMessages) { : " AND ({chatmessage}.ikind = :kind_user OR {chatmessage}.ikind = :kind_agent)")
$values[':kind_user'] = Thread::KIND_USER; . ")";
$values[':kind_agent'] = Thread::KIND_AGENT; if (!$search_in_system_messages) {
} $values[':kind_user'] = Thread::KIND_USER;
} $values[':kind_agent'] = Thread::KIND_AGENT;
if ($searchType == 'operator' || $searchType == 'all') { }
$searchConditions[] = "({chatthread}.agentName LIKE :query)"; }
} if ($search_type == 'operator' || $search_type == 'all') {
if ($searchType == 'visitor' || $searchType == 'all') { $search_conditions[] = "({chatthread}.agentName LIKE :query)";
$searchConditions[] = "({chatthread}.userName LIKE :query)"; }
$searchConditions[] = "({chatthread}.remote LIKE :query)"; if ($search_type == 'visitor' || $search_type == 'all') {
} $search_conditions[] = "({chatthread}.userName LIKE :query)";
$search_conditions[] = "({chatthread}.remote LIKE :query)";
}
// Load threads // Load threads
list($threads_count) = $db->query( list($threads_count) = $db->query(
"SELECT COUNT(DISTINCT {chatthread}.dtmcreated) " . ("SELECT COUNT(DISTINCT {chatthread}.dtmcreated) "
"FROM {chatthread}, {chatmessage} " . . "FROM {chatthread}, {chatmessage} "
"WHERE {chatmessage}.threadid = {chatthread}.threadid " . . "WHERE {chatmessage}.threadid = {chatthread}.threadid "
"AND ({chatthread}.invitationstate = :invitation_accepted " . . "AND ({chatthread}.invitationstate = :invitation_accepted "
"OR {chatthread}.invitationstate = :invitation_not_invited) " . . "OR {chatthread}.invitationstate = :invitation_not_invited) "
"AND (" . implode(' OR ', $searchConditions) . ")", . "AND (" . implode(' OR ', $search_conditions) . ")"),
$values, $values,
array( array(
'return_rows' => Database::RETURN_ONE_ROW, 'return_rows' => Database::RETURN_ONE_ROW,
'fetch_type' => Database::FETCH_NUM 'fetch_type' => Database::FETCH_NUM,
) )
); );
$pagination_info = pagination_info($threads_count); $pagination_info = pagination_info($threads_count);
if ($threads_count && $pagination_info) { if ($threads_count && $pagination_info) {
$page['pagination'] = $pagination_info; $page['pagination'] = $pagination_info;
$limit_start = intval($pagination_info['start']); $limit_start = intval($pagination_info['start']);
$limit_end = intval($pagination_info['end'] - $pagination_info['start']); $limit_end = intval($pagination_info['end'] - $pagination_info['start']);
$threads_list = $db->query( $threads_list = $db->query(
"SELECT DISTINCT {chatthread}.* " . ("SELECT DISTINCT {chatthread}.* "
"FROM {chatthread}, {chatmessage} " . . "FROM {chatthread}, {chatmessage} "
"WHERE {chatmessage}.threadid = {chatthread}.threadid " . . "WHERE {chatmessage}.threadid = {chatthread}.threadid "
"AND ({chatthread}.invitationstate = :invitation_accepted " . . "AND ({chatthread}.invitationstate = :invitation_accepted "
"OR {chatthread}.invitationstate = :invitation_not_invited) " . . "OR {chatthread}.invitationstate = :invitation_not_invited) "
"AND (" . implode(' OR ', $searchConditions) . ") " . . "AND (" . implode(' OR ', $search_conditions) . ") "
"ORDER BY {chatthread}.dtmcreated DESC " . . "ORDER BY {chatthread}.dtmcreated DESC "
"LIMIT " . $limit_start . ", " .$limit_end, . "LIMIT " . $limit_start . ", " . $limit_end),
$values, $values,
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
foreach ($threads_list as $item) { foreach ($threads_list as $item) {
$page['pagination.items'][] = Thread::createFromDbInfo($item); $page['pagination.items'][] = Thread::createFromDbInfo($item);
} }
} else { } else {
$page['pagination'] = false; $page['pagination'] = false;
$page['pagination.items'] = false; $page['pagination.items'] = false;
} }
$page['formq'] = topage($query); $page['formq'] = to_page($query);
} else { } else {
$page['pagination'] = false; $page['pagination'] = false;
$page['pagination.items'] = false; $page['pagination.items'] = false;
} }
$page['formtype'] = $searchType; $page['formtype'] = $search_type;
$page['forminsystemmessages'] = $searchInSystemMessages; $page['forminsystemmessages'] = $search_in_system_messages;
$page['title'] = getlocal("page_analysis.search.title"); $page['title'] = getlocal("page_analysis.search.title");
$page['menuid'] = "history"; $page['menuid'] = "history";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('thread_search', $page); $page_style->render('thread_search', $page);
?>

View File

@ -20,34 +20,29 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
$isonline = is_operator_online($operator['operatorid']); $is_online = is_operator_online($operator['operatorid']);
$page = array( $page = array(
'version' => MIBEW_VERSION, 'version' => MIBEW_VERSION,
'localeLinks' => get_locale_links(MIBEW_WEB_ROOT . "/operator/index.php"), 'localeLinks' => get_locale_links(MIBEW_WEB_ROOT . "/operator/index.php"),
'needUpdate' => Settings::get('dbversion') != DB_VERSION, 'needUpdate' => Settings::get('dbversion') != DB_VERSION,
'needChangePassword' => check_password_hash($operator['vclogin'], '', $operator['vcpassword']), 'needChangePassword' => check_password_hash($operator['vclogin'], '', $operator['vcpassword']),
'profilePage' => MIBEW_WEB_ROOT . "/operator/operator.php?op=".$operator['operatorid'], 'profilePage' => MIBEW_WEB_ROOT . "/operator/operator.php?op=" . $operator['operatorid'],
'updateWizard' => MIBEW_WEB_ROOT . "/install/", 'updateWizard' => MIBEW_WEB_ROOT . "/install/",
'newFeatures' => Settings::get('featuresversion') != FEATURES_VERSION, 'newFeatures' => Settings::get('featuresversion') != FEATURES_VERSION,
'featuresPage' => MIBEW_WEB_ROOT . "/operator/features.php", 'featuresPage' => MIBEW_WEB_ROOT . "/operator/features.php",
'isOnline' => $isonline, 'isOnline' => $is_online,
'title' => getlocal("topMenu.admin"), 'title' => getlocal("topMenu.admin"),
'menuid' => "main", 'menuid' => "main",
); );
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('menu', $page); $page_style->render('menu', $page);
?>

View File

@ -15,11 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/invitation.php'); require_once(MIBEW_FS_ROOT . '/libs/invitation.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
$processor = \Mibew\RequestProcessor\InviteProcessor::getInstance(); $processor = \Mibew\RequestProcessor\InviteProcessor::getInstance();
$processor->receiveRequest($_POST['data']); $processor->receiveRequest($_POST['data']);
?>

View File

@ -20,36 +20,33 @@ use Mibew\Style\InvitationStyle;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
$operator = check_login(); $operator = check_login();
$stylelist = InvitationStyle::availableStyles(); $style_list = InvitationStyle::availableStyles();
$preview = verifyparam("preview", "/^\w+$/", "default"); $preview = verify_param("preview", "/^\w+$/", "default");
if (!in_array($preview, $stylelist)) { if (!in_array($preview, $style_list)) {
$preview = $stylelist[0]; $preview = $style_list[0];
} }
$page['formpreview'] = $preview; $page['formpreview'] = $preview;
$page['preview'] = $preview; $page['preview'] = $preview;
$page['availablePreviews'] = $stylelist; $page['availablePreviews'] = $style_list;
$page['operatorName'] = (empty($operator['vclocalname'])?$operator['vccommonname']:$operator['vclocalname']); $page['operatorName'] = (empty($operator['vclocalname'])
? $operator['vccommonname']
: $operator['vclocalname']);
$page['title'] = getlocal("page.preview.title"); $page['title'] = getlocal("page.preview.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(5); $page['tabs'] = setup_settings_tabs(5);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('invitation_themes', $page); $page_style->render('invitation_themes', $page);
?>

View File

@ -15,24 +15,23 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/invitation.php'); require_once(MIBEW_FS_ROOT . '/libs/invitation.php');
require_once(MIBEW_FS_ROOT.'/libs/track.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
$visitorid = verifyparam("visitor", "/^\d{1,8}$/"); $visitor_id = verify_param("visitor", "/^\d{1,8}$/");
$thread = invitation_invite($visitorid, $operator); $thread = invitation_invite($visitor_id, $operator);
if (!$thread) { if (!$thread) {
die("Invitation failed!"); die("Invitation failed!");
} }
// Open chat window for operator // Open chat window for operator
$redirect_to = MIBEW_WEB_ROOT . $redirect_to = MIBEW_WEB_ROOT
'/operator/agent.php?thread=' . intval($thread->id) . . '/operator/agent.php?thread=' . intval($thread->id)
'&token=' . urlencode($thread->lastToken); . '&token=' . urlencode($thread->lastToken);
header('Location: ' . $redirect_to); header('Location: ' . $redirect_to);
?>

View File

@ -19,44 +19,47 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
$page = array( $page = array(
'formisRemember' => true, 'formisRemember' => true,
'version' => MIBEW_VERSION, 'version' => MIBEW_VERSION,
'errors' => array(), 'errors' => array(),
); );
if (isset($_POST['login']) && isset($_POST['password'])) { if (isset($_POST['login']) && isset($_POST['password'])) {
$login = getparam('login'); $login = get_param('login');
$password = getparam('password'); $password = get_param('password');
$remember = isset($_POST['isRemember']) && $_POST['isRemember'] == "on"; $remember = isset($_POST['isRemember']) && $_POST['isRemember'] == "on";
$operator = operator_by_login($login); $operator = operator_by_login($login);
if ($operator && isset($operator['vcpassword']) && check_password_hash($operator['vclogin'], $password, $operator['vcpassword']) && !operator_is_disabled($operator)) { $operator_can_login = $operator
&& isset($operator['vcpassword'])
&& check_password_hash($operator['vclogin'], $password, $operator['vcpassword'])
&& !operator_is_disabled($operator);
$target = $password == '' if ($operator_can_login) {
? MIBEW_WEB_ROOT . "/operator/operator.php?op=" . intval($operator['operatorid']) $target = $password == ''
: (isset($_SESSION['backpath']) ? MIBEW_WEB_ROOT . "/operator/operator.php?op=" . intval($operator['operatorid'])
? $_SESSION['backpath'] : (isset($_SESSION['backpath']) ? $_SESSION['backpath'] : MIBEW_WEB_ROOT . "/operator/index.php");
: MIBEW_WEB_ROOT . "/operator/index.php");
login_operator($operator, $remember, is_secure_request()); login_operator($operator, $remember, is_secure_request());
header("Location: $target"); header("Location: $target");
exit; exit;
} else { } else {
if (operator_is_disabled($operator)) { if (operator_is_disabled($operator)) {
$page['errors'][] = getlocal('page_login.operator.disabled'); $page['errors'][] = getlocal('page_login.operator.disabled');
} else { } else {
$page['errors'][] = getlocal("page_login.error"); $page['errors'][] = getlocal("page_login.error");
} }
$page['formlogin'] = $login; $page['formlogin'] = $login;
} }
} else if(isset($_GET['login'])) { } elseif (isset($_GET['login'])) {
$login = getgetparam('login'); $login = get_get_param('login');
if (preg_match("/^(\w{1,15})$/", $login)) if (preg_match("/^(\w{1,15})$/", $login)) {
$page['formlogin'] = $login; $page['formlogin'] = $login;
}
} }
$page['localeLinks'] = get_locale_links(MIBEW_WEB_ROOT . "/operator/login.php"); $page['localeLinks'] = get_locale_links(MIBEW_WEB_ROOT . "/operator/login.php");
@ -67,5 +70,3 @@ $page['fixedwrap'] = true;
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('login', $page); $page_style->render('login', $page);
?>

View File

@ -15,11 +15,9 @@
* limitations under the License. * limitations under the License.
*/ */
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
logout_operator(); logout_operator();
header("Location: " . MIBEW_WEB_ROOT . "/operator/login.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/login.php");
exit;
?>

View File

@ -19,155 +19,158 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/operator_settings.php'); require_once(MIBEW_FS_ROOT . '/libs/operator_settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'opid' => '', 'opid' => '',
'errors' => array(), 'errors' => array(),
); );
$opId = ''; $op_id = '';
if ((isset($_POST['login']) || !is_capable(CAN_ADMINISTRATE, $operator)) && isset($_POST['password'])) { if ((isset($_POST['login']) || !is_capable(CAN_ADMINISTRATE, $operator)) && isset($_POST['password'])) {
$opId = verifyparam("opid", "/^(\d{1,9})?$/", ""); $op_id = verify_param("opid", "/^(\d{1,9})?$/", "");
if (is_capable(CAN_ADMINISTRATE, $operator)) { if (is_capable(CAN_ADMINISTRATE, $operator)) {
$login = getparam('login'); $login = get_param('login');
} else { } else {
$login = $operator['vclogin']; $login = $operator['vclogin'];
} }
$email = getparam('email'); $email = get_param('email');
$password = getparam('password'); $password = get_param('password');
$passwordConfirm = getparam('passwordConfirm'); $password_confirm = get_param('passwordConfirm');
$localname = getparam('name'); $local_name = get_param('name');
$commonname = getparam('commonname'); $common_name = get_param('commonname');
$code = getparam('code'); $code = get_param('code');
if (!$localname) if (!$local_name) {
$page['errors'][] = no_field("form.field.agent_name"); $page['errors'][] = no_field("form.field.agent_name");
}
if (!$commonname) if (!$common_name) {
$page['errors'][] = no_field("form.field.agent_commonname"); $page['errors'][] = no_field("form.field.agent_commonname");
}
if (!$login) { if (!$login) {
$page['errors'][] = no_field("form.field.login"); $page['errors'][] = no_field("form.field.login");
} else if (!preg_match("/^[\w_\.]+$/", $login)) { } elseif (!preg_match("/^[\w_\.]+$/", $login)) {
$page['errors'][] = getlocal("page_agent.error.wrong_login"); $page['errors'][] = getlocal("page_agent.error.wrong_login");
} }
if ($email == '' || !is_valid_email($email)) { if ($email == '' || !is_valid_email($email)) {
$page['errors'][] = wrong_field("form.field.mail"); $page['errors'][] = wrong_field("form.field.mail");
} }
if ($code != '' && (! preg_match("/^[A-z0-9_]+$/", $code))) { if ($code != '' && (!preg_match("/^[A-z0-9_]+$/", $code))) {
$page['errors'][] = getlocal("page_agent.error.wrong_agent_code"); $page['errors'][] = getlocal("page_agent.error.wrong_agent_code");
} }
if (!$opId && !$password) if (!$op_id && !$password) {
$page['errors'][] = no_field("form.field.password"); $page['errors'][] = no_field("form.field.password");
}
if ($password != $passwordConfirm) if ($password != $password_confirm) {
$page['errors'][] = getlocal("my_settings.error.password_match"); $page['errors'][] = getlocal("my_settings.error.password_match");
}
$existing_operator = operator_by_login($login); $existing_operator = operator_by_login($login);
if ((!$opId && $existing_operator) || $duplicate_login = (!$op_id && $existing_operator)
($opId && $existing_operator && $opId != $existing_operator['operatorid'])) || ($op_id
$page['errors'][] = getlocal("page_agent.error.duplicate_login"); && $existing_operator
&& $op_id != $existing_operator['operatorid']);
if ($duplicate_login) {
$page['errors'][] = getlocal("page_agent.error.duplicate_login");
}
// Check if operator with specified email already exists in the database // Check if operator with specified email already exists in the database
$existing_operator = operator_by_email($email); $existing_operator = operator_by_email($email);
if ( $duplicate_email =
// Create operator with email already in database // Create operator with email already in database
(!$opId && $existing_operator) || (!$op_id && $existing_operator)
// Update operator email to existing one // Update operator email to existing one
($opId && $existing_operator && $opId != $existing_operator['operatorid']) || ($op_id
) { && $existing_operator
$page['errors'][] = getlocal("page_agent.error.duplicate_email"); && $op_id != $existing_operator['operatorid']);
} if ($duplicate_email) {
$page['errors'][] = getlocal("page_agent.error.duplicate_email");
}
$canmodify = ($opId == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator)) $can_modify = ($op_id == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator))
|| is_capable(CAN_ADMINISTRATE, $operator); || is_capable(CAN_ADMINISTRATE, $operator);
if (!$canmodify) { if (!$can_modify) {
$page['errors'][] = getlocal('page_agent.cannot_modify'); $page['errors'][] = getlocal('page_agent.cannot_modify');
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
if (!$opId) { if (!$op_id) {
$newop = create_operator($login, $email, $password, $localname, $commonname, "", $code); $new_operator = create_operator($login, $email, $password, $local_name, $common_name, "", $code);
header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($newop['operatorid'])); header("Location: " . MIBEW_WEB_ROOT . "/operator/avatar.php?op=" . intval($new_operator['operatorid']));
exit; exit;
} else { } else {
update_operator($opId, $login, $email, $password, $localname, $commonname, $code); update_operator($op_id, $login, $email, $password, $local_name, $common_name, $code);
// update the session password // update the session password
if (!empty($password) && $opId == $operator['operatorid']) { if (!empty($password) && $op_id == $operator['operatorid']) {
$toDashboard = check_password_hash($login, '', $operator['vcpassword']) && $password != ''; $to_dashboard = check_password_hash($login, '', $operator['vcpassword']) && $password != '';
$_SESSION[SESSION_PREFIX."operator"]['vcpassword'] = calculate_password_hash($login, $password); $_SESSION[SESSION_PREFIX . "operator"]['vcpassword'] = calculate_password_hash($login, $password);
if($toDashboard) { if ($to_dashboard) {
header("Location: " . MIBEW_WEB_ROOT . "/operator/index.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/index.php");
exit; exit;
} }
} }
header("Location: " . MIBEW_WEB_ROOT . "/operator/operator.php?op=" . intval($opId) . "&stored"); header("Location: " . MIBEW_WEB_ROOT . "/operator/operator.php?op=" . intval($op_id) . "&stored");
exit; exit;
} }
} else { } else {
$page['formlogin'] = topage($login); $page['formlogin'] = to_page($login);
$page['formname'] = topage($localname); $page['formname'] = to_page($local_name);
$page['formemail'] = topage($email); $page['formemail'] = to_page($email);
$page['formcommonname'] = topage($commonname); $page['formcommonname'] = to_page($common_name);
$page['formcode'] = topage($code); $page['formcode'] = to_page($code);
$page['opid'] = topage($opId); $page['opid'] = to_page($op_id);
} }
} elseif (isset($_GET['op'])) {
$op_id = verify_param('op', "/^\d{1,9}$/");
$op = operator_by_id($op_id);
} else if (isset($_GET['op'])) { if (!$op) {
$opId = verifyparam('op', "/^\d{1,9}$/"); $page['errors'][] = getlocal("no_such_operator");
$op = operator_by_id($opId); $page['opid'] = to_page($op_id);
} else {
//show an error if the admin password hasn't been set yet.
if (check_password_hash($operator['vclogin'], '', $operator['vcpassword']) && !isset($_GET['stored'])) {
$page['errors'][] = getlocal("my_settings.error.no_password");
}
if (!$op) { $page['formlogin'] = to_page($op['vclogin']);
$page['errors'][] = getlocal("no_such_operator"); $page['formname'] = to_page($op['vclocalename']);
$page['opid'] = topage($opId); $page['formemail'] = to_page($op['vcemail']);
} else { $page['formcommonname'] = to_page($op['vccommonname']);
//show an error if the admin password hasn't been set yet. $page['formcode'] = to_page($op['code']);
if (check_password_hash($operator['vclogin'], '', $operator['vcpassword']) && !isset($_GET['stored'])) $page['opid'] = to_page($op['operatorid']);
{ }
$page['errors'][] = getlocal("my_settings.error.no_password");
}
$page['formlogin'] = topage($op['vclogin']);
$page['formname'] = topage($op['vclocalename']);
$page['formemail'] = topage($op['vcemail']);
$page['formcommonname'] = topage($op['vccommonname']);
$page['formcode'] = topage($op['code']);
$page['opid'] = topage($op['operatorid']);
}
} }
if (!$opId && !is_capable(CAN_ADMINISTRATE, $operator)) { if (!$op_id && !is_capable(CAN_ADMINISTRATE, $operator)) {
$page['errors'][] = getlocal("page_agent.error.forbidden_create"); $page['errors'][] = getlocal("page_agent.error.forbidden_create");
} }
$canmodify = ($opId == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator)) $can_modify = ($op_id == $operator['operatorid'] && is_capable(CAN_MODIFYPROFILE, $operator))
|| is_capable(CAN_ADMINISTRATE, $operator); || is_capable(CAN_ADMINISTRATE, $operator);
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
$page['canmodify'] = $canmodify ? "1" : ""; $page['canmodify'] = $can_modify ? "1" : "";
$page['canchangelogin'] = is_capable(CAN_ADMINISTRATE, $operator); $page['canchangelogin'] = is_capable(CAN_ADMINISTRATE, $operator);
$page['needChangePassword'] = check_password_hash($operator['vclogin'], '', $operator['vcpassword']); $page['needChangePassword'] = check_password_hash($operator['vclogin'], '', $operator['vcpassword']);
$page['title'] = getlocal("page_agent.title"); $page['title'] = getlocal("page_agent.title");
$page['menuid'] = ($opId == $operator['operatorid']) ? "profile" : "operators"; $page['menuid'] = ($op_id == $operator['operatorid']) ? "profile" : "operators";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_operator_settings_tabs($opId, 0); $page['tabs'] = setup_operator_settings_tabs($op_id, 0);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('agent', $page); $page_style->render('agent', $page);
?>

View File

@ -20,99 +20,101 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
if (isset($_GET['act'])) { if (isset($_GET['act'])) {
$operatorid = isset($_GET['id']) ? $_GET['id'] : ""; $operator_id = isset($_GET['id']) ? $_GET['id'] : "";
if (!preg_match("/^\d+$/", $operatorid)) { if (!preg_match("/^\d+$/", $operator_id)) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} }
if ($_GET['act'] == 'del') { if ($_GET['act'] == 'del') {
if (!is_capable(CAN_ADMINISTRATE, $operator)) { if (!is_capable(CAN_ADMINISTRATE, $operator)) {
$page['errors'][] = getlocal("page_agents.error.forbidden_remove"); $page['errors'][] = getlocal("page_agents.error.forbidden_remove");
} }
if ($operatorid == $operator['operatorid']) { if ($operator_id == $operator['operatorid']) {
$page['errors'][] = getlocal("page_agents.error.cannot_remove_self"); $page['errors'][] = getlocal("page_agents.error.cannot_remove_self");
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$op = operator_by_id($operatorid); $op = operator_by_id($operator_id);
if (!$op) { if (!$op) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} else if ($op['vclogin'] == 'admin') { } elseif ($op['vclogin'] == 'admin') {
$page['errors'][] = getlocal("page_agents.error.cannot_remove_admin"); $page['errors'][] = getlocal("page_agents.error.cannot_remove_admin");
} }
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
delete_operator($operatorid); delete_operator($operator_id);
header("Location: " . MIBEW_WEB_ROOT . "/operator/operators.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/operators.php");
exit; exit;
} }
} }
if ($_GET['act'] == 'disable' || $_GET['act'] == 'enable') { if ($_GET['act'] == 'disable' || $_GET['act'] == 'enable') {
$act_disable = ($_GET['act'] == 'disable'); $act_disable = ($_GET['act'] == 'disable');
if (!is_capable(CAN_ADMINISTRATE, $operator)) { if (!is_capable(CAN_ADMINISTRATE, $operator)) {
$page['errors'][] = $act_disable?getlocal('page_agents.disable.not.allowed'):getlocal('page_agents.enable.not.allowed'); $page['errors'][] = $act_disable
} ? getlocal('page_agents.disable.not.allowed')
: getlocal('page_agents.enable.not.allowed');
}
if ($operatorid == $operator['operatorid'] && $act_disable) { if ($operator_id == $operator['operatorid'] && $act_disable) {
$page['errors'][] = getlocal('page_agents.cannot.disable.self'); $page['errors'][] = getlocal('page_agents.cannot.disable.self');
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$op = operator_by_id($operatorid); $op = operator_by_id($operator_id);
if (!$op) { if (!$op) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} else if ($op['vclogin'] == 'admin' && $act_disable) { } elseif ($op['vclogin'] == 'admin' && $act_disable) {
$page['errors'][] = getlocal('page_agents.cannot.disable.admin'); $page['errors'][] = getlocal('page_agents.cannot.disable.admin');
} }
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"update {chatoperator} set idisabled = ? where operatorid = ?", "update {chatoperator} set idisabled = ? where operatorid = ?",
array(($act_disable ? '1' : '0'), $operatorid) array(($act_disable ? '1' : '0'), $operator_id)
); );
header("Location: " . MIBEW_WEB_ROOT . "/operator/operators.php"); header("Location: " . MIBEW_WEB_ROOT . "/operator/operators.php");
exit; exit;
} }
} }
} }
$sort['by'] = verifyparam("sortby", "/^(login|commonname|localename|lastseen)$/", "login"); $sort['by'] = verify_param("sortby", "/^(login|commonname|localename|lastseen)$/", "login");
$sort['desc'] = (verifyparam("sortdirection", "/^(desc|asc)$/", "desc") == "desc"); $sort['desc'] = (verify_param("sortdirection", "/^(desc|asc)$/", "desc") == "desc");
$page['formsortby'] = $sort['by']; $page['formsortby'] = $sort['by'];
$page['formsortdirection'] = $sort['desc']?'desc':'asc'; $page['formsortdirection'] = $sort['desc'] ? 'desc' : 'asc';
$list_options['sort'] = $sort; $list_options['sort'] = $sort;
if (in_isolation($operator)) { if (in_isolation($operator)) {
$list_options['isolated_operator_id'] = $operator['operatorid']; $list_options['isolated_operator_id'] = $operator['operatorid'];
} }
$page['allowedAgents'] = get_operators_list($list_options); $page['allowedAgents'] = get_operators_list($list_options);
$page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator); $page['canmodify'] = is_capable(CAN_ADMINISTRATE, $operator);
$page['availableOrders'] = array( $page['availableOrders'] = array(
array('id' => 'login', 'name' => getlocal('page_agents.login')), array('id' => 'login', 'name' => getlocal('page_agents.login')),
array('id' => 'localename', 'name' => getlocal('page_agents.agent_name')), array('id' => 'localename', 'name' => getlocal('page_agents.agent_name')),
array('id' => 'commonname', 'name' => getlocal('page_agents.commonname')), array('id' => 'commonname', 'name' => getlocal('page_agents.commonname')),
array('id' => 'lastseen', 'name' => getlocal('page_agents.status')) array('id' => 'lastseen', 'name' => getlocal('page_agents.status')),
); );
$page['availableDirections'] = array( $page['availableDirections'] = array(
array('id' => 'desc', 'name' => getlocal('page_agents.sortdirection.desc')), array('id' => 'desc', 'name' => getlocal('page_agents.sortdirection.desc')),
array('id' => 'asc', 'name' => getlocal('page_agents.sortdirection.asc')), array('id' => 'asc', 'name' => getlocal('page_agents.sortdirection.asc')),
); );
$page['title'] = getlocal("page_agents.title"); $page['title'] = getlocal("page_agents.title");
@ -120,12 +122,7 @@ $page['menuid'] = "operators";
setlocale(LC_TIME, getstring("time.locale")); setlocale(LC_TIME, getstring("time.locale"));
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('agents', $page); $page_style->render('agents', $page);
?>

View File

@ -19,69 +19,67 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/operator_settings.php'); require_once(MIBEW_FS_ROOT . '/libs/operator_settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$operator_in_isolation = in_isolation($operator); $operator_in_isolation = in_isolation($operator);
$opId = verifyparam("op", "/^\d{1,9}$/"); $op_id = verify_param("op", "/^\d{1,9}$/");
$page = array('opid' => $opId); $page = array('opid' => $op_id);
$page['groups'] = $operator_in_isolation?get_all_groups_for_operator($operator):get_all_groups(); $page['groups'] = $operator_in_isolation
? get_all_groups_for_operator($operator)
: get_all_groups();
$page['errors'] = array(); $page['errors'] = array();
$canmodify = is_capable(CAN_ADMINISTRATE, $operator); $can_modify = is_capable(CAN_ADMINISTRATE, $operator);
$op = operator_by_id($opId); $op = operator_by_id($op_id);
if (!$op) { if (!$op) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} elseif (isset($_POST['op'])) {
} else if (isset($_POST['op'])) { if (!$can_modify) {
$page['errors'][] = getlocal('page_agent.cannot_modify');
}
if (!$canmodify) { if (count($page['errors']) == 0) {
$page['errors'][] = getlocal('page_agent.cannot_modify'); $new_groups = array();
} foreach ($page['groups'] as $group) {
if (verify_param("group" . $group['groupid'], "/^on$/", "") == "on") {
$new_groups[] = $group['groupid'];
}
}
if (count($page['errors']) == 0) { update_operator_groups($op['operatorid'], $new_groups);
$new_groups = array(); header("Location: " . MIBEW_WEB_ROOT . "/operator/opgroups.php?op=" . intval($op_id) . "&stored");
foreach ($page['groups'] as $group) { exit;
if (verifyparam("group" . $group['groupid'], "/^on$/", "") == "on") { }
$new_groups[] = $group['groupid'];
}
}
update_operator_groups($op['operatorid'], $new_groups);
header("Location: " . MIBEW_WEB_ROOT . "/operator/opgroups.php?op=" . intval($opId) . "&stored");
exit;
}
} }
$page['formgroup'] = array(); $page['formgroup'] = array();
$page['currentop'] = $op ? topage(get_operator_name($op)) . " (" . $op['vclogin'] . ")" : getlocal("not_found"); $page['currentop'] = $op
$page['canmodify'] = $canmodify ? "1" : ""; ? to_page(get_operator_name($op)) . " (" . $op['vclogin'] . ")"
: getlocal("not_found");
$page['canmodify'] = $can_modify ? "1" : "";
if ($op) { if ($op) {
foreach (get_operator_groupids($opId) as $rel) { foreach (get_operator_group_ids($op_id) as $rel) {
$page['formgroup'][] = $rel['groupid']; $page['formgroup'][] = $rel['groupid'];
} }
} }
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
$page['title'] = getlocal("operator.groups.title"); $page['title'] = getlocal("operator.groups.title");
$page['menuid'] = ($page['operatorid'] == $opId) ? "profile" : "operators"; $page['menuid'] = ($page['operatorid'] == $op_id) ? "profile" : "operators";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_operator_settings_tabs($opId, 2); $page['tabs'] = setup_operator_settings_tabs($op_id, 2);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('operator_groups', $page); $page_style->render('operator_groups', $page);
?>

View File

@ -19,47 +19,42 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
$operator = check_login(); $operator = check_login();
$stylelist = PageStyle::availableStyles(); $style_list = PageStyle::availableStyles();
$preview = verifyparam("preview", "/^\w+$/", "default"); $preview = verify_param("preview", "/^\w+$/", "default");
if (!in_array($preview, $stylelist)) { if (!in_array($preview, $style_list)) {
$style_names = array_keys($stylelist); $style_names = array_keys($style_list);
$preview = $stylelist[$style_names[0]]; $preview = $style_list[$style_names[0]];
} }
$preview_style = new PageStyle($preview); $preview_style = new PageStyle($preview);
$style_config = $preview_style->configurations(); $style_config = $preview_style->configurations();
$screenshots = array(); $screenshots = array();
foreach($style_config['screenshots'] as $name => $desc) { foreach ($style_config['screenshots'] as $name => $desc) {
$screenshots[] = array( $screenshots[] = array(
'name' => $name, 'name' => $name,
'file' => MIBEW_WEB_ROOT . '/' . $preview_style->filesPath() 'file' => (MIBEW_WEB_ROOT . '/' . $preview_style->filesPath()
. '/screenshots/' . $name . '.png', . '/screenshots/' . $name . '.png'),
'description' => $desc 'description' => $desc,
); );
} }
$page['formpreview'] = $preview; $page['formpreview'] = $preview;
$page['availablePreviews'] = $stylelist; $page['availablePreviews'] = $style_list;
$page['screenshotsList'] = $screenshots; $page['screenshotsList'] = $screenshots;
$page['title'] = getlocal("page.preview.title"); $page['title'] = getlocal("page.preview.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(3); $page['tabs'] = setup_settings_tabs(3);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('page_themes', $page); $page_style->render('page_themes', $page);
?>

View File

@ -20,92 +20,98 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'agentId' => '', 'agentId' => '',
'errors' => array(), 'errors' => array(),
); );
$options = array( $options = array(
'online_timeout', 'updatefrequency_operator', 'updatefrequency_chat', 'online_timeout',
'max_connections_from_one_host', 'updatefrequency_operator',
'updatefrequency_tracking', 'visitors_limit', 'invitation_lifetime', 'updatefrequency_chat',
'tracking_lifetime', 'thread_lifetime', 'statistics_aggregation_interval'); 'max_connections_from_one_host',
'updatefrequency_tracking',
'visitors_limit',
'invitation_lifetime',
'tracking_lifetime',
'thread_lifetime',
'statistics_aggregation_interval',
);
$params = array(); $params = array();
foreach ($options as $opt) { foreach ($options as $opt) {
$params[$opt] = Settings::get($opt); $params[$opt] = Settings::get($opt);
} }
if (isset($_POST['onlinetimeout'])) { if (isset($_POST['onlinetimeout'])) {
$params['online_timeout'] = getparam('onlinetimeout'); $params['online_timeout'] = get_param('onlinetimeout');
if (!is_numeric($params['online_timeout'])) { if (!is_numeric($params['online_timeout'])) {
$page['errors'][] = wrong_field("settings.onlinetimeout"); $page['errors'][] = wrong_field("settings.onlinetimeout");
} }
$params['updatefrequency_operator'] = getparam('frequencyoperator'); $params['updatefrequency_operator'] = get_param('frequencyoperator');
if (!is_numeric($params['updatefrequency_operator'])) { if (!is_numeric($params['updatefrequency_operator'])) {
$page['errors'][] = wrong_field("settings.frequencyoperator"); $page['errors'][] = wrong_field("settings.frequencyoperator");
} }
$params['updatefrequency_chat'] = getparam('frequencychat'); $params['updatefrequency_chat'] = get_param('frequencychat');
if (!is_numeric($params['updatefrequency_chat'])) { if (!is_numeric($params['updatefrequency_chat'])) {
$page['errors'][] = wrong_field("settings.frequencychat"); $page['errors'][] = wrong_field("settings.frequencychat");
} }
$params['max_connections_from_one_host'] = getparam('onehostconnections'); $params['max_connections_from_one_host'] = get_param('onehostconnections');
if (!is_numeric($params['max_connections_from_one_host'])) { if (!is_numeric($params['max_connections_from_one_host'])) {
$page['errors'][] = getlocal("settings.wrong.onehostconnections"); $page['errors'][] = getlocal("settings.wrong.onehostconnections");
} }
$params['thread_lifetime'] = getparam('threadlifetime'); $params['thread_lifetime'] = get_param('threadlifetime');
if (!is_numeric($params['thread_lifetime'])) { if (!is_numeric($params['thread_lifetime'])) {
$page['errors'][] = getlocal("settings.wrong.threadlifetime"); $page['errors'][] = getlocal("settings.wrong.threadlifetime");
} }
$params['statistics_aggregation_interval'] = getparam('statistics_aggregation_interval'); $params['statistics_aggregation_interval'] = get_param('statistics_aggregation_interval');
if (!is_numeric($params['statistics_aggregation_interval'])) { if (!is_numeric($params['statistics_aggregation_interval'])) {
$page['errors'][] = wrong_field("settings.statistics_aggregation_interval"); $page['errors'][] = wrong_field("settings.statistics_aggregation_interval");
} }
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$params['updatefrequency_tracking'] = getparam('frequencytracking'); $params['updatefrequency_tracking'] = get_param('frequencytracking');
if (!is_numeric($params['updatefrequency_tracking'])) { if (!is_numeric($params['updatefrequency_tracking'])) {
$page['errors'][] = wrong_field("settings.frequencytracking"); $page['errors'][] = wrong_field("settings.frequencytracking");
} }
$params['visitors_limit'] = getparam('visitorslimit'); $params['visitors_limit'] = get_param('visitorslimit');
if (!is_numeric($params['visitors_limit'])) { if (!is_numeric($params['visitors_limit'])) {
$page['errors'][] = wrong_field("settings.visitorslimit"); $page['errors'][] = wrong_field("settings.visitorslimit");
} }
$params['invitation_lifetime'] = getparam('invitationlifetime'); $params['invitation_lifetime'] = get_param('invitationlifetime');
if (!is_numeric($params['invitation_lifetime'])) { if (!is_numeric($params['invitation_lifetime'])) {
$page['errors'][] = wrong_field("settings.invitationlifetime"); $page['errors'][] = wrong_field("settings.invitationlifetime");
} }
$params['tracking_lifetime'] = getparam('trackinglifetime'); $params['tracking_lifetime'] = get_param('trackinglifetime');
if (!is_numeric($params['tracking_lifetime'])) { if (!is_numeric($params['tracking_lifetime'])) {
$page['errors'][] = wrong_field("settings.trackinglifetime"); $page['errors'][] = wrong_field("settings.trackinglifetime");
} }
}
} if (count($page['errors']) == 0) {
foreach ($options as $opt) {
if (count($page['errors']) == 0) { Settings::set($opt, $params[$opt]);
foreach ($options as $opt) { }
Settings::set($opt,$params[$opt]); Settings::update();
} header("Location: " . MIBEW_WEB_ROOT . "/operator/performance.php?stored");
Settings::update(); exit;
header("Location: " . MIBEW_WEB_ROOT . "/operator/performance.php?stored"); }
exit;
}
} }
$page['formonlinetimeout'] = $params['online_timeout']; $page['formonlinetimeout'] = $params['online_timeout'];
@ -117,11 +123,10 @@ $page['formstatistics_aggregation_interval'] = $params['statistics_aggregation_i
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$page['formfrequencytracking'] = $params['updatefrequency_tracking']; $page['formfrequencytracking'] = $params['updatefrequency_tracking'];
$page['formvisitorslimit'] = $params['visitors_limit']; $page['formvisitorslimit'] = $params['visitors_limit'];
$page['forminvitationlifetime'] = $params['invitation_lifetime']; $page['forminvitationlifetime'] = $params['invitation_lifetime'];
$page['formtrackinglifetime'] = $params['tracking_lifetime']; $page['formtrackinglifetime'] = $params['tracking_lifetime'];
} }
$page['enabletracking'] = Settings::get('enabletracking'); $page['enabletracking'] = Settings::get('enabletracking');
@ -130,14 +135,9 @@ $page['stored'] = isset($_GET['stored']);
$page['title'] = getlocal("settings.title"); $page['title'] = getlocal("settings.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(2); $page['tabs'] = setup_settings_tabs(2);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('performance', $page); $page_style->render('performance', $page);
?>

View File

@ -19,77 +19,70 @@
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/operator_settings.php'); require_once(MIBEW_FS_ROOT . '/libs/operator_settings.php');
$operator = check_login(); $operator = check_login();
csrfchecktoken(); csrf_check_token();
$opId = verifyparam("op", "/^\d{1,9}$/"); $op_id = verify_param("op", "/^\d{1,9}$/");
$page = array( $page = array(
'opid' => $opId, 'opid' => $op_id,
'canmodify' => is_capable(CAN_ADMINISTRATE, $operator) ? "1" : "", 'canmodify' => is_capable(CAN_ADMINISTRATE, $operator) ? "1" : "",
'errors' => array(), 'errors' => array(),
); );
$op = operator_by_id($opId); $op = operator_by_id($op_id);
if (!$op) { if (!$op) {
$page['errors'][] = getlocal("no_such_operator"); $page['errors'][] = getlocal("no_such_operator");
} elseif (isset($_POST['op'])) {
} else if (isset($_POST['op'])) { if (!is_capable(CAN_ADMINISTRATE, $operator)) {
$page['errors'][] = getlocal('page_agent.cannot_modify');
}
if (!is_capable(CAN_ADMINISTRATE, $operator)) { $new_permissions = isset($op['iperm']) ? $op['iperm'] : 0;
$page['errors'][] = getlocal('page_agent.cannot_modify');
}
$new_permissions = isset($op['iperm']) ? $op['iperm'] : 0; foreach (permission_ids() as $perm => $id) {
if (verify_param("permissions$id", "/^on$/", "") == "on") {
$new_permissions |= (1 << $perm);
} else {
$new_permissions &= ~(1 << $perm);
}
}
foreach (permission_ids() as $perm => $id) { if (count($page['errors']) == 0) {
if (verifyparam("permissions$id", "/^on$/", "") == "on") { update_operator_permissions($op['operatorid'], $new_permissions);
$new_permissions |= (1 << $perm);
} else {
$new_permissions &= ~(1 << $perm);
}
}
if (count($page['errors']) == 0) {
update_operator_permissions($op['operatorid'], $new_permissions);
if ($opId && $_SESSION[SESSION_PREFIX."operator"] && $operator['operatorid'] == $opId) {
$_SESSION[SESSION_PREFIX."operator"]['iperm'] = $new_permissions;
}
header("Location: " . MIBEW_WEB_ROOT . "/operator/permissions.php?op=" . intval($opId) . "&stored");
exit;
}
if ($op_id && $_SESSION[SESSION_PREFIX . "operator"] && $operator['operatorid'] == $op_id) {
$_SESSION[SESSION_PREFIX . "operator"]['iperm'] = $new_permissions;
}
header("Location: " . MIBEW_WEB_ROOT . "/operator/permissions.php?op=" . intval($op_id) . "&stored");
exit;
}
} }
$page['permissionsList'] = get_permission_list(); $page['permissionsList'] = get_permission_list();
$page['formpermissions'] = array(""); $page['formpermissions'] = array("");
$page['currentop'] = $op ? topage(get_operator_name($op)) . " (" . $op['vclogin'] . ")" : getlocal("not_found"); $page['currentop'] = $op ? to_page(get_operator_name($op)) . " (" . $op['vclogin'] . ")" : getlocal("not_found");
if ($op) { if ($op) {
foreach (permission_ids() as $perm => $id) { foreach (permission_ids() as $perm => $id) {
if (is_capable($perm, $op)) { if (is_capable($perm, $op)) {
$page['formpermissions'][] = $id; $page['formpermissions'][] = $id;
} }
} }
} }
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
$page['title'] = getlocal("permissions.title"); $page['title'] = getlocal("permissions.title");
$page['menuid'] = ($operator['operatorid'] == $opId) ? "profile" : "operators"; $page['menuid'] = ($operator['operatorid'] == $op_id) ? "profile" : "operators";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_operator_settings_tabs($opId, 3); $page['tabs'] = setup_operator_settings_tabs($op_id, 3);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('permissions', $page); $page_style->render('permissions', $page);
?>

View File

@ -21,108 +21,110 @@ use Mibew\Thread;
use Mibew\Style\ChatStyle; use Mibew\Style\ChatStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
$threadid = verifyparam("thread", "/^\d{1,8}$/"); $thread_id = verify_param("thread", "/^\d{1,8}$/");
$token = verifyparam("token", "/^\d{1,8}$/"); $token = verify_param("token", "/^\d{1,8}$/");
$thread = Thread::load($threadid, $token); $thread = Thread::load($thread_id, $token);
if (! $thread) { if (!$thread) {
die("wrong thread"); die("wrong thread");
} }
$page = array( $page = array(
'errors' => array(), 'errors' => array(),
); );
// Initialize chat style which is currently used in system // Initialize chat style which is currently used in system
$chat_style = new ChatStyle(ChatStyle::currentStyle()); $chat_style = new ChatStyle(ChatStyle::currentStyle());
if (isset($_GET['nextGroup'])) { if (isset($_GET['nextGroup'])) {
$nextid = verifyparam("nextGroup", "/^\d{1,8}$/"); $next_id = verify_param("nextGroup", "/^\d{1,8}$/");
$nextGroup = group_by_id($nextid); $next_group = group_by_id($next_id);
if ($nextGroup) { if ($next_group) {
$page['message'] = getlocal2("chat.redirected.group.content", array(topage(get_group_name($nextGroup)))); $page['message'] = getlocal2(
if ($thread->state == Thread::STATE_CHATTING) { "chat.redirected.group.content",
$thread->state = Thread::STATE_WAITING; array(to_page(get_group_name($next_group)))
$thread->nextAgent = 0; );
$thread->groupId = $nextid; if ($thread->state == Thread::STATE_CHATTING) {
$thread->agentId = 0; $thread->state = Thread::STATE_WAITING;
$thread->agentName = ''; $thread->nextAgent = 0;
$thread->save(); $thread->groupId = $next_id;
$thread->agentId = 0;
$thread->postMessage( $thread->agentName = '';
Thread::KIND_EVENTS, $thread->save();
getstring2_(
"chat.status.operator.redirect",
array(get_operator_name($operator)),
$thread->locale
)
);
} else {
$page['errors'][] = getlocal("chat.redirect.cannot");
}
} else {
$page['errors'][] = "Unknown group";
}
$thread->postMessage(
Thread::KIND_EVENTS,
getstring2_(
"chat.status.operator.redirect",
array(get_operator_name($operator)),
$thread->locale
)
);
} else {
$page['errors'][] = getlocal("chat.redirect.cannot");
}
} else {
$page['errors'][] = "Unknown group";
}
} else { } else {
$nextid = verifyparam("nextAgent", "/^\d{1,8}$/"); $next_id = verify_param("nextAgent", "/^\d{1,8}$/");
$nextOperator = operator_by_id($nextid); $next_operator = operator_by_id($next_id);
if ($nextOperator) { if ($next_operator) {
$page['message'] = getlocal2("chat.redirected.content", array(topage(get_operator_name($nextOperator)))); $page['message'] = getlocal2(
if ($thread->state == Thread::STATE_CHATTING) { "chat.redirected.content",
$thread->state = Thread::STATE_WAITING; array(to_page(get_operator_name($next_operator)))
$thread->nextAgent = $nextid; );
$thread->agentId = 0; if ($thread->state == Thread::STATE_CHATTING) {
if ($thread->groupId != 0) { $thread->state = Thread::STATE_WAITING;
$db = Database::getInstance(); $thread->nextAgent = $next_id;
list($groups_count) = $db->query( $thread->agentId = 0;
"select count(*) AS count from {chatgroupoperator} " . if ($thread->groupId != 0) {
"where operatorid = ? and groupid = ?", $db = Database::getInstance();
array($nextid, $thread->groupId), list($groups_count) = $db->query(
array( ("SELECT count(*) AS count "
'return_rows' => Database::RETURN_ONE_ROW, . "FROM {chatgroupoperator} "
'fetch_type' => Database::FETCH_NUM . "WHERE operatorid = ? AND groupid = ?"),
) array($next_id, $thread->groupId),
); array(
if ($groups_count === 0) { 'return_rows' => Database::RETURN_ONE_ROW,
$thread->groupId = 0; 'fetch_type' => Database::FETCH_NUM,
} )
} );
$thread->save(); if ($groups_count === 0) {
$thread->postMessage( $thread->groupId = 0;
Thread::KIND_EVENTS, }
getstring2_( }
"chat.status.operator.redirect", $thread->save();
array(get_operator_name($operator)), $thread->postMessage(
$thread->locale Thread::KIND_EVENTS,
) getstring2_(
); "chat.status.operator.redirect",
} else { array(get_operator_name($operator)),
$page['errors'][] = getlocal("chat.redirect.cannot"); $thread->locale
} )
} else { );
$page['errors'][] = "Unknown operator"; } else {
} $page['errors'][] = getlocal("chat.redirect.cannot");
}
} else {
$page['errors'][] = "Unknown operator";
}
} }
$page = array_merge_recursive( $page = array_merge_recursive($page, setup_logo());
$page,
setup_logo()
);
if (count($page['errors']) > 0) { if (count($page['errors']) > 0) {
$chat_style->render('error', $page); $chat_style->render('error', $page);
} else { } else {
$chat_style->render('redirected', $page); $chat_style->render('redirected', $page);
} }
?>

View File

@ -20,65 +20,69 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
$page = array( $page = array(
'version' => MIBEW_VERSION, 'version' => MIBEW_VERSION,
'showform' => true, 'showform' => true,
'title' => getlocal("resetpwd.title"), 'title' => getlocal("resetpwd.title"),
'headertitle' => getlocal("app.title"), 'headertitle' => getlocal("app.title"),
'show_small_login' => true, 'show_small_login' => true,
'fixedwrap' => true, 'fixedwrap' => true,
'errors' => array(), 'errors' => array(),
); );
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$opId = verifyparam("id", "/^\d{1,9}$/"); $op_id = verify_param("id", "/^\d{1,9}$/");
$token = verifyparam("token", "/^[\dabcdef]+$/"); $token = verify_param("token", "/^[\dabcdef]+$/");
$operator = operator_by_id($opId); $operator = operator_by_id($op_id);
if (!$operator) { if (!$operator) {
$page['errors'][] = "No such operator"; $page['errors'][] = "No such operator";
$page['showform'] = false; $page['showform'] = false;
} else if ($token != $operator['vcrestoretoken']) { } elseif ($token != $operator['vcrestoretoken']) {
$page['errors'][] = "Wrong token"; $page['errors'][] = "Wrong token";
$page['showform'] = false; $page['showform'] = false;
} }
if (count($page['errors']) == 0 && isset($_POST['password'])) { if (count($page['errors']) == 0 && isset($_POST['password'])) {
$password = getparam('password'); $password = get_param('password');
$passwordConfirm = getparam('passwordConfirm'); $password_confirm = get_param('passwordConfirm');
if (!$password) if (!$password) {
$page['errors'][] = no_field("form.field.password"); $page['errors'][] = no_field("form.field.password");
}
if ($password != $passwordConfirm) if ($password != $password_confirm) {
$page['errors'][] = getlocal("my_settings.error.password_match"); $page['errors'][] = getlocal("my_settings.error.password_match");
}
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$page['isdone'] = true; $page['isdone'] = true;
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"update {chatoperator} set vcpassword = ?, vcrestoretoken = '' " . ("UPDATE {chatoperator} "
"where operatorid = ?", . "SET vcpassword = ?, vcrestoretoken = '' "
array(calculate_password_hash($operator['vclogin'], $password), $opId) . "WHERE operatorid = ?"),
); array(
calculate_password_hash($operator['vclogin'], $password),
$op_id,
)
);
$page['loginname'] = $operator['vclogin']; $page['loginname'] = $operator['vclogin'];
$page_style->render('resetpwd', $page); $page_style->render('resetpwd', $page);
exit; exit;
} }
} }
$page['id'] = $opId; $page['id'] = $op_id;
$page['token'] = $token; $page['token'] = $token;
$page['isdone'] = false; $page['isdone'] = false;
$page_style->render('resetpwd', $page); $page_style->render('resetpwd', $page);
?>

View File

@ -20,65 +20,77 @@ use Mibew\Database;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
require_once(MIBEW_FS_ROOT.'/libs/notify.php'); require_once(MIBEW_FS_ROOT . '/libs/notify.php');
$page = array( $page = array(
'version' => MIBEW_VERSION, 'version' => MIBEW_VERSION,
'title' => getlocal("restore.title"), 'title' => getlocal("restore.title"),
'headertitle' => getlocal("app.title"), 'headertitle' => getlocal("app.title"),
'show_small_login' => true, 'show_small_login' => true,
'fixedwrap' => true, 'fixedwrap' => true,
'errors' => array(), 'errors' => array(),
); );
$loginoremail = ""; $login_or_email = "";
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
if (isset($_POST['loginoremail'])) { if (isset($_POST['loginoremail'])) {
$loginoremail = getparam("loginoremail"); $login_or_email = get_param("loginoremail");
$torestore = is_valid_email($loginoremail) ? operator_by_email($loginoremail) : operator_by_login($loginoremail); $to_restore = is_valid_email($login_or_email)
if (!$torestore) { ? operator_by_email($login_or_email)
$page['errors'][] = getlocal("no_such_operator"); : operator_by_login($login_or_email);
} if (!$to_restore) {
$page['errors'][] = getlocal("no_such_operator");
}
$email = $torestore['vcemail']; $email = $to_restore['vcemail'];
if (count($page['errors']) == 0 && !is_valid_email($email)) { if (count($page['errors']) == 0 && !is_valid_email($email)) {
$page['errors'][] = "Operator hasn't set his e-mail"; $page['errors'][] = "Operator hasn't set his e-mail";
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
$token = sha1($torestore['vclogin'] . (function_exists('openssl_random_pseudo_bytes') ? openssl_random_pseudo_bytes(32) : (time() + microtime()) . mt_rand(0, 99999999))); $token = sha1($to_restore['vclogin'] . (function_exists('openssl_random_pseudo_bytes')
? openssl_random_pseudo_bytes(32)
: (time() + microtime()) . mt_rand(0, 99999999)));
$db = Database::getInstance(); $db = Database::getInstance();
$db->query( $db->query(
"update {chatoperator} set dtmrestore = :now, " . ("UPDATE {chatoperator} "
"vcrestoretoken = :token where operatorid = :operatorid", . "SET dtmrestore = :now, vcrestoretoken = :token "
array( . "WHERE operatorid = :operatorid"),
':now' => time(), array(
':token' => $token, ':now' => time(),
':operatorid' => $torestore['operatorid'] ':token' => $token,
) ':operatorid' => $to_restore['operatorid'],
); )
);
$href = get_app_location(true, false) . "/operator/resetpwd.php?id=" . $torestore['operatorid'] . "&token=$token"; $href = get_app_location(true, false) . "/operator/resetpwd.php?id="
mibew_mail($email, $email, getstring("restore.mailsubj"), getstring2("restore.mailtext", array(get_operator_name($torestore), $href))); . $to_restore['operatorid'] . "&token=$token";
mibew_mail(
$email,
$email,
getstring("restore.mailsubj"),
getstring2(
"restore.mailtext",
array(get_operator_name($to_restore), $href)
)
);
$page['isdone'] = true; $page['isdone'] = true;
$page_style->render('restore', $page); $page_style->render('restore', $page);
exit; exit;
} }
} }
$page['formloginoremail'] = topage($loginoremail); $page['formloginoremail'] = to_page($login_or_email);
$page['localeLinks'] = get_locale_links(MIBEW_WEB_ROOT . "/operator/restore.php"); $page['localeLinks'] = get_locale_links(MIBEW_WEB_ROOT . "/operator/restore.php");
$page['isdone'] = false; $page['isdone'] = false;
$page_style->render('restore', $page); $page_style->render('restore', $page);
?>

View File

@ -22,129 +22,139 @@ use Mibew\Style\InvitationStyle;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
require_once(MIBEW_FS_ROOT.'/libs/cron.php'); require_once(MIBEW_FS_ROOT . '/libs/cron.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
csrfchecktoken(); csrf_check_token();
$page = array( $page = array(
'agentId' => '', 'agentId' => '',
'errors' => array(), 'errors' => array(),
); );
// Load system configs // Load system configs
$options = array( $options = array(
'email', 'email',
'title', 'title',
'logo', 'logo',
'hosturl', 'hosturl',
'usernamepattern', 'usernamepattern',
'chattitle', 'chattitle',
'geolink', 'geolink',
'geolinkparams', 'geolinkparams',
'sendmessagekey', 'sendmessagekey',
'cron_key' 'cron_key',
); );
$params = array(); $params = array();
foreach ($options as $opt) { foreach ($options as $opt) {
$params[$opt] = Settings::get($opt); $params[$opt] = Settings::get($opt);
} }
// Load styles configs // Load styles configs
$styles_params = array( $styles_params = array(
'chat_style' => ChatStyle::defaultStyle(), 'chat_style' => ChatStyle::defaultStyle(),
'page_style' => PageStyle::defaultStyle(), 'page_style' => PageStyle::defaultStyle(),
); );
$chat_style_list = ChatStyle::availableStyles(); $chat_style_list = ChatStyle::availableStyles();
$page_style_list = PageStyle::availableStyles(); $page_style_list = PageStyle::availableStyles();
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$styles_params['invitation_style'] = InvitationStyle::defaultStyle(); $styles_params['invitation_style'] = InvitationStyle::defaultStyle();
$invitation_style_list = InvitationStyle::availableStyles(); $invitation_style_list = InvitationStyle::availableStyles();
} }
if (isset($_POST['email']) && isset($_POST['title']) && isset($_POST['logo'])) { if (isset($_POST['email']) && isset($_POST['title']) && isset($_POST['logo'])) {
$params['email'] = getparam('email'); $params['email'] = get_param('email');
$params['title'] = getparam('title'); $params['title'] = get_param('title');
$params['logo'] = getparam('logo'); $params['logo'] = get_param('logo');
$params['hosturl'] = getparam('hosturl'); $params['hosturl'] = get_param('hosturl');
$params['usernamepattern'] = getparam('usernamepattern'); $params['usernamepattern'] = get_param('usernamepattern');
$params['chattitle'] = getparam('chattitle'); $params['chattitle'] = get_param('chattitle');
$params['geolink'] = getparam('geolink'); $params['geolink'] = get_param('geolink');
$params['geolinkparams'] = getparam('geolinkparams'); $params['geolinkparams'] = get_param('geolinkparams');
$params['sendmessagekey'] = verifyparam('sendmessagekey', "/^c?enter$/"); $params['sendmessagekey'] = verify_param('sendmessagekey', "/^c?enter$/");
$params['cron_key'] = getparam('cronkey'); $params['cron_key'] = get_param('cronkey');
$styles_params['chat_style'] = verifyparam("chat_style", "/^\w+$/", $styles_params['chat_style']); $styles_params['chat_style'] = verify_param("chat_style", "/^\w+$/", $styles_params['chat_style']);
if (!in_array($styles_params['chat_style'], $chat_style_list)) { if (!in_array($styles_params['chat_style'], $chat_style_list)) {
$styles_params['chat_style'] = $chat_style_list[0]; $styles_params['chat_style'] = $chat_style_list[0];
} }
$styles_params['page_style'] = verifyparam("page_style", "/^\w+$/", $styles_params['page_style']); $styles_params['page_style'] = verify_param("page_style", "/^\w+$/", $styles_params['page_style']);
if (!in_array($styles_params['page_style'], $page_style_list)) { if (!in_array($styles_params['page_style'], $page_style_list)) {
$styles_params['page_style'] = $page_style_list[0]; $styles_params['page_style'] = $page_style_list[0];
} }
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$styles_params['invitation_style'] = verifyparam("invitation_style", "/^\w+$/", $styles_params['invitation_style']); $styles_params['invitation_style'] = verify_param(
if (!in_array($styles_params['invitation_style'], $invitation_style_list)) { "invitation_style",
$styles_params['invitation_style'] = $invitation_style_list[0]; "/^\w+$/",
} $styles_params['invitation_style']
} );
if (!in_array($styles_params['invitation_style'], $invitation_style_list)) {
$styles_params['invitation_style'] = $invitation_style_list[0];
}
}
if ($params['email'] && !is_valid_email($params['email'])) { if ($params['email'] && !is_valid_email($params['email'])) {
$page['errors'][] = getlocal("settings.wrong.email"); $page['errors'][] = getlocal("settings.wrong.email");
} }
if ($params['geolinkparams']) { if ($params['geolinkparams']) {
foreach (preg_split("/,/", $params['geolinkparams']) as $oneparam) { foreach (preg_split("/,/", $params['geolinkparams']) as $one_param) {
if (!preg_match("/^\s*(toolbar|scrollbars|location|status|menubar|width|height|resizable)=\d{1,4}$/", $oneparam)) { $wrong_param = !preg_match(
$page['errors'][] = "Wrong link parameter: \"$oneparam\", should be one of 'toolbar, scrollbars, location, status, menubar, width, height or resizable'"; "/^\s*(toolbar|scrollbars|location|status|menubar|width|height|resizable)=\d{1,4}$/",
} $one_param
} );
} if ($wrong_param) {
$page['errors'][] = "Wrong link parameter: \"$one_param\", "
. "should be one of 'toolbar, scrollbars, location, "
. "status, menubar, width, height or resizable'";
}
}
}
if (preg_match("/^[0-9A-z]*$/", $params['cron_key']) == 0) { if (preg_match("/^[0-9A-z]*$/", $params['cron_key']) == 0) {
$page['errors'][] = getlocal("settings.wrong.cronkey"); $page['errors'][] = getlocal("settings.wrong.cronkey");
} }
if (count($page['errors']) == 0) { if (count($page['errors']) == 0) {
// Update system settings // Update system settings
foreach ($options as $opt) { foreach ($options as $opt) {
Settings::set($opt,$params[$opt]); Settings::set($opt, $params[$opt]);
} }
Settings::update(); Settings::update();
// Update styles params // Update styles params
ChatStyle::setDefaultStyle($styles_params['chat_style']); ChatStyle::setDefaultStyle($styles_params['chat_style']);
PageStyle::setDefaultStyle($styles_params['page_style']); PageStyle::setDefaultStyle($styles_params['page_style']);
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
InvitationStyle::setDefaultStyle($styles_params['invitation_style']); InvitationStyle::setDefaultStyle($styles_params['invitation_style']);
} }
// Redirect the user // Redirect the user
header("Location: " . MIBEW_WEB_ROOT . "/operator/settings.php?stored"); header("Location: " . MIBEW_WEB_ROOT . "/operator/settings.php?stored");
exit; exit;
} }
} }
$page['formemail'] = topage($params['email']); $page['formemail'] = to_page($params['email']);
$page['formtitle'] = topage($params['title']); $page['formtitle'] = to_page($params['title']);
$page['formlogo'] = topage($params['logo']); $page['formlogo'] = to_page($params['logo']);
$page['formhosturl'] = topage($params['hosturl']); $page['formhosturl'] = to_page($params['hosturl']);
$page['formgeolink'] = topage($params['geolink']); $page['formgeolink'] = to_page($params['geolink']);
$page['formgeolinkparams'] = topage($params['geolinkparams']); $page['formgeolinkparams'] = to_page($params['geolinkparams']);
$page['formusernamepattern'] = topage($params['usernamepattern']); $page['formusernamepattern'] = to_page($params['usernamepattern']);
$page['formpagestyle'] = $styles_params['page_style']; $page['formpagestyle'] = $styles_params['page_style'];
$page['availablePageStyles'] = $page_style_list; $page['availablePageStyles'] = $page_style_list;
$page['formchatstyle'] = $styles_params['chat_style']; $page['formchatstyle'] = $styles_params['chat_style'];
$page['formchattitle'] = topage($params['chattitle']); $page['formchattitle'] = to_page($params['chattitle']);
$page['formsendmessagekey'] = $params['sendmessagekey']; $page['formsendmessagekey'] = $params['sendmessagekey'];
$page['availableChatStyles'] = $chat_style_list; $page['availableChatStyles'] = $chat_style_list;
$page['stored'] = isset($_GET['stored']); $page['stored'] = isset($_GET['stored']);
@ -157,18 +167,13 @@ $page['title'] = getlocal("settings.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
if (Settings::get('enabletracking')) { if (Settings::get('enabletracking')) {
$page['forminvitationstyle'] = $styles_params['invitation_style']; $page['forminvitationstyle'] = $styles_params['invitation_style'];
$page['availableInvitationStyles'] = $invitation_style_list; $page['availableInvitationStyles'] = $invitation_style_list;
} }
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(0); $page['tabs'] = setup_settings_tabs(0);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('settings', $page); $page_style->render('settings', $page);
?>

View File

@ -21,11 +21,12 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/statistics.php'); require_once(MIBEW_FS_ROOT . '/libs/statistics.php');
require_once(MIBEW_FS_ROOT.'/libs/cron.php'); require_once(MIBEW_FS_ROOT . '/libs/cron.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
force_password($operator); force_password($operator);
@ -33,164 +34,158 @@ force_password($operator);
setlocale(LC_TIME, getstring("time.locale")); setlocale(LC_TIME, getstring("time.locale"));
$page = array(); $page = array();
$page['operator'] = topage(get_operator_name($operator)); $page['operator'] = to_page(get_operator_name($operator));
$page['availableDays'] = range(1, 31); $page['availableDays'] = range(1, 31);
$page['availableMonth'] = get_month_selection(time() - 400 * 24 * 60 * 60, time() + 50 * 24 * 60 * 60); $page['availableMonth'] = get_month_selection(time() - 400 * 24 * 60 * 60, time() + 50 * 24 * 60 * 60);
$page['showresults'] = false; $page['showresults'] = false;
$statisticstype = verifyparam("type", "/^(bydate|byagent|bypage)$/", "bydate"); $statistics_type = verify_param("type", "/^(bydate|byagent|bypage)$/", "bydate");
$page['type'] = $statisticstype; $page['type'] = $statistics_type;
$page['showbydate'] = ($statisticstype == 'bydate'); $page['showbydate'] = ($statistics_type == 'bydate');
$page['showbyagent'] = ($statisticstype == 'byagent'); $page['showbyagent'] = ($statistics_type == 'byagent');
$page['showbypage'] = ($statisticstype == 'bypage'); $page['showbypage'] = ($statistics_type == 'bypage');
$page['cron_path'] = cron_get_uri(Settings::get('cron_key')); $page['cron_path'] = cron_get_uri(Settings::get('cron_key'));
$page['last_cron_run'] = Settings::get('_last_cron_run'); $page['last_cron_run'] = Settings::get('_last_cron_run');
$page['show_invitations_info'] = (bool)Settings::get('enabletracking'); $page['show_invitations_info'] = (bool) Settings::get('enabletracking');
$page['errors'] = array(); $page['errors'] = array();
if (isset($_GET['startday'])) { if (isset($_GET['startday'])) {
$startday = verifyparam("startday", "/^\d+$/"); $start_day = verify_param("startday", "/^\d+$/");
$startmonth = verifyparam("startmonth", "/^\d{2}.\d{2}$/"); $start_month = verify_param("startmonth", "/^\d{2}.\d{2}$/");
$endday = verifyparam("endday", "/^\d+$/"); $end_day = verify_param("endday", "/^\d+$/");
$endmonth = verifyparam("endmonth", "/^\d{2}.\d{2}$/"); $end_month = verify_param("endmonth", "/^\d{2}.\d{2}$/");
$start = get_form_date($startday, $startmonth); $start = get_form_date($start_day, $start_month);
$end = get_form_date($endday, $endmonth) + 24 * 60 * 60; $end = get_form_date($end_day, $end_month) + 24 * 60 * 60;
} else { } else {
$curr = getdate(time()); $curr = getdate(time());
if ($curr['mday'] < 7) { if ($curr['mday'] < 7) {
// previous month // previous month
if ($curr['mon'] == 1) { if ($curr['mon'] == 1) {
$month = 12; $month = 12;
$year = $curr['year'] - 1; $year = $curr['year'] - 1;
} else { } else {
$month = $curr['mon'] - 1; $month = $curr['mon'] - 1;
$year = $curr['year']; $year = $curr['year'];
} }
$start = mktime(0, 0, 0, $month, 1, $year); $start = mktime(0, 0, 0, $month, 1, $year);
$end = mktime(0, 0, 0, $month, date("t", $start), $year) + 24 * 60 * 60; $end = mktime(0, 0, 0, $month, date("t", $start), $year) + 24 * 60 * 60;
} else { } else {
$start = mktime(0, 0, 0, $curr['mon'], 1, $curr['year']); $start = mktime(0, 0, 0, $curr['mon'], 1, $curr['year']);
$end = time() + 24 * 60 * 60; $end = time() + 24 * 60 * 60;
} }
} }
$page = array_merge( $page = array_merge(
$page, $page,
set_form_date($start, "start"), set_form_date($start, "start"),
set_form_date($end - 24 * 60 * 60, "end") set_form_date($end - 24 * 60 * 60, "end")
); );
if ($start > $end) { if ($start > $end) {
$page['errors'][] = getlocal("statistics.wrong.dates"); $page['errors'][] = getlocal("statistics.wrong.dates");
} }
$activetab = 0; $active_tab = 0;
$db = Database::getInstance(); $db = Database::getInstance();
if ($statisticstype == 'bydate') { if ($statistics_type == 'bydate') {
$page['reportByDate'] = $db->query( $page['reportByDate'] = $db->query(
"SELECT DATE(FROM_UNIXTIME(date)) AS date, " . ("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
"threads, " . . "threads, "
"missedthreads, " . . "missedthreads, "
"sentinvitations, " . . "sentinvitations, "
"acceptedinvitations, " . . "acceptedinvitations, "
"rejectedinvitations, " . . "rejectedinvitations, "
"ignoredinvitations, " . . "ignoredinvitations, "
"operatormessages AS agents, " . . "operatormessages AS agents, "
"usermessages AS users, " . . "usermessages AS users, "
"averagewaitingtime AS avgwaitingtime, " . . "averagewaitingtime AS avgwaitingtime, "
"averagechattime AS avgchattime " . . "averagechattime AS avgchattime "
"FROM {chatthreadstatistics} s " . . "FROM {chatthreadstatistics} s "
"WHERE s.date >= :start " . . "WHERE s.date >= :start "
"AND s.date < :end " . . "AND s.date < :end "
"GROUP BY DATE(FROM_UNIXTIME(date)) " . . "GROUP BY DATE(FROM_UNIXTIME(date)) "
"ORDER BY s.date DESC", . "ORDER BY s.date DESC"),
array( array(
':start' => $start, ':start' => $start,
':end' => $end ':end' => $end,
), ),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
$page['reportByDateTotal'] = $db->query( $page['reportByDateTotal'] = $db->query(
"SELECT DATE(FROM_UNIXTIME(date)) AS date, " . ("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
"SUM(threads) AS threads, " . . "SUM(threads) AS threads, "
"SUM(missedthreads) AS missedthreads, " . . "SUM(missedthreads) AS missedthreads, "
"SUM(sentinvitations) AS sentinvitations, " . . "SUM(sentinvitations) AS sentinvitations, "
"SUM(acceptedinvitations) AS acceptedinvitations, " . . "SUM(acceptedinvitations) AS acceptedinvitations, "
"SUM(rejectedinvitations) AS rejectedinvitations, " . . "SUM(rejectedinvitations) AS rejectedinvitations, "
"SUM(ignoredinvitations) AS ignoredinvitations, " . . "SUM(ignoredinvitations) AS ignoredinvitations, "
"SUM(operatormessages) AS agents, " . . "SUM(operatormessages) AS agents, "
"SUM(usermessages) AS users, " . . "SUM(usermessages) AS users, "
"ROUND(SUM(averagewaitingtime * s.threads) / SUM(s.threads),1) AS avgwaitingtime, " . . "ROUND(SUM(averagewaitingtime * s.threads) / SUM(s.threads),1) AS avgwaitingtime, "
"ROUND(SUM(averagechattime * s.threads) / SUM(s.threads),1) AS avgchattime " . . "ROUND(SUM(averagechattime * s.threads) / SUM(s.threads),1) AS avgchattime "
"FROM {chatthreadstatistics} s " . . "FROM {chatthreadstatistics} s "
"WHERE s.date >= :start " . . "WHERE s.date >= :start "
"AND s.date < :end", . "AND s.date < :end"),
array( array(
':start' => $start, ':start' => $start,
':end' => $end ':end' => $end,
), ),
array('return_rows' => Database::RETURN_ONE_ROW) array('return_rows' => Database::RETURN_ONE_ROW)
); );
$activetab = 0; $active_tab = 0;
} elseif($statisticstype == 'byagent') { } elseif ($statistics_type == 'byagent') {
$page['reportByAgent'] = $db->query( $page['reportByAgent'] = $db->query(
"SELECT o.vclocalename AS name, " . ("SELECT o.vclocalename AS name, "
"SUM(s.threads) AS threads, " . . "SUM(s.threads) AS threads, "
"SUM(s.messages) AS msgs, " . . "SUM(s.messages) AS msgs, "
"ROUND( " . . "ROUND( "
"SUM(s.averagelength * s.messages) / SUM(s.messages), " . . "SUM(s.averagelength * s.messages) / SUM(s.messages), "
"1) AS avglen, " . . "1) AS avglen, "
"SUM(sentinvitations) AS sentinvitations, " . . "SUM(sentinvitations) AS sentinvitations, "
"SUM(acceptedinvitations) AS acceptedinvitations, " . . "SUM(acceptedinvitations) AS acceptedinvitations, "
"SUM(rejectedinvitations) AS rejectedinvitations, " . . "SUM(rejectedinvitations) AS rejectedinvitations, "
"SUM(ignoredinvitations) AS ignoredinvitations " . . "SUM(ignoredinvitations) AS ignoredinvitations "
"FROM {chatoperatorstatistics} s, {chatoperator} o " . . "FROM {chatoperatorstatistics} s, {chatoperator} o "
"WHERE s.operatorid = o.operatorid " . . "WHERE s.operatorid = o.operatorid "
"AND s.date >= :start " . . "AND s.date >= :start "
"AND s.date < :end " . . "AND s.date < :end "
"GROUP BY s.operatorid", . "GROUP BY s.operatorid"),
array( array(
':start' => $start, ':start' => $start,
':end' => $end ':end' => $end,
), ),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
$activetab = 1; $active_tab = 1;
} elseif($statisticstype == 'bypage') { } elseif ($statistics_type == 'bypage') {
$page['reportByPage'] = $db->query( $page['reportByPage'] = $db->query(
"SELECT SUM(visits) as visittimes, " . ("SELECT SUM(visits) as visittimes, "
"address, " . . "address, "
"SUM(chats) as chattimes, " . . "SUM(chats) as chattimes, "
"SUM(sentinvitations) AS sentinvitations, " . . "SUM(sentinvitations) AS sentinvitations, "
"SUM(acceptedinvitations) AS acceptedinvitations, " . . "SUM(acceptedinvitations) AS acceptedinvitations, "
"SUM(rejectedinvitations) AS rejectedinvitations, " . . "SUM(rejectedinvitations) AS rejectedinvitations, "
"SUM(ignoredinvitations) AS ignoredinvitations " . . "SUM(ignoredinvitations) AS ignoredinvitations "
"FROM {visitedpagestatistics} " . . "FROM {visitedpagestatistics} "
"WHERE date >= :start " . . "WHERE date >= :start "
"AND date < :end " . . "AND date < :end "
"GROUP BY address", . "GROUP BY address"),
array(':start' => $start, ':end' => $end), array(':start' => $start, ':end' => $end),
array('return_rows' => Database::RETURN_ALL_ROWS) array('return_rows' => Database::RETURN_ALL_ROWS)
); );
$activetab = 2; $active_tab = 2;
} }
$page['showresults'] = count($page['errors']) == 0; $page['showresults'] = count($page['errors']) == 0;
$page['title'] = getlocal("statistics.title"); $page['title'] = getlocal("statistics.title");
$page['menuid'] = "statistics"; $page['menuid'] = "statistics";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_statistics_tabs($activetab); $page['tabs'] = setup_statistics_tabs($active_tab);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('statistics', $page); $page_style->render('statistics', $page);
?>

View File

@ -20,21 +20,22 @@ use Mibew\Style\ChatStyle;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/pagination.php'); require_once(MIBEW_FS_ROOT . '/libs/pagination.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/settings.php'); require_once(MIBEW_FS_ROOT . '/libs/settings.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
$stylelist = ChatStyle::availableStyles(); $style_list = ChatStyle::availableStyles();
$preview = verifyparam("preview", "/^\w+$/", "default"); $preview = verify_param("preview", "/^\w+$/", "default");
if (!in_array($preview, $stylelist)) { if (!in_array($preview, $style_list)) {
$style_names = array_keys($stylelist); $style_names = array_keys($style_list);
$preview = $stylelist[$style_names[0]]; $preview = $style_list[$style_names[0]];
} }
$chat_style = new ChatStyle($preview); $chat_style = new ChatStyle($preview);
@ -42,29 +43,24 @@ $chat_style = new ChatStyle($preview);
$style_config = $chat_style->configurations(); $style_config = $chat_style->configurations();
$screenshots = array(); $screenshots = array();
foreach($style_config['screenshots'] as $name => $desc) { foreach ($style_config['screenshots'] as $name => $desc) {
$screenshots[] = array( $screenshots[] = array(
'name' => $name, 'name' => $name,
'file' => MIBEW_WEB_ROOT . '/' . $chat_style->filesPath() 'file' => (MIBEW_WEB_ROOT . '/' . $chat_style->filesPath()
. '/screenshots/' . $name . '.png', . '/screenshots/' . $name . '.png'),
'description' => $desc 'description' => $desc
); );
} }
$page['formpreview'] = $preview; $page['formpreview'] = $preview;
$page['availablePreviews'] = $stylelist; $page['availablePreviews'] = $style_list;
$page['screenshotsList'] = $screenshots; $page['screenshotsList'] = $screenshots;
$page['title'] = getlocal("page.preview.title"); $page['title'] = getlocal("page.preview.title");
$page['menuid'] = "settings"; $page['menuid'] = "settings";
$page = array_merge( $page = array_merge($page, prepare_menu($operator));
$page,
prepare_menu($operator)
);
$page['tabs'] = setup_settings_tabs(4); $page['tabs'] = setup_settings_tabs(4);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('themes', $page); $page_style->render('themes', $page);
?>

View File

@ -20,11 +20,12 @@ use Mibew\Thread;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/groups.php'); require_once(MIBEW_FS_ROOT . '/libs/groups.php');
require_once(MIBEW_FS_ROOT.'/libs/userinfo.php'); require_once(MIBEW_FS_ROOT . '/libs/userinfo.php');
require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
@ -33,31 +34,26 @@ $page = array();
setlocale(LC_TIME, getstring("time.locale")); setlocale(LC_TIME, getstring("time.locale"));
if (isset($_GET['threadid'])) { if (isset($_GET['threadid'])) {
// Load thread info // Load thread info
$threadid = verifyparam("threadid", "/^(\d{1,9})?$/", ""); $thread_id = verify_param("threadid", "/^(\d{1,9})?$/", "");
$thread = Thread::load($threadid); $thread = Thread::load($thread_id);
$group = group_by_id($thread->groupId); $group = group_by_id($thread->groupId);
$thread_info = array( $thread_info = array(
'thread' => $thread, 'thread' => $thread,
'groupName' => get_group_name($group), 'groupName' => get_group_name($group),
); );
$page['thread_info'] = $thread_info; $page['thread_info'] = $thread_info;
// Build messages list // Build messages list
$lastid = -1; $last_id = -1;
$messages = $thread_info['thread']->getMessages(false, $lastid); $messages = $thread_info['thread']->getMessages(false, $last_id);
$page['threadMessages'] = json_encode($messages); $page['threadMessages'] = json_encode($messages);
} }
$page['title'] = getlocal("thread.chat_log"); $page['title'] = getlocal("thread.chat_log");
$page = array_merge( $page = array_merge($page, prepare_menu($operator, false));
$page,
prepare_menu($operator, false)
);
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('thread_log', $page); $page_style->render('thread_log', $page);
?>

View File

@ -20,10 +20,10 @@ use Mibew\Settings;
use Mibew\Style\PageStyle; use Mibew\Style\PageStyle;
// Initialize libraries // Initialize libraries
require_once(dirname(dirname(__FILE__)).'/libs/init.php'); require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
require_once(MIBEW_FS_ROOT.'/libs/chat.php'); require_once(MIBEW_FS_ROOT . '/libs/chat.php');
require_once(MIBEW_FS_ROOT.'/libs/operator.php'); require_once(MIBEW_FS_ROOT . '/libs/operator.php');
require_once(MIBEW_FS_ROOT.'/libs/track.php'); require_once(MIBEW_FS_ROOT . '/libs/track.php');
$operator = check_login(); $operator = check_login();
@ -34,22 +34,20 @@ if (Settings::get('enabletracking') == "0") {
} }
if (isset($_GET['thread'])) { if (isset($_GET['thread'])) {
$threadid = verifyparam("thread", "/^\d{1,8}$/"); $thread_id = verify_param("thread", "/^\d{1,8}$/");
} } else {
else { $visitor_id = verify_param("visitor", "/^\d{1,8}$/");
$visitorid = verifyparam("visitor", "/^\d{1,8}$/");
} }
if (isset($threadid)) { if (isset($thread_id)) {
$visitor = track_get_visitor_by_threadid($threadid); $visitor = track_get_visitor_by_thread_id($thread_id);
if (!$visitor) { if (!$visitor) {
die("Wrong thread!"); die("Wrong thread!");
} }
} } else {
else { $visitor = track_get_visitor_by_id($visitor_id);
$visitor = track_get_visitor_by_id($visitorid);
if (!$visitor) { if (!$visitor) {
die("Wrong visitor!"); die("Wrong visitor!");
} }
} }
$path = track_get_path($visitor); $path = track_get_path($visitor);
@ -58,13 +56,13 @@ $page['entry'] = htmlspecialchars($visitor['entry']);
$page['history'] = array(); $page['history'] = array();
ksort($path); ksort($path);
foreach ($path as $k => $v) { foreach ($path as $k => $v) {
$page['history'][] = array( 'date' => date_to_text($k), $page['history'][] = array(
'link' => htmlspecialchars($v) ); 'date' => date_to_text($k),
'link' => htmlspecialchars($v),
);
} }
$page['title'] = getlocal("tracked.path"); $page['title'] = getlocal("tracked.path");
$page_style = new PageStyle(PageStyle::currentStyle()); $page_style = new PageStyle(PageStyle::currentStyle());
$page_style->render('tracked', $page); $page_style->render('tracked', $page);
?>

Some files were not shown because too many files have changed in this diff Show More