ElixirVault/www/system-brs-core/sys/sysEmpty/inc/sysEmptyController.php

606 lines
20 KiB
PHP

<?php
namespace BRSystems\Core\Sys\sysEmpty\inc;
use BRSystems\Core\Library\cApc\cApc;
use BRSystems\Core\Library\cCore\cCore;
use BRSystems\Core\Library\cGoogleApi\cGoogleApi;
use BRSystems\Core\Library\cJSON\cJSON;
use BRSystems\Core\Sys\sysUsers\inc\sysUsersCfg;
use Exception;
/**
* sysEmpty Controller
*
* @category sysEmpty Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @since Version 1.0
*/
class sysEmptyController extends cCore
{
public $dir;
public $name;
static $iRefreshRate = 3600; // Once per hour
const USER_ID_VKADMIN = 1;
const USER_ID_CRON = 7;
const USER_ID_AIVARS = 8;
public $cfg = [
self::USER_ID_VKADMIN => self::USER_ID_VKADMIN,
self::USER_ID_AIVARS => self::USER_ID_AIVARS,
self::USER_ID_CRON => self::USER_ID_CRON,
];
const LEFT_MENU_ARRAY = [
'SITE_SETTINGS_LEFT',
'USERS_LEFT',
'MODULE_CONETENT_LEFT',
'APP_MANAGER_LEFT',
'MANAGE_LEFT',
'CATALOG_LEFT',
'SITE_MAP_CONTENT_LEFT',
'E_COMMERCE_CONTENT_LEFT',
];
/**
* Class constructor
*/
public function __construct($uriData, $dir, $name)
{
$this->dir = $dir;
$this->name = $name;
parent:: __construct($uriData);
$this->module = new sysEmptyModule();
$this->oView->setTemplateDir($this->dir . "/tmpl/");
if (!$this->oView->cacheUsed()) {
$this->oView->setJs(getCurrentFolder($this->dir) . '/js/' . $this->name . '.js');
$this->oView->setCss(getCurrentFolder($this->dir) . '/css/' . $this->name . '.css');
}
// Set JS module init title
$this->oView->setAsJSON(cCore::JS_MOD, ucfirst($name));
}
/**
* Function to show main form
*
* @category sysEmpty Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @returns bool true or redirect to error
*/
public function run()
{
// Redirect to menu if this class is hit
$mnuF = false;
$search = true;
$menuPriority = self::LEFT_MENU_ARRAY;
foreach ($menuPriority as $v) {
if ($search && $mnu = $this->oView->$v) {
if (!$mnuF)
$mnuF = $mnu;
foreach ($mnu as $k) {
if (isset($k['active']) && $k['active']) {
$mnuF = false;
$search = false;
break;
}
}
} elseif (!$search) {
break;
}
}
if ($mnuF) {
$mnuF = firstE($mnuF);
redirectToUri($mnuF['url']);
}
$this->oView->LOGO = true;
$this->oView->display('sys');
}
/**
* Function to show plugin form base
*
* @category sysEmpty Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @returns bool true or redir to error
*/
public function pluginsAction()
{
$this->oView->LOGO = true;
$this->oView->setAsJSON('isStarPage', true);
$this->oView->display();
}
/**
* Function to get & create plugin form
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @return void
*/
public function setupPluginForm(): void
{
$plugins = [];
if ($userId = $this->oUser->getUser()) {
// Setup as post actions
$_SERVER['REQUEST_METHOD'] = 'POST';
// Load user configuration data
$config = $this->oUser->oCfg->getUserCFG();
// Load table column titles from configuration modules
if (isset($config[sysUsersCfg::plugins]) && count($config[sysUsersCfg::plugins])) {
foreach ($config[sysUsersCfg::plugins] as $k => $v) {
if ($v && count($v)) {
if (isset($v['m']) && !$v['m'] || !isset($v['m'])) {
$pluginData = false;
$module = new $k($this->uri_data);
if ($module) {
if (method_exists($module->controller, $run = 'getPluginData')) {
$pluginData = $module->controller->$run(true);
}
}
// Add titles
if (!$pluginData) {
unset($config[sysUsersCfg::plugins][$k]);
continue;
}
unset($module);
}
// Add titles
if ($v['e']) {
if ($v['e']) {
$v['title'] = $this->gM($k);
if (isset($this->oUser->oCfg->siteMapId[$k]))
$v['l'] = $this->gL($this->oUser->oCfg->siteMapId[$k]);
$plugins[$v['c']][$k] = $v;
}
}
}
}
}
$this->oView->CFG = $plugins;
}
}
/**
* Function to load plugin by id
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @param string $id - plugin id
* @return void
*/
public function loadPluginData($id)
{
if ($id && $this->oUser->getUser()) {
// Load user configuration data
$config = $this->oUser->oCfg->getUserCFG();
// Load table column titles from configuration modules
if (isset($config[sysUsersCfg::plugins][$id]) && count($config[sysUsersCfg::plugins][$id])) {
$module = new $id($this->uri_data);
if ($module) {
if (method_exists($module->controller, $run = 'getPluginData')) {
$module->controller->oView = &$this->oView;
if ($module->controller->$run()) {
cJSON::sendOk(array('html' => $this->oView->genTemplate('genPluginTable')));
}
}
}
unset($module);
}
}
cJSON::sendError();
}
/**
* Function to get user data
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @return array of data
*/
public function loadPluginPageData()
{
$this->setupPluginForm();
// Prepare dashboard data or throw exception message if in debug mode
$vData = array();
try {
$vData = $this->setAndPrepDashboardData4Display();
} catch (Exception $e) {
if (defined('DEBUG_MODE') && DEBUG_MODE) {
// Print error
// pr($e->getMessage());
}
}
return array(
'chartData' => $vData,
'show' => array('buttons_top' => false, 'buttons_bottom' => true),
'btn' => array(),
'html' => $this->oView->genTemplate('sysWelcome'),
);
}
/**
* Function to save portlets positions
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @param string $portlets - json encoded portlet positions
* @return array of data
*/
public function savePortletPositions($portlets)
{
if ($portlets)
$portlets = cJSON::decode($portlets, true);
if ($portlets && count($portlets) && $userId = $this->oUser->getUser()) {
// Load user configuration data
$config = $this->oUser->oCfg->getUserCFG(sysUsersCfg::plugins);
foreach ($portlets as $k => $v) {
if ($v && count($v)) {
foreach ($v as $vv) {
if (isset($config[$vv])) {
$c = $config[$vv];
unset($config[$vv]);
$c['c'] = $k;
$config[$vv] = $c;
}
}
}
}
$this->oUser->oCfg->addPropertiesAdvanced($config, sysUsersCfg::plugins);
cJSON::sendOk();
}
cJSON::sendError();
}
/**
* Function to save portlet box state
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @param string $portlet - json encoded portlet state
* @return void
*/
public function savePortletBoxState($portlet)
{
if ($portlet) {
$portlet = cJSON::decode($portlet, true);
}
if ($portlet && count($portlet) && $userId = $this->oUser->getUser()) {
// Load user configuration data
$config = $this->oUser->oCfg->getUserCFG(sysUsersCfg::plugins);
$k = '';
foreach ($portlet as $k => $v) {
if (isset($config[$k]))
$config[$k]['m'] = ($v ? 0 : 1);
}
$this->oUser->oCfg->addPropertiesAdvanced(array($k => $config[$k]), sysUsersCfg::plugins);
cJSON::sendOk();
}
cJSON::sendError();
}
/**
* Function to show page not found message
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @return void
*/
public function displayPageNotFound()
{
$this->oView->PAGE_NOT_FOUND = true;
die($this->oView->genHelperView('/cmsc/errors/errDieOnPageAccess'));
}
/**
* Function to prepare & set dashboard data to view
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @return array
*/
public function getUsersOnline()
{
return [
'users' => $this->cronGatherDataAndSetToAPC(
self::$sIDAllVisitors,
'Zutenis Analytics application',
true
)
];
}
/**
* Function to prepare & set dashboard data to view
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
*/
public static $vGAViews = [
'WEB' => 'ga:196262392',
'CMS' => 'ga:196226777',
'SYS' => 'ga:196281799',
];
public static $sIDAllVisitors = 'ga:196305821';
public function setAndPrepDashboardData4Display()
{
$vReturn = [];
$this->oView->TIME = date('d.m.Y H:i');
$this->oView->REFRESH_RATE = $this->createDateStringFromSeconds();
$count = $this->module->getCountForBaseCategories();
// Try to get total visitors
$this->oView->SUMMERY_DATA = array(
array(
'd' => false,
't' => $this->gM('Total APP users'),
'c' => 'ico-users', // Icon class
'v' => (!empty($count['users']) ? $count['users'] : 0), // Value to show
'l' => $this->gL(678), // link to jump to
),
array(
'd' => false,
't' => $this->gM('Total Accounts'),
'c' => 'ico-accounts', // Icon class
'v' => (!empty($count['accounts']) ? $count['accounts'] : 0), // Value to show
'l' => $this->gL(681), // link to jump to
),
array(
'd' => false,
't' => $this->gM('Inquiries received'),
'c' => 'ico-inq', // Icon class
'v' => (!empty($count['msg']) ? $count['msg'] : 0), // Value to show
'l' => $this->gL(741), // link to jump to
),
array(
'd' => false,
't' => $this->gM('Subscriptions'),
'c' => 'ico-mails', // Icon class
'v' => (!empty($count['subscriptions']) ? $count['subscriptions'] : 0), // Value to show
'l' => $this->gL(745), // link to jump to
),
array(
'd' => false,
't' => $this->gM('Users online'),
'c' => 'ico-online', // Icon class
'v' => 0, // Value to show
//'l' => $this->gL(648), // link to jump to
),
);
$vReturn['months'] = $this->getTranslatedMonthsWithKeyBasedOrder();
$vDays = array_fill(1, date("t"), 0);
$k = date('n'); //1;
$kk = date('n', strtotime('first day of last month')); //12;
// Months
$vEmptyMonths = array_fill(1, 12, 0);
$kYear = date('Y');
$kkYear = date('Y', strtotime('-1year'));
// Create each view data
if (!!self::$vGAViews) {
foreach (self::$vGAViews as $sysKey => $gaViewKey) {
// Get data
$vData = $this->cronGatherDataAndSetToAPC($gaViewKey, 'Zutenis Analytics application');
// Users charts
$vUserPerDay = $vData['usersPerDay'];
if (!empty($vUserPerDay) && is_array($vUserPerDay)) {
if (empty($vUserPerDay[$k])) {
$vUserPerDay[$k] = $vDays;
} else {
$vUserPerDay[$k] = array_replace($vDays, $vUserPerDay[$k]);
}
if (empty($vUserPerDay[$kk])) {
$vUserPerDay[$kk] = $vDays;
} else {
$vUserPerDay[$kk] = array_replace($vDays, $vUserPerDay[$kk]);
}
}
$vUserPerMonth = $vData['usersPerMonth'];
if (!empty($vUserPerMonth) && is_array($vUserPerMonth)) {
if (empty($vUserPerMonth[$kYear])) {
$vUserPerMonth[$kYear] = $vEmptyMonths;
} else {
$vUserPerMonth[$kYear] = array_replace($vEmptyMonths, $vUserPerMonth[$kYear]);
}
if (empty($vUserPerMonth[$kkYear])) {
$vUserPerMonth[$kkYear] = $vEmptyMonths;
} else {
$vUserPerMonth[$kkYear] = array_replace($vEmptyMonths, $vUserPerMonth[$kkYear]);
}
}
$vReturn["usersPerDay_{$sysKey}"] = $vUserPerDay;
$vReturn["usersPerMonth_{$sysKey}"] = $vUserPerMonth;
}
}
// Latest activity
$iStart = strtotime('-1day', strtotime("midnight"));
$iEnd = strtotime('+1day', strtotime("midnight")) - 1;
$idsToSee = $this->createUserCfgForActionsLogs();
$vLastActivity = $this->module->getActionsByDate(array('s' => $iStart, 'e' => $iEnd), $idsToSee);
if (!empty($vLastActivity) && is_array($vLastActivity)) {
foreach ($vLastActivity as &$v) {
$v['time'] = date('d.m.Y H:i', $v['time']);
}
unset($v);
}
$this->oView->ACTIVITY_DATA = $vLastActivity;
return $vReturn;
}
/**
* Function to create user cfg for action logs
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @returns string
*/
public function createUserCfgForActionsLogs()
{
$vUsersIds = $this->module->getSiteUsersIds($this->cfg);
if (isset($this->cfg[$this->selUserId])) {
return $idsToSee = array_merge($vUsersIds, $this->cfg);
} else {
return $idsToSee = $vUsersIds;
}
}
/**
* Function to create date string from seconds
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @returns string
*/
public function createDateStringFromSeconds()
{
$h = floor(self::$iRefreshRate / 3600);
$m = (self::$iRefreshRate / 60) % 60;
$s = self::$iRefreshRate % 60;
$sTime = '';
if ($h > 0) $sTime .= ($h > 1 ? "{$h} hours" : "{$h} hour");
if ($m > 0) {
if (strlen($sTime)) $sTime .= ", ";
$sTime .= ($m > 1 ? "{$m} minutes" : "{$m} minute");
}
if ($s > 0) {
if (strlen($sTime)) $sTime .= ", ";
$sTime .= ($s > 1 ? "{$s} seconds" : "{$s} second");
}
return $sTime;
}
/**
* Function to get all 12 months translated with key based order ( 1 - January, 2 - February, 3 - March)
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @return array of data
*/
public function getTranslatedMonthsWithKeyBasedOrder()
{
if (!!!($vMonths = $this->oApc->check("MONTHS_KEY_ORDERED_TRANSLATIONS" . $this->langId))) {
$vMonths =[];
for ($i = 1; $i <= 12; $i++) {
$vMonths[$i] = $this->gM(date("F", strtotime("1-{$i}-2015")));
}
$this->oApc->store("MONTHS_KEY_ORDERED_TRANSLATIONS" . $this->langId, $vMonths);
}
return $vMonths;
}
/**
* Function to prepare & set dashboard data to view
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category sysEmpty Controller
* @param string $sViewID - google analytics view id
* @param bool $bOnlineUsersOnly - regenerate user data only
* @param bool $bCronCall - called via cron
* @return mixed (int for users online, array for the rest)
*/
public static function cronGatherDataAndSetToAPC(
$sViewID,
$sAppTitle,
$bOnlineUsersOnly = false,
$bCronCall = false
) {
$vReturn = [
'usersPerDay' => [],
'usersPerMonth' => [],
];
return $vReturn;
$oApc = new cApc();
// Load the Google API PHP Client Library.
$cGoogleApi = new cGoogleApi($sAppTitle, $sViewID);
$iUsersOnline = $oApc->check("GOOGLE_API_ONLINE_USERS_{$sViewID}");
if ($bCronCall || $bOnlineUsersOnly && !!!$iUsersOnline) {
$iUsersOnline = $cGoogleApi->getTotalVisitors();
$oApc->store("GOOGLE_API_ONLINE_USERS_{$sViewID}", $iUsersOnline, 60 * 2); // 2 mins
return $iUsersOnline;
}
$vDatesLastAndThisMonth = array(
's' => strtotime('first day of last month'),
'e' => strtotime('last day of')
);
$vDatesLastToThisYear = array(
's' => strtotime(date('Y-m-d', strtotime('first day of January ' . (date('Y') - 1)))),
'e' => strtotime('last day of December' . date('Y'))
);
$vReturn['usersPerDay'] = $oApc->check("GOOGLE_API_USERS_PER_DAY_{$sViewID}");
if ($bCronCall || !!!$vReturn['usersPerDay']) {
$vReturn['usersPerDay'] = $cGoogleApi->getUsersPerDayForOneMonth($vDatesLastAndThisMonth);
$oApc->store("GOOGLE_API_USERS_PER_DAY_{$sViewID}", $vReturn['usersPerDay'], self::$iRefreshRate);
}
// $vReturn['usersPerDay'][12] = $vReturn['usersPerDay'][1];
// $vReturn['usersPerDay'][1] = $vReturn['usersPerDay'][2];
// unset($vReturn['usersPerDay'][2]);
$vReturn['usersPerMonth'] = $oApc->check("GOOGLE_API_USERS_PER_MONTH_{$sViewID}");
if ($bCronCall || !!!$vReturn['usersPerMonth']) {
$vReturn['usersPerMonth'] = $cGoogleApi->getUsersPerMonthForYear($vDatesLastToThisYear);
$oApc->store("GOOGLE_API_USERS_PER_MONTH_{$sViewID}", $vReturn['usersPerMonth'], self::$iRefreshRate);
}
return $vReturn;
}
}