<?php

function canonizeNumber($num) {
    global $prefixe;

    if (preg_match('/^\+33([1-9][0-9]{8})$/',$num,$matches) == 1) {
        // Numero international francais
        $num=$prefixe.'0'.$matches[1];
    } elseif (preg_match('/^\+(\d+)$/',$num,$matches) == 1) {
        $num=$prefixe."00".$matches[1];
    } elseif (preg_match('/^0[1-9][0-9]{8}$/',$num) == 1) {
        //Numero national Francais
        $num=$prefixe.$num;
    } elseif (preg_match('/^33([1-9][0-9]{8})$/',$num,$matches) == 1) {
        // Numero international francais
        $num=$prefixe.'0'.$matches[1];
    } elseif (preg_match('/^[1-9][0-9]{10}/',$num,$matches) == 1) {
        // Numero international autres (les francais sont prit avant)
        $num=$prefixe.'00'.$matches[1];
    } elseif (preg_match('/^00[1-9][0-9]{10}/',$num) == 1) {
        // Numero international avec le 00
        $num=$zero.$num;
    } elseif (preg_match('/^0(0[1-9][0-9]{8})$/',$num,$matches) == 1) {
        //Numero national Francais avec un zero pour sortir
        $num=$prefixe.$matches[1];
    } elseif (preg_match('/^0(00[1-9][0-9]{10})/',$num,$matches) == 1) {
        // Numero international autres (les francais sont prit avant) avec un zero pour sortir
        $num=$prefixe.$matches[1];
    }
    return($num);
}


function searchLDAP($action,$company,$service,$user,$device,$NAME) {
    global $NAME,$debug,$db,$prefixe,$ampconf;

    $maxsearch=100;

    // A modifier pour savoir le type de prefixe pour ce service et non pas celui du global
    $cid=$ampconf['TNE_CID_EXPAND'];
    $result=mysql_query("SELECT data FROM asterisk.tne_param WHERE param='cid_param' and value='$cid'");
    $row = mysql_fetch_row($result);
    $prefixe=$row[0];

    $ldap="ldap://{$ampconf['TNE_LDAPIP']}";
    $ldaph=-1;

    $ldaph=ldap_connect($ldap);
    ldap_set_option($ldaph, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldaph, LDAP_OPT_REFERRALS, 0);
    ldap_set_option($ldaph, LDAP_OPT_TIMELIMIT, 3);
    ldap_set_option($ldaph, LDAP_OPT_SIZELIMIT, $maxsearch);
    if (isset($ampconf['TNE_LDAP_STARTTLS']) && ($ampconf['TNE_LDAP_STARTTLS'] == 'yes')) {
        ldap_start_tls($ldaph);
    }
    ldap_bind($ldaph, "{$ampconf['TNE_LDAPADMIN']},{$ampconf['TNE_LDAPDN']}", $ampconf['TNE_LDAPPWD']);

    $justthese = array('sn', 'cn','givenname', 'o','telephoneNumber','mobile','description','dn','displayname');


    //(&(|(sn=*mer*)(givenName=*mer*))(|(memberOf=cn=telGroups,dc=telnowedge,dc=local)(ou=*,ou=208,ou=mcPrivateDirectory,dc=telnowedge,dc=local)))
    if ($ampconf['TNE_SERVICEORCOMPANY'] == 'service') {
        if ($action =='all') {
            $dn="{$ampconf['TNE_LDAPDN']}";
        } elseif ($action =='ext') {
            $dn="ou=mcDirectory,{$ampconf['TNE_LDAPDN']}";
        } elseif ($action =='int') {
            $dn= "ou=telUsers,{$ampconf['TNE_LDAPDN']}";
        }else {
            $dn="{$ampconf['TNE_LDAPDN']}";
        }
        if (file_exists('./customFilter.php')) {
            require_once('./customFilter.php');
        } else {
            $filter = "(|(sn=*$NAME*)(givenname=*$NAME*)(telephoneNumber=*$NAME*)(mobile=*$NAME*))";

            if ($action == 'int') {
                $filter = sprintf('(&%s(description=yes_directory_yes))', $filter);
            }

            if ($action == 'ext') {
                $array = array(
                    sprintf('(ou:dn:=%s)', $user),
                    '(ou:dn:=SpeedDial)',
                    '(ou:dn:=Externe)',
                );

                $filter = sprintf('(&%s%s)', $filter, implode($array));
            }

            if ($action == 'all') {
                $array = array(
                    '(&(ou:dn:=telUsers)(description=yes_directory_yes))',
                    sprintf('(ou:dn:=%s)', $user),
                    '(ou:dn:=SpeedDial)',
                    '(ou:dn:=Externe)',
                );

                $filter = sprintf('(&%s(|%s))', $filter, implode($array));
            }
        }
    } else {
        if ($action =='all') {
            $dn="{$ampconf['TNE_LDAPDN']}";
        } elseif ($action =='ext') {
            $dn="ou=mcDirectory,{$ampconf['TNE_LDAPDN']}";
        } elseif ($action =='int') {
            $dn= "ou=telUsers,{$ampconf['TNE_LDAPDN']}";
        }else {
            $dn="{$ampconf['TNE_LDAPDN']}";
        }
        //TODO Faire le filtrage sur les comapany doit être OK il faut tester
        if (file_exists('./customFilter.php')) {
            require_once('./customFilter.php');
        } else {
            $filter="(&(|(sn=*$NAME*)(givenname=*$NAME*)(telephoneNumber=*$NAME*)(mobile=*$NAME*))(|(ou=*ou=$user,ou=mcPrivateDirectory,{$ampconf['TNE_LDAPDN']})(ou=*ou=$company,ou=Externe,ou=mcDirectory,{$ampconf['TNE_LDAPDN']})(memberOf=cn=$service,ou=$company,ou=telGroups,{$ampconf['TNE_LDAPDN']})))";
        }
    }
    tne_trace("searchLDAP Filter:$filter\n");
    $results  = ldap_search($ldaph, $dn, $filter, $justthese);
    $entries = ldap_get_entries($ldaph, $results);
    foreach ($entries as $e) {
        //echo print_r($e)."\n";
        $givenname=(isset($e['givenname'])?$e['givenname'][0]:'');
        $sn=(isset($e['sn'])?$e['sn'][0]:'');
        $o=(isset($e['o'])?$e['o'][0]:'');
        if (strpos($e['dn'],'telUsers') !== false) {
            // C'est une entry interne on regarde si on doit afficher ce numero ou pas
            if (strpos($e['description'][0],'yes') !== false) {
                $number=canonizeNumber($e['cn'][0]);
                mysql_query("INSERT INTO ldapSearchCache (device,typeNum,sn,givenName,o,number) VALUES('$device','I','$sn','$givenname','$o','$number')",$db);
            } else {
                continue;
            }
        } elseif (strpos($e['dn'],'SpeedDial') !== false) {
            // C'est un speedDial
            if (isset($e['displayname'])) {
                $number=$e['displayname'][0];
                mysql_query("INSERT INTO ldapSearchCache (device,typeNum,sn,givenName,o,number) VALUES('$device','R','$sn','$givenname','$o','$number')",$db);
                continue;
            }
        }
        if (isset($e['telephonenumber'])) {
            for ($i=0; $i < $e['telephonenumber']['count']; $i++) {
                $type='';
                if (preg_match('/(\w+)\/(.*)/',$e['telephonenumber'][$i],$matches) == 1) {
                    tne_trace("telephonenumber matches".print_r($matches,true));
                    $type=$matches[1];
                    $number=$matches[2];
                }
                $number=canonizeNumber(preg_replace('/[^0-9\+]/','',$e['telephonenumber'][$i]));
                mysql_query("INSERT INTO ldapSearchCache (device,typeNum,sn,givenName,o,number) VALUES('$device','$type','$sn','$givenname','$o','$number')",$db);
            }
        }
        if (isset($e['mobile'])) {
            for ($i=0; $i < $e['mobile']['count']; $i++) {
                $number=canonizeNumber(preg_replace('/[^0-9\+]/','',$e['mobile'][$i]));
                mysql_query("INSERT INTO ldapSearchCache (device,typeNum,sn,givenName,o,number) VALUES('$device','M','$sn','$givenname','$o','$number')",$db);
            }
        }
    }
    ldap_unbind($ldaph);
    return('OK');
}


function searchDB($action,$company,$user,$per_page,$device) {
    global $db,$NAME,$PPAGE,$COUNT,$page,$total_pages,$debug,$MULTICOMPANY;
    if ($PPAGE) $page=$PPAGE;

    $result= mysql_query("SELECT count(sn) as total FROM ldapSearchCache WHERE device='$device'", $db);
    $howmany = mysql_fetch_row($result);

    $total_pages = ceil ($howmany[0] / $per_page);
    $limitstart = 'LIMIT '.(($page-1) * $per_page).','.$per_page;

    tne_trace("searchDB: SELECT typeNum,sn,givenName,o,number FROM ldapSearchCache WHERE device='$device' ORDER BY sn,givenName,number DESC $limitstart\n");
    $result = mysql_query("SELECT typeNum,sn,givenName,o,number FROM ldapSearchCache WHERE device='$device' ORDER BY sn,givenName,number DESC $limitstart", $db);
    $COUNT=$howmany[0];
    return($result);
}

?>
