I have this directory script that has it built-in.. hope you find it helpful. strip out the php and js.
Modify anything needed. Makesure, you change the agi creds in click2call()
<?php
/*******************************************************************************************************************
* Don't give me crap for Poor Documentation; It was create for me. But Enjoy
* Distribute / modify or take it to the moon or end of galaxy; but make contribution to help others.
* I am not responsible if this script blows up your computer / phone. Use it at your own Risk.
* License: MIT
* Author: <Insert Your Name HERE>
* Version: 1.5
* Filename: index.php
* Desc: File will create/maintain contacts in a sqlite; change the path & name below. It's not
* aesthetically pleasing, but it gets the job done.
*
* Security Risks: Database isn't encrypted, but hey it's a phone directory. It's to keep dumb people out.
* So, make sure you change the filename & path so it's not residing in the same directory
* as this file. Your password is stored using md5, better than plain text.
*
* Requirements: PDO-PHP/sqlite
* Useage: 1. <filename>.php
* 2. <filename>.php?phone=
* yealink -- creates xml for yealink
* grandstream -- create xml for grandstream
* ... and any function that you create for xml schema
* ?phone=(phonesXML)&dir=(TABLE) -- If not set will use const PUBLIC_PHONEBOOK_TABLE
* 3. <filename>.php?login=logout -- Logs out of GUI contact entry
* Modification of functions:
* getDirectory(model,list directory)
* ==> Creates a new object from class Phone
* ==> when <filename>.php?phone=<PhoneModelXML> is called goes to function above and uses xml to genrate
* invoke function for to genrate xml schema for phones which resides in class Phone.
* create more functions like yealink($pass_directory/ies_as_param) within the Phone class
* class Phone ==> function $model(table of directory)
* ==> added pipe to conslidate directories such as index.php?phone=yealink&Management|Employees"
* ==> when creating a new function for the model make sure to include
* > header('Content-Type: text/xml') or anything you need to pass it as
* > explode dir= pram when its presented with pipe
* > foreach loop to recurse the exploded dir param
*
* Yealink 7.0 Example Lists both directory for Private User
* remote_phonebook.data.1.url = http://server:port/contacts/index.php?phone=yealink&dir=Management
* remote_phonebook.data.1.name = Private Directory
* remote_phonebook.data.2.url = http://server:port/contacts/index.php?phone=yealink
* remote_phonebook.data.2.name = Public Directory
*
* For Grandstrem: http://www.grandstream.com/products/gxp_series/general/documents/gxp_wp_xml_phonebook.pdf
*
*****************************************************************************************************************/
/************************************************************************************************************************
** CONFIGURE THE FOLLOWING SECTION **
***********************************************************************************************************************/
define("DB_NAME","contacts.db");
define("sqlite_connection","PDO_CONNECT"); // VALUES: CLASS_CONNECT / PDO_CONNECT
define("FOOTER_NOTICE","©".date("Y")." My Company Name. All Rights Reserved.");
define("DEFAULT_PHONE_TYPE","yealink"); // default schema function for class Phone to use as phone_type (file request type ?xml or ?phone)
/** END OF CONFIGURATION SECTION **
***********************************************************************************************************************/
/************************************************************************************************************************
** CLASS FOR PHONE SCHEMA **
** **/
/******************************* Defined Class Phone functions below for your phone's XML *******************************
>> These are the functions called when phone=xmlTemplate_<function name> is passed into URL
ex. http://hostname/this_scriptname.php?phone=<functions listed below>
>> Create a function makesure to add xmlTemplate_<phone type> to function to define
phone schema.
************************************************************************************************************************/
class Phone {/* Using class can help prevent from access from outside functions such as main functions */
/** Start Phone Schema Functions **/
/** Function for Yealink for Phones **/
public function yealink ($tables) {
/*
Fields defined in each directory:
<YealinkIPPhoneDirectory>
<DirectoryEntry>
<Name>FirstName LastName</Name>
<Telephone>Phone1</Telephone>
<Telephone>Phone2</Telephone>
..
</DirectoryEntry>
<DirectoryEntry>
<Name>FirstName LastName</Name>
<Telephone>Phone1</Telephone>
<Telephone>Phone2</Telephone>
..
</DirectoryEntry>
</YealinkIPPhoneDirectory>
*/
header('Content-Type: text/xml'); // show that it's xml
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/* echo "<?xml-stylesheet type=\"text/xsl\" href=\"xmlSS-tmplt.xslt\"?>"; */
$tables = explode ("|", $tables); // included to conslidate the tables of contacts if request with | is given
echo "<YealinkIPPhoneDirectory>"; // Opening XML for the file
foreach ($tables as $table) { // Loop for each table requested
$contacts = sqlite("query","SELECT * FROM ".$table." ORDER BY FirstName ASC;"); // get array as an contact
foreach ($contacts as $contact=>$field) { // Get contacts info Loop for each contact in directory
echo "<DirectoryEntry>"; // Opening XML for the contact
// -- echo Contact Info if any field is empty it will skip it
echo "<Name>".parseName($field['FirstName']).' '.parseName($field['LastName'])."</Name>";
if ($field['Phone'] != "" ) echo "<Telephone>" .parsePhone($field['Phone'])."</Telephone>";
if ($field['Mobile'] != "") echo "<Telephone>".parsePhone($field['Mobile'])."</Telephone>";
if ($field['Home'] != "") echo "<Telephone>".parsePhone($field['Home'])."</Telephone>";
//if ($field['Emergency'] != "") echo "<Telephone>".parsePhone($field['Emergency'])."</Telephone>";
if ($field['Emergency'] != ""){
$EmgName = parseName($field['FirstName'])." ".substr(parseName($field['LastName']),0,1).": ". parseName($field['EmergencyName']);
$EmergencyContact[$EmgName] = $field['Emergency'];
}
echo "</DirectoryEntry>"; // Close off the Directory Listing
}
foreach ($EmergencyContact as $contact=>$phone) { // Get contacts info Loop for each contact in directory
echo "<DirectoryEntry>"; // Opening XML for the contact
// -- echo Contact Info if any field is empty it will skip it
echo "<Name>EMG:".$contact."</Name>";
echo "<Telephone>" .parsePhone($phone)."</Telephone>";
echo "</DirectoryEntry>"; // Close off the Directory Listing
}
}
echo "\n</YealinkIPPhoneDirectory>"; // Close off the file
$db=NULL; //free the $db
}
/** Function for Yealink for Phones **/
public function grandstream($tables){
/*
http://www.grandstream.com/products/gxp_series/general/documents/gxp_wp_xml_phonebook.pdf
Since the Old XML Grandstream Doesn't support multiple numbers per entry; each contact will listed seprated
Having Name[M - Mobile|H - Home|E - Emergency] will be added to tell you difference
Fields defined in each directory:
FirstName
LastName
Phone
Mobile
Home
Emergency
Group
*/
header('Content-Type: text/xml'); // show that it's xml
$tables = explode ("|", $tables); // included to conslidate the tables of contacts if request with | is given
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
/* echo "<?xml-stylesheet type=\"text/xsl\" href=\"xmlSS-tmplt.xslt\"?>\n"; */
echo "<AddressBook>\n"; // Opening XML for the file
foreach ($tables as $table) { // Loop for each table requested
$contacts = sqlite("query","SELECT * FROM ".$table." ORDER BY FirstName ASC;"); // get array as an contact
foreach ($contacts as $contact=>$field) { // Get contacts info Loop for each contact in directory
if ($field['Phone'] != "" ) {
$numberType ="";
}
if ($field['Mobile'] != "" ) {
$numberType ="[M]";
}
if ($field['Home'] != "" ) {
$numberType ="[H]";
}
if ($field['Emergency'] != "" ) {
$numberType = "[E]";
}
echo "\n<Contact>"; // Opening XML for the contact
echo "\n<LastName>". (!$field['Emergency'] ?
( parseName($field['LastName']) ) :
("EMG:". parseName(substr($field['FirstName'],0,1)) .". ".
parseName($field['LastName']) )
) ."</LastName>";
echo "\n<FirstName>". (!$field['Emergency'] ? ( parseName($field['FirstName']) ) : (parseName($field['EmergencyName'])) ) .$numberType."</FirstName>";
echo "\n<phonenumber>". (!$field['Emergency'] ? ( parsePhone($field['Phone']) ): (parsePhone($field['Emergency'])) ) ."</phonenumber>";
echo "\n<accountindex>".$field['PrimaryLine']."</accountindex>";
echo "\n<Groups><groupid>".$field['PrimaryGroup']."</groupid></Groups>";
echo "\n</Contact>";
}
}
echo "\n</AddressBook>"; // Close off the file
$db=NULL; //free the $db
}
} // end Phone Class
/** END OF XML SCHEMA SECTION **
************************************************************************************************************************/
if (!file_exists(DB_NAME) || isset($_REQUEST['setupDB'])){
setupDB();
} else {
$settings = sqlite("query","SELECT setting, value FROM settings WHERE setting='pwd' OR setting='default' OR setting='dial_prefix' OR setting='default_primary_line' OR setting='default_primary_group'");
//print_r(serialize($settings));
foreach ($settings as $row=>$value){
if ($value['setting'] == 'pwd') define("ADMIN_PW", $value['value']);
if ($value['setting'] == 'default') define("DEFAULT_DIRECTORY", $value['value']);
if ($value['setting'] == 'dial_prefix') define("DIAL_PREFIX", $value['value']);
if ($value['setting'] == 'default_primary_line') define("DEFAULT_LINE", $value['value']);
if ($value['setting'] == 'default_primary_group') define("DEFAULT_PRIMARY_GROUP", $value['value']);
}
}
if (isset($_REQUEST['login'])){
if ((isset($_POST['password'])) && (md5($_POST['password']) == ADMIN_PW)){
checkAdmin("Allowed");
die();
}
if ($_REQUEST['login'] == "logoff"){
checkAdmin("logoff");
}
else {
checkAdmin("Disallowed");
}
} elseif (isset($_REQUEST['admin'])){
if (isset($_POST['Action'])){
$Action = $_POST['Action'];
$Table = $_POST['Table'];
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$Phone = $_POST['Phone'];
$Mobile = $_POST['Mobile'];
$Home = $_POST['Home'];
$EmergencyName = $_POST['EmergencyName'];
$Emergency = $_POST['Emergency'];
$PrimaryGroup = $_POST['PrimaryGroup'];
$PrimaryLine = $_POST['PrimaryLine'];
$Remove = $_POST['Remove'];
if ($FirstName != "" && ( !isset($Phone) && !isset($Mobile) && !isset($Home) && !isset($Emergency))) {
echo "<font color='red'><strong><center>Adding Contact Failed: Name or Phone # is empty!</center></strong></font>";
} else {
if ($Action == "newContact"){
addContact($Table,$FirstName,$LastName,$Phone,$Mobile,$Home,$EmergencyName,$Emergency,$PrimaryGroup,$PrimaryLine);
}
if ($Action == "updateContact"){
$Id = $_POST['Id'];
if ($Remove == "Remove") {
removeContact($Table,$Id);
}else{
updateContact($Table,$Id,$FirstName,$LastName,$Phone,$Mobile,$Home,$EmergencyName,$Emergency,$PrimaryGroup,$PrimaryLine);
}
}
}
}
checkAdmin();
} elseif (isset($_REQUEST['phone']) || isset($_REQUEST['xml']) ){
$phone = $_REQUEST['phone'];
$dir = $_REQUEST['dir'];
getDirectory($phone,$dir);
} elseif (isset($_REQUEST['list'])) {
listdir($_REQUEST['list']);
} elseif (isset($_REQUEST['changePwd'])) {
setupDB("ChangePwd");
}
elseif (isset($_REQUEST['click2call'])) {
click2call ($_REQUEST['click2call'],$_REQUEST['ext']);
}
else{
checkAdmin();
}
/* --------------------- Functions ------------------------ */
function setupDB ($SetupString=NULL) {
//if (!isset($SetupString)) $SetupString = "NewDB";
if (file_exists(DB_NAME) && isset($SetupString)) {
if ($SetupString == "ChangePwd"){
if (isset($_POST['pwdChangeBtn'])){
if (md5($_POST['oldpassword']) == ADMIN_PW) {
if (($_POST['password'] == $_POST['password2']) && ($_POST['password'] != "" || $_POST['password2'] !="" )) {
$db = new PDO('sqlite:'.DB_NAME);
sqlite("exec","UPDATE settings SET value='".md5($_POST['password'])."' WHERE setting='pwd';");
$db = NULL;
header("location: ?login=logoff");
echo "<br /><strong><font color='#0000ff'>Password Change Successful!</font></strong>";
} else echo "<br /><strong><font color='#ff0000'>Password Change Failed! <br />New Password do not match or empty!</font></strong>";
} else echo "<br /><strong><font color='#ff0000'>Incorrect Old Password!</font></strong>";
}
echo "<html>";
echo "<head>";
echo "<title>Phonebook Password Change</title>";
echo "</head>";
echo "<body>";
echo "<center><h1>Phonebook Password Change</h1></center>";
echo "<form name=\"pwdChange\" method=\"POST\" action=\"?changePwd\" >";
echo "<table align='center'>";
echo "<tr><td colspan='2' align='center'><strong><font color='#0000ff'>Change Password Form</font></strong></td></tr>";
echo "<tr><td>Old Password: </td><td><input type='password' name='oldpassword' size='20'></td></tr>";
echo "<tr><td>Password: </td><td><input type='password' name='password' size='20'></td></tr>";
echo "<tr><td>Confirm Password: </td><td><input type='password' name='password2' size='20'></td></td>";
echo "<tr><td colspan='2'><center><input type='submit' name='pwdChangeBtn' value='Change Password'></center></td></tr>";
echo "<table>";
echo "</form>";
echo "</body>";
echo "</html>";
checkAdmin();
die();
}
} elseif ((stristr($SetupString,":")) && (!file_exists(DB_NAME)) ) {
$settings = explode(":", $SetupString);
$Password = $settings[0];
$tables = $settings[1];
$default = $settings[2];
$dial_prefix = $settings[3];
$primary_group = $settings[4];
$primary_line = $settings[5];
echo "<strong>No Databases Found!";
echo "<br />Creating one Now! </strong>";
$tables = explode("|",$tables);
echo "<br \>Creating... [Database File] $db_name";
//create the database
sqlite("exec","CREATE TABLE settings (Id INTEGER PRIMARY KEY, setting TEXT, value TEXT);");
sqlite("exec","INSERT INTO settings (setting, value) VALUES ('pwd','".md5($Password)."');");
sqlite("exec","INSERT INTO settings (setting, value) VALUES ('default','".$default."');");
if (isset($dial_prefix)) sqlite("exec","INSERT INTO settings (setting, value) VALUES ('dial_prefix','".$dial_prefix."');");
sqlite("exec","INSERT INTO settings (setting, value) VALUES ('default_primary_group','".$primary_group."');");
sqlite("exec","INSERT INTO settings (setting, value) VALUES ('default_primary_line','".$primary_line."');");
foreach ($tables as $table) {
echo "<br \>Creating... [Table : Contacts] $table";
sqlite("exec","CREATE TABLE $table (Id INTEGER PRIMARY KEY, FirstName TEXT, LastName TEXT, Phone TEXT, Mobile TEXT, Home TEXT, EmergencyName TEXT, Emergency TEXT, PrimaryGroup TEXT, PrimaryLine TEXT);");
}
echo "<br /><strong><font color='#0000ff'><center>Use your password that was defined and Login!</center></font></strong>";
$db=NULL;
checkAdmin();
} elseif ((isset($_REQUEST['runSetup'])) && (!file_exists(DB_NAME))) {
if (($_POST['password'] == $_POST['password2']) && (($_POST['password'] != "") || ($_POST['password2'] != "")) && ($_POST['tables'] != "") && ($_POST['default_primary_group'] != "") && ($_POST['default_primary_line'] != "") && (in_array($_POST['default'], explode("|",$_POST['tables'])))) {
setupDB($_POST['password'] . ":" . $_POST['tables'] . ":" . $_POST['default'].":".$_POST['dial_prefix'] .":".$_POST['default_primary_group'].":".$_POST['default_primary_line']);
} else {
echo "<font color='#ff0000'>";
if (($_POST['password'] == "") || ($_POST['password2'] == "")) echo "<br /> Error: Password is empty!";
if ($_POST['password'] != $_POST['password2']) echo "<br />Error: Passwords Do not Match!";
if ($_POST['tables'] == "") echo "<br /> Error: Table(s) are not Defined, Multiple can be defined by adding | (pipe) in between lists.";
if (!in_array($_POST['default'], explode("|",$_POST['tables']))) echo "<br />Error: Default contact list is not listed in the contacts lists above.";
if ($_POST['default_primary_line'] == "") echo "<br />Error: Default Primary Line Undefined!";
if ($_POST['default_primary_group'] == "") echo "<br />Error: Default Primary Group Undefined!";
echo "</font>";
$_REQUEST = "";
$_POST = "";
setupDB();
}
} else {
echo "<html>";
echo "<head>";
echo "<title>Phonebook Setup</title>";
echo "</head>";
echo "<body>";
echo "<center><h1>Setup Phonebook</h1></center>";
echo "<form name=\"setupDB\" method=\"POST\" action=\"?setupDB&runSetup=1\" >";
echo "<table>";
echo "<tr><td colspan=2><strong>Setup Password</strong></td></tr>";
echo "<tr><td>Password: </td><td><input type='password' name='password' size='20'></td></tr>";
echo "<tr><td>Confirm Password: </td><td><input type='password' name='password2' size='20'></td></tr>";
echo "<tr><td colspan=2><strong>Setup Tables (Put Pipes (|) in between) Only Alphanumeric:</strong></td></tr>";
echo "<tr><td>Directory Lists: </td><td><input type='text' value='Phonebook1|Phonebook2' name='tables' size='50'></td></tr>";
echo "<tr><td>Default Directory: </td><td><input type='text' value='Phonebook1' name='default' size='25'>(make sure it matches one of the above listed table)</td></tr>";
echo "<tr><td>Dial Prefix (eg. 9)</td><td><input type='text' value='9' name='dial_prefix' size='5'>(This will add a prefix to directory.)</td></tr>";
echo "<tr><td>Default Account Index</td><td><input type='text' value='1' name='default_primary_line' size='5'>(Default Outgoing SIP Line)</td></tr>";
echo "<tr><td>Default Primary Group</td><td><input type='text' value='1' name='default_primary_group' size='5'>(Assign Primary Group for the Contact)</td></tr>";
echo "<tr><td colspan=2><input type='submit' value='Setup'></td></tr>";
echo "</table>";
echo "</form>";
echo "<hr /><center>".FOOTER_NOTICE."</center>";
echo "</body>";
echo "</html>";
}
die();
}
function sqlite($db_command,$sqlString){
//echo $sqlString;
if (sqlite_connection == "PDO_CONNECT"){
$db = new PDO('sqlite:'.DB_NAME);
} elseif (sqlite_connection == "CLASS_CONNECT") {
$db = new SQLite3(DB_NAME);
} else die("<br /><font color='#ff0000'><strong>SQLITE connection Failed! define(sqlite_connection string)!</strong></font>");
$sqlResults = $db->$db_command($sqlString);
if ($db_command == "query") {
if (sqlite_connection == "CLASS_CONNECT") {
while ($row = $sqlResults->fetchArray()) {
$results[] = $row;
}
}
elseif (sqlite_connection == "PDO_CONNECT") {
foreach ($sqlResults as $row) {
$results[] = $row;
}
}
return $results;
}
$db = NULL;
}
function showColumns($table_name){
$result = sqlite("query","PRAGMA table_info(" . $table_name . ");");
foreach ($result as $row) {
$meta[$row['name']] = array(
'pk' => $row['pk'] == '1',
'type' => $row['type'],
);
}
return $meta;
}
function addContact($Table,$FirstName, $LastName, $Phone, $Mobile, $Home,$EmergencyName, $Emergency, $PrimaryGroup, $PrimaryLine){
sqlite("exec","INSERT INTO ".$Table." (FirstName, LastName, Phone, Mobile, Home, EmergencyName, Emergency, PrimaryGroup, PrimaryLine) VALUES ('".$FirstName."', '".$LastName."', '".$Phone."', '".$Mobile."', '".$Home."', '".$EmergencyName."', '".$Emergency."', '".$PrimaryGroup."', '".$PrimaryLine."')");
echo "Contact Added: $LastName, $FirstName - Phone [$Phone] - Mobile [$Mobile] - Home [$Home] - Emergency Name [$EmergencyName] - Emergency [$Emergency] as PrimaryGroup $PrimaryGroup into $Table";
}
function updateContact($Table,$Id,$FirstName,$LastName,$Phone, $Mobile, $Home, $EmergencyName, $Emergency, $PrimaryGroup, $PrimaryLine){
sqlite("exec","UPDATE ".$Table." SET FirstName='".$FirstName."', LastName='".$LastName."', Phone='".$Phone."', Mobile='".$Mobile."', Home='".$Home. "', EmergencyName='".$EmergencyName."', Emergency='".$Emergency."', PrimaryGroup='".$PrimaryGroup."', PrimaryLine='".$PrimaryLine."' WHERE Id=".$Id);
echo "Contact Updated: $LastName, $FirstName - Phone [$Phone] - Mobile [$Mobile] - Home [$Home] - Emergency Name [$EmergencyName] - Emergency [$Emergency] as PrimaryGroup $PrimaryGroup into $Table";
}
function removeContact($Table,$Id){
sqlite("exec","DELETE FROM ".$Table." WHERE Id=".$Id);
echo "Contact Removed: ID $Id from $Table.";
}
// Function List Directory, for HTML Output
function listdir ($tables){
$operatorExtensions = array("","301","302",
"311","312",
"351","352",
"361","362",
"371","372",
"381","382",
"399","398");
header('Content-Type: text/html'); // show that it's xml
echo "<html>\n";
echo "<head>\n";
echo '<script type="text/javascript">';
echo ' function status (txtStatus){document.getElementById("lblStatus").innerHTML = txtStatus+"<br />";}';
echo ' function click2call(phone){';
echo ' var xhttp;';
echo ' var myExt = document.getElementById("myExtension").value;';
echo ' if (myExt == "") {';
echo ' status ("To make a call, a extension must be defined!");';
echo ' return;';
echo ' }';
echo ' if (phone == "") {';
echo ' status ("To make a call, a phone number must be defined!");';
echo ' return;';
echo ' }';
echo ' var r = confirm("You are about to call: "+phone+" on your Extension: "+myExt+"\nAre You Sure?");';
echo ' if (r == false) { status ("You have cancelled the call."); return;}';
echo ' xhttp = new XMLHttpRequest();';
echo ' xhttp.onreadystatechange = function() {';
echo ' if (this.readyState == 4 && this.status == 200) {';
echo ' status (this.responseText);';
echo ' }';
echo ' };';
echo ' xhttp.open("GET", "'.$_SERVER['PHP_SELF'].'?click2call="+phone+"&ext="+myExt, true);';
echo ' xhttp.send();';
echo ' ';
echo ' }';
echo '</script>';
echo "</head>";
echo "<body>";
$tables = explode ("|", $tables); // included to conslidate the tables of contacts if request with | is given
echo "<table border=0 cellspacing=0 >"; // Opening XML for the file
echo "<tr><td colspan=2>Your extension is: <select name=\"myExtension\" id=\"myExtension\">";
foreach ($operatorExtensions as $option) {
echo "<option value=\"$option\">$option</option>";
}
echo "</select></td></tr>";
echo "<tr><td colspan=2 bgcolor=\"#f2f2f2\"><label id=\"lblStatus\"></label></td></tr>";
foreach ($tables as $table) { // Loop for each table requested
$contacts = sqlite("query","SELECT * FROM ".$table." ORDER BY FirstName ASC;",CONTACTS_DB_NAME); // get array as an contact
echo "<tr><th colspan=2 align=center><br /><h2>$table Directory</h2></th></tr>";
echo "<tr><td colspan=2>";
echo "| ";
foreach (range('A', 'Z') as $letter){
echo "<a href=\"#$table-$letter\">$letter</a> | ";
}
$letter="";
$currentLetter = "";
echo "</td></tr>";
foreach ($contacts as $contact=>$field) { // Get contacts info Loop for each contact in directory
echo "<tr>"; // Opening XML for the contact
// -- echo Contact Info if any field is empty it will skip it
echo "<td colspan=2>";
echo "<!-- ".$field['FirstName'][0]." -->";
if ($field['FirstName'][0] != $currentLetter ){
$currentLetter = $field['FirstName'][0];
echo "<a name=\"$table-$currentLetter\"></a>";
echo "<hr /><h3>$currentLetter</h3>";
}
echo "</td></tr>";
echo "<tr><td colspan=2 bgcolor=\"#cecece\"><strong>".parseName($field['FirstName']).' '.parseName($field['LastName'])."</strong></td>";
if ($field['Mobile'] != "") echo "<tr><td bgcolor=\"#f2f2f2\" align=\"right\">Mobile</td><td bgcolor=\"#f2f2f2\">".
"<a href=\"#\" onclick=\"click2call('".parsePhone("^".$field['Mobile'],"strip")."');\">".
parsePhone("^".$field['Mobile'])."</a></td></tr>";
if ($field['Home'] != "")echo "<tr><td bgcolor=\"#f2f2f2\" align=\"right\">Home</td><td bgcolor=\"#f2f2f2\">".
"<a href=\"#\" onclick=\"click2call('".parsePhone("^".$field['Home'],"strip")."');\">".
parsePhone("^".$field['Home'])."</a></td></tr>";
if ($field['Phone'] != "")echo "<tr><td bgcolor=\"#f2f2f2\" align=\"right\">Phone</td><td bgcolor=\"#f2f2f2\">".
"<a href=\"#\" onclick=\"click2call('".parsePhone("^".$field['Phone'],"strip")."');\">".
parsePhone("^".$field['Phone'])."</a></td></tr>";
if ($field['Emergency'] != "")echo "<tr><td bgcolor=\"#f2f2f2\" align=\"right\">Emergency Contact: </td><td bgcolor=\"#f2f2f2\">".
$field['EmergencyName']."</td></tr>";
if ($field['Emergency'] != "")echo "<tr><td bgcolor=\"#f2f2f2\" align=\"right\">Emergency Phone: </td><td bgcolor=\"#f2f2f2\">".
"<a href=\"#\" onclick=\"click2call('".parsePhone("^".$field['Emergency'],"strip")."');\">".
parsePhone("^".$field['Emergency'])."</a></td></tr>";
echo "</tr>"; // Close off the Directory Listing
}
}
echo "\n</table>"; // Close off the file
$db=NULL; //free the $db
echo "</body>";
echo "</html>";
}
function click2call ($number2call, $myExt) {
//die ("click2call Unavailable at the moment.");
if (($myExt > 999 && $myExt < 300) || ($myExt > 7400 && $myExt < 7300)){
die("function ".__FUNCTION__.": Invalid extension!");
}
echo "You have requested to call $number2call from extension $myExt <br />";
$timeout = 10;
$asterisk_ip = "127.0.0.1";
$socket = fsockopen($asterisk_ip,"5038", $errno, $errstr, $timeout);
fputs($socket, "Action: Login\r\n");
fputs($socket, "UserName: phpagi\r\n");
fputs($socket, "Secret: phpagi\r\n");
fputs($socket, "Events: off\r\n\r\n");
sleep (2);
$wrets = fread($socket, 4096);
fputs($socket, "Action: Originate\r\n" );
fputs($socket, "Channel: Local/$myExt\r\n" );
fputs($socket, "Exten: $number2call\r\n" );
fputs($socket, "Context: from-internal\r\n" ); // very important to change to your outbound context
fputs($socket, "CallerID: Click2Call <$number2call>\r\n");
fputs($socket, "Priority: 1\r\n" );
fputs($socket, "Async: yes\r\n" );
fputs($socket, "Action: Logoff\r\n\r\n");
//sleep(1);
$wrets = fread($socket, 4096);
fclose($socket);
}
function checkAdmin ($control=NULL) {
session_start();
if ((($control == "Allowed") || ($_SESSION['timeout'] >= time())) && ($control != "Disallowed" && $control != "logoff")) {
$_SESSION['timeout'] = time() + 3600;
webAdmin();
}
else {
session_destroy();
session_regenerate_id();
echo "<html>";
echo "<head>";
echo "<title>Phonebook Administration</title>";
echo "</head>";
echo "<body>";
echo "<center><h1>Phonebook Administration</h1></center>";
echo "<form name=\"password\" method=\"POST\" action=\"?login\" >";
echo "<center>";
echo "Password: <input type='password' name='password' size='20'>";
echo "<input type='submit' value='Go'>";
if ($control == "Disallowed")
echo "<br /><strong><font color='#ff0000'>Invalid Password!</font></strong>";
if ($control == "logoff")
echo "<br /><strong><font color='#0000ff'>Logout Successful!</font></strong>";
echo "</center>";
echo "</form>";
echo "<hr />";
echo "<h3>View Directories</h3>";
echo "<ul>";
$tables = sqlite("query","SELECT name FROM sqlite_master WHERE (type='table' AND name !='settings') ORDER BY name;");
foreach($tables as $table=>$table_name){
echo "<li><a href=\"".$_SERVER['PHP_SELF']."?list=$table_name[0]\">$table_name[0]</a></li>";
}
echo "</ul>";
echo "";
echo "<hr /><center>".FOOTER_NOTICE."</center>";
echo "</body>";
echo "</html>";
die();
}
}
function webAdmin(){
echo "<html>";
echo "<head>";
echo "<title>Phonebook Administration</title>";
echo "</head>";
echo "<body>";
echo "<center><h1>Phonebook Administration</h1>[<a href='?changePwd'>Change Password</a> | <a href='?login=logoff'>Logout</a> ]</center>";
echo "<hr \><h3>Usage: </h3>";
echo "<ul>";
if (DIAL_PREFIX != ""){
echo "<li>Your Administrator has Set Prefix Digit as: <strong>". DIAL_PREFIX ."</strong>, so don't add that digit in the phone number";
echo " <br /> Add ^ (Caret) to leave the number uneffected and does not add your prefix number.";
}
echo "<li>To Add a Number the Bottom at each list.</li>";
echo "<li>To Edit a Number and/or name make changes to the row that you need update and press the update button on that row. </li>";
echo "<li>To Remove a contact select Remove checkbox and click update.</li>";
echo "<li>For Phone Browsers: ?phone=(yealink|grandstream|...)&(optional)dir=(name of directory)</li>";
echo "</ul>";
echo "<br \>";
$tables = sqlite("query","SELECT name FROM sqlite_master WHERE (type='table' AND name !='settings') ORDER BY name;");
foreach($tables as $table=>$table_name){
echo "<hr><h2>Directory: ".$table_name[0]."</h2>";
echo "<table border=1 cellpadding=1 cellspacing=0>";
echo "<tr>";
$fields = showColumns($table_name[0]);
foreach($fields as $field=>$value){
echo "<th>".$field."</th>";
}
echo "<th colspan='2'> </th>";
echo "</tr>";
$contacts = sqlite("query","SELECT * FROM ".$table_name[0]." ORDER BY FirstName ASC;");
$i=0;
foreach ($contacts as $contact=>$field) {
echo "<tr ".($i++ % 2 ? "bgcolor='#ffffff'":"bgcolor='#c0c0c0'").">";
echo "<form name=\"contacts\" method=\"POST\" action=\"?admin\" >";
echo "<input type='hidden' name='Action' value='updateContact'>";
echo "<input type='hidden' name='Table' value='".$table_name[0]."'>";
echo "<td><input type='hidden' name='Id' value='".$field['Id']."'>".$field['Id']."</td>";
echo "<td><input type='text' size='10' name='FirstName' value='".$field['FirstName']."'></td>";
echo "<td><input type='text' size='10' name='LastName' value='".$field['LastName']."'></td>";
echo "<td><input type='text' size='15' name='Phone' value='".$field['Phone']."'></td>";
echo "<td><input type='text' size='15' name='Mobile' value='".$field['Mobile']."'></td>";
echo "<td><input type='text' size='15' name='Home' value='".$field['Home']."'></td>";
echo "<td><input type='text' size='15' name='EmergencyName' value='".$field['EmergencyName']."'></td>";
echo "<td><input type='text' size='15' name='Emergency' value='".$field['Emergency']."'></td>";
echo "<td><input type='text' size='5' name='PrimaryGroup' value='".$field['PrimaryGroup']."'></td>";
echo "<td><input type='text' size='5' name='PrimaryLine' value='".$field['PrimaryLine']."'></td>";
echo "<td><label><input type='checkbox' name='Remove' value='Remove'>Remove<label></td>";
echo "<td><input type='button' name='Update' value='Update' onClick='form.submit();'></td></form></tr>";
}
echo "<tr bgcolor='#000000'>";
echo "<form name=\"contacts\" method=\"POST\" action=\"?admin\" >";
echo "<input type='hidden' name='Action' value='newContact'>";
echo "<input type='hidden' name='Table' value='".$table_name[0]."'>";
foreach($fields as $field=>$value){
if ($field == "Id" || $field == "ID" || $field == "id") {
echo "<td><font color='#ffffff'>New</font></td>";
} elseif ($field == "PrimaryLine"){
echo "<td><input type='text' size='5' name='".$field."' value='".DEFAULT_LINE."' /></td>";
} elseif ($field == "PrimaryGroup") {
echo "<td><input type='text' size='5' name='".$field."' value='".DEFAULT_PRIMARY_GROUP."'/></td>";
} else {
echo "<td><input type='text' size='15' name='".$field."' /></td>";
}
}
echo "<td colspan='2'><input type='submit' name='newContact' value='Add' /></td>";
echo "</form>";
echo "</tr>";
echo "</table>";
}
echo "<br />";
echo "<br />";
echo "<br />";
echo "<hr \><center>".FOOTER_NOTICE."</center>";
echo "</body>";
echo "</html>";
}
function getDirectory($phone_type,$directory){
if ($phone_type == "") $phone_type = DEFAULT_PHONE_TYPE;
$Phone = new Phone;
if (isset($directory) || $directory != ""){
$Phone->$phone_type($directory);
}
else {
$Phone->$phone_type(DEFAULT_DIRECTORY);
}
}
function FormatName($string) {
$sentences = preg_split('/([\s.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$new_string = '';
foreach ($sentences as $key => $sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
return trim($new_string);
}
function parsePhone($phoneString, $strip=NULL){
if (isset($strip)){
return preg_replace('/\D+/', '', $phoneString);
}
else {
if (stristr($phoneString,"^"))
return substr_replace($phoneString,"",0,1);
else
if (DIAL_PREFIX != "" ){
// Replace the Space
$phoneString = str_replace(str_split('-\ ()'),'',$phoneString);
// return the Value
return DIAL_PREFIX . $phoneString;
}
else {
return $phoneString;
}
}
}
function xmlEscape($string) {
return str_replace(array('&', '<', '>', '\'', '"'), array('&', '<', '>', ''', '"'), $string);
}
function parseName($nameString){
return FormatName(xmlEscape($nameString));
}
?>