Exemple #1
2
/**
 * @return void
 * @param
 * @param
 * @desc A generic function, that can be used by all programs. Does all the basic login stuff.
 */
function initProgramlib($ctype = null)
{
    global $gbl, $sgbl, $login, $ghtml;
    // /*
    // --- solution for some scripts running well in slave
    // REVERT - back to original
    if ($sgbl->is_this_slave()) {
        print "This is a Slave Server. Operate it at the Master server.\n";
        exit;
    }
    // */
    static $var = 0;
    $var++;
    $progname = $sgbl->__var_program_name;
    lfile_put_contents($sgbl->__var_error_file, "");
    set_exception_handler("lx_exception_handler");
    //xdebug_disable();
    set_error_handler("lx_error_handler");
    //setcookie("XDEBUG_SESSION", "sess");
    if ($var >= 2) {
        dprint("initProgramlib called twice \n <br> ");
    }
    if ($ctype === 'superadmin') {
        $sgbl->__var_dbf = $sgbl->__path_supernode_db;
        $sgbl->__path_admin_pass = $sgbl->__path_super_pass;
        $sgbl->__var_admin_user = $sgbl->__var_super_user;
        $login = new SuperClient(null, null, 'superadmin', 'login', 'forced');
        $login->get();
        return;
    } else {
        if ($ctype === "guest") {
            $login = new Client(null, null, "____________", "guest");
            $login->get();
            return;
        } else {
            if ($ctype != "") {
                $login = new Client(null, null, $ctype, "login", "forced");
                $login->get();
                return;
            }
        }
    }
    $sessobj = null;
    if ($ghtml->frm_consumedlogin === 'true') {
        $clientname = $_COOKIE["{$progname}-consumed-clientname"];
        $classname = $_COOKIE["{$progname}-consumed-classname"];
        $session_id = $_COOKIE["{$progname}-consumed-session-id"];
        get_login($classname, $clientname);
        $login->__session_id = $session_id;
        $sessobj = $login->getObject('ssession');
    } else {
        if (isset($_COOKIE["{$progname}-session-id"])) {
            $clientname = $_COOKIE["{$progname}-clientname"];
            $classname = $_COOKIE["{$progname}-classname"];
            $session_id = $_COOKIE["{$progname}-session-id"];
            if ($classname === 'superclient') {
                $sgbl->__var_dbf = $sgbl->__path_supernode_db;
                $sgbl->__path_admin_pass = $sgbl->__path_super_pass;
                $sgbl->__var_admin_user = $sgbl->__var_super_user;
            }
            if ($classname === 'slave') {
                $sgbl->__var_dbf = $sgbl->__path_slave_db;
            }
            if ($classname) {
                get_login($classname, $clientname);
                $login->__session_id = $session_id;
                $sessobj = $login->getObject('ssession');
            }
        }
    }
    if (!$sessobj || $sessobj->dbaction === 'add') {
        if ($ghtml->frm_ssl) {
            $ssl = unserialize(base64_decode($ghtml->frm_ssl));
            $string = $ssl['string'];
            $ssl_param = $ssl['ssl_param'];
            $encrypted_string = base64_decode($ssl['encrypted_string']);
            if (!$string || !checkPublicKey($string, $encrypted_string)) {
                print "SSL Connection Failed <br> \n";
                exit;
            }
            $class = 'client';
            $clientname = 'admin';
            get_login($class, $clientname);
            do_login($class, $clientname, $ssl_param);
            $sessobj = $gbl->c_session;
            $sessobj->write();
            $sessobj->dbaction = 'clean';
        }
    }
    //get_savedlogin($classname, $clientname);
    //print_time('login_get', "Login Get");
    //dprintr($login);
    //avoid some php warnings
    if (isset($login)) {
        $gbl->client = $login->nname;
        $gbl->client_ttype = $login->cttype;
    }
    //dprintr($login->hpfilter);
    // This means the session object got created fresh.
    if (!$sessobj || $sessobj->dbaction === 'add') {
        dprint("Session id is empty. Clearing cookies and redirect to login.");
        clear_all_cookie();
        $ghtml->print_redirect_self("/login/");
    }
    $gbl->c_session = $sessobj;
    if ($login->getClName() !== $sessobj->parent_clname) {
        dprint_r($login->ssession_l);
        dprint(" <br> {$session_id} <br> <br> <br> ");
        print "Session error! Login again.";
        clear_all_cookie();
        $ghtml->print_redirect_self("/login/?frm_emessage=sessionname_not_client");
    }
    $gen = $login->getObject('general')->generalmisc_b;
    if (!$gen->isOn('disableipcheck') && $_SERVER['REMOTE_ADDR'] != $sessobj->ip_address) {
        $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
        log_message("An attempt to hack from {$hostname} (" . $_SERVER['REMOTE_ADDR'] . ") with sess {$sessobj->nname}, session ip: {$sessobj->ip_address}");
        if ($gen->isOn('disableipcheck')) {
        } else {
            clear_all_cookie();
            if ($gbl->c_session->ssl_param) {
                $sessobj->delete();
                $sessobj->write();
                $ghtml->print_redirect("{$gbl->c_session->ssl_param['backurl']}&frm_emessage=ipaddress_changed_amidst_session");
            } else {
                $ghtml->print_redirect_self("/login/?frm_emessage=ipaddress_changed_amidst_session");
            }
        }
    }
    if (intval($login->getSpecialObject('sp_specialplay')->ssession_timeout) <= 100) {
        $login->getSpecialObject('sp_specialplay')->ssession_timeout = 100;
        $login->setUpdateSubaction();
    }
    $timeout = $sessobj->last_access + $login->getSpecialObject('sp_specialplay')->ssession_timeout;
    $sessobj->timeout = $timeout;
    //$timeout  =  $sessobj->last_access + 4;
    $sessobj->last_access = time();
    $sessobj->setUpdateSubaction();
    if ($sessobj->auxiliary_id) {
        $aux = new Auxiliary(null, null, $sessobj->auxiliary_id);
        $aux->get();
        $login->__auxiliary_object = $aux;
    }
    if (time() > $timeout) {
        $sessobj->delete();
        $sessobj->write();
        //print("session error timeout");
        if ($gbl->c_session->ssl_param) {
            $ghtml->print_redirect("{$gbl->c_session->ssl_param['backurl']}&frm_emessage=session_timeout");
        } else {
            $ghtml->print_redirect_self("/login/?frm_emessage=session_timeout");
        }
    }
    addToUtmp($sessobj, 'update');
}
Exemple #2
0
 function AddRedirect()
 {
     $vlist = $this->main->__t_new_redirect_a_list;
     foreach ($vlist as $v) {
         $id = $this->main->iisid;
         $v->nname;
         $v->redirect;
         dprint_r($v->nname);
         $siteVRootDir = new lxCOM("IIS://localhost/w3svc/{$id}/Root");
         $vdir = $siteVRootDir->create("IIsWebVirtualDir", $v->nname);
         $vdir->AppIsolated = array(2);
         $vdir->Path = array("{$homedir}/{$v->nname}");
         $vdir->AccessFlags = array(513);
         $vdir->FrontPageWeb = array(1);
         $vdir->AppRoot = array("/LM/W3SVC/{$id}/Root/{$v->nname}");
         $vdir->AppFriendlyName = array("Script");
         $vdir->Put("HttpRedirect", $v->redirect);
         $vdir->SetInfo();
     }
     /*	$v = $this->main->__t_new_redirect_a;
     			$id = $this->main->iisid;
     			$v->nname;
     			$v->redirect;
     			dprint_r($v->nname);
     			$siteVRootDir = new COM("IIS://localhost/w3svc/$id/Root");
     			$vdir = $siteVRootDir->create("IIsWebVirtualDir", $v->nname);
     			$vdir->AppIsolated = array(2);
     			$vdir->Path = array("$homedir/$v->nname");
     			$vdir->AccessFlags = array(513);
     			$vdir->FrontPageWeb = array(1);
     			$vdir->AppRoot = array("/LM/W3SVC/$id/Root/{$v->nname}");
     			$vdir->AppFriendlyName = array("Script");
     			$vdir->Put("HttpRedirect", $v->redirect);
     			$vdir->SetInfo();
     
     			/*	$providerObj = new COM("winmgmts://MyServer/root/MicrosoftIISv2"); 
     			$IIsWebVirtualDirObj =$providerObj->get("IIsWebVirtualD	irSetting='W3SVC/1/Root/Scripts'"); */
 }
Exemple #3
0
    function updateVoicemail() {
        dprint("updateVoicemail()");

        $account=array("sipId"    => $this->sipId,
                       "email"    => $this->email,
                       "name"     => $this->firstName.' '.$this->lastName,
                       "password" => $this->voicemail['Password'],
                       "options"  => $this->voicemail['Options']
                       );

        dprint_r($account);

        $this->VoicemailPort->addHeader($this->SoapAuthVoicemail);
        $result     = $this->VoicemailPort->updateAccount($account);

        if (PEAR::isError($result)) {
            $error_msg=$result->getMessage();
            $error_fault=$result->getFault();
            $error_code=$result->getCode();
            print "$error_msg\n";
            printf ("<p><font color=red>Error (VoicemailPort): %s (%s): %s</font>",$error_msg, $error_fault->detail->exception->errorcode,$error_fault->detail->exception->errorstring);
            return false;
        }

        return true;
    }
Exemple #4
0
/**
 * Prints human-readable information about a variable, wrapped in a <pre> block
 * then dies
 *
 * @param mixed $variable the variable to dump
 */
function dieprint_r($variable)
{
    dprint_r($variable);
    die;
}
Exemple #5
0
function lxguard_main($clearflag = false)
{
    include_once "htmllib/lib/lxguardincludelib.php";
    lxfile_mkdir("__path_home_root/lxguard");
    $lxgpath = "__path_home_root/lxguard";
    $file = "/var/log/secure";
    $fp = fopen($file, "r");
    $fsize = filesize($file);
    $newtime = time();
    $oldtime = time() - 60 * 10;
    $rmt = lfile_get_unserialize("{$lxgpath}/hitlist.info");
    if ($rmt) {
        $oldtime = max((int) $oldtime, (int) $rmt->ddate);
    }
    $ret = FindRightPosition($fp, $fsize, $oldtime, $newtime, "getTimeFromSysLogString");
    $list = lfile_get_unserialize("{$lxgpath}/access.info");
    if ($ret) {
        parse_sshd_and_ftpd($fp, $list);
        lfile_put_serialize("{$lxgpath}/access.info", $list);
    }
    get_total($list, $total);
    //dprintr($list['192.168.1.11']);
    dprint_r("Debug: Total: " . $total . "\n");
    $deny = get_deny_list($total);
    $hdn = lfile_get_unserialize("{$lxgpath}/hostdeny.info");
    $deny = lx_array_merge(array($deny, $hdn));
    $string = null;
    foreach ($deny as $k => $v) {
        if (csb($k, "127")) {
            continue;
        }
        $string .= "ALL : {$k}\n";
    }
    dprint("Debug: \$string is:\n" . $string . "\n");
    $stlist[] = "###Start Program Hostdeny config Area";
    $stlist[] = "###Start Lxdmin Area";
    $stlist[] = "###Start Kloxo Area";
    $stlist[] = "###Start Lxadmin Area";
    $endlist[] = "###End Program HostDeny config Area";
    $endlist[] = "###End Kloxo Area";
    $endlist[] = "###End Lxadmin Area";
    $startstring = $stlist[0];
    $endstring = $endlist[0];
    file_put_between_comments("root", $stlist, $endlist, $startstring, $endstring, "/etc/hosts.deny", $string);
    if ($clearflag) {
        lxfile_rm("{$lxgpath}/access.info");
        $rmt = new Remote();
        $rmt->hl = $total;
        $rmt->ddate = time();
        lfile_put_serialize("{$lxgpath}/hitlist.info", $rmt);
    }
    return $list;
}
Exemple #6
0
    function generateRecords() {
        print "<p>";
        if (!$this->checkGenerateRequest()) {
            return false;
        }
        print "<p>Generating records
        <ol>";

        $_p=array(
                  array('name'       => 'enum_generator_sip_domain',
                        'category'   => 'web',
                        'value'      => strval($this->template['domain']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_range',
                        'category'   => 'web',
                        'value'      => strval($this->template['range']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_strip_digits',
                        'category'   => 'web',
                        'value'      => strval($this->template['strip_digits']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_number_length',
                        'category'   => 'web',
                        'value'      => strval($this->template['number_length']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_add_prefix',
                        'category'   => 'web',
                        'value'      => strval($this->template['add_prefix']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_rpid_strip_digits',
                        'category'   => 'web',
                        'value'      => strval($this->template['rpid_strip_digits']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_call_limit',
                        'category'   => 'web',
                        'value'      => strval($this->template['call_limit']),
                        'permission' => 'customer'
                       ),
                  array('name'       => 'enum_generator_ip_access_list',
                        'category'   => 'web',
                        'value'      => strval($this->template['ip_access_list']),
                        'permission' => 'customer'
                       )
                  );

        $this->enumRecords->setCustomerProperties($_p);

        if ($this->template['owner']) {
            if ($customer = $this->customerRecords->getRecord($this->template['owner'])) {
                $this->template['email']     = $customer->email;
                $this->template['firstName'] = $customer->firstName;
                $this->template['lastName']  = $customer->lastName;
                if (!strlen($this->template['info'])) {
                    $this->template['info'] = $customer->firstName.' '.$customer->lastName;
                }
            } else {
                printf ("<font color=red>Error: cannot retrieve customer information for owner %d</font>",$this->template['owner']);
            }
        }

        dprint_r($this->template);
        $i=0;

        while ($i < $this->template['nr_records']) {

            $number   = sprintf("%.0f", $this->template['firstNumber'] + $i);
            $username = substr($number,$this->template['strip_digits']);
            $mapto    = 'sip:'.$username.'@'.$this->template['domain'];

            print "<li>";
            printf ('Generating number +%s with mapping %s ',$number,$mapto);
            flush();

            $enumMapping = array('tld'      => $this->template['tld'],
                                 'number'   => $number,
                                 'type'     => 'sip',
                                 'mapto'    => $mapto,
                                 'info'     => $this->template['info'],
                                 'owner'    => $this->template['owner']
                                );

            if ($this->template['create_sip']) {
                if (preg_match("/^0/",$username)) {
                    printf ('SIP accounts starting with 0 are not generated (%s@%s)',$username,$this->template['domain']);
                    continue;
                }

                $groups=array();

                printf ('and sip account %s@%s ',$username,$this->template['domain']);

                $ip_access_list = check_ip_access_list($this->template['ip_access_list']);

                $sipAccount = array('account'        => $username.'@'.$this->template['domain'],
                                    'quota'          => $this->template['quota'],
                                    'prepaid'        => $this->template['prepaid'],
                                    'password'       => $this->template['password'],
                                    'groups'         => $groups,
                                    'owner'          => $this->template['owner'],
                                    'pstn'           => $this->template['pstn'],
                                    'ip_access_list' => $ip_access_list,
                                    'call_limit'     => $this->template['call_limit']
                                    );

                if ($this->template['firstName']) {
                    $sipAccount['fullname'] = $this->template['firstName'].' '.$this->template['lastName'];
                }

                if ($this->template['email'])     {
                    $sipAccount['email']     = $this->template['email'];
                }


                if ($this->template['pstn']) {

                    $strip_rpid=intval($this->template['rpid_strip_digits']);

                	if ($strip_rpid && strlen($number) > $strip_rpid) {
                    	$sipAccount['rpid']=substr($number,intval($this->template['rpid_strip_digits']));
                    } else {
                		$sipAccount['rpid']=$number;
                    }
                }

            } else {
                unset($sipAccount);
            }

            dprint_r($sipAccount);

            if (is_array($enumMapping)) $this->enumRecords->addRecord($enumMapping);
            if (is_array($sipAccount))  $this->sipRecords->addRecord($sipAccount);

            $i++;
        }

        print "</ol>";
        return true;
    }
Exemple #7
0
    function show() {
        global $perm;

        foreach ($this->FormElements as $_el) {
            ${$_el} = trim($_REQUEST[$_el]);
        }

        if ($begin_time) {
            list($begin_hour,$begin_min)=explode(":",$begin_time);
        }

        if ($end_time) {
            list($end_hour,$end_min)=explode(":",$end_time);
        }

        if ($begin_date) {
            list($begin_year,$begin_month,$begin_day)=explode("-",$begin_date);
        }

        if ($end_date) {
            list($end_year,$end_month,$end_day)=explode("-",$end_date);
        }

        // overwrite some elements based on user rights
        if ($this->CDRTool['filter']['gateway']) {
            $gateway =$this->CDRTool['filter']['gateway'];
        }

        if (!$this->export) {
            if (!$begin_datetime) {
                $begin_datetime="$begin_year-$begin_month-$begin_day $begin_hour:$begin_min";
                $begin_datetime_timestamp=mktime($begin_hour, $begin_min, 0, $begin_month,$begin_day,$begin_year);
            } else {
                $begin_datetime_timestamp=$begin_datetime;
                $begin_datetime=Date("Y-m-d H:i",$begin_datetime);
            }

            if (!$end_datetime) {
                $end_datetime_timestamp=mktime($end_hour, $end_min, 0, $end_month,$end_day,$end_year);
                $end_datetime="$end_year-$end_month-$end_day $end_hour:$end_min";
            } else {
                $end_datetime_timestamp=$end_datetime;
                $end_datetime=Date("Y-m-d H:i",$end_datetime);
            }
        } else {
            $begin_datetime=Date("Y-m-d H:i",$begin_datetime);
            $end_datetime=Date("Y-m-d H:i",$end_datetime);
        }

        if (!$order_by || (!$group_by && $order_by == "group_by")) {
            $order_by=$this->idField;
        }

        $mongo_where = array();

        if (!$cdr_table) $cdr_table=$this->table;
        $mongo_table_ro = $this->getMongoTable($cdr_table);
        $mongo_table_rw = $this->getMongoTable($cdr_table, true);

        $this->url=sprintf("?cdr_source=%s&cdr_table=%s",$this->cdr_source,$cdr_table);

        if ($this->CDRTool['filter']['domain']) {
            $this->url  .= sprintf("&Realms=%s",urlencode($this->CDRTool['filter']['domain']));
            $Realms      = explode(" ",$this->CDRTool['filter']['domain']);
        } else if ($Realms) {
            $this->url   .= sprintf("&Realms=%s",urlencode($Realms));
            $Realms      = explode(" ",$Realms);
        }

        if ($this->CDRTool['filter']['aNumber']) {
            $this->url   .= sprintf("&UserName=%s",urlencode($this->CDRTool['filter']['aNumber']));
        }

        if ($this->CDRTool['filter']['after_date']) {
            $mongo_where[$this->startTimeField] = array('$gte' => $this->CDRTool['filter']['after_date']);
        }

        if ($order_by) {
            $this->url.=sprintf("&order_by=%s&order_type=%s",addslashes($order_by),addslashes($order_type));
        }

        $this->url.=sprintf("&begin_datetime=%s",urlencode($begin_datetime_timestamp));
        $this->url.=sprintf("&end_datetime=%s",urlencode($end_datetime_timestamp));

        if (!$call_id && $begin_datetime && $end_datetime) {
            $mongo_where[$this->startTimeField] = array('$gte' => $begin_datetime, '$lt' => $end_datetime);
        } else {
            $mongo_where[$this->startTimeField] = array('$gte' => '1970-01-01');
        }

        if ($MONTHYEAR) {
            $mongo_where[$this->startTimeField] = new MongoRegex("/^$MONTHYEAR/");
            $this->url.= sprintf("&MONTHYEAR=%s",urlencode($MONTHYEAR));
        }

        if ($flow) {
            $this->url.=sprintf("&flow=%s",urlencode($flow));
            $mongo_where[$this->flowField] = $flow;
        }

        if ($this->CDRTool['filter']['aNumber']) {
            // force user to see only CDRS with his a_numbers
            $mongo_where['$or'] = array(array($this->usernameField => $this->CDRTool['filter']['aNumber']), array($this->CanonicalURIField => $this->CDRTool['filter']['aNumber']));
            $UserName_comp='equal';
            $UserName=$this->CDRTool['filter']['aNumber'];
        }

        if ($UserName_comp == "empty") {
            $mongo_where[$this->usernameField] = '';
            $this->url.=sprintf("&UserName_comp=%s",urlencode($UserName_comp));
        } else if (strlen($UserName) && !$this->CDRTool['filter']['aNumber']) {
            if (!$UserName_comp) $UserName_comp='begin';

            if ($UserName_comp=="begin") {
                $mongo_where[$this->usernameField] = new MongoRegex("/^$UserName/");
            } elseif ($UserName_comp=="contain") {
                $mongo_where[$this->usernameField] = new MongoRegex("/$UserName/");
            } elseif ($UserName_comp=="equal") {
                $mongo_where[$this->usernameField] = $UserName;
            } else {
                $mongo_where[$this->usernameField] = '';
            }

            $this->url.=sprintf("&UserName=%s&UserName_comp=%s",urlencode($UserName),$UserName_comp);
        }

        $a_number=trim($a_number);
        if ($a_number_comp == "empty") {
            $mongo_where[$this->aNumberField] = '';
            $this->url.=sprintf("&a_number_comp=%s",urlencode($a_number_comp));
        } else if (strlen($a_number)) {
            $a_number=urldecode($a_number);
            if (!$a_number_comp) $a_number_comp="equal";

            $this->url.=sprintf("&a_number=%s",urlencode($a_number));

            if ($a_number_comp=="begin") {
                $mongo_where[$this->aNumberField] = new MongoRegex("/^$a_number/");
            } elseif ($a_number_comp=="contain") {
                $mongo_where[$this->aNumberField] = new MongoRegex("/$a_number/");
            } elseif ($a_number_comp=="equal") {
                $mongo_where[$this->aNumberField] = $a_number;
            }

            $this->url.=sprintf("&a_number_comp=%s",urlencode($a_number_comp));
        }

        $c_number=trim($c_number);
        if ($c_number_comp == "empty") {
            $mongo_where[$this->CanonicalURIField] = '';
            $this->url.=sprintf("&c_number_comp=%s",urlencode($c_number_comp));
        } else if (strlen($c_number)) {
            $c_number=urldecode($c_number);
            if (!$c_number_comp) $c_number_comp="begin";

            if (!$c_number_comp || $c_number_comp=="begin") {
                $mongo_where[$this->CanonicalURIField] =  new MongoRegex("/^$c_number/");
            } elseif ($c_number_comp=="contain") {
                $mongo_where[$this->CanonicalURIField] =  new MongoRegex("/$c_number/");
            } elseif ($c_number_comp=="equal") {
                $mongo_where[$this->CanonicalURIField] =  $c_number;
            }
            $this->url.=sprintf("&c_number=%s&c_number_comp=%s",urlencode($c_number),urlencode($c_number_comp));
        }

        $Realm=trim($Realm);

        if ($Realms)  {
            $d_array=array();
            foreach ($Realms as $realm) {
                $d_array[] = array($this->domainField => $realm);
            }
            $mongo_where['$or'] = $d_array;
        } else if ($Realm) {
            $Realm=urldecode($Realm);
            $mongo_where[$this->domainField] =  $Realm;
            $this->url.=sprintf("&Realm=%s",urlencode($Realm));
        }

        $BillingId=trim($BillingId);
        if (preg_match("/^\d+$/",$BillingId) && $this->BillingIdField) {
            $mongo_where[$this->BillingIdField] = $BillingId;
            $this->url.=sprintf("&BillingId=%s",urlencode($BillingId));
        }

        if ($application) {
            $mongo_where[$this->applicationField] = new MongoRegex("/$application/");
            $this->url.=sprintf("&application=%s",urlencode($application));
        }

        if ($DestinationId) {
            if ($DestinationId=="empty") {
                $DestinationIdSQL="";
            } else {
                $DestinationIdSQL=$DestinationId;
            }
            $mongo_where[$this->DestinationIdField] = $DestinationIdSQL;
            $this->url.=sprintf("&DestinationId=%s",urlencode($DestinationId));
        }

        if (strlen(trim($ExcludeDestinations))) {
            # TODO: migrateb clause to mongo
            $ExcludeDestArray=explode(" ",trim($ExcludeDestinations));

            foreach ($ExcludeDestArray as $exclDst) {
                if (preg_match("/^0+(\d+)$/",$exclDst,$m)) {
                    $exclDest_id=$m[1];
                } else {
                    $exclDest_id=$exclDst;
                }

                $where .= " and ".
                $this->CanonicalURIField.
                " not like '".
                addslashes(trim($exclDst)).
                "'";
            }

            $this->url.=sprintf("&ExcludeDestinations=%s",urlencode($ExcludeDestinations));
        }

        $call_id=trim($call_id);

        if ($call_id) {
            $call_id=urldecode($call_id);
            $mongo_where[$this->callIdField] = $call_id;
            $this->url.=sprintf("&call_id=%s",urlencode($call_id));
        }

        if ($sip_proxy) {
            $sip_proxy=urldecode($sip_proxy);
            $mongo_where[$this->SipProxyServerField] = $sip_proxy;
            $this->url.=sprintf("&sip_proxy=%s",urlencode($sip_proxy));
        }

        if ($SipCodec) {
            $this->url.=sprintf("&SipCodec=%s",urlencode($SipCodec));
            if ($SipCodec != "empty") {
                $mongo_where[$this->SipCodecField] = $SipCodec;
            } else {
                $mongo_where[$this->SipCodecField] = '';
            }
        }

        if ($SipRPID) {
            $this->url.=sprintf("&SipRPID=%s",urlencode($SipRPID));
            if ($SipRPID != "empty") {
                $mongo_where[$this->SipRPIDField] = $SipRPID;
            } else {
                $mongo_where[$this->SipRPIDField] = '';
            }
        }

        if ($UserAgent) {
            $mongo_where[$this->UserAgentField] = $UserAgent;
            $this->url.=sprintf("&UserAgent=%s",urlencode($UserAgent));
        }

        if (strlen($sip_status)) {
            $mongo_where[$this->disconnectField] = $sip_status;
            $this->url.=sprintf("&sip_status=%s",urlencode($sip_status));
        }

        if ($sip_status_class) {
            $mongo_where[$this->disconnectField] = new MongoRegex("/^$sip_status_class/");
            $this->url.=sprintf("&sip_status_class=%s",urlencode($sip_status_class));
        }

        if ($this->CDRTool[filter]["gateway"]) {
            $mongo_where[$this->gatewayField] = $this->CDRTool[filter]["gateway"];
        } else if ($gateway) {
            $gateway=urldecode($gateway);
            $mongo_where[$this->gatewayField] = $gateway;
            $this->url.=sprintf("&gateway=%s",$gateway);
        }

        if ($duration) {
            if (preg_match("/\d+/",$duration) ) {
                $mongo_where[$this->durationField] = array('$gt' => 0);;
            } elseif (preg_match("/onehour/",$duration) ) {
                $mongo_where[$this->durationField] = array('$lt' => 3610, '$gt' => 3530);
            } elseif ($duration == "zero") {
                $mongo_where[$this->durationField] = 0;
            } elseif ($duration == "zeroprice" && $this->priceField) {
                $mongo_where[$this->durationField] = array('$gt' => 0);
                $mongo_where[$this->priceField] = NULL;
            } elseif ($duration == "nonzero") {
                $mongo_where[$this->durationField] = array('$gt' => 0);
            } elseif ($duration == "onewaymedia") {
                $mongo_where['$or'] = array(array($this->outputTrafficField => 0), array($this->inputTrafficField => 0));
            } elseif ($duration == "nomedia") {
                $mongo_where[$this->inputTrafficField] = 0;
                $mongo_where[$this->outputTrafficField] = 0;
            }
            $this->url.=sprintf("&duration=%s",urlencode($duration));
        }

        if ($media_info) {
            $this->url.=sprintf("&media_info=%s",urlencode($media_info));
            $mongo_where[$this->MediaInfoField] = $media_info;
        }

        $this->url.=sprintf("&maxrowsperpage=%s",addslashes($this->maxrowsperpage));
        $url_calls = $this->scriptFile.$this->url."&action=search";

        if ($group_by) {
            $this->url.=sprintf("&group_by=%s",urlencode($group_by));
        }

        $this->url_edit   = $this->scriptFile.$this->url."&action=edit";
        $this->url_run    = $this->scriptFile.$this->url."&action=search";
        $this->url_export = $_SERVER["PHP_SELF"].$this->url."&action=search&export=1";

        if ($duration == "unnormalized") {
            $mongo_where[$this->normalizedField] = '0';
        }

        if ($duration == "unnormalized_duration") {
            $mongo_where[$this->normalizedField] = '0';
            $mongo_where[$this->durationField] = array('$gt' => 0);
        }

        if ($group_by) {

            $this->group_byOrig=$group_by;

            if ($group_by=="hour") {
                $group_by="HOUR(AcctStartTime)";
            } else if (preg_match("/^DAY/",$group_by)) {
                $group_by="$group_by(AcctStartTime)";
            } else if (preg_match("/BYMONTH/",$group_by)) {
                $group_by="DATE_FORMAT(AcctStartTime,'%Y-%m')";
            } else if (preg_match("/BYYEAR/",$group_by)) {
                $group_by="DATE_FORMAT(AcctStartTime,'%Y')";
            } else if ($group_by=="UserAgentType") {
                $group_by="SUBSTRING_INDEX($this->SipUserAgentsField, ' ', '1')";
            }

            $this->group_by=$group_by;

            if ($group_by==$this->callIdField) {
                $having=sprintf(" having count(%s) > 1 ", addslashes($group_by));
            }

            $field = array_search($group_by, $this->CDRFields);
            $pipeline=array(
                            array('$match' => $mongo_where),
                            array('$group' => array("_id"      => sprintf('$%s', $field),
                                                    'calls'    => array('$sum' => 1))),
                            array('$match' => array('calls' => array('$gte' => 0)))
            );

            $rows = 0;
            if ($mongo_table_ro) {
                try {
                    $group_results = $mongo_table_ro->aggregate($pipeline);
                    $rows = count($group_results);
                } catch (Exception $e) {
                    printf("<p>Caught Mongo exception in show(): %s", $e->getMessage());
                }
            }

        } else {
            $rows = 0;
            if ($mongo_table_ro) {
                try {
                    $rows = $mongo_table_ro->find($mongo_where)->slaveOkay()->count();
                } catch (Exception $e) {
                    printf("<p>Caught Mongo exception in show(): %s", $e->getMessage());
                }
            }
        }

        dprint_r($mongo_where);

        $this->rows=$rows;

        if ($this->CDRTool['filter']['aNumber']) {
            $this->showResultsMenuSubscriber('0',$begin_datetime,$end_datetime);
        } else {
            $this->showResultsMenu('0',$begin_datetime,$end_datetime);
        }

        if (!$this->next)   {
            $i=0;
            $this->next=0;
        } else {
            $i=$this->next;
        }
        $j=0;
        $z=0;


        if ($rows>0)  {

            if ($call_id && $ReNormalize) {
                if ($mongo_table_rw) {
                    $mongo_table_rw->update(array($this->normalizedField=>0), array('$set' => array($this->callIdField => $call_id)));
                }
            }

            if ($UnNormalizedCalls=$this->getUnNormalized($mongo_where,$cdr_table)) {
                if (!$this->DATASOURCES[$this->cdr_source]['skipNormalizeOnPageLoad']) {
                    if ($UnNormalizedCalls < $this->maxCDRsNormalizeWeb) {
                        $this->NormalizeCDRS($mongo_where,$cdr_table);
                        if (!$this->export && $this->status['normalized'] ) {
                            print "<div class=\"alert alert-info\">";
                            printf ("<b><span class=\"alert-heading\">%d</span></b> CDRs normalized. ",$this->status['normalized']);
                            if ($this->status['cached_keys']['saved_keys']) {
                                printf ("Quota usage updated for <b><span class=\"alert-heading\">%d</span></b> accounts. ",$this->status['cached_keys']['saved_keys']);
                            }
                            print "</div>";
                        }
                    }
                }
            }

            if ($rows > $this->maxrowsperpage)  {
                $maxrows=$this->maxrowsperpage+$this->next;
                if ($maxrows > $rows) {
                    $maxrows=$rows;
                    $prev_rows=$maxrows;
                }
            } else {
                $maxrows=$rows;
            }

            if ($duration == "unnormalized") {
                // if display un normalized calls we must substract
                // the amount of calls normalized above
                $maxrows=$maxrows-$this->status['normalized'];
            }

            $mongo_order_by = '_id';

            if ($order_type == DESC) {
                $mongo_order_type = -1;
            } else {
                $mongo_order_type = 1;
            }

            if ($group_by) {
                if ($order_by == "group_by") {
                    $mongo_order_by = '_id';
                } else {
                    $_tmp = array_search($order_by, $this->CDRFields);
                    if (in_array($_tmp, array('price', 'duration','inputTraffic', 'outputTraffic'))) {
                        $mongo_order_by = $_tmp;
                    } else {
                        $mongo_order_by = 'calls';
                    }
                }

                $pipeline=array(
                                array('$match' => $mongo_where),
                                array('$group' => array('_id'           => sprintf('$%s', $field),
                                                        'calls'         => array( '$sum' => 1),
                                                        'duration'      => array( '$sum' => '$duration'),
                                                        'inputTraffic'  => array( '$sum' => '$inputTraffic'),
                                                        'outputTraffic' => array( '$sum' => '$outputTraffic'),
                                                        'price'         => array( '$sum' => '$price'),
                                                        'zero'          => array( '$sum' => array('$cond'=> array(array('$eq' => array('$duration', 0)), 1, 0 ))),
                                                        'nonzero'       => array( '$sum' => array('$cond'=> array(array('$gt' => array('$duration', 0)), 1, 0 )))
                                                        )
                                         ),

                                array('$match' => array('calls' => array('$gte' => 0))),
                                array('$sort'  => array($mongo_order_by => $mongo_order_type)),
                                array('$skip'  => intval($i)),
                                array('$limit' => intval($this->maxrowsperpage))
                );

                //dprint_r($pipeline);

                try {
                    $group_results = $mongo_table_ro->aggregate($pipeline);
                } catch (Exception $e) {
                    printf("<p>Caught Mongo exception in show(): %s", $e->getMessage());
                }

                $this->showTableHeaderStatistics();

                foreach ($group_results as $result) {
                    $found=$i+1;

                    $mygroup            = $result['_id'];

                    $calls              = $result['calls'];
                    $seconds            = $result['duration'];
                    $price              = $result['price'];
                    $zero               = $result['zero'];
                    $zeroP              = $calls/$zero * 100;
                    $nonzero            = $result['nonzero'];
                    $nonzeroP           = $calls/$nonzero * 100;
                    $seconds_print      = number_format($seconds,0);
                    $minutes            = number_format($seconds/60,0,"","");
                    $minutes_print      = number_format($seconds/60,0);
                    $hours              = sec2hms($seconds);

                    $AcctInputOctets    = number_format($result['inputTraffic'] * 2/ 1024/1024,2,".","");
                    $AcctOutputOctets   = number_format($result['outputTraffic'] * 2/ 1024/1024,2,".","");
                    $NetRateIn          = $result['inputTraffic']*8*2/1024/$seconds;
                    $NetRateOut         = $result['outputTraffic']*8*2/1024/$seconds;
                    $success            = number_format($nonzero/$calls*100,2,".","");
                    $failure            = number_format($zero/$calls*100,2,".","");

                    $NetworkRateIn      = number_format($NetRateIn,2);
                    $NetworkRateOut     = number_format($NetRateOut,2);
                    $NetworkRate        = max($NetworkRateIn,$NetworkRateOut);

                    $rr=floor($found/2);
                    $mod=$found-$rr*2;

                    if ($mod ==0) {
                        $inout_color="lightgrey";
                    } else {
                        $inout_color="white";
                    }

                    $traceValue="";
                    $mygroup_print=quoted_printable_decode($mygroup);

                    if ($this->group_byOrig==$this->DestinationIdField) {
                        if ($this->CDRTool['filter']['domain'] && $this->destinations[$this->CDRTool['filter']['domain']]) {
                            list($_dst_id,$_dst_name)=$this->getPSTNDestinationId($mygroup,'',$this->CDRTool['filter']['domain']);
                            $description=$_dst_name;
                        } else {
                            $description=$this->destinations[0]["default"][$mygroup]["name"];
                        }

                        if ($mygroup) {
                            $traceValue=$mygroup;
                        } else {
                            $traceValue="empty";
                        }

                    } else if ($this->group_byOrig==$this->aNumberField) {
                        # Normalize Called Station Id
                        $N=$this->NormalizeNumber($mygroup);
                        $mygroup_print=$N['username']."@".$N[domain];
                        $description="";
                        $traceField="a_number";
                        $traceValue=urlencode($mygroup);
                    } else if ($this->group_byOrig==$this->CanonicalURIField) {
                        $traceField="c_number";
                        $traceValue=urlencode($mygroup);
                    } else if ($this->group_byOrig==$this->SipProxyServerField) {
                        $traceField="sip_proxy";
                        $traceValue=urlencode($mygroup);
                    } else if ($this->group_byOrig==$this->SipCodecField) {
                        $traceField="SipCodec";
                    } else if (preg_match("/UserAgent/",$this->group_byOrig)) {
                        $traceField="UserAgent";
                    } else if (preg_match("/^BY/",$this->group_byOrig)) {
                        $traceField="MONTHYEAR";
                    } else if ($this->group_byOrig==$this->callIdField) {
                        $traceField="call_id";
                    } else if ($this->group_byOrig=="SourceIP") {
                        $traceField = "gateway";
                    } else if ($this->group_byOrig=="SipResponseCode") {
                        $description = $this->disconnectCodesDescription[$mygroup];
                        $traceField="sip_status";
                    } else if ($this->group_byOrig=="SipApplicationType") {
                        $traceField="application";
                    } else if ($this->group_byOrig=="ServiceType") {
                        $traceField="flow";
                    } else {
                        $description="";
                    }

                    if (!$traceField) {
                        $traceField    = $group_by;
                    }

                    if (!$traceValue) {
                        $traceValue    = $mygroup;
                    }

                    if (!$traceValue) {
                        $traceValue="";
                        $comp_type="empty";
                    } else {
                        $comp_type="begin";
                    }

                    $traceValue_enc=urlencode($traceValue);

                    if (!$this->export) {
                        print "
                            <tr>
                            <td><b>$found</b></td>
                            <td align=right>$calls</td>
                            <td align=right>$seconds_print</td>
                            <td align=right>$minutes_print</td>
                            <td align=right>$hours</td>
                            ";
                            if ($perm->have_perm("showPrice")) {
                                $pricePrint=number_format($price,4,".","");
                            } else {
                                $pricePrint='x.xxx';
                            }
                            print "
                            <td align=right>$pricePrint</td>
                            <td align=right>$AcctInputOctets</td>
                            <td align=right>$AcctOutputOctets</td>
                            <td align=right>$success%</td>
                            <td align=right>($nonzero calls)</td>
                            <td align=right>$failure%</td>
                            <td align=right>($zero calls)</td>
                            <td>$mygroup_print</td>
                            <td>$description</td>
                            <td>";
                            printf("<a href=%s&%s=%s&%s_comp=%s target=_new>Display calls</a></td>",$url_calls,$traceField,$traceValue_enc,$traceField,$comp_type);
                            print "
                            </tr>
                            ";
                        } else {
                             print "$found,";
                             print "$calls,";
                             print "$seconds,";
                             print "$minutes,";
                             print "$hours,";
                             if ($perm->have_perm("showPrice")) {
                                 $pricePrint=$price;
                             } else {
                                 $pricePrint='x.xxx';
                             }
                             print "$pricePrint,";
                             print "$AcctInputOctets,";
                             print "$AcctOutputOctets,";
                             print "$success,";
                             print "$nonzero,";
                             print "$failure,";
                             print "$zero,";
                             print "$mygroup_print,";
                             print "$description";
                             print "\n";
                        }
                        $i++;
                     }

                     if (!$this->export) {
                        print "
                        </table>
                        ";
                     }

                } else {
                    if (!$this->export) {
                       // printf ("<div class='alert alert-info'><i style='font-size:13px' class='icon-info-sign'></i> For more information about each call click on its Id column.</div>");
                    }

                if ($order_by=="zeroP" || $order_by=="nonzeroP") {
                    $order_by="timestamp";
                }

                if ($mongo_table_ro) {
                    $cursor = $mongo_table_ro->find($mongo_where)->sort(array($mongo_order_by=>$mongo_order_type))->skip($i)->limit($this->maxrowsperpage)->slaveOkay();
                } else {
                    $cursor = array();
                }

                if ($this->CDRTool['filter']['aNumber']) {
                    $this->showTableHeaderSubscriber();
                } else {
                    if (!$this->export) {
                        $this->showTableHeader();
                    } else {
                        $this->showExportHeader();
                    }
                }

                foreach ($cursor as $result) {
                    global $found;
                    $found=$i+1;

                    $Structure=$this->_readCDRFieldsFromDB($result);
                    $CDR = new $this->CDR_class($this, $Structure);

                    if ($this->CDRTool['filter']['aNumber']) {
                        $CDR->showSubscriber();
                    } else {
                         if (!$this->export) {
                            $CDR->show();
                        } else {
                            $CDR->export();
                        }
                    }

                    $i++;
                 }

                 if (!$this->export) {
                    print "
                    </table>
                    ";
                 }

            }

            $this->showPagination($this->next,$maxrows);
        }
    }
Exemple #8
0
    function CDR_asterisk($parent,$CDRfields) {

        dprint("<hr>Init CDR");
        dprint_r($CDRfields);

        $this->CDRS= $parent;

        foreach (array_keys($this->CDRS->CDRFields) as $field) {
        	$key=$this->CDRS->CDRFields[$field];
            $this->$field = $CDRfields[$key];
            $mysqlField=$this->CDRS->CDRFields[$field];
            $_field=$field."Field";
            $this->$_field=$mysqlField;
        }

        $this->dayofweek        = date("w",$this->timestamp);
        $this->hourofday        = date("G",$this->timestamp);
        $this->dayofyear        = date("Y-m-d",$this->timestamp);

        $this->aNumberPrint     = $this->aNumber;

        $NormalizedNumber       = $this->CDRS->NormalizeNumber($this->cNumber,"destination",$this->aNumberPrint,$this->domain,"");
        $this->cNumberNormalized= $NormalizedNumber[Normalized];
        $this->cNumberPrint     = $NormalizedNumber[NumberPrint];
        $this->DestinationId    = $NormalizedNumber[DestinationId];
        $this->destinationName  = $NormalizedNumber[destinationName];

        $this->durationPrint    = sec2hms($this->duration);
        $this->appDurationPrint = sec2hms($this->appDuration);

        if ($this->CDRS->rating) {
            $this->showRate           = $this->CDRS->showRate;
        }

		$chanIn_els  = explode("/",$this->channelIn);
        $chanOut_els = explode("/",$this->channelOut);

        $this->remoteGatewayIn  = $chanIn_els[0];
        $this->remoteGatewayOut = $chanOut_els[0];

        $this->traceIn();
        $this->traceOut();

		if ($this->price == "0.0000") {
        	$this->pricePrint="";
        } else {
        	$this->pricePrint=$this->price;
        }

		if (!strlen($this->username)) {
        	$this->username="******";
        }

        if ($this->domain) {
            $_from=$this->username."@".$this->domain;
        } else {
            $_from=$this->username;
        }

        $this->NetworkRateDictionary=array(
                                  'callId'          => $this->id,
                                  'Timestamp'       => $this->timestamp,
                                  'Duration'        => $this->duration,
                                  'Application'     => 'audio',
                                  'From'            => $_from,
                                  'To'              => $this->cNumberNormalized
                                  );
    }
Exemple #9
0
    function CDR_cisco(&$parent, $CDRfields) {

        $this->CDRS = & $parent;
        dprint("<hr>Init CDR");
        dprint($this->timestampField);
        dprint_r($CDRfields);

        foreach (array_keys($this->CDRS->CDRFields) as $field) {
        	$key=$this->CDRS->CDRFields[$field];
            $this->$field = quoted_printable_decode($CDRfields[$key]);
            $mysqlField=$this->CDRS->CDRFields[$field];
            $_field=$field."Field";
            $this->$_field=$mysqlField;
        }

        if ($this->CDRS->rating) {
            $this->showRate           = $this->CDRS->showRate;
        }

        $this->dayofweek       = date("w",$this->timestamp);
        $this->hourofday       = date("G",$this->timestamp);
        $this->dayofyear       = date("Y-m-d",$this->timestamp);
        $this->traffic         = 2*($this->inputTraffic+$this->outputTraffic);

        if (!$this->NASPortId) {
            $this->NASPortIdPrint=$this->RemoteAddress;
        } else {
            $this->NASPortIdPrint=$this->NASPortId;
        }

        if (preg_match("/^(ISDN) ([0-9]+)/",$this->NASPortIdPrint,$m)) {
            $this->gateway=$this->localGateway."-".$m[1]."-".$m[2];
        } else if ($this->RemoteAddress) {
            $this->gateway=$this->RemoteAddress;
        }

        if ($this->H323GWID) {
            $this->aNumberPrint=$this->aNumber."@".$this->H323GWID;
        } else {
            $this->aNumberPrint=$this->aNumber;
        }

        dprint("A number");
        $NormalizedNumber         = $this->CDRS->NormalizeNumber($this->aNumber,"source");
	    $this->aNumberPrint       = $NormalizedNumber[NumberPrint];
        $this->aNumberNormalized  = $NormalizedNumber[Normalized];

        dprint("C number");
		$NormalizedNumber         = $this->CDRS->NormalizeNumber($this->cNumber);
	    $this->cNumberPrint       = $NormalizedNumber[NumberPrint];
        $this->cNumberNormalized  = $NormalizedNumber[Normalized];
        $this->DestinationId      = $NormalizedNumber[DestinationId];
        $this->destinationName    = $NormalizedNumber[destinationName];

        $this->inputTrafficPrint  = number_format(2*$this->inputTraffic/1024,2);
        $this->outputTrafficPrint = number_format(2*$this->outputTraffic/1024,2);

        $this->durationPrint=sec2hms($this->duration);
        $this->disconnectPrint=$this->NormalizeDisconnect($this->disconnect);

        if ($this->H323CallOrigin=="answer") {
            $this->H323CallOrigin="incoming";
        } elseif ($this->H323CallOrigin=="originate") {
            $this->H323CallOrigin="outgoing";
        }

        $this->traceIn();
        $this->traceOut();

		if ($this->price == "0.0000") {
        	$this->pricePrint="";
        } else {
        	$this->pricePrint=$this->price;
        }

        $this->NetworkRateDictionary=array(
                                  'callId'          => $this->callId,
                                  'Timestamp'       => $this->timestamp,
                                  'Duration'        => $this->duration,
                                  'inputTraffic'    => $this->inputTraffic,
                                  'outputTraffic'   => $this->outputTraffic,
                                  'Application'     => "audio",
                                  'Gateway'         => $this->gateway,
                                  'From'            => $this->aNumberNormalized,
                                  'To'              => $this->cNumberNormalized
                                  );
    }