示例#1
0
 function zb_AskoziaGetConf()
 {
     $result = array();
     $emptyArray = array();
     //getting url
     $url = zb_StorageGet('ASKOZIAPBX_URL');
     if (empty($url)) {
         $url = 'http://sip.isp/';
         zb_StorageSet('ASKOZIAPBX_URL', $url);
     }
     //getting login
     $login = zb_StorageGet('ASKOZIAPBX_LOGIN');
     if (empty($login)) {
         $login = '******';
         zb_StorageSet('ASKOZIAPBX_LOGIN', $login);
     }
     //getting password
     $password = zb_StorageGet('ASKOZIAPBX_PASSWORD');
     if (empty($password)) {
         $password = '******';
         zb_StorageSet('ASKOZIAPBX_PASSWORD', $password);
     }
     //getting caching time
     $cache = zb_StorageGet('ASKOZIAPBX_CACHETIME');
     if (empty($cache)) {
         $cache = '1';
         zb_StorageSet('ASKOZIAPBX_CACHETIME', $cache);
     }
     $result['url'] = $url;
     $result['login'] = $login;
     $result['password'] = $password;
     $result['cachetime'] = $cache;
     return $result;
 }
示例#2
0
 function web_CashCashtypeDefaultForm()
 {
     $defCashType = zb_StorageGet('DEF_CT');
     if (empty($defCashType)) {
         $defCashType = 'NOP';
     }
     $allCashTypes = zb_CashGetAllCashTypes();
     $inputs = wf_Selector('setdefaultcashtype', $allCashTypes, __('Current default cashtype for manual input'), $defCashType, true);
     $inputs .= wf_Submit(__('Set as default cash type'));
     $result = wf_Form('', 'POST', $inputs, 'glamour');
     return $result;
 }
示例#3
0
 /**
  * Loads config from database
  * 
  * @return void
  */
 protected function loadConfig()
 {
     $config = zb_StorageGet('ARPU_LINES');
     $this->config = $config;
     if (!empty($config)) {
         $raw = explode(',', $config);
         if (!empty($raw)) {
             foreach ($raw as $io => $each) {
                 $clearLine = trim($each);
                 $this->lines[$clearLine] = $clearLine;
             }
         }
     }
 }
示例#4
0
 /**
  * Returns FDB cache lister MAC filters setup form
  * 
  * @return string
  */
 function web_FDBTableFiltersForm()
 {
     $currentFilters = '';
     $oldFilters = zb_StorageGet('FDBCACHEMACFILTERS');
     if (!empty($oldFilters)) {
         $currentFilters = base64_decode($oldFilters);
     }
     $inputs = __('One MAC address per line') . wf_tag('br');
     $inputs .= wf_TextArea('newmacfilters', '', $currentFilters, true, '40x10');
     $inputs .= wf_HiddenInput('setmacfilters', 'true');
     $inputs .= wf_CheckInput('deletemacfilters', __('Cleanup'), true, false);
     $inputs .= wf_Submit(__('Save'));
     $result = wf_Form('', 'POST', $inputs, 'glamour');
     return $result;
 }
示例#5
0
 function zb_AsteriskGetConf()
 {
     $result = array();
     $emptyArray = array();
     //getting url
     $host = zb_StorageGet('ASTERISK_HOST');
     if (empty($host)) {
         $host = 'localhost';
         zb_StorageSet('ASTERISK_HOST', $host);
     }
     //getting login
     $login = zb_StorageGet('ASTERISK_LOGIN');
     if (empty($login)) {
         $login = '******';
         zb_StorageSet('ASTERISK_LOGIN', $login);
     }
     //getting DB name
     $db = zb_StorageGet('ASTERISK_DB');
     if (empty($db)) {
         $db = 'asteriskdb';
         zb_StorageSet('ASTERISK_DB', $db);
     }
     //getting CDR table name
     $table = zb_StorageGet('ASTERISK_TABLE');
     if (empty($table)) {
         $table = 'cdr';
         zb_StorageSet('ASTERISK_TABLE', $table);
     }
     //getting password
     $password = zb_StorageGet('ASTERISK_PASSWORD');
     if (empty($password)) {
         $password = '******';
         zb_StorageSet('ASTERISK_PASSWORD', $password);
     }
     //getting caching time
     $cache = zb_StorageGet('ASTERISK_CACHETIME');
     if (empty($cache)) {
         $cache = '1';
         zb_StorageSet('ASTERISK_CACHETIME', $cache);
     }
     $result['host'] = $host;
     $result['db'] = $db;
     $result['table'] = $table;
     $result['login'] = $login;
     $result['password'] = $password;
     $result['cachetime'] = $cache;
     return $result;
 }
示例#6
0
 function zb_GetHelpdeskDeniedAll()
 {
     $access_raw = zb_StorageGet('ZBS_HELP_DENIED');
     $result = array();
     if (!empty($access_raw)) {
         $access_raw = base64_decode($access_raw);
         $access_raw = unserialize($access_raw);
         $result = $access_raw;
     } else {
         //first access
         $newarray = serialize($result);
         $newarray = base64_encode($newarray);
         zb_StorageSet('ZBS_HELP_DENIED', $newarray);
     }
     return $result;
 }
示例#7
0
 function zb_PaySysPercentGetAll()
 {
     $result = array();
     $data_raw = zb_StorageGet('PAYSYSPC');
     if (!empty($data_raw)) {
         //unpack data
         $data_raw = base64_decode($data_raw);
         $result = unserialize($data_raw);
     } else {
         //first usage
         $newdata = serialize($result);
         $newdata = base64_encode($newdata);
         zb_StorageSet('PAYSYSPC', $newdata);
         log_register("PAYSYSPC CREATE EMPTY");
     }
     return $result;
 }
示例#8
0
 function docsis_ModemSnmpWalkGet()
 {
     $path = zb_StorageGet('DOCSIS_SNMPWALK_PATH');
     //if first run
     if (empty($path)) {
         $path = '/usr/local/bin/snmpwalk';
         zb_StorageSet('DOCSIS_SNMPWALK_PATH', $path);
         log_register("DOCSIS SNMPWALK SET `" . $path . "`");
     }
     return $path;
 }
示例#9
0
 /**
  * Renders available and enabled alerts into  DarkVoid notification area
  * 
  * @return void
  */
 protected function updateAlerts()
 {
     //new tickets alert
     if ($this->altCfg['TB_NEWTICKETNOTIFY']) {
         $newticketcount = zb_TicketsGetAllNewCount();
         if ($newticketcount != 0) {
             $this->alerts .= wf_Link('?module=ticketing', wf_img('skins/ticketnotify.gif', $newticketcount . ' ' . __('support tickets expected processing')), false);
         }
     }
     //new signups notification
     if ($this->altCfg['SIGREQ_ENABLED']) {
         $signups = new SignupRequests();
         $newreqcount = $signups->getAllNewCount();
         if ($newreqcount != 0) {
             $this->alerts .= wf_Link('?module=sigreq', wf_img('skins/sigreqnotify.gif', $newreqcount . ' ' . __('signup requests expected processing')), false);
         }
     }
     //check for unread messages in instant messanger
     if ($this->altCfg['TB_UBIM']) {
         if (cfr('UBIM')) {
             $unreadMessageCount = im_CheckForUnreadMessages();
             if ($unreadMessageCount) {
                 //we have new messages
                 $unreadIMNotify = __('You received') . ' ' . $unreadMessageCount . ' ' . __('new messages');
                 $urlIM = $unreadIMNotify . wf_delimiter() . wf_Link("?module=ubim&checknew=true", __('Click here to go to the instant messaging service.'), false, 'ubButton');
                 $this->alerts .= wf_Link("?module=ubim&checknew=true", wf_img("skins/ubim_blink.gif", $unreadMessageCount . ' ' . __('new message received')), false, '');
                 //$this->alerts.=wf_modalOpened(__('New messages received'), $urlIM, '450', '200');
             }
         }
     }
     //check sms sending queue
     if ($this->altCfg['WATCHDOG_ENABLED']) {
         $smsQueueCount = rcms_scandir(DATA_PATH . 'tsms/');
         $smsQueueCount = sizeof($smsQueueCount);
         if ($smsQueueCount > 0) {
             $this->alerts .= wf_Link("?module=tsmsqueue", wf_img("skins/sms.png", $smsQueueCount . ' ' . __('SMS in queue')), false, '');
         }
     }
     if ($this->altCfg['TB_TASKMANNOTIFY']) {
         //only "for me" tasks notification
         if ($this->altCfg['TB_TASKMANNOTIFY'] == 1) {
             $undoneTasksCount = ts_GetUndoneCountersMy();
             if ($undoneTasksCount > 0) {
                 $undoneAlert = $undoneTasksCount . ' ' . __('Undone tasks') . ' ' . __('for me');
                 $this->alerts .= wf_Link("?module=taskman&show=undone", wf_img("skins/jobnotify.png", $undoneAlert), false, '');
             }
         }
         //total undone tasks count notification
         if ($this->altCfg['TB_TASKMANNOTIFY'] == 2) {
             $undoneTasksCount = ts_GetUndoneCountersAll();
             if ($undoneTasksCount > 0) {
                 $undoneAlert = $undoneTasksCount . ' ' . __('Undone tasks') . ' ' . __('for all');
                 $this->alerts .= wf_Link("?module=taskman&show=undone", wf_img("skins/jobnotify.png", $undoneAlert), false, '');
             }
         }
         //total+my undone tasks count notification
         if ($this->altCfg['TB_TASKMANNOTIFY'] == 3) {
             $undoneTasksCount = ts_GetUndoneCountersAll();
             if ($undoneTasksCount > 0) {
                 $undoneTasksCountMy = ts_GetUndoneCountersMy();
                 $undoneAlert = $undoneTasksCount . ' ' . __('Undone tasks') . ': ' . __('for all') . ' ' . ($undoneTasksCount - $undoneTasksCountMy) . ' / ' . __('for me') . ' ' . $undoneTasksCountMy;
                 $this->alerts .= wf_Link("?module=taskman&show=undone", wf_img("skins/jobnotify.png", $undoneAlert), false, '');
             }
         }
     }
     //switchmon at notify area
     if ($this->altCfg['TB_SWITCHMON']) {
         $dead_raw = zb_StorageGet('SWDEAD');
         $last_pingtime = zb_StorageGet('SWPINGTIME');
         $deathTime = zb_SwitchesGetAllDeathTime();
         $deadarr = array();
         $content = '';
         if ($this->altCfg['SWYMAP_ENABLED']) {
             $content = wf_Link('?module=switchmap', wf_img('skins/swmapsmall.png', __('Switches map')), false);
         }
         $content .= wf_AjaxLoader() . wf_AjaxLink("?module=switches&forcereping=true&ajaxping=true", wf_img('skins/refresh.gif', __('Force ping')), 'switchping', true, '');
         if ($dead_raw) {
             $deadarr = unserialize($dead_raw);
             if (!empty($deadarr)) {
                 //there is some dead switches
                 $deadcount = sizeof($deadarr);
                 if ($this->altCfg['SWYMAP_ENABLED']) {
                     //getting geodata
                     $switchesGeo = zb_SwitchesGetAllGeo();
                 }
                 //ajax container
                 $content .= wf_tag('div', false, '', 'id="switchping"');
                 foreach ($deadarr as $ip => $switch) {
                     if ($this->altCfg['SWYMAP_ENABLED']) {
                         if (isset($switchesGeo[$ip])) {
                             if (!empty($switchesGeo[$ip])) {
                                 $devicefind = wf_Link('?module=switchmap&finddevice=' . $switchesGeo[$ip], wf_img('skins/icon_search_small.gif', __('Find on map'))) . ' ';
                             } else {
                                 $devicefind = '';
                             }
                         } else {
                             $devicefind = '';
                         }
                     } else {
                         $devicefind = '';
                     }
                     //check morgue records for death time
                     if (isset($deathTime[$ip])) {
                         $deathClock = wf_img('skins/clock.png', __('Switch dead since') . ' ' . $deathTime[$ip]) . ' ';
                     } else {
                         $deathClock = '';
                     }
                     //switch location link
                     $switchLocator = wf_Link('?module=switches&gotoswitchbyip=' . $ip, web_edit_icon(__('Go to switch')));
                     //add switch as dead
                     $content .= $devicefind . ' ' . $switchLocator . ' ' . $deathClock . $ip . ' - ' . $switch . '<br>';
                 }
                 //ajax container end
                 $content .= wf_delimiter() . __('Cache state at time') . ': ' . date("H:i:s", $last_pingtime) . wf_tag('div', true);
                 $this->alerts .= wf_tag('div', false, 'ubButton') . wf_modal(__('Dead switches') . ': ' . $deadcount, __('Dead switches'), $content, '', '500', '400') . wf_tag('div', true);
             } else {
                 $content .= wf_tag('div', false, '', 'id="switchping"') . __('Switches are okay, everything is fine - I guarantee') . wf_delimiter() . __('Cache state at time') . ': ' . date("H:i:s", $last_pingtime) . wf_tag('div', true);
                 $this->alerts .= wf_tag('div', false, 'ubButton') . wf_modal(__('All switches alive'), __('All switches alive'), $content, '', '500', '400') . wf_tag('div', true);
             }
         } else {
             $content .= wf_tag('div', false, '', 'id="switchping"') . __('Switches are okay, everything is fine - I guarantee') . wf_delimiter() . __('Cache state at time') . ': ' . @date("H:i:s", $last_pingtime) . wf_tag('div', true);
             $this->alerts .= wf_tag('div', false, 'ubButton') . wf_modal(__('All switches alive'), __('All switches alive'), $content, '', '500', '400') . wf_tag('div', true);
         }
     }
     file_put_contents(self::CACHE_PATH . self::CACHE_PREFIX . $this->myLogin, $this->alerts);
 }
示例#10
0
/**
 * function that display JSON data for display FDB cache
 * 
 * @param $fdbData_raw - array of existing cache _fdb files
 * 
 * @return string
 */
function sn_SnmpParseFdbCacheJson($fdbData_raw)
{
    $allusermacs = zb_UserGetAllMACs();
    $allusermacs = array_flip($allusermacs);
    $alladdress = zb_AddressGetFulladdresslist();
    $allswitches = zb_SwitchesGetAll();
    $rawFilters = zb_StorageGet('FDBCACHEMACFILTERS');
    $filteredCounter = 0;
    $switchdata = array();
    $allfilters = array();
    //switch data preprocessing
    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $eachswitch) {
            $switchdata[$eachswitch['ip']] = $eachswitch['location'];
        }
    }
    //mac filters preprocessing
    if (!empty($rawFilters)) {
        $rawFilters = base64_decode($rawFilters);
        $rawFilters = explodeRows($rawFilters);
        if (!empty($rawFilters)) {
            foreach ($rawFilters as $rawfindex => $rawfmac) {
                $eachMacFilter = strtolower($rawfmac);
                $allfilters[trim($eachMacFilter)] = $rawfindex;
            }
        }
    }
    $result = '{ 
                  "aaData": [';
    foreach ($fdbData_raw as $each_raw) {
        $nameExplode = explode('_', $each_raw);
        if (sizeof($nameExplode) == 2) {
            $switchIp = $nameExplode[0];
            if (file_exists('exports/' . $each_raw)) {
                $eachfdb_raw = file_get_contents('exports/' . $each_raw);
                $eachfdb = unserialize($eachfdb_raw);
                if (!empty($eachfdb_raw)) {
                    foreach ($eachfdb as $mac => $port) {
                        //detecting user login by his mac
                        if (isset($allusermacs[$mac])) {
                            $userlogin = $allusermacs[$mac];
                        } else {
                            $userlogin = false;
                        }
                        if ($userlogin) {
                            $userlink = '<a href=?module=userprofile&username='******'><img src=skins/icon_user.gif> ' . @$alladdress[$userlogin] . '</a>';
                        } else {
                            $userlink = '';
                        }
                        if (sn_FDBFilterCheckMac($mac, $allfilters)) {
                            $result .= '
                    [
                    "' . $switchIp . '",
                    "' . $port . '",
                    "' . @$switchdata[$switchIp] . '",
                    "' . $mac . '",
                    "' . $userlink . '"
                    ],';
                            $filteredCounter++;
                        }
                    }
                }
            }
        }
    }
    //show some data if filters failed
    if ($filteredCounter == 0) {
        $result .= '
                    [
                    "",
                    "",
                    "",
                    "' . __('Nothing found') . '",
                    ""
                    ],';
    }
    $result = substr($result, 0, -1);
    $result .= '] 
        }';
    return $result;
}
示例#11
0
 function zb_PhpConsoleGetTemplate($templatekey)
 {
     $templatedata = zb_StorageGet($templatekey);
     $result = unserialize($templatedata);
     return $result;
 }
示例#12
0
/**
 * Returns full map of switch links
 * 
 * @param int $traceid switch ID to trace uplinks
 * 
 * @return string
 */
function sm_MapDrawSwitchUplinks($traceid = '')
{
    global $ubillingConfig;
    $ym_conf = $ubillingConfig->getYmaps();
    $query = "SELECT * from `switches` WHERE `geo` != '' ";
    $tmpSwitches = simple_queryall($query);
    $allswitches = array();
    $alllinks = array();
    $result = '';
    //dead switches detection
    $dead_raw = zb_StorageGet('SWDEAD');
    $deadarr = array();
    if ($dead_raw) {
        $deadarr = unserialize($dead_raw);
    }
    if (!empty($tmpSwitches)) {
        //transform array to id=>switchdata
        foreach ($tmpSwitches as $io => $each) {
            $allswitches[$each['id']] = $each;
        }
        //making id=>parentid array if needed
        if (!empty($traceid)) {
            foreach ($tmpSwitches as $io => $each) {
                $alllinks[$each['id']] = $each['parentid'];
            }
        }
    }
    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $each) {
            if (!empty($each['parentid'])) {
                if (isset($allswitches[$each['parentid']])) {
                    if ($allswitches[$each['parentid']]['geo'] != '') {
                        $coord1 = $each['geo'];
                        $coord2 = $allswitches[$each['parentid']]['geo'];
                        $hint = $each['location'] . ' ' . $each['ip'] . ' → ' . $allswitches[$each['parentid']]['location'] . ' ' . $allswitches[$each['parentid']]['ip'];
                        if (!isset($deadarr[$each['ip']]) and !isset($deadarr[$allswitches[$each['parentid']]['ip']])) {
                            $color = '#00FF00';
                        } else {
                            $color = '#FF0000';
                        }
                        /**
                         * Круглый год без забот жить бы в норке как енот,
                         * Вырыть ход в огород, воровать, что в нём растёт,
                         * Но боюсь, снег пойдёт - все тропинки заметёт.
                         * Кто-нибудь не разберёт и с ружьём за мной придёт.
                         * 
                         * 
                         * Жрать не буду целый день, и сдохну всем на зло!
                         * Пусть охотники идут - им не повезло!
                         */
                        //trace mode
                        if (!empty($traceid)) {
                            //switch is traced device
                            if ($each['id'] == $traceid) {
                                $width = 5;
                                $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                            } else {
                                //detecting uplinks
                                if (sm_MapIsLinked($alllinks, $traceid, $each['id'])) {
                                    $width = 3;
                                    $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                                }
                            }
                        } else {
                            $width = 1;
                            $result .= sm_MapAddLine($coord1, $coord2, $color, $hint, $width);
                        }
                    }
                }
            }
        }
    }
    return $result;
}
示例#13
0
 /**
  * Gets watchdog settings from database and load it into settings property
  * Also it sets default values into the database
  * 
  * @return void
  */
 public function loadSettings()
 {
     $alert = zb_StorageGet('WATCHDOG_ALERT');
     if (empty($alert)) {
         $alert = __('Watchdog notifies that');
         zb_StorageSet('WATCHDOG_ALERT', $alert);
     }
     $phones = zb_StorageGet('WATCHDOG_PHONES');
     if (empty($phones)) {
         zb_StorageSet('WATCHDOG_PHONES', '');
     }
     $emails = zb_StorageGet('WATCHDOG_EMAILS');
     if (empty($emails)) {
         zb_StorageSet('WATCHDOG_EMAILS', '');
     }
     $telegramchats = zb_StorageGet('WATCHDOG_TELEGRAM');
     $this->settings['WATCHDOG_ALERT'] = $alert;
     $this->settings['WATCHDOG_PHONES'] = $phones;
     $this->settings['WATCHDOG_EMAILS'] = $emails;
     $this->settings['WATCHDOG_TELEGRAM'] = $telegramchats;
 }
示例#14
0
/**
 * Shows payments year graph with caching
 * 
 * @param int $year
 */
function web_PaymentsShowGraph($year)
{
    $months = months_array();
    $year_summ = zb_PaymentsGetYearSumm($year);
    $curtime = time();
    $yearPayData = array();
    $yearStats = array();
    $cacheTime = 3600;
    //sec intervall to cache
    $cells = wf_TableCell('');
    $cells .= wf_TableCell(__('Month'));
    $cells .= wf_TableCell(__('Payments count'));
    $cells .= wf_TableCell(__('ARPU'));
    $cells .= wf_TableCell(__('Cash'));
    $cells .= wf_TableCell(__('Visual'), '50%');
    $rows = wf_TableRow($cells, 'row1');
    //caching subroutine
    $renewTime = zb_StorageGet('YPD_LAST');
    if (empty($renewTime)) {
        //first usage
        $renewTime = $curtime;
        zb_StorageSet('YPD_LAST', $renewTime);
        $updateCache = true;
    } else {
        //cache time already set
        $timeShift = $curtime - $renewTime;
        if ($timeShift > $cacheTime) {
            //cache update needed
            $updateCache = true;
        } else {
            //load data from cache or init new cache
            $yearPayData_raw = zb_StorageGet('YPD_CACHE');
            if (empty($yearPayData_raw)) {
                //first usage
                $emptyCache = array();
                $emptyCache = serialize($emptyCache);
                $emptyCache = base64_encode($emptyCache);
                zb_StorageSet('YPD_CACHE', $emptyCache);
                $updateCache = true;
            } else {
                // data loaded from cache
                $yearPayData = base64_decode($yearPayData_raw);
                $yearPayData = unserialize($yearPayData);
                $updateCache = false;
                //check is current year already cached?
                if (!isset($yearPayData[$year]['graphs'])) {
                    $updateCache = true;
                }
                //check is manual cache refresh is needed?
                if (wf_CheckGet(array('forcecache'))) {
                    $updateCache = true;
                    rcms_redirect("?module=report_finance");
                }
            }
        }
    }
    if ($updateCache) {
        //extracting all of needed payments in one query
        $allYearPayments_q = "SELECT * from `payments` WHERE `date` LIKE '" . $year . "-%' AND `summ`>'0';";
        $allYearPayments = simple_queryall($allYearPayments_q);
        if (!empty($allYearPayments)) {
            foreach ($allYearPayments as $idx => $eachYearPayment) {
                //Here we can get up to 50% of CPU time on month extraction, but this hacks is to ugly :(
                //Benchmark results: http://pastebin.com/i7kadpN7
                $statsMonth = date("m", strtotime($eachYearPayment['date']));
                if (isset($yearStats[$statsMonth])) {
                    $yearStats[$statsMonth]['count']++;
                    $yearStats[$statsMonth]['summ'] = $yearStats[$statsMonth]['summ'] + $eachYearPayment['summ'];
                } else {
                    $yearStats[$statsMonth]['count'] = 1;
                    $yearStats[$statsMonth]['summ'] = $eachYearPayment['summ'];
                }
            }
        }
        foreach ($months as $eachmonth => $monthname) {
            $month_summ = isset($yearStats[$eachmonth]) ? $yearStats[$eachmonth]['summ'] : 0;
            $paycount = isset($yearStats[$eachmonth]) ? $yearStats[$eachmonth]['count'] : 0;
            $cells = wf_TableCell($eachmonth);
            $cells .= wf_TableCell(wf_Link('?module=report_finance&month=' . $year . '-' . $eachmonth, rcms_date_localise($monthname)));
            $cells .= wf_TableCell($paycount);
            $cells .= wf_TableCell(@round($month_summ / $paycount, 2));
            $cells .= wf_TableCell(web_roundValue($month_summ, 2));
            $cells .= wf_TableCell(web_bar($month_summ, $year_summ));
            $rows .= wf_TableRow($cells, 'row3');
        }
        $result = wf_TableBody($rows, '100%', '0', 'sortable');
        $yearPayData[$year]['graphs'] = $result;
        //write to cache
        zb_StorageSet('YPD_LAST', $curtime);
        $newCache = serialize($yearPayData);
        $newCache = base64_encode($newCache);
        zb_StorageSet('YPD_CACHE', $newCache);
    } else {
        //take data from cache
        if (isset($yearPayData[$year]['graphs'])) {
            $result = $yearPayData[$year]['graphs'];
            $result .= __('Cache state at time') . ': ' . date("Y-m-d H:i:s", $renewTime) . ' ';
            $result .= wf_Link("?module=report_finance&forcecache=true", wf_img('skins/icon_cleanup.png', __('Renew')), false, '');
        } else {
            $result = __('Strange exeption');
        }
    }
    show_window(__('Payments by') . ' ' . $year, $result);
}
示例#15
0
 /**
  * Preloads alter config, for further usage as key=>value
  * 
  * @global object $ubillingConfig
  * 
  * @return void
  */
 protected function loadConfig()
 {
     global $ubillingConfig;
     $this->altCfg = $ubillingConfig->getAlter();
     //sets current month
     $this->curmonth = curmonth();
     //loading complex tariffs config
     if ($this->altCfg['COMPLEX_ENABLED']) {
         $this->complexFlag = true;
         if (!empty($this->altCfg['COMPLEX_MASKS'])) {
             $masksRaw = explode(",", $this->altCfg['COMPLEX_MASKS']);
             if (!empty($masksRaw)) {
                 foreach ($masksRaw as $eachmask) {
                     $this->complexMasks[] = trim($eachmask);
                 }
             }
         } else {
             throw new Exception(self::CPL_EMPTY_EX);
         }
     }
     //loading UKV options
     if ($this->altCfg['UKV_ENABLED']) {
         $this->ukvFlag = true;
         $this->ukvComplex = $this->altCfg['UKV_COMPLEX_TARIFFID'];
         $this->ukvIllegal = $this->altCfg['UKV_ILLEGAL_TARIFFID'];
         $this->ukvSocial = $this->altCfg['UKV_SOCIAL_TARIFFID'];
         $this->ukvDebtLimit = $this->altCfg['UKV_MONTH_DEBTLIMIT'];
     }
     //Askozia PBX integration
     if ($this->altCfg['ASKOZIA_ENABLED']) {
         $this->askoziaFlag = true;
         $this->askoziaUrl = zb_StorageGet('ASKOZIAPBX_URL');
         $this->askoziaLogin = zb_StorageGet('ASKOZIAPBX_LOGIN');
         $this->askoziaPassword = zb_StorageGet('ASKOZIAPBX_PASSWORD');
     }
     //PONizer enabled?
     if ($this->altCfg['PON_ENABLED']) {
         $this->ponFlag = true;
     }
     //is DOCSIS support enabled?
     if ($this->altCfg['DOCSIS_SUPPORT']) {
         $this->docsisFlag = true;
     }
 }
示例#16
0
 function tsms_GetTz()
 {
     $tz = zb_StorageGet('TSMS_TZ');
     if (empty($tz)) {
         //create new one
         $tz = '2';
         zb_StorageSet('TSMS_TZ', $tz);
         log_register("TSMS TIMEZONE CREATE");
     }
     return $tz;
 }
示例#17
0
 /**
  * Loads SMS-Fly service config
  * 
  * @return void
  */
 protected function loadSmsflyConfig()
 {
     $smsgateway = zb_StorageGet('SENDDOG_SMSFLY_GATEWAY');
     if (empty($smsgateway)) {
         $smsgateway = 'http://sms-fly.com/api/api.php';
         zb_StorageSet('SENDDOG_SMSFLY_GATEWAY', $smsgateway);
     }
     $smslogin = zb_StorageGet('SENDDOG_SMSFLY_LOGIN');
     if (empty($smslogin)) {
         $smslogin = '******';
         zb_StorageSet('SENDDOG_SMSFLY_LOGIN', $smslogin);
     }
     $smspassword = zb_StorageGet('SENDDOG_SMSFLY_PASSWORD');
     if (empty($smspassword)) {
         $smspassword = '******';
         zb_StorageSet('SENDDOG_SMSFLY_PASSWORD', $smspassword);
     }
     $smssign = zb_StorageGet('SENDDOG_SMSFLY_SIGN');
     if (empty($smssign)) {
         $smssign = 'InfoCentr';
         zb_StorageSet('SENDDOG_SMSFLY_SIGN', $smssign);
     }
     $this->settings['SMSFLY_GATEWAY'] = $smsgateway;
     $this->settings['SMSFLY_LOGIN'] = $smslogin;
     $this->settings['SMSFLY_PASSWORD'] = $smspassword;
     $this->settings['SMSFLY_SIGN'] = $smssign;
 }
示例#18
0
/**
 * Returns list of all available switches devices with its controls. Also catches ajaxping and forcereping events.
 * 
 * @return string
 */
function web_SwitchesShow()
{
    global $ubillingConfig;
    $alterconf = $ubillingConfig->getAlter();
    $allswitches = zb_SwitchesGetAll();
    $modelnames = zb_SwitchModelsGetAllTag();
    $currenttime = time();
    $reping_timeout = $alterconf['SW_PINGTIMEOUT'];
    $deathTime = zb_SwitchesGetAllDeathTime();
    //counters
    $countTotal = 0;
    $countAlive = 0;
    $countDead = 0;
    $countNp = 0;
    $countOnMap = 0;
    $countSwpoll = 0;
    $countMtsigmon = 0;
    $countOlt = 0;
    $countLinked = 0;
    //non realtime switches pinging
    $last_pingtime = zb_StorageGet('SWPINGTIME');
    if (!$last_pingtime) {
        zb_SwitchesRepingAll();
        zb_StorageSet('SWPINGTIME', $currenttime);
        $last_pingtime = $currenttime;
    } else {
        if ($currenttime > $last_pingtime + $reping_timeout * 60) {
            // normal timeout reping sub here
            zb_SwitchesRepingAll();
            zb_StorageSet('SWPINGTIME', $currenttime);
        }
    }
    //force total reping and update cache
    if (wf_CheckGet(array('forcereping'))) {
        zb_SwitchesRepingAll();
        zb_StorageSet('SWPINGTIME', $currenttime);
        if (wf_CheckGet(array('ajaxping'))) {
            $dead_raw = zb_StorageGet('SWDEAD');
            $deathTime = zb_SwitchesGetAllDeathTime();
            $deadarr = array();
            $ajaxResult = '';
            if ($dead_raw) {
                $deadarr = unserialize($dead_raw);
                if (!empty($deadarr)) {
                    //there is some dead switches
                    $deadcount = sizeof($deadarr);
                    if ($alterconf['SWYMAP_ENABLED']) {
                        //getting geodata
                        $switchesGeo = zb_SwitchesGetAllGeo();
                    }
                    //ajax container
                    $ajaxResult .= wf_tag('div', false, '', 'id="switchping"');
                    foreach ($deadarr as $ip => $switch) {
                        if ($alterconf['SWYMAP_ENABLED']) {
                            if (isset($switchesGeo[$ip])) {
                                if (!empty($switchesGeo[$ip])) {
                                    $devicefind = wf_Link('?module=switchmap&finddevice=' . $switchesGeo[$ip], wf_img('skins/icon_search_small.gif', __('Find on map'))) . ' ';
                                } else {
                                    $devicefind = '';
                                }
                            } else {
                                $devicefind = '';
                            }
                        } else {
                            $devicefind = '';
                        }
                        //check morgue records for death time
                        if (isset($deathTime[$ip])) {
                            $deathClock = wf_img('skins/clock.png', __('Switch dead since') . ' ' . $deathTime[$ip]) . ' ';
                        } else {
                            $deathClock = '';
                        }
                        //switch location link
                        $switchLocator = wf_Link('?module=switches&gotoswitchbyip=' . $ip, web_edit_icon(__('Go to switch')));
                        //add switch as dead
                        $ajaxResult .= $devicefind . ' ' . $switchLocator . ' ' . $deathClock . $ip . ' - ' . $switch . '<br>';
                    }
                } else {
                    $ajaxResult = __('Switches are okay, everything is fine - I guarantee');
                }
            }
            $ajaxResult .= wf_delimiter() . __('Cache state at time') . ': ' . date("H:i:s");
            print $ajaxResult;
            //darkvoid update
            $notifyArea = new DarkVoid();
            $notifyArea->flushCache();
            die;
        }
    }
    //load dead switches cache
    $dead_switches_raw = zb_StorageGet('SWDEAD');
    if (!$dead_switches_raw) {
        $dead_switches = array();
    } else {
        $dead_switches = unserialize($dead_switches_raw);
    }
    //create new ADcomments object if enabled
    if ($alterconf['ADCOMMENTS_ENABLED']) {
        $adcomments = new ADcomments('SWITCHES');
    }
    $tablecells = wf_TableCell(__('ID'));
    $tablecells .= wf_TableCell(__('IP'));
    $tablecells .= wf_TableCell(__('Location'));
    $tablecells .= wf_TableCell(__('Active'));
    $tablecells .= wf_TableCell(__('Model'));
    $tablecells .= wf_TableCell(__('SNMP community'));
    $tablecells .= wf_TableCell(__('Geo location'));
    $tablecells .= wf_TableCell(__('Description'));
    $tablecells .= wf_TableCell(__('Actions'));
    $tablerows = wf_TableRow($tablecells, 'row1');
    $lighter = 'onmouseover="this.className = \'row2\';" onmouseout="this.className = \'row3\';" ';
    if (!empty($allswitches)) {
        foreach ($allswitches as $io => $eachswitch) {
            if (isset($dead_switches[$eachswitch['ip']])) {
                if (isset($deathTime[$eachswitch['ip']])) {
                    $obituary = __('Switch dead since') . ' ' . $deathTime[$eachswitch['ip']];
                } else {
                    $obituary = '';
                }
                $aliveled = web_red_led($obituary);
                $aliveflag = '0';
                $countDead++;
            } else {
                if (strpos($eachswitch['desc'], 'NP') === false) {
                    $aliveled = web_green_led();
                    $aliveflag = '1';
                    $countAlive++;
                } else {
                    $aliveled = web_yellow_led();
                    $aliveflag = '2';
                    $countNp++;
                }
            }
            $tablecells = wf_TableCell($eachswitch['id']);
            $tablecells .= wf_TableCell($eachswitch['ip'], '', '', 'sorttable_customkey="' . ip2int($eachswitch['ip']) . '"');
            $tablecells .= wf_TableCell($eachswitch['location']);
            $tablecells .= wf_TableCell($aliveled, '', '', 'sorttable_customkey="' . $aliveflag . '"');
            $tablecells .= wf_TableCell(@$modelnames[$eachswitch['modelid']]);
            $tablecells .= wf_TableCell($eachswitch['snmp']);
            $tablecells .= wf_TableCell($eachswitch['geo']);
            $tablecells .= wf_TableCell($eachswitch['desc']);
            $switchcontrols = '';
            if (cfr('SWITCHESEDIT')) {
                $switchcontrols .= wf_Link('?module=switches&edit=' . $eachswitch['id'], web_edit_icon());
            }
            if (cfr('SWITCHPOLL')) {
                if (!empty($eachswitch['snmp']) and ispos($eachswitch['desc'], 'SWPOLL')) {
                    $switchcontrols .= '&nbsp;' . wf_Link('?module=switchpoller&switchid=' . $eachswitch['id'], wf_img('skins/snmp.png', __('SNMP query')));
                    $countSwpoll++;
                }
            }
            if ($alterconf['SWYMAP_ENABLED']) {
                if (!empty($eachswitch['geo'])) {
                    $switchcontrols .= wf_Link('?module=switchmap&finddevice=' . $eachswitch['geo'], wf_img('skins/icon_search_small.gif', __('Find on map')));
                    $countOnMap++;
                }
                if (!empty($eachswitch['parentid'])) {
                    $switchcontrols .= wf_Link('?module=switchmap&finddevice=' . $eachswitch['geo'] . '&showuplinks=true&traceid=' . $eachswitch['id'], wf_img('skins/ymaps/uplinks.png', __('Uplink switch')));
                    $countLinked++;
                }
            }
            if (ispos($eachswitch['desc'], 'MTSIGMON')) {
                $countMtsigmon++;
            }
            if (ispos($eachswitch['desc'], 'OLT')) {
                $countOlt++;
            }
            if ($alterconf['ADCOMMENTS_ENABLED']) {
                $switchcontrols .= $adcomments->getCommentsIndicator($eachswitch['id']);
            }
            if (isset($alterconf['SW_WEBNAV'])) {
                if ($alterconf['SW_WEBNAV']) {
                    $switchcontrols .= ' ' . wf_tag('a', false, '', 'href="http://' . $eachswitch['ip'] . '" target="_BLANK"') . wf_img('skins/ymaps/globe.png', __('Go to the web interface')) . wf_tag('a', true);
                }
            }
            $tablecells .= wf_TableCell($switchcontrols);
            $tablerows .= wf_tag('tr', false, 'row3', $lighter);
            $tablerows .= $tablecells;
            $tablerows .= wf_tag('tr', true);
            $countTotal++;
        }
    }
    $result = wf_TableBody($tablerows, '100%', '0', 'sortable');
    $result .= wf_img('skins/icon_active.gif') . ' ' . __('Alive switches') . ' - ' . ($countAlive + $countNp) . ' (' . $countAlive . '+' . $countNp . ')' . wf_tag('br');
    $result .= wf_img('skins/icon_inactive.gif') . ' ' . __('Dead switches') . ' - ' . $countDead . wf_tag('br');
    $result .= wf_img('skins/yellow_led.png') . ' ' . __('NP switches') . ' - ' . $countNp . wf_tag('br');
    $result .= wf_img('skins/snmp.png') . ' ' . __('SWPOLL query') . ' - ' . $countSwpoll . wf_tag('br');
    $result .= wf_img('skins/wifi.png') . ' ' . __('MTSIGMON devices') . ' - ' . $countMtsigmon . wf_tag('br');
    $result .= wf_img('skins/pon_icon.gif') . ' ' . __('OLT devices') . ' - ' . $countOlt . wf_tag('br');
    $result .= wf_img('skins/icon_search_small.gif') . ' ' . __('Placed on map') . ' - ' . $countOnMap . wf_tag('br');
    $result .= wf_img('skins/ymaps/uplinks.png') . ' ' . __('Have uplinks') . ' - ' . $countLinked . wf_tag('br');
    $result .= wf_tag('br') . wf_tag('b') . __('Total') . ': ' . $countTotal . wf_tag('b', true) . wf_tag('br');
    return $result;
}
示例#19
0
 public function loadSettings()
 {
     $alert = zb_StorageGet('WATCHDOG_ALERT');
     if (empty($alert)) {
         $alert = __('Watchdog notifies that');
         zb_StorageSet('WATCHDOG_ALERT', $alert);
     }
     $phones = zb_StorageGet('WATCHDOG_PHONES');
     if (empty($phones)) {
         zb_StorageSet('WATCHDOG_PHONES', '');
     }
     $emails = zb_StorageGet('WATCHDOG_EMAILS');
     if (empty($emails)) {
         zb_StorageSet('WATCHDOG_EMAILS', '');
     }
     $smsgateway = zb_StorageGet('WATCHDOG_TSMS_GATEWAY');
     if (empty($smsgateway)) {
         $altcfg = rcms_parse_ini_file(CONFIG_PATH . 'alter.ini');
         $smsgateway = $altcfg['TSMS_GATEWAY'];
         zb_StorageSet('WATCHDOG_TSMS_GATEWAY', $smsgateway);
     }
     $smslogin = zb_StorageGet('WATCHDOG_TSMS_LOGIN');
     if (empty($smslogin)) {
         $smslogin = $altcfg['TSMS_LOGIN'];
         zb_StorageSet('WATCHDOG_TSMS_LOGIN', $smslogin);
     }
     $smspassword = zb_StorageGet('WATCHDOG_TSMS_PASSWORD');
     if (empty($smspassword)) {
         $smspassword = $altcfg['TSMS_PASSWORD'];
         zb_StorageSet('WATCHDOG_TSMS_PASSWORD', $smspassword);
     }
     $smssign = zb_StorageGet('WATCHDOG_TSMS_SIGN');
     if (empty($smssign)) {
         $smssign = 'Ubilling';
         zb_StorageSet('WATCHDOG_TSMS_SIGN', $smssign);
     }
     $this->settings['WATCHDOG_ALERT'] = $alert;
     $this->settings['WATCHDOG_PHONES'] = $phones;
     $this->settings['WATCHDOG_EMAILS'] = $emails;
     $this->settings['WATCHDOG_TSMS_GATEWAY'] = $smsgateway;
     $this->settings['WATCHDOG_TSMS_LOGIN'] = $smslogin;
     $this->settings['WATCHDOG_TSMS_PASSWORD'] = $smspassword;
     $this->settings['WATCHDOG_TSMS_SIGN'] = $smssign;
 }
示例#20
0
/**
 * Returns task typical problems editing form
 * 
 * @return string
 */
function ts_TaskProblemsEditForm()
{
    $rawNotes = zb_StorageGet('PROBLEMS');
    //extract old or create new typical problems array
    if (!empty($rawNotes)) {
        $rawNotes = base64_decode($rawNotes);
        $rawNotes = unserialize($rawNotes);
    } else {
        $emptyArray = array();
        $newNotes = serialize($emptyArray);
        $newNotes = base64_encode($newNotes);
        zb_StorageSet('PROBLEMS', $newNotes);
        $rawNotes = $emptyArray;
    }
    //adding and deletion subroutines
    if (wf_CheckPost(array('createtypicalnote'))) {
        $toPush = strip_tags($_POST['createtypicalnote']);
        array_push($rawNotes, $toPush);
        $newNotes = serialize($rawNotes);
        $newNotes = base64_encode($newNotes);
        zb_StorageSet('PROBLEMS', $newNotes);
        log_register('TASKMAN ADD TYPICALPROBLEM');
        rcms_redirect("?module=taskman&probsettings=true");
    }
    if (wf_CheckPost(array('deletetypicalnote', 'typicalnote'))) {
        $toUnset = $_POST['typicalnote'];
        if (($delkey = array_search($toUnset, $rawNotes)) !== false) {
            unset($rawNotes[$delkey]);
        }
        $newNotes = serialize($rawNotes);
        $newNotes = base64_encode($newNotes);
        zb_StorageSet('PROBLEMS', $newNotes);
        log_register('TASKMAN DELETE TYPICALPROBLEM');
        rcms_redirect("?module=taskman&probsettings=true");
    }
    $rows = '';
    $result = wf_Link("?module=taskman", __('Back'), true, 'ubButton');
    if (!empty($rawNotes)) {
        foreach ($rawNotes as $eachNote) {
            $cells = wf_TableCell($eachNote);
            $rows .= wf_TableRow($cells, 'row3');
        }
    }
    $result .= wf_TableBody($rows, '100%', '0', '');
    $result .= wf_delimiter();
    $addinputs = wf_TextInput('createtypicalnote', __('Create'), '', true, '20');
    $addinputs .= wf_Submit(__('Save'));
    $addform = wf_Form("", "POST", $addinputs, 'glamour');
    $result .= $addform;
    $delinputs = ts_TaskTypicalNotesSelector(false);
    $delinputs .= wf_HiddenInput('deletetypicalnote', 'true');
    $delinputs .= wf_Submit(__('Delete'));
    $delform = wf_Form("", "POST", $delinputs, 'glamour');
    $result .= $delform;
    return $result;
}
示例#21
0
     $import_rawdata = $_POST['import_rawdata'];
     zb_StorageSet('IMPORT_RAWDATA', $import_rawdata);
     $import_opts = array('login_col' => $_POST['login_col'], 'password_col' => $_POST['password_col'], 'ip_col' => $_POST['ip_col'], 'mac_col' => $_POST['mac_col'], 'tariff_col' => $_POST['tariff_col'], 'cash_col' => $_POST['cash_col'], 'phone_col' => $_POST['phone_col'], 'mobile_col' => $_POST['mobile_col'], 'email_col' => $_POST['email_col'], 'credit_col' => $_POST['credit_col'], 'creditex_col' => $_POST['creditex_col'], 'address_col' => $_POST['address_col'], 'realname_col' => $_POST['realname_col'], 'contract_col' => $_POST['contract_col'], 'ao_col' => $_POST['ao_col'], 'down_col' => $_POST['down_col'], 'passive_col' => $_POST['passive_col'], 'netid' => $_POST['networkselect'], 'regtype' => $_POST['regtype']);
     $import_opts = serialize($import_opts);
     $import_opts = base64_encode($import_opts);
     zb_StorageSet('IMPORT_OPTS', $import_opts);
 } else {
     $import_rawdata = zb_StorageGet('IMPORT_RAWDATA');
     $import_opts = zb_StorageGet('IMPORT_OPTS');
 }
 //last checks
 if (!wf_CheckGet(array('goregister'))) {
     web_MigrationPrepare($import_rawdata, $import_opts);
 } else {
     //register imported users
     $regdata_raw = zb_StorageGet('IMPORT_REGDATA');
     $regdata = unserialize(base64_decode($regdata_raw));
     $querybuff = '';
     if (!empty($regdata)) {
         foreach ($regdata as $io => $user) {
             debarr($user);
             //typical register of each user
             $login = vf($user['login']);
             $password = vf($user['password']);
             $ip = $user['ip'];
             $iopts = unserialize(base64_decode($import_opts));
             $netid = $iopts['netid'];
             //Ubilling normal registration mode
             if ($iopts['regtype'] == 'UB') {
                 $billing->createuser($login);
                 log_register("StgUser REGISTER " . $login);
示例#22
0
 /**
  * shows payments graph for some year
  * 
  * @param string $year year to show
  * 
  * @return void
  */
 protected function paymentsShowGraph($year)
 {
     $months = months_array();
     $year_summ = $this->paymentsGetYearSumm($year);
     $curtime = time();
     $yearPayData = array();
     $cells = wf_TableCell('');
     $cells .= wf_TableCell(__('Month'));
     $cells .= wf_TableCell(__('Payments count'));
     $cells .= wf_TableCell(__('ARPU'));
     $cells .= wf_TableCell(__('Cash'));
     $cells .= wf_TableCell(__('Visual'), '50%');
     $rows = wf_TableRow($cells, 'row1');
     //caching subroutine
     $renewTime = zb_StorageGet('UKVYPD_LAST');
     if (empty($renewTime)) {
         //first usage
         $renewTime = $curtime;
         zb_StorageSet('UKVYPD_LAST', $renewTime);
         $updateCache = true;
     } else {
         //cache time already set
         $timeShift = $curtime - $renewTime;
         if ($timeShift > 3600) {
             //cache update needed
             $updateCache = true;
         } else {
             //load data from cache or init new cache
             $yearPayData_raw = zb_StorageGet('UKVYPD_CACHE');
             if (empty($yearPayData_raw)) {
                 //first usage
                 $emptyCache = array();
                 $emptyCache = serialize($emptyCache);
                 $emptyCache = base64_encode($emptyCache);
                 zb_StorageSet('UKVYPD_CACHE', $emptyCache);
                 $updateCache = true;
             } else {
                 // data loaded from cache
                 $yearPayData = base64_decode($yearPayData_raw);
                 $yearPayData = unserialize($yearPayData);
                 $updateCache = false;
                 //check is current year already cached?
                 if (!isset($yearPayData[$year]['graphs'])) {
                     $updateCache = true;
                 }
                 //check is manual cache refresh is needed?
                 if (wf_CheckGet(array('forcecache'))) {
                     $updateCache = true;
                     rcms_redirect(self::URL_REPORTS_MGMT . 'reportFinance');
                 }
             }
         }
     }
     if ($updateCache) {
         foreach ($months as $eachmonth => $monthname) {
             $month_summ = $this->paymentsGetMonthSumm($year, $eachmonth);
             $paycount = $this->paymentsGetMonthCount($year, $eachmonth);
             $cells = wf_TableCell($eachmonth);
             $cells .= wf_TableCell(wf_Link(self::URL_REPORTS_MGMT . 'reportFinance&month=' . $year . '-' . $eachmonth, rcms_date_localise($monthname)));
             $cells .= wf_TableCell($paycount);
             $cells .= wf_TableCell(@round($month_summ / $paycount, 2));
             $cells .= wf_TableCell(web_roundValue($month_summ, 2));
             $cells .= wf_TableCell(web_bar($month_summ, $year_summ));
             $rows .= wf_TableRow($cells, 'row3');
         }
         $result = wf_TableBody($rows, '100%', '0', 'sortable');
         $yearPayData[$year]['graphs'] = $result;
         //write to cache
         zb_StorageSet('UKVYPD_LAST', $curtime);
         $newCache = serialize($yearPayData);
         $newCache = base64_encode($newCache);
         zb_StorageSet('UKVYPD_CACHE', $newCache);
     } else {
         //take data from cache
         if (isset($yearPayData[$year]['graphs'])) {
             $result = $yearPayData[$year]['graphs'];
             $result .= __('Cache state at time') . ': ' . date("Y-m-d H:i:s", $renewTime) . ' ';
             $result .= wf_Link(self::URL_REPORTS_MGMT . 'reportFinance&forcecache=true', wf_img('skins/icon_cleanup.png', __('Renew')), false, '');
         } else {
             $result = __('Strange exeption');
         }
     }
     show_window(__('Payments by') . ' ' . $year, $result);
 }
示例#23
0
 public function run()
 {
     // Проверить, обновилась ли выгрузка из реестра. Для этого вызвать метод
     // getLastDumpDateEx и сравнить полученное значение со значением, полученным на
     // предыдущей итерации. В случае если значение lastDumpDateUrgently изменилось, то
     // незамедлительно запросить обновленную выгрузку. В остальных случаях обновлять
     // выгрузку на усмотрение, но не реже одного раза в сутки.
     // P.S. Для Ubilling`а "своё усмотрение" - это обновить немедленно!
     $lastSync = zb_StorageGet(self::STORAGE_LASTSYNC_KEY);
     try {
         if (($this->_isUrgent = $lastSync < $this->getLastDumpDateEx('lastDumpDateUrgently')) || $lastSync < $this->getLastDumpDateEx('lastDumpDate')) {
             // В случае, если выгрузка обновилась, направить запрос на получение выгрузки с
             // использованием метода sendRequest и получить в ответ код запроса
             if ($this->sendRequest('result') == true) {
                 // Через несколько минут для получения результата обработки запроса вызвать метод
                 // getResult с кодом, полученным на этапе 2. Данный метод необходимо опрашивать с
                 // определенным интервалом (1-2 минуты) до тех пор, пока значение resultCode равно нулю.
                 // При получении ненулевого значения запрос результата по данному коду необходимо
                 // прекратить, так как будет либо получена выгрузка, либо код ошибки.
                 // P.S. Ubilling не ждёт, после отправки запроса он сразу пытается получить ответ...
                 if ($this->getResult('result') == true) {
                     // Записываем полученный от Роскомнадзора zip-архив во временный
                     // файл
                     $tmp = tempnam(sys_get_temp_dir(), 'rbs_');
                     file_put_contents($tmp, $this->getResult('registerZipArchive'));
                     try {
                         $zip = new ZipArchive();
                         $resource = $zip->open($tmp);
                         if ($resource === true) {
                             // Чистим БД от старых записей
                             nr_query("TRUNCATE `rbs_banned`");
                             nr_query("TRUNCATE `rbs_banned_ips`");
                             nr_query("TRUNCATE `rbs_banned_urls`");
                             nr_query("TRUNCATE `rbs_banned_domains`");
                             nr_query("TRUNCATE `rbs_banned_ipSubnets`");
                             nr_query("TRUNCATE `rbs_banned_decisions`");
                             // Инициируем DomDocument, открываем извлечённый xml-документ
                             // и вносим данные из xml-документа в базу данных
                             $dom = new DOMDocument();
                             $dom->loadXML($zip->getFromName('dump.xml'));
                             foreach ($dom->documentElement->getElementsByTagName('content') as $content) {
                                 // Добавляем данные о записях, подлежащих блокировке:
                                 //  * Уникальный идентификатор записи в Роскомнадзоре;
                                 //  * Момент времени, с которого возникает необходимость
                                 //    ограничения доступа;
                                 //  * Тип срочности реагирования;
                                 //  * Код типа реестра;
                                 nr_query("INSERT INTO `rbs_banned` VALUES(\r\n                    '" . $content->getAttribute('id') . "',\r\n                    '" . $content->getAttribute('includeTime') . "',\r\n                    '" . $content->getAttribute('urgencyType') . "',\r\n                    '" . $content->getAttribute('entryType') . "'\r\n                  )");
                                 // Вносим реквизиты решения о необходимости ограничения доступа
                                 //  * Дата решения;
                                 //  * Номер решения;
                                 //  * Орган, принявший решение;
                                 foreach ($content->getElementsByTagName('decision') as $decision) {
                                     nr_query("INSERT INTO `rbs_banned_decisions` VALUES(\r\n                      NULL,\r\n                      '" . $content->getAttribute('id') . "',\r\n                      '" . $decision->getAttribute('date') . "',\r\n                      '" . $decision->getAttribute('number') . "',\r\n                      '" . $decision->getAttribute('org') . "'\r\n                    )");
                                 }
                                 // Добавляем указатели страниц сайтов
                                 foreach ($content->getElementsByTagName('url') as $url) {
                                     nr_query("INSERT INTO `rbs_banned_urls` VALUES(NULL, '" . $content->getAttribute('id') . "', '" . $url->nodeValue . "')");
                                 }
                                 // Добавляем доменные имена
                                 foreach ($content->getElementsByTagName('domain') as $domain) {
                                     nr_query("INSERT INTO `rbs_banned_domains` VALUES(NULL, '" . $content->getAttribute('id') . "', '" . $domain->nodeValue . "')");
                                 }
                                 // Добавляем IP-адреса
                                 foreach ($content->getElementsByTagName('ip') as $ip) {
                                     nr_query("INSERT INTO `rbs_banned_ips` VALUES(NULL, '" . $content->getAttribute('id') . "', '" . $ip->nodeValue . "' )");
                                 }
                                 // Добавляем IP-подсети
                                 foreach ($content->getElementsByTagName('ipSubnet') as $ipSubnet) {
                                     nr_query("INSERT INTO `rbs_banned_ipSubnets` VALUES(NULL, '" . $content->getAttribute('id') . "', '" . $ipSubnet->nodeValue . "')");
                                 }
                             }
                             // Закрываем zip-архив
                             $zip->close();
                             // Обновляем время последней синхронизации
                             zb_StorageSet(self::STORAGE_LASTSYNC_KEY, time() * 1000);
                         } else {
                             throw new Exception("Couldn't open zip-archive, code: " . $resource);
                         }
                     } catch (Exception $ex) {
                         throw $ex;
                     }
                     // Удаляем временный файл
                     unlink($tmp);
                 } else {
                     throw new Exception("Невозможно получить результат: " . $this->getResult('resultComment'));
                 }
             } else {
                 throw new Exception("Невозможно отправить запрос: " . $this->sendRequest('resultComment'));
             }
         } else {
             throw new Exception("Обновление пока не требуется...");
         }
     } catch (Exception $ex) {
         print $ex->getMessage();
     }
 }