Просмотр исходного кода

Add a missing file sip_profile_copy.php to the dev branch.

Mark Crane 13 лет назад
Сommit
cbbc7fdb6e
100 измененных файлов с 14809 добавлено и 0 удалено
  1. 5 0
      .htaccess
  2. 45 0
      core/backup/backup.php
  3. 87 0
      core/backup/backupandrestore.php
  4. 50 0
      core/backup/root.php
  5. 97 0
      core/databases/app_config.php
  6. 58 0
      core/databases/database_delete.php
  7. 346 0
      core/databases/database_edit.php
  8. 162 0
      core/databases/databases.php
  9. 50 0
      core/databases/root.php
  10. 65 0
      core/default_settings/app_config.php
  11. 29 0
      core/default_settings/app_defaults.php
  12. 190 0
      core/default_settings/default_settings.php
  13. 58 0
      core/default_settings/default_settings_delete.php
  14. 372 0
      core/default_settings/default_settings_edit.php
  15. 50 0
      core/default_settings/root.php
  16. 115 0
      core/domains/app_config.php
  17. 37 0
      core/domains/app_defaults.php
  18. 189 0
      core/domains/domain_settings.php
  19. 60 0
      core/domains/domain_settings_delete.php
  20. 369 0
      core/domains/domain_settings_edit.php
  21. 197 0
      core/domains/domains.php
  22. 195 0
      core/domains/domains_delete.php
  23. 216 0
      core/domains/domains_edit.php
  24. 50 0
      core/domains/root.php
  25. 232 0
      core/menu/app_config.php
  26. 118 0
      core/menu/app_defaults.php
  27. 152 0
      core/menu/menu.php
  28. 83 0
      core/menu/menu_delete.php
  29. 245 0
      core/menu/menu_edit.php
  30. 62 0
      core/menu/menu_item_delete.php
  31. 464 0
      core/menu/menu_item_edit.php
  32. 371 0
      core/menu/menu_item_list.php
  33. 88 0
      core/menu/menu_item_move_down.php
  34. 75 0
      core/menu/menu_item_move_up.php
  35. 63 0
      core/menu/menu_restore_default.php
  36. 50 0
      core/menu/root.php
  37. 98 0
      core/servers/app_config.php
  38. 50 0
      core/servers/root.php
  39. 161 0
      core/servers/v_server_settings.php
  40. 60 0
      core/servers/v_server_settings_delete.php
  41. 244 0
      core/servers/v_server_settings_edit.php
  42. 158 0
      core/servers/v_servers.php
  43. 59 0
      core/servers/v_servers_delete.php
  44. 212 0
      core/servers/v_servers_edit.php
  45. 71 0
      core/upgrade/app_config.php
  46. 132 0
      core/upgrade/app_defaults.php
  47. 50 0
      core/upgrade/root.php
  48. 101 0
      core/upgrade/upgrade.php
  49. 188 0
      core/upgrade/upgrade_domains.php
  50. 71 0
      core/upgrade/upgrade_schema.php
  51. 296 0
      core/upgrade/upgrade_svn.php
  52. 356 0
      core/users/app_config.php
  53. 169 0
      core/users/app_defaults.php
  54. 275 0
      core/users/group_permissions.php
  55. 134 0
      core/users/groupadd.php
  56. 56 0
      core/users/groupdelete.php
  57. 137 0
      core/users/grouplist.php
  58. 80 0
      core/users/groupmemberadd.php
  59. 68 0
      core/users/groupmemberdelete.php
  60. 166 0
      core/users/groupmembers.php
  61. 57 0
      core/users/index.php
  62. 50 0
      core/users/root.php
  63. 258 0
      core/users/signup.php
  64. 87 0
      core/users/userdelete.php
  65. 192 0
      core/users/userlist.php
  66. 612 0
      core/users/usersupdate.php
  67. BIN
      favicon.ico
  68. BIN
      images/background_cell_active.gif
  69. BIN
      images/background_cell_conference.gif
  70. BIN
      images/background_cell_fifo.gif
  71. BIN
      images/background_cell_light.gif
  72. BIN
      images/blank.gif
  73. BIN
      images/icon_cal.gif
  74. BIN
      images/icon_e.gif
  75. BIN
      images/icon_e.png
  76. BIN
      images/icon_plus.gif
  77. BIN
      images/icon_plus.png
  78. BIN
      images/icon_restart.gif
  79. BIN
      images/icon_start.gif
  80. BIN
      images/icon_stop.gif
  81. BIN
      images/icon_up.gif
  82. BIN
      images/icon_view.gif
  83. BIN
      images/icon_x.gif
  84. BIN
      images/icon_x.png
  85. 189 0
      includes/calendar_lw_layers.js
  86. 376 0
      includes/calendar_lw_menu.js
  87. 637 0
      includes/calendar_popcalendar.js
  88. 108 0
      includes/captcha/config.php
  89. BIN
      includes/captcha/fonts/ROUGD.TTF
  90. BIN
      includes/captcha/fonts/Zebra.ttf
  91. BIN
      includes/captcha/fonts/hanshand.ttf
  92. 123 0
      includes/captcha/img.php
  93. 48 0
      includes/captcha/root.php
  94. 159 0
      includes/checkauth.php
  95. 30 0
      includes/checkstring.php
  96. 1896 0
      includes/class.phpmailer.php
  97. 1062 0
      includes/class.smtp.php
  98. 198 0
      includes/class_vcard.php
  99. 45 0
      includes/classes/array_order.php
  100. 195 0
      includes/classes/call_forward.php

+ 5 - 0
.htaccess

@@ -0,0 +1,5 @@
+RewriteEngine	On
+
+
+RewriteRule     ^([A-Fa-f0-9]{12})(\.(xml|cfg))?$                        mod/provision/index.php?mac=$1 [QSA]
+RewriteRule     ^([A-Fa-f0-9]{2}[:-][A-Fa-f0-9]{2}[:-][A-Fa-f0-9]{2}[:-][A-Fa-f0-9]{2}[:-][A-Fa-f0-9]{2}[:-][A-Fa-f0-9]{2}[:-])(\.(xml|cfg))?$                        mod/provision/index.php?mac=$1 [QSA]

+ 45 - 0
core/backup/backup.php

@@ -0,0 +1,45 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+
+if (if_group("superadmin")) {
+
+	$fh = fopen($db_file_path.'/'.$dbfilename, 'r+b');
+	$contents = fread($fh, filesize($db_file_path.'/'.$dbfilename));
+
+	header("Content-disposition: attachment; filename=$dbfilename");
+	header("Content-Type: application/force-download");
+	header("Content-Transfer-Encoding: binary");
+	header("Content-Length: ".strlen($contents));
+	header("Pragma: no-cache");
+	header("Expires: 0");
+
+	echo $contents;
+}
+
+?>

+ 87 - 0
core/backup/backupandrestore.php

@@ -0,0 +1,87 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+
+if (if_group("superadmin")) {
+
+	echo "<table width=\"100%\" border=\"0\" cellpadding=\"7\" cellspacing=\"0\">\n";
+	echo "<tr>\n";
+	echo "	<th colspan='2' align='left'>Backup</th>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "	<td width='20%' class=\"vncell\" style='text-align: left;'>\n";
+	echo "	<a href='".PROJECT_PATH."/core/backup/backup.php'>download</a>	\n";
+	echo "	</td>\n";
+	echo "	<td class=\"row_style1\">\n";
+	echo "	<br />\n";
+	echo "To backup your application click on the download link and then choose  \n";
+	echo "a safe location on your computer to save the file. You may want to \n";
+	echo "save the backup to more than one computer to prevent the backup from being lost. \n";
+	echo "	<br />\n";
+	echo "	<br />\n";
+	echo "	</td>\n";
+	echo "</tr>\n";
+	echo "</table>\n";
+	echo "\n";
+
+	echo "<span  class=\"\" ><strong></strong></span><br>\n";
+	echo "<br>";
+	echo "<br><br>";
+
+	/*
+	echo "<span  class=\"\" >Restore Application</span><br>\n";
+	echo "<div class='borderlight' style='padding:10px;'>\n";
+	//Browse to  Backup File
+	echo "Click on 'Browse' then locate and select the application backup file named '.bak'.  \n";
+	echo "Then click on 'Restore.' \n";
+	echo "<br><br>";
+
+	echo "<div align='center'>";
+	echo "<form name='frmrestore' method='post' action='restore2.php'>";
+	echo "	<table border='0' cellpadding='0' cellspacing='0'>";
+	echo "	<tr>\n";
+	echo "		<td class='' colspan='2' nowrap align='left'>\n";
+	echo "          <table width='200'><tr>";
+	echo "			<td><input type='file' class='frm' onChange='frmrestore.fileandpath.value = frmrestore.filename.value;' style='font-family: verdana; font-size: 11px;' name='filename'></td>";
+	echo "          <td>";
+	echo "			<input type='hidden' name='fileandpath' value=''>\n";
+	echo "			<input type='submit' class='btn' value='Restore'>\n";
+	echo "          </td>";
+	echo "          </tr></table>";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "	</table>\n";
+	echo "</form>\n";
+	echo "</div>";
+
+	echo "</div>";
+	*/
+
+ }
+
+?>

+ 50 - 0
core/backup/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 97 - 0
core/databases/app_config.php

@@ -0,0 +1,97 @@
+<?php
+	//application details
+		$apps[$x]['name'] = 'Databases';
+		$apps[$x]['uuid'] = '8d229b6d-1383-fcec-74c6-4ce1682479e2';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'Storeds database connection information.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Databases';
+		$apps[$x]['menu'][0]['uuid'] = 'ebbd754d-ca74-d5b1-a77e-9206ba3ecc3f';
+		$apps[$x]['menu'][0]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/core/databases/databases.php';
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+	//permission details
+		$apps[$x]['permissions'][0]['name'] = 'database_view';
+		$apps[$x]['permissions'][0]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][1]['name'] = 'database_add';
+		$apps[$x]['permissions'][1]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][2]['name'] = 'database_edit';
+		$apps[$x]['permissions'][2]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][3]['name'] = 'database_delete';
+		$apps[$x]['permissions'][3]['groups'][] = 'superadmin';
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_databases';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'database_connection_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT PRIMARY KEY';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'database_connection_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_type';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_type';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Select the database type.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_host';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_host';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the host name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_port';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_port';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the port number.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_name';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the database name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_username';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_username';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the database username.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_password';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_password';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the database password.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_path';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_path';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the database file path.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'database_description';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'db_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the description.';
+		$z++;
+?>

+ 58 - 0
core/databases/database_delete.php

@@ -0,0 +1,58 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+}
+
+if (strlen($id)>0) {
+	$sql = "";
+	$sql .= "delete from v_databases ";
+	$sql .= "where database_uuid = '$id' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	unset($sql);
+}
+
+require_once "includes/header.php";
+echo "<meta http-equiv=\"refresh\" content=\"2;url=databases.php\">\n";
+echo "<div align='center'>\n";
+echo "Delete Complete\n";
+echo "</div>\n";
+require_once "includes/footer.php";
+return;
+
+?>

+ 346 - 0
core/databases/database_edit.php

@@ -0,0 +1,346 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$database_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+//clear the values
+	$database_type = '';
+	$database_host = '';
+	$database_port = '';
+	$database_name = '';
+	$database_username = '';
+	$database_password = '';
+	$database_path = '';
+	$database_description = '';
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$database_type = check_str($_POST["database_type"]);
+		$database_host = check_str($_POST["database_host"]);
+		$database_port = check_str($_POST["database_port"]);
+		$database_name = check_str($_POST["database_name"]);
+		$database_username = check_str($_POST["database_username"]);
+		$database_password = check_str($_POST["database_password"]);
+		$database_path = check_str($_POST["database_path"]);
+		$database_description = check_str($_POST["database_description"]);
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$database_uuid = check_str($_POST["database_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($database_type) == 0) { $msg .= "Please provide: Type<br>\n"; }
+		//if (strlen($database_host) == 0) { $msg .= "Please provide: Host<br>\n"; }
+		//if (strlen($database_port) == 0) { $msg .= "Please provide: Port<br>\n"; }
+		//if (strlen($database_name) == 0) { $msg .= "Please provide: Name<br>\n"; }
+		//if (strlen($database_username) == 0) { $msg .= "Please provide: Username<br>\n"; }
+		//if (strlen($database_password) == 0) { $msg .= "Please provide: Password<br>\n"; }
+		//if (strlen($database_path) == 0) { $msg .= "Please provide: Path<br>\n"; }
+		//if (strlen($database_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+	if ($_POST["persistformvar"] != "true") {
+		if ($action == "add") {
+			$database_uuid = uuid();
+			$sql = "insert into v_databases ";
+			$sql .= "(";
+			//$sql .= "domain_uuid, ";
+			$sql .= "database_uuid, ";
+			$sql .= "database_type, ";
+			$sql .= "database_host, ";
+			$sql .= "database_port, ";
+			$sql .= "database_name, ";
+			$sql .= "database_username, ";
+			$sql .= "database_password, ";
+			$sql .= "database_path, ";
+			$sql .= "database_description ";
+			$sql .= ")";
+			$sql .= "values ";
+			$sql .= "(";
+			//$sql .= "'$domain_uuid', ";
+			$sql .= "'$database_uuid', ";
+			$sql .= "'$database_type', ";
+			$sql .= "'$database_host', ";
+			$sql .= "'$database_port', ";
+			$sql .= "'$database_name', ";
+			$sql .= "'$database_username', ";
+			$sql .= "'$database_password', ";
+			$sql .= "'$database_path', ";
+			$sql .= "'$database_description' ";
+			$sql .= ")";
+			$db->exec(check_sql($sql));
+			unset($sql);
+
+			require_once "includes/header.php";
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=databases.php\">\n";
+			echo "<div align='center'>\n";
+			echo "Add Complete\n";
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		} //if ($action == "add")
+
+		if ($action == "update") {
+			$sql = "update v_databases set ";
+			$sql .= "database_type = '$database_type', ";
+			$sql .= "database_host = '$database_host', ";
+			$sql .= "database_port = '$database_port', ";
+			$sql .= "database_name = '$database_name', ";
+			$sql .= "database_username = '$database_username', ";
+			$sql .= "database_password = '$database_password', ";
+			$sql .= "database_path = '$database_path', ";
+			$sql .= "database_description = '$database_description' ";
+			$sql .= "where database_uuid = '$database_uuid' ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+
+			require_once "includes/header.php";
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=databases.php\">\n";
+			echo "<div align='center'>\n";
+			echo "Update Complete\n";
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		} //if ($action == "update")
+	} //if ($_POST["persistformvar"] != "true") 
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$database_uuid = $_GET["id"];
+		$sql = "select * from v_databases ";
+		$sql .= "where database_uuid = '$database_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$database_type = $row["database_type"];
+			$database_host = $row["database_host"];
+			$database_port = $row["database_port"];
+			$database_name = $row["database_name"];
+			$database_username = $row["database_username"];
+			$database_password = $row["database_password"];
+			$database_path = $row["database_path"];
+			$database_description = $row["database_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='3' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align=\"left\" width='30%' nowrap=\"nowrap\"><b>Database Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align=\"left\" width='30%' nowrap=\"nowrap\"><b>Database Edit</b></td>\n";
+	}
+	echo "<td width='70%' align=\"right\"><input type='button' class='btn' name='' alt='back' onclick=\"window.location='databases.php'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align=\"left\" colspan='2'>\n";
+	echo "Database connection information.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Type:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<select class='formfld' name='database_type'>\n";
+	echo "	<option value=''></option>\n";
+	if ($database_type == "sqlite") {
+		echo "	<option value='sqlite' selected='selected'>sqlite</option>\n";
+	}
+	else {
+		echo "	<option value='sqlite'>sqlite</option>\n";
+	}
+	if ($database_type == "odbc") {
+		echo "	<option value='odbc' selected='selected'>odbc</option>\n";
+	}
+	else {
+		echo "	<option value='odbc'>odbc</option>\n";
+	}
+	if ($database_type == "pgsql") {
+		echo "	<option value='pgsql' selected='selected'>pgsql</option>\n";
+	}
+	else {
+		echo "	<option value='pgsql'>pgsql</option>\n";
+	}
+	if ($database_type == "mysql") {
+		echo "	<option value='mysql' selected='selected'>mysql</option>\n";
+	}
+	else {
+		echo "	<option value='mysql'>mysql</option>\n";
+	}
+
+	echo "	</select>\n";
+	echo "<br />\n";
+	echo "Select the database type.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Host:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_host' maxlength='255' value=\"$database_host\">\n";
+	echo "<br />\n";
+	echo "Enter the host name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Port:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_port' maxlength='255' value=\"$database_port\">\n";
+	echo "<br />\n";
+	echo "Enter the port number.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_name' maxlength='255' value=\"$database_name\">\n";
+	echo "<br />\n";
+	echo "Enter the database name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Username:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_username' maxlength='255' value=\"$database_username\">\n";
+	echo "<br />\n";
+	echo "Enter the database username.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Password:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_password' maxlength='255' value=\"$database_password\">\n";
+	echo "<br />\n";
+	echo "Enter the database password.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Path:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_path' maxlength='255' value=\"$database_path\">\n";
+	echo "<br />\n";
+	echo "Enter the database file path.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='database_description' maxlength='255' value=\"$database_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='database_uuid' value='$database_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 162 - 0
core/databases/databases.php

@@ -0,0 +1,162 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br>";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' align=\"left\" nowrap=\"nowrap\"><b>Databases</b></td>\n";
+	echo "		<td width='50%' align=\"right\">&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td align=\"left\" colspan='2'>\n";
+	echo "			Database information.<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = " select count(*) as num_rows from v_databases ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 150;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; }
+		list($paging_controls, $rows_per_page, $var_3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the  list
+		$sql = " select * from v_databases ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	echo "<tr>\n";
+	echo th_order_by('database_type', 'Type', $order_by, $order);
+	echo th_order_by('database_host', 'Host', $order_by, $order);
+	//echo th_order_by('database_port', 'Port', $order_by, $order);
+	echo th_order_by('database_name', 'Name', $order_by, $order);
+	//echo th_order_by('database_username', 'Username', $order_by, $order);
+	//echo th_order_by('database_path', 'Path', $order_by, $order);
+	echo th_order_by('database_description', 'Description', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	echo "	<a href='database_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_type']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_host']."&nbsp;</td>\n";
+			//echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_port']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_name']."&nbsp;</td>\n";
+			//echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_username']."&nbsp;</td>\n";
+			//echo "	<td valign='top' class='".$row_style[$c]."'>".$row['database_path']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='row_stylebg'>".$row['database_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='database_edit.php?id=".$row['database_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='database_delete.php?id=".$row['database_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='10' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='database_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br><br>";
+	echo "<br><br>";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br><br>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 50 - 0
core/databases/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 65 - 0
core/default_settings/app_config.php

@@ -0,0 +1,65 @@
+<?php
+	//application details
+		$apps[$x]['name'] = 'Default Settings';
+		$apps[$x]['guid'] = '2c2453c0-1bea-4475-9f44-4d969650de09';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'Default settings that apply to all domains.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Default Settings';
+		$apps[$x]['menu'][0]['uuid'] = '834b2739-9e99-4345-9b0b-7ec3ca332b67';
+		$apps[$x]['menu'][0]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/core/default_settings/default_settings.php';
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+	//permission details
+		$y = 0;
+		$apps[$x]['permissions'][$y]['name'] = 'default_setting_add';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'default_setting_edit';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'default_setting_delete';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_default_settings';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_category';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the category.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_subcategory';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the subcategory.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_value';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the value.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_enabled';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'default_setting_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+?>

+ 29 - 0
core/default_settings/app_defaults.php

@@ -0,0 +1,29 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2010
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+
+
+?>

+ 190 - 0
core/default_settings/default_settings.php

@@ -0,0 +1,190 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br />";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' align='left' nowrap='nowrap'><b>Default Settings</b></td>\n";
+	echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td align='left' colspan='2'>\n";
+	echo "			Settings used for all domains.<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = "";
+		$sql .= " select count(*) as num_rows from v_default_settings ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 100;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the domain list
+		$sql = "";
+		$sql .= " select * from v_default_settings ";
+		if (strlen($order_by) == 0) {
+			$sql .= "order by default_setting_category, default_setting_subcategory asc ";
+		}
+		else {
+			$sql .= "order by $order_by $order ";
+		}
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	if ($result_count > 0) {
+		$previous_category = '';
+		foreach($result as $row) {
+			if ($previous_category != $row['default_setting_category']) {
+				echo "<tr><td colspan='4' align='left'>\n";
+				echo "	<br />\n";
+				echo "	<b>".ucfirst($row['default_setting_category'])."</b>&nbsp;</td></tr>\n";
+				echo "<tr>\n";
+				echo th_order_by('default_setting_subcategory', 'Category', $order_by, $order);
+				echo th_order_by('default_setting_name', 'Name', $order_by, $order);
+				echo th_order_by('default_setting_value', 'Value', $order_by, $order);
+				echo th_order_by('default_setting_enabled', 'Enabled', $order_by, $order);
+				echo th_order_by('default_setting_description', 'Description', $order_by, $order);
+				echo "<td align='right' width='42'>\n";
+				echo "	<a href='default_settings_edit.php' alt='add'>$v_link_label_add</a>\n";
+				echo "</td>\n";
+				echo "</tr>\n";
+			}
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['default_setting_subcategory']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['default_setting_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>\n";
+
+			$category = $row['default_setting_category'];
+			$subcategory = $row['default_setting_subcategory'];
+			$name = $row['default_setting_name'];
+			if ($category == "domain" && $subcategory == "menu" && $name == "uuid" ) {
+				$sql = "";
+				$sql .= "select * from v_menus ";
+				$sql .= "where menu_uuid = '".$row['default_setting_value']."' ";
+				$sub_prep_statement = $db->prepare(check_sql($sql));
+				$sub_prep_statement->execute();
+				$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+				foreach ($sub_result as &$sub_row) {
+					echo $sub_row["menu_language"]." - ".$sub_row["menu_name"]."\n";
+				}
+			} else {
+				echo 		$row['default_setting_value'];
+			}	
+			echo "		&nbsp;\n";
+			echo "	</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['default_setting_enabled']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['default_setting_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='default_settings_edit.php?id=".$row['default_setting_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='default_settings_delete.php?id=".$row['default_setting_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			$previous_category = $row['default_setting_category'];
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='6' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='default_settings_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+	echo "<br /><br />";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 58 - 0
core/default_settings/default_settings_delete.php

@@ -0,0 +1,58 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+}
+
+if (strlen($id)>0) {
+	$sql = "";
+	$sql .= "delete from v_default_settings ";
+	$sql .= "where default_setting_uuid = '$id' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	unset($sql);
+}
+
+require_once "includes/header.php";
+echo "<meta http-equiv=\"refresh\" content=\"2;url=default_settings_edit.php\">\n";
+echo "<div align='center'>\n";
+echo "Delete Complete\n";
+echo "</div>\n";
+require_once "includes/footer.php";
+return;
+
+?>

+ 372 - 0
core/default_settings/default_settings_edit.php

@@ -0,0 +1,372 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$default_setting_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$default_setting_category = check_str($_POST["default_setting_category"]);
+		$default_setting_subcategory = check_str($_POST["default_setting_subcategory"]);
+		$default_setting_name = check_str($_POST["default_setting_name"]);
+		$default_setting_value = check_str($_POST["default_setting_value"]);
+		$default_setting_enabled = check_str($_POST["default_setting_enabled"]);
+		$default_setting_description = check_str($_POST["default_setting_description"]);		
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$default_setting_uuid = check_str($_POST["default_setting_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($default_setting_category) == 0) { $msg .= "Please provide: Category<br>\n"; }
+		//if (strlen($default_setting_subcategory) == 0) { $msg .= "Please provide: Subcategory<br>\n"; }
+		//if (strlen($default_setting_name) == 0) { $msg .= "Please provide: Name<br>\n"; }
+		//if (strlen($default_setting_value) == 0) { $msg .= "Please provide: Value<br>\n"; }
+		//if (strlen($default_setting_enabled) == 0) { $msg .= "Please provide: Enabled<br>\n"; }
+		//if (strlen($default_setting_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add") {
+				$sql = "insert into v_default_settings ";
+				$sql .= "(";
+				$sql .= "default_setting_uuid, ";
+				$sql .= "default_setting_category, ";
+				$sql .= "default_setting_subcategory, ";
+				$sql .= "default_setting_name, ";
+				$sql .= "default_setting_value, ";
+				$sql .= "default_setting_enabled, ";
+				$sql .= "default_setting_description ";	
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'".uuid()."', ";
+				$sql .= "'$default_setting_category', ";
+				$sql .= "'$default_setting_subcategory', ";
+				$sql .= "'$default_setting_name', ";
+				$sql .= "'$default_setting_value', ";
+				$sql .= "'$default_setting_enabled', ";
+				$sql .= "'$default_setting_description' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=default_settings.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "add")
+
+			if ($action == "update") {
+				$sql = "update v_default_settings set ";
+				$sql .= "default_setting_category = '$default_setting_category', ";
+				$sql .= "default_setting_subcategory = '$default_setting_subcategory', ";
+				$sql .= "default_setting_name = '$default_setting_name', ";
+				$sql .= "default_setting_value = '$default_setting_value', ";
+				$sql .= "default_setting_enabled = '$default_setting_enabled', ";
+				$sql .= "default_setting_description = '$default_setting_description' ";	
+				$sql .= "where default_setting_uuid = '$default_setting_uuid'";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=default_settings.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Update Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "update")
+		} //if ($_POST["persistformvar"] != "true") 
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$default_setting_uuid = $_GET["id"];
+		$sql = "select * from v_default_settings ";
+		$sql .= "where default_setting_uuid = '$default_setting_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$default_setting_category = $row["default_setting_category"];
+			$default_setting_subcategory = $row["default_setting_subcategory"];
+			$default_setting_name = $row["default_setting_name"];
+			$default_setting_value = $row["default_setting_value"];
+			$default_setting_enabled = $row["default_setting_enabled"];
+			$default_setting_description = $row["default_setting_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Default Setting Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Default Setting Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'><input type='button' class='btn' name='' alt='back' onclick=\"window.location='default_settings.php'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align='left' colspan='2'>\n";
+	echo "Settings used for all domains.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Category:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='default_setting_category' maxlength='255' value=\"$default_setting_category\">\n";
+	echo "<br />\n";
+	echo "Enter the category.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Subcategory:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='default_setting_subcategory' maxlength='255' value=\"$default_setting_subcategory\">\n";
+	echo "<br />\n";
+	echo "Enter the category.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='default_setting_name' maxlength='255' value=\"$default_setting_name\">\n";
+	echo "<br />\n";
+	echo "Enter the name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Value:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	$category = $row['default_setting_category'];
+	$subcategory = $row['default_setting_subcategory'];
+	$name = $row['default_setting_name'];
+	if ($category == "domain" && $subcategory == "menu" && $name == "uuid" ) {
+		echo "		<select id='default_setting_value' name='default_setting_value' class='formfld' style=''>\n";
+		echo "		<option value=''></option>\n";
+		$sql = "";
+		$sql .= "select * from v_menus ";
+		$sql .= "order by menu_language, menu_name asc ";
+		$sub_prep_statement = $db->prepare(check_sql($sql));
+		$sub_prep_statement->execute();
+		$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($sub_result as $sub_row) {
+			if (strtolower($row['default_setting_value']) == strtolower($sub_row["menu_uuid"])) {
+				echo "		<option value='".$sub_row["menu_uuid"]."' selected='selected'>".$sub_row["menu_language"]." - ".$sub_row["menu_name"]."\n";
+			}
+			else {
+				echo "		<option value='".$sub_row["menu_uuid"]."'>".$sub_row["menu_language"]." - ".$sub_row["menu_name"]."</option>\n";
+			}
+		}
+		unset ($sub_prep_statement);
+		echo "		</select>\n";
+	} elseif ($category == "domain" && $subcategory == "template" && $name == "name" ) {
+		echo "		<select id='default_setting_value' name='default_setting_value' class='formfld' style=''>\n";
+		echo "		<option value=''></option>\n";
+		//add all the themes to the list
+		$theme_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes';
+		if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes')) {
+			while (false !== ($dir_name = readdir($handle))) {
+				if ($dir_name != "." && $dir_name != ".." && $dir_name != ".svn" && is_dir($theme_dir.'/'.$dir_name)) {
+					$dir_label = str_replace('_', ' ', $dir_name);
+					$dir_label = str_replace('-', ' ', $dir_label);
+					if ($dir_name == $row['default_setting_value']) {
+						echo "		<option value='$dir_name' selected='selected'>$dir_label</option>\n";
+					}
+					else {
+						echo "		<option value='$dir_name'>$dir_label</option>\n";
+					}
+				}
+			}
+			closedir($handle);
+		}
+		echo "		</select>\n";
+	} elseif ($category == "domain" && $subcategory == "time_zone" && $name == "name" ) {
+			echo "		<select id='default_setting_value' name='default_setting_value' class='formfld' style=''>\n";
+			echo "		<option value=''></option>\n";
+			//$list = DateTimeZone::listAbbreviations();
+			$time_zone_identifiers = DateTimeZone::listIdentifiers();
+			$previous_category = '';
+			$x = 0;
+			foreach ($time_zone_identifiers as $key => $val) {
+				$time_zone = explode("/", $val);
+				$category = $time_zone[0];
+				if ($category != $previous_category) {
+					if ($x > 0) {
+						echo "		</optgroup>\n";
+					}
+					echo "		<optgroup label='".$category."'>\n";
+				}
+				if (strlen($val) > 0) {
+					$time_zone_offset = get_time_zone_offset($val)/3600;
+					$time_zone_offset_hours = floor($time_zone_offset);
+					$time_zone_offset_minutes = ($time_zone_offset - $time_zone_offset_hours) * 60;
+					$time_zone_offset_minutes = number_pad($time_zone_offset_minutes, 2);
+					if ($time_zone_offset > 0) {
+						$time_zone_offset_hours = number_pad($time_zone_offset_hours, 2);
+						$time_zone_offset_hours = "+".$time_zone_offset_hours;
+					}
+					else {
+						$time_zone_offset_hours = str_replace("-", "", $time_zone_offset_hours);
+						$time_zone_offset_hours = "-".number_pad($time_zone_offset_hours, 2);
+					}
+				}
+				if ($val == $row['default_setting_value']) {
+					echo "			<option value='".$val."' selected='selected'>(UTC ".$time_zone_offset_hours.":".$time_zone_offset_minutes.") ".$val."</option>\n";
+				}
+				else {
+					echo "			<option value='".$val."'>(UTC ".$time_zone_offset_hours.":".$time_zone_offset_minutes.") ".$val."</option>\n";
+				}
+				$previous_category = $category;
+				$x++;
+			}
+			echo "		</select>\n";
+	} else {
+			echo "	<input class='formfld' type='text' name='default_setting_value' maxlength='255' value=\"$default_setting_value\">\n";
+	}
+	echo "<br />\n";
+	echo "Enter the value.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap>\n";
+	echo "    Enabled:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "    <select class='formfld' name='default_setting_enabled'>\n";
+	echo "    <option value=''></option>\n";
+	if ($default_setting_enabled == "true") { 
+		echo "    <option value='true' selected='selected'>true</option>\n";
+	}
+	else {
+		echo "    <option value='true'>true</option>\n";
+	}
+	if ($default_setting_enabled == "false") { 
+		echo "    <option value='false' selected='selected'>false</option>\n";
+	}
+	else {
+		echo "    <option value='false'>false</option>\n";
+	}
+	echo "    </select>\n";
+	echo "<br />\n";
+	echo "Choose to enable or disable the value.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='default_setting_description' maxlength='255' value=\"$default_setting_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='default_setting_uuid' value='$default_setting_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 50 - 0
core/default_settings/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 115 - 0
core/domains/app_config.php

@@ -0,0 +1,115 @@
+<?php
+	//application details
+		$apps[$x]['name'] = 'Domains';
+		$apps[$x]['guid'] = 'b31e723a-bf70-670c-a49b-470d2a232f71';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'Manage a single domain or multiple domains for multi-tenant.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Domains';
+		$apps[$x]['menu'][0]['uuid'] = '4fa7e90b-6d6c-12d4-712f-62857402b801';
+		$apps[$x]['menu'][0]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/core/domains/domains.php';
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+	//permission details
+		$y = 0;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_view';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_add';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_edit';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_delete';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_view';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_setting_add';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_setting_edit';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'domain_setting_delete';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the domain name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the description.';
+
+		$y = 1; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_domain_settings';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_category';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the category.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_subcategory';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the subcategory.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_value';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the value.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_enabled';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_setting_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+?>

+ 37 - 0
core/domains/app_defaults.php

@@ -0,0 +1,37 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2010
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//remove external from the end of the gateway path
+	if (substr($v_gateways_dir, -8) == "external") {
+		//$v_gateways_dir = substr($v_gateways_dir, 0, (strlen($v_gateways_dir)-9));
+		//$sql = "update v_domain_settings set ";
+		//$sql .= "v_gateways_dir = '$v_gateways_dir' ";
+		//$sql .= "where domain_uuid = '$domain_uuid'";
+		//$db->exec($sql);
+		//unset($sql);
+	}
+
+?>

+ 189 - 0
core/domains/domain_settings.php

@@ -0,0 +1,189 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br />";
+
+	//echo "<table width='100%' border='0'>\n";
+	//echo "	<tr>\n";
+	//echo "		<td width='50%' nowrap><b>Domain Settings</b></td>\n";
+	//echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	//echo "	</tr>\n";
+	//echo "	<tr>\n";
+	//echo "		<td colspan='2'>\n";
+	//echo "			Settings used for each domain.<br /><br />\n";
+	//echo "		</td>\n";
+	//echo "	</tr>\n";
+	//echo "</table>\n";
+
+	//prepare to page the results
+		$sql = " select count(*) as num_rows from v_domain_settings ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		$sql .= " and domain_uuid = '$domain_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 100;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the domain list
+		$sql = "";
+		$sql .= " select * from v_domain_settings ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		$sql .= " and domain_uuid = '$domain_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	if ($result_count > 0) {
+		$previous_category = '';
+		foreach($result as $row) {
+			if ($previous_category != $row['domain_setting_category']) {
+				echo "<tr><td colspan='4' align='left'>\n";
+				echo "	<br />\n";
+				echo "	<br />\n";
+				echo "	<b>".ucfirst($row['domain_setting_category'])."</b>&nbsp;</td></tr>\n";
+				echo "<tr>\n";
+				echo th_order_by('domain_setting_subcategory', 'Category', $order_by, $order);
+				echo th_order_by('domain_setting_name', 'Name', $order_by, $order);
+				echo th_order_by('domain_setting_value', 'Value', $order_by, $order);
+				echo th_order_by('domain_setting_enabled', 'Enabled', $order_by, $order);
+				echo th_order_by('domain_setting_description', 'Description', $order_by, $order);
+				echo "<td align='right' width='42'>\n";
+				echo "	<a href='domain_settings_edit.php?domain_uuid=".$_GET['id']."' alt='add'>$v_link_label_add</a>\n";
+				echo "</td>\n";
+				echo "</tr>\n";
+			}
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_setting_subcategory']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_setting_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>\n";
+
+			$category = $row['domain_setting_category'];
+			$subcategory = $row['domain_setting_subcategory'];
+			$name = $row['domain_setting_name'];
+			if ($category == "domain" && $subcategory == "menu" && $name == "uuid" ) {
+				$sql = "";
+				$sql .= "select * from v_menus ";
+				$sql .= "where menu_uuid = '".$row['domain_setting_value']."' ";
+				$sub_prep_statement = $db->prepare(check_sql($sql));
+				$sub_prep_statement->execute();
+				$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+				foreach ($sub_result as &$sub_row) {
+					echo $sub_row["menu_language"]." - ".$sub_row["menu_name"]."\n";
+				}
+			} else {
+				echo 		$row['domain_setting_value'];
+			}	
+			echo "		&nbsp;\n";
+			echo "	</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_setting_enabled']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_setting_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='domain_settings_edit.php?domain_uuid=".$row['domain_uuid']."&id=".$row['domain_setting_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='domain_settings_delete.php?domain_uuid=".$row['domain_uuid']."&id=".$row['domain_setting_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			$previous_category = $row['domain_setting_category'];
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='6' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='domain_settings_edit.php?domain_uuid=".$_GET['id']."' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+	echo "<br /><br />";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 60 - 0
core/domains/domain_settings_delete.php

@@ -0,0 +1,60 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+	$domain_uuid = check_str($_GET["domain_uuid"]);
+}
+
+if (strlen($id)>0) {
+	$sql = "";
+	$sql .= "delete from v_domain_settings ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and domain_setting_uuid = '$id' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	unset($sql);
+}
+
+require_once "includes/header.php";
+echo "<meta http-equiv=\"refresh\" content=\"2;url=domains_edit.php?id=$domain_uuid\">\n";
+echo "<div align='center'>\n";
+echo "Delete Complete\n";
+echo "</div>\n";
+require_once "includes/footer.php";
+return;
+
+?>

+ 369 - 0
core/domains/domain_settings_edit.php

@@ -0,0 +1,369 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$domain_setting_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+if (strlen($_GET["domain_uuid"]) > 0) {
+	$domain_uuid = check_str($_GET["domain_uuid"]);
+}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$domain_setting_category = check_str($_POST["domain_setting_category"]);
+		$domain_setting_subcategory = check_str($_POST["domain_setting_subcategory"]);
+		$domain_setting_name = check_str($_POST["domain_setting_name"]);
+		$domain_setting_value = check_str($_POST["domain_setting_value"]);
+		$domain_setting_enabled = check_str($_POST["domain_setting_enabled"]);
+		$domain_setting_description = check_str($_POST["domain_setting_description"]);		
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$domain_setting_uuid = check_str($_POST["domain_setting_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($domain_uuid) == 0) { $msg .= "Please provide: domain_uuid<br>\n"; }
+		//if (strlen($domain_setting_category) == 0) { $msg .= "Please provide: Category<br>\n"; }
+		//if (strlen($domain_setting_subcategory) == 0) { $msg .= "Please provide: Subcategory<br>\n"; }
+		//if (strlen($domain_setting_name) == 0) { $msg .= "Please provide: Name<br>\n"; }
+		//if (strlen($domain_setting_value) == 0) { $msg .= "Please provide: Value<br>\n"; }
+		//if (strlen($domain_setting_enabled) == 0) { $msg .= "Please provide: Enabled<br>\n"; }
+		//if (strlen($domain_setting_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add") {
+				$sql = "insert into v_domain_settings ";
+				$sql .= "(";
+				$sql .= "domain_uuid, ";
+				$sql .= "domain_setting_uuid, ";
+				$sql .= "domain_setting_category, ";
+				$sql .= "domain_setting_subcategory, ";
+				$sql .= "domain_setting_name, ";
+				$sql .= "domain_setting_value, ";
+				$sql .= "domain_setting_enabled, ";
+				$sql .= "domain_setting_description ";	
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'$domain_uuid', ";
+				$sql .= "'".uuid()."', ";
+				$sql .= "'$domain_setting_category', ";
+				$sql .= "'$domain_setting_subcategory', ";
+				$sql .= "'$domain_setting_name', ";
+				$sql .= "'$domain_setting_value', ";
+				$sql .= "'$domain_setting_enabled', ";
+				$sql .= "'$domain_setting_description' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=domains_edit.php?id=$domain_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "add")
+
+			if ($action == "update") {
+				$sql = "update v_domain_settings set ";
+				$sql .= "domain_setting_category = '$domain_setting_category', ";
+				$sql .= "domain_setting_subcategory = '$domain_setting_subcategory', ";
+				$sql .= "domain_setting_name = '$domain_setting_name', ";
+				$sql .= "domain_setting_value = '$domain_setting_value', ";
+				$sql .= "domain_setting_enabled = '$domain_setting_enabled', ";
+				$sql .= "domain_setting_description = '$domain_setting_description' ";	
+				$sql .= "where domain_uuid = '$domain_uuid' ";
+				$sql .= "and domain_setting_uuid = '$domain_setting_uuid'";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=domains_edit.php?id=$domain_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Update Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "update")
+		} //if ($_POST["persistformvar"] != "true") 
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$domain_setting_uuid = $_GET["id"];
+		$sql = "select * from v_domain_settings ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$sql .= "and domain_setting_uuid = '$domain_setting_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$domain_setting_category = $row["domain_setting_category"];
+			$domain_setting_subcategory = $row["domain_setting_subcategory"];
+			$domain_setting_name = $row["domain_setting_name"];
+			$domain_setting_value = $row["domain_setting_value"];
+			$domain_setting_enabled = $row["domain_setting_enabled"];
+			$domain_setting_description = $row["domain_setting_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Domain Setting Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Domain Setting Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'><input type='button' class='btn' name='' alt='back' onclick=\"window.location='domains_edit.php?id=$domain_uuid'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align='left' colspan='2'>\n";
+	echo "Settings used for each domain.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Category:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_setting_category' maxlength='255' value=\"$domain_setting_category\">\n";
+	echo "<br />\n";
+	echo "Enter the category.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Subcategory:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_setting_subcategory' maxlength='255' value=\"$domain_setting_subcategory\">\n";
+	echo "<br />\n";
+	echo "Enter the category.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_setting_name' maxlength='255' value=\"$domain_setting_name\">\n";
+	echo "<br />\n";
+	echo "Enter the name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Value:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	$category = $row['domain_setting_category'];
+	$subcategory = $row['domain_setting_subcategory'];
+	$name = $row['domain_setting_name'];
+	if ($category == "domain" && $subcategory == "menu" && $name == "uuid" ) {
+		echo "		<select id='domain_setting_value' name='domain_setting_value' class='formfld' style=''>\n";
+		echo "		<option value=''></option>\n";
+		$sql = "";
+		$sql .= "select * from v_menus ";
+		$sql .= "order by menu_language, menu_name asc ";
+		$sub_prep_statement = $db->prepare(check_sql($sql));
+		$sub_prep_statement->execute();
+		$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($sub_result as $sub_row) {
+			if (strtolower($row['domain_setting_value']) == strtolower($sub_row["menu_uuid"])) {
+				echo "		<option value='".$sub_row["menu_uuid"]."' selected='selected'>".$sub_row["menu_language"]." - ".$sub_row["menu_name"]."\n";
+			}
+			else {
+				echo "		<option value='".$sub_row["menu_uuid"]."'>".$sub_row["menu_language"]." - ".$sub_row["menu_name"]."</option>\n";
+			}
+		}
+		unset ($sub_prep_statement);
+		echo "		</select>\n";
+	} elseif ($category == "domain" && $subcategory == "template" && $name == "name" ) {
+		echo "		<select id='domain_setting_value' name='domain_setting_value' class='formfld' style=''>\n";
+		echo "		<option value=''></option>\n";
+		//add all the themes to the list
+		$theme_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes';
+		if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes')) {
+			while (false !== ($dir_name = readdir($handle))) {
+				if ($dir_name != "." && $dir_name != ".." && $dir_name != ".svn" && is_dir($theme_dir.'/'.$dir_name)) {
+					$dir_label = str_replace('_', ' ', $dir_name);
+					$dir_label = str_replace('-', ' ', $dir_label);
+					if ($dir_name == $row['domain_setting_value']) {
+						echo "		<option value='$dir_name' selected='selected'>$dir_label</option>\n";
+					}
+					else {
+						echo "		<option value='$dir_name'>$dir_label</option>\n";
+					}
+				}
+			}
+			closedir($handle);
+		}
+		echo "		</select>\n";
+	} elseif ($category == "domain" && $subcategory == "time" && $name == "zone" ) {
+			echo "		<select id='domain_setting_value' name='domain_setting_value' class='formfld' style=''>\n";
+			echo "		<option value=''></option>\n";
+			//$list = DateTimeZone::listAbbreviations();
+			$time_zone_identifiers = DateTimeZone::listIdentifiers();
+			$previous_category = '';
+			$x = 0;
+			foreach ($time_zone_identifiers as $key => $val) {
+				$time_zone = explode("/", $val);
+				$category = $time_zone[0];
+				if ($category != $previous_category) {
+					if ($x > 0) {
+						echo "		</optgroup>\n";
+					}
+					echo "		<optgroup label='".$category."'>\n";
+				}
+				if ($val == $row['domain_setting_value']) {
+					echo "			<option value='".$val."' selected='selected'>".$val."</option>\n";
+				}
+				else {
+					echo "			<option value='".$val."'>".$val."</option>\n";
+				}
+				$previous_category = $category;
+				$x++;
+			}
+			echo "		</select>\n";
+			break;
+	} else {
+			echo "	<input class='formfld' type='text' name='domain_setting_value' maxlength='255' value=\"$domain_setting_value\">\n";
+	}
+	echo "<br />\n";
+	echo "Enter the value.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap>\n";
+	echo "    Enabled:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "    <select class='formfld' name='domain_setting_enabled'>\n";
+	echo "    <option value=''></option>\n";
+	if ($domain_setting_enabled == "true") { 
+		echo "    <option value='true' selected='selected'>true</option>\n";
+	}
+	else {
+		echo "    <option value='true'>true</option>\n";
+	}
+	if ($domain_setting_enabled == "false") { 
+		echo "    <option value='false' selected='selected'>false</option>\n";
+	}
+	else {
+		echo "    <option value='false'>false</option>\n";
+	}
+	echo "    </select>\n";
+	echo "<br />\n";
+	echo "Choose to enable or disable the value.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_setting_description' maxlength='255' value=\"$domain_setting_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	echo "				<input type='hidden' name='domain_uuid' value='$domain_uuid'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='domain_setting_uuid' value='$domain_setting_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 197 - 0
core/domains/domains.php

@@ -0,0 +1,197 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//change the tenant
+	if (strlen($_GET["domain_uuid"]) > 0 && $_GET["domain_change"] == "true") {
+		//get the domain_uuid
+			$sql = "select * from v_domains ";
+			$sql .= "order by domain_name asc ";
+			$prep_statement = $db->prepare($sql);
+			$prep_statement->execute();
+			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+			foreach($result as $row) {
+				if (count($result) == 0) {
+					$_SESSION["domain_uuid"] = $row["domain_uuid"];
+					$_SESSION["domain_name"] = $row['domain_name'];
+				}
+				else {
+					if ($row['domain_name'] == $domain_array[0] || $row['domain_name'] == 'www.'.$domain_array[0]) {
+						$_SESSION["domain_uuid"] = $row["domain_uuid"];
+						$_SESSION["domain_name"] = $row['domain_name'];
+					}
+					$_SESSION['domains'][$row['domain_uuid']]['domain_uuid'] = $row['domain_uuid'];
+					$_SESSION['domains'][$row['domain_uuid']]['domain_name'] = $row['domain_name'];
+				}
+			}
+			unset($result, $prep_statement);
+
+		//update the domain session variables
+			$domain_uuid = check_str($_GET["domain_uuid"]);
+			$_SESSION['domain_uuid'] = $domain_uuid;
+			$_SESSION["domain_name"] = $_SESSION['domains'][$domain_uuid]['domain_name'];
+			$_SESSION['domain']['template']['name'] = $_SESSION['domains'][$domain_uuid]['template_name'];
+		//clear the menu session so that it is regenerated for the selected domain
+			$_SESSION["menu"] = '';
+		//clear the extension array so that it is regenerated for the selected domain
+			unset($_SESSION['extension_array']);
+		//set the context
+			if (count($_SESSION["domains"]) > 1) {
+				$_SESSION["context"] = $_SESSION["domain_name"];
+			}
+			else {
+				$_SESSION["context"] = 'default';
+			}
+	}
+
+//includes
+	require_once "includes/header.php";
+	require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br />";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' align='left' nowrap='nowrap'><b>Domains</b></td>\n";
+	echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td align='left' colspan='2'>\n";
+	echo "			Control the list of domains to manage.<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = "select count(*) as num_rows from v_domains ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 100;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the  list
+		$sql = "select * from v_domains ";
+		$sql .= "order by domain_name asc ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+	echo "<tr>\n";
+	echo th_order_by('domain_name', 'Domain', $order_by, $order);
+	echo th_order_by('domain_description', 'Description', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	echo "	<a href='domains_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['domain_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='domains_edit.php?id=".$row['domain_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='domains_delete.php?id=".$row['domain_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+
+	echo "<tr>\n";
+	echo "<td colspan='3' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='domains_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+	echo "<br /><br />";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 195 - 0
core/domains/domains_delete.php

@@ -0,0 +1,195 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+}
+
+if (strlen($id) > 0) {
+	//get the domain using the id
+		$sql = "select * from v_domains ";
+		$sql .= "where domain_uuid = '$id' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$domain_name = $row["domain_name"];
+		}
+		unset ($prep_statement);
+
+	//get the domain settings
+		$sql = "select * from v_domain_settings ";
+		$sql .= "where domain_uuid = '".$id."' ";
+		$sql .= "and domain_setting_enabled = 'true' ";
+		$prep_statement = $db->prepare($sql);
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach($result as $row) {
+			$name = $row['domain_setting_name'];
+			$category = $row['domain_setting_category'];
+			$subcategory = $row['domain_setting_subcategory'];	
+			if (strlen($subcategory) == 0) {
+				//$$category[$name] = $row['domain_setting_value'];
+				$_SESSION[$category][$name] = $row['domain_setting_value'];
+			}
+			else {
+				//$$category[$subcategory][$name] = $row['domain_setting_value'];
+				$_SESSION[$category][$subcategory][$name] = $row['domain_setting_value'];
+			}
+		}
+
+	//get the $apps array from the installed apps from the core and mod directories
+		$config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php");
+		$x=0;
+		foreach ($config_list as &$config_path) {
+			include($config_path);
+			$x++;
+		}
+
+	//delete the domain data from all tables in the database
+		$db->beginTransaction();
+		foreach ($apps as &$app) {
+			foreach ($app['db'] as $row) {
+				$table_name = $row['table'];
+				foreach ($row['fields'] as $field) {
+					if ($field['name'] == "domain_uuid") {
+						$sql = "delete from $table_name where domain_uuid = '$id' ";
+						$db->query($sql);
+					}
+				}
+			}
+		}
+		$db->commit();
+
+	if (strlen($domain_name) > 0) {
+		//set the needle
+			if (count($_SESSION["domains"]) > 1) {
+				$v_needle = 'v_'.$domain_name.'_';
+			}
+			else {
+				$v_needle = 'v_';
+			}
+
+		//delete the dialplan
+			unlink($_SESSION['switch']['dialplan']['dir'].'/'.$domain_name.'.xml');
+			if (strlen($_SESSION['switch']['dialplan']['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['dialplan']['dir'].'/'.$domain_name);
+			}
+
+		//delete the dialplan public
+			unlink($_SESSION['switch']['dialplan']['dir'].'/public/'.$domain_name.'.xml');
+			if (strlen($_SESSION['switch']['dialplan']['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['dialplan']['dir'].'/public/'.$domain_name);	
+			}
+
+		//delete the extension
+			unlink($_SESSION['switch']['extensions']['dir'].'/'.$domain_name.'.xml');
+			if (strlen($_SESSION['switch']['extensions']['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['extensions']['dir'].'/'.$domain_name);
+			}
+
+		//delete fax
+			if (strlen($_SESSION['switch']['storage']['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['storage']['dir'].'/fax/'.$domain_name);
+			}
+
+		//delete the gateways
+			if($dh = opendir($_SESSION['switch']['gateways']['dir'])) {
+				$files = Array();
+				while($file = readdir($dh)) {
+					if($file != "." && $file != ".." && $file[0] != '.') {
+						if(is_dir($dir . "/" . $file)) {
+							//this is a directory do nothing
+						} else {
+							//check if file extension is xml
+							if (strpos($file, $v_needle) !== false && substr($file,-4) == '.xml') {
+								unlink($_SESSION['switch']['gateways']['dir']."/".$file);
+							}
+						}
+					}
+				}
+				closedir($dh);
+			}
+
+		//delete the ivr menu
+			if($dh = opendir($_SESSION['switch']['conf']['dir']."/ivr_menus/")) {
+				$files = Array();
+				while($file = readdir($dh)) {
+					if($file != "." && $file != ".." && $file[0] != '.') {
+						if(is_dir($dir . "/" . $file)) {
+							//this is a directory
+						} else {
+							if (strpos($file, $v_needle) !== false && substr($file,-4) == '.xml') {
+								unlink($_SESSION['switch']['conf']['dir']."/ivr_menus/".$file);
+							}
+						}
+					}
+				}
+				closedir($dh);
+			}
+
+		//delete the recordings
+			if (strlen($_SESSION['switch'][recordings]['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['recordings']['dir'].'/'.$domain_name);
+			}
+
+		//delete voicemail
+			if (strlen($_SESSION['switch']['voicemail']['dir']) > 0) {
+				system('rm -rf '.$_SESSION['switch']['voicemail']['dir'].'/'.$domain_name);
+			}
+	}
+
+	//apply settings reminder
+		$_SESSION["reload_xml"] = true;
+
+	//clear the domains session array to update it
+		unset($_SESSION["domains"]);
+		unset($_SESSION["domain_uuid"]);
+		unset($_SESSION["domain_name"]);
+		unset($_SESSION['domain']);
+		unset($_SESSION['switch']);
+}
+
+//redirect the browser
+	require_once "includes/header.php";
+	echo "<meta http-equiv=\"refresh\" content=\"2;url=domains.php\">\n";
+	echo "<div align='center'>\n";
+	echo "Delete Complete\n";
+	echo "</div>\n";
+	require_once "includes/footer.php";
+	return;
+
+?>

+ 216 - 0
core/domains/domains_edit.php

@@ -0,0 +1,216 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$domain_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$domain_name = check_str($_POST["domain_name"]);
+		$domain_description = check_str($_POST["domain_description"]);
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$domain_uuid = check_str($_POST["domain_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($domain_name) == 0) { $msg .= "Please provide: Domain<br>\n"; }
+		//if (strlen($domain_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add") {
+				$sql = "insert into v_domains ";
+				$sql .= "(";
+				$sql .= "domain_uuid, ";
+				$sql .= "domain_name, ";
+				$sql .= "domain_description ";
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'".uuid()."', ";
+				$sql .= "'$domain_name', ";
+				$sql .= "'$domain_description' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+			}
+
+			if ($action == "update") {
+				$sql = "update v_domains set ";
+				$sql .= "domain_name = '$domain_name', ";
+				$sql .= "domain_description = '$domain_description' ";
+				$sql .= "where domain_uuid = '$domain_uuid' ";
+				$db->exec(check_sql($sql));
+				unset($sql);
+			}
+
+		//upgrade the domains
+			require_once "core/upgrade/upgrade_domains.php";
+
+		//clear the domains session array to update it
+			unset($_SESSION["domains"]);
+			unset($_SESSION["domain_uuid"]);
+			unset($_SESSION["domain_name"]);
+			unset($_SESSION['domain']);
+			unset($_SESSION['switch']);
+
+		//redirect the browser
+			require_once "includes/header.php";
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=domains.php\">\n";
+			echo "<div align='center'>\n";
+			if ($action == "update") {
+				echo "Update Complete\n";
+			}
+			if ($action == "add") {
+				echo "Add Complete\n";
+			}
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		} //if ($_POST["persistformvar"] != "true")
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$domain_uuid = $_GET["id"];
+		$sql = "select * from v_domains ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$domain_name = $row["domain_name"];
+			$domain_description = $row["domain_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Domain Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Domain Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'><input type='button' class='btn' name='' alt='back' onclick=\"window.location='domains.php'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align='left' colspan='2'>\n";
+	echo "Control the list of domains to manage.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Domain:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_name' maxlength='255' value=\"$domain_name\">\n";
+	echo "<br />\n";
+	echo "Enter the domain name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='domain_description' maxlength='255' value=\"$domain_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='domain_uuid' value='$domain_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	if ($action == "update") {
+		require "domain_settings.php";
+	}
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 50 - 0
core/domains/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 232 - 0
core/menu/app_config.php

@@ -0,0 +1,232 @@
+<?php
+	//application details
+		$apps[$x]['name'] = "Menu Manager";
+		$apps[$x]['uuid'] = 'f4b3b3d2-6287-489c-2a00-64529e46f2d7';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'The menu can be customized using this tool.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Menu Manager';
+		$apps[$x]['menu'][0]['uuid'] = 'da3a9ab4-c28e-ea8d-50cc-e8405ac8e76e';
+		$apps[$x]['menu'][0]['parent_uuid'] = '02194288-6d56-6d3e-0b1a-d53a2bc10788';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		//$apps[$x]['menu'][0]['path'] = '/core/menu/menu_list.php';
+		$apps[$x]['menu'][0]['path'] = '/core/menu/menu.php';
+
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][1]['title']['en'] = 'System';
+		$apps[$x]['menu'][1]['uuid'] = '02194288-6d56-6d3e-0b1a-d53a2bc10788';
+		$apps[$x]['menu'][1]['parent_uuid'] = '';
+		$apps[$x]['menu'][1]['category'] = 'internal';
+		$apps[$x]['menu'][1]['path'] = '/index2.php';
+		$apps[$x]['menu'][1]['order'] = '5';
+		$apps[$x]['menu'][1]['groups'][] = 'user';
+		$apps[$x]['menu'][1]['groups'][] = 'admin';
+		$apps[$x]['menu'][1]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][2]['title']['en'] = 'Accounts';
+		$apps[$x]['menu'][2]['uuid'] = 'bc96d773-ee57-0cdd-c3ac-2d91aba61b55';
+		$apps[$x]['menu'][2]['parent_uuid'] = '';
+		$apps[$x]['menu'][2]['category'] = 'internal';
+		$apps[$x]['menu'][2]['path'] = '/app/extensions/v_extensions.php';
+		$apps[$x]['menu'][2]['order'] = '10';
+		$apps[$x]['menu'][2]['groups'][] = 'admin';
+		$apps[$x]['menu'][2]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][3]['title']['en'] = 'Dialplan2';
+		$apps[$x]['menu'][3]['uuid'] = 'b94e8bd9-9eb5-e427-9c26-ff7a6c21552a';
+		$apps[$x]['menu'][3]['parent_uuid'] = '';
+		$apps[$x]['menu'][3]['category'] = 'internal';
+		$apps[$x]['menu'][3]['path'] = '/app/dialplan/dialplans.php';
+		$apps[$x]['menu'][3]['order'] = '15';
+		$apps[$x]['menu'][3]['groups'][] = 'admin';
+		$apps[$x]['menu'][3]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][4]['title']['en'] = 'Status';
+		$apps[$x]['menu'][4]['uuid'] = '0438b504-8613-7887-c420-c837ffb20cb1';
+		$apps[$x]['menu'][4]['parent_uuid'] = '';
+		$apps[$x]['menu'][4]['category'] = 'internal';
+		$apps[$x]['menu'][4]['path'] = '/app/calls_active/v_calls_active_extensions.php';
+		$apps[$x]['menu'][4]['order'] = '25';
+		$apps[$x]['menu'][4]['groups'][] = 'user';
+		$apps[$x]['menu'][4]['groups'][] = 'admin';
+		$apps[$x]['menu'][4]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][5]['title']['en'] = 'Advanced';
+		$apps[$x]['menu'][5]['uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][5]['parent_uuid'] = '';
+		$apps[$x]['menu'][5]['category'] = 'internal';
+		$apps[$x]['menu'][5]['path'] = '/app/exec/v_exec.php';
+		$apps[$x]['menu'][5]['order'] = '30';
+		$apps[$x]['menu'][5]['groups'][] = 'superadmin';
+
+	//permission details
+		$apps[$x]['permissions'][0]['name'] = 'menu_view';
+		$apps[$x]['permissions'][0]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][1]['name'] = 'menu_add';
+		$apps[$x]['permissions'][1]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][2]['name'] = 'menu_edit';
+		$apps[$x]['permissions'][2]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][3]['name'] = 'menu_delete';
+		$apps[$x]['permissions'][3]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][4]['name'] = 'menu_restore';
+		$apps[$x]['permissions'][4]['groups'][] = 'superadmin';
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_menus';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name of the menu.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_language';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the language.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_description';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_desc';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the description.';
+		$z++;
+
+		$y = 1; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_menu_items';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_item_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_menus';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'menu_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_item_parent_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_parent_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_title';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_item_link';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_str';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_category';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_protected';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_order';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'numeric';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_item_description';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_desc';
+		
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_add_user';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_add_date';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_mod_user';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'menu_item_mod_date';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+		$y = 2; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_menu_item_groups';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_group_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_menus';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'menu_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'menu_item_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'menu_item_guid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_menu_items';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'menu_item_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+?>

+ 118 - 0
core/menu/app_defaults.php

@@ -0,0 +1,118 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//if there are no items in the menu then add the default menu
+	$sql = "SELECT count(*) as count FROM v_menus ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$sub_result = $prep_statement->fetch(PDO::FETCH_ASSOC);
+	unset ($prep_statement);
+	if ($sub_result['count'] > 0) {
+		if ($display_type == "text") {
+			echo "	Menu:			no change\n";
+		}
+	}
+	else {
+		//create the uuid
+			$menu_uuid = 'b4750c3f-2a86-b00d-b7d0-345c14eca286';
+		//set the defaults
+			$menu_name = 'default';
+			$menu_language = 'en';
+			$menu_description = '';
+		//add the menu
+			$sql = "insert into v_menus ";
+			$sql .= "(";
+			$sql .= "menu_uuid, ";
+			$sql .= "menu_name, ";
+			$sql .= "menu_language, ";
+			$sql .= "menu_description ";
+			$sql .= ")";
+			$sql .= "values ";
+			$sql .= "(";
+			$sql .= "'".$menu_uuid."', ";
+			$sql .= "'$menu_name', ";
+			$sql .= "'$menu_language', ";
+			$sql .= "'$menu_description' ";
+			$sql .= ")";
+			$db->exec(check_sql($sql));
+			unset($sql);
+		//add the menu items
+			require_once "includes/classes/menu.php";
+			$menu = new menu;
+			$menu->db = $db;
+			$menu->menu_uuid = $menu_uuid;
+			$menu->restore();
+			unset($menu);
+			if ($display_type == "text") {
+				echo "	Menu:			added\n";
+			}
+	}
+	unset($prep_statement, $sub_result);
+
+//if there are no groups listed in v_menu_item_groups then add the default groups
+	$sql = "SELECT * FROM v_menus ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$result_count = count($result);
+	foreach($result as $field) {
+		//get the menu_uuid
+			$menu_uuid = $field['menu_uuid'];
+		//check each menu to see if there are items in the menu assigned to it
+			$sql = "";
+			$sql .= "select count(*) as count from v_menu_item_groups ";
+			$sql .= "where menu_uuid = '$menu_uuid' ";
+			$prep_statement = $db->prepare($sql);
+			$prep_statement->execute();
+			$sub_result = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			unset ($prep_statement);
+			if ($sub_result['count'] == 0) {
+				//no menu item groups found add the defaults
+					foreach($apps as $app) {
+						foreach ($app['menu'] as $sub_row) {
+							foreach ($sub_row['groups'] as $group) {
+								//add the record
+								$sql = "insert into v_menu_item_groups ";
+								$sql .= "(";
+								$sql .= "menu_uuid, ";
+								$sql .= "menu_item_uuid, ";
+								$sql .= "group_name ";
+								$sql .= ")";
+								$sql .= "values ";
+								$sql .= "(";
+								$sql .= "'$menu_uuid', ";
+								$sql .= "'".$sub_row['uuid']."', ";
+								$sql .= "'".$group."' ";
+								$sql .= ")";
+								$db->exec($sql);
+								unset($sql);
+							}
+						}
+					}
+			}
+	}
+
+?>

+ 152 - 0
core/menu/menu.php

@@ -0,0 +1,152 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br>";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' align='left' nowrap='nowrap'><b>Menu Manager</b></td>\n";
+	echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td align='left' colspan='2'>\n";
+	echo "			Used to customize one or more menus.<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = " select count(*) as num_rows from v_menus ";
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 150;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var_3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the  list
+		$sql = " select * from v_menus ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+	echo "<tr>\n";
+	echo th_order_by('menu_name', 'Name', $order_by, $order);
+	echo th_order_by('menu_language', 'Language', $order_by, $order);
+	echo th_order_by('menu_description', 'Description', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	echo "	<a href='menu_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['menu_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['menu_language']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['menu_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='menu_edit.php?id=".$row['menu_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='menu_delete.php?id=".$row['menu_uuid']."&menu_uuid=".$row['menu_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='5' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='menu_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br><br>";
+	echo "<br><br>";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br><br>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 83 - 0
core/menu/menu_delete.php

@@ -0,0 +1,83 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+	$menu_uuid = check_str($_GET["menu_uuid"]);
+}
+
+if (strlen($id)>0) {
+	//start the database transaction
+		$db->beginTransaction();
+
+	//delete the menu
+		$sql = "";
+		$sql .= "delete from v_menus ";
+		$sql .= "where menu_uuid = '$menu_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		unset($sql);
+
+	//delete the items in the menu
+		$sql = "";
+		$sql .= "delete from v_menu_items ";
+		$sql .= "where menu_uuid = '$menu_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		unset($sql);
+
+	//delete the menu permissions
+		$sql = "";
+		$sql .= "delete from v_menu_item_groups ";
+		$sql .= "where menu_uuid = '$menu_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		unset($sql);
+
+	//save the changes to the database
+		$db->commit();
+}
+
+//redirect the user
+	require_once "includes/header.php";
+	echo "<meta http-equiv=\"refresh\" content=\"2;url=menu.php\">\n";
+	echo "<div align='center'>\n";
+	echo "Delete Complete\n";
+	echo "</div>\n";
+	require_once "includes/footer.php";
+	return;
+
+?>

+ 245 - 0
core/menu/menu_edit.php

@@ -0,0 +1,245 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$menu_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$menu_uuid = check_str($_POST["menu_uuid"]);
+		$menu_name = check_str($_POST["menu_name"]);
+		$menu_language = check_str($_POST["menu_language"]);
+		$menu_description = check_str($_POST["menu_description"]);
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$menu_uuid = check_str($_POST["menu_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($menu_uuid) == 0) { $msg .= "Please provide: Menu UUID<br>\n"; }
+		//if (strlen($menu_name) == 0) { $msg .= "Please provide: Name<br>\n"; }
+		//if (strlen($menu_language) == 0) { $msg .= "Please provide: Language<br>\n"; }
+		//if (strlen($menu_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+	if ($_POST["persistformvar"] != "true") {
+		if ($action == "add") {
+			//create a new unique id
+				$menu_uuid = uuid();
+
+			//start a new menu
+				$sql = "insert into v_menus ";
+				$sql .= "(";
+				$sql .= "menu_uuid, ";
+				$sql .= "menu_name, ";
+				$sql .= "menu_language, ";
+				$sql .= "menu_description ";
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'".$menu_uuid."', ";
+				$sql .= "'$menu_name', ";
+				$sql .= "'$menu_language', ";
+				$sql .= "'$menu_description' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+			//add the default items in the menu
+				require_once "includes/classes/menu.php";
+				$menu = new menu;
+				$menu->db = $db;
+				$menu->menu_uuid = $menu_uuid;
+				$menu->restore();
+
+			//redirect the user back to the main menu
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=menu.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+		} //if ($action == "add")
+
+		if ($action == "update") {
+			//update the menu
+				$sql = "update v_menus set ";
+				$sql .= "menu_name = '$menu_name', ";
+				$sql .= "menu_language = '$menu_language', ";
+				$sql .= "menu_description = '$menu_description' ";
+				$sql .= "where menu_uuid = '$menu_uuid'";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+			//redirect the user back to the main menu
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=menu.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Update Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+		} //if ($action == "update")
+	} //if ($_POST["persistformvar"] != "true") 
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$menu_uuid = $_GET["id"];
+		$sql = "select * from v_menus ";
+		$sql .= "where menu_uuid = '$menu_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$menu_uuid = $row["menu_uuid"];
+			$menu_name = $row["menu_name"];
+			$menu_language = $row["menu_language"];
+			$menu_description = $row["menu_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Menu Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Menu Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'>\n";
+	if (permission_exists('menu_restore')) {
+		echo "	<input type='button' class='btn' value='Restore Default' onclick=\"document.location.href='menu_restore_default.php?menu_uuid=$menu_uuid&menu_uuid=$menu_uuid';\" />";
+	}
+	echo "	<input type='button' class='btn' name='' alt='back' onclick=\"window.location='menu.php'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align='left' colspan='2'>\n";
+	echo "Used to customize one or more menus.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='menu_name' maxlength='255' value=\"$menu_name\">\n";
+	echo "<br />\n";
+	echo "Enter the name of the menu.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Language:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='menu_language' maxlength='255' value=\"$menu_language\">\n";
+	echo "<br />\n";
+	echo "Enter the language.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='menu_description' maxlength='255' value=\"$menu_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='menu_uuid' value='$menu_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//show the menu items
+	require_once "core/menu/menu_item_list.php";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 62 - 0
core/menu/menu_item_delete.php

@@ -0,0 +1,62 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_delete')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+if (count($_GET)>0) {
+	//clear the menu session so it will rebuild with the update
+		$_SESSION["menu"] = "";
+
+	//get the menu uuid
+		$menu_uuid = check_str($_GET["id"]);
+		$menu_item_id = check_str($_GET["menu_item_id"]);
+
+	//delete the item in the menu
+		$sql  = "delete from v_menu_items ";
+		$sql .= "where menu_item_id = '$menu_item_id' ";
+		$sql .= "and menu_uuid = '$menu_uuid' ";
+		$db->exec(check_sql($sql));
+		unset($sql);
+
+	//redirect the user
+		require_once "includes/header.php";
+		echo "<meta http-equiv=\"refresh\" content=\"2;url=menu_edit.php?id=$menu_uuid\">\n";
+		echo "<div align='center'>";
+		echo "Delete Completed";
+		echo "</div>";
+		require_once "includes/footer.php";
+		return;
+}
+
+?>

+ 464 - 0
core/menu/menu_item_edit.php

@@ -0,0 +1,464 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_add') || permission_exists('menu_edit') || permission_exists('menu_delete')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//include the header
+	require_once "includes/header.php";
+
+//get the menu_uuid
+	$menu_uuid = check_str($_REQUEST["id"]);
+	$menu_item_uuid = check_str($_REQUEST['menu_item_uuid']);
+	$group_name = check_str($_REQUEST['group_name']);
+
+//delete the group from the user
+	if ($_REQUEST["a"] == "delete" && permission_exists("menu_delete")) {
+		//delete the group from the users
+			$sql = "delete from v_menu_item_groups  ";
+			$sql .= "where menu_uuid = '".$menu_uuid."' ";
+			$sql .= "and menu_item_uuid = '".$menu_item_uuid."' ";
+			$sql .= "and group_name = '".$group_name."' ";
+			$db->exec(check_sql($sql));
+		//redirect the browser
+			require_once "includes/header.php";
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=menu_item_edit.php?id=$menu_uuid&menu_item_uuid=$menu_item_uuid&menu_uuid=$menu_uuid\">\n";
+			echo "<div align='center'>\n";
+			echo "Delete Complete\n";
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+	}
+
+//add a group to the menu
+	if ($_REQUEST["a"] != "delete" && strlen($group_name) > 0 && permission_exists('menu_add')) {
+		//add the group to the menu
+			if (strlen($menu_item_uuid) > 0) {
+				$sql_insert = "insert into v_menu_item_groups ";
+				$sql_insert .= "(";
+				$sql_insert .= "menu_uuid, ";
+				$sql_insert .= "menu_item_uuid, ";
+				$sql_insert .= "group_name ";
+				$sql_insert .= ")";
+				$sql_insert .= "values ";
+				$sql_insert .= "(";
+				$sql_insert .= "'".$menu_uuid."', ";
+				$sql_insert .= "'".$menu_item_uuid."', ";
+				$sql_insert .= "'".$group_name."' ";
+				$sql_insert .= ")";
+				$db->exec($sql_insert);
+			}
+	}
+
+//action add or update
+	if (isset($_REQUEST["menu_item_uuid"])) {
+		if (strlen($_REQUEST["menu_item_uuid"]) > 0) {
+			$action = "update";
+			$menu_item_uuid = check_str($_REQUEST["menu_item_uuid"]);
+		}
+		else {
+			$action = "add";
+		}
+	}
+	else {
+		$action = "add";
+	}
+
+//clear the menu session so it will rebuild with the update
+	$_SESSION["menu"] = "";
+
+//get the HTTP POST variables and set them as PHP variables
+	if (count($_POST)>0) {
+		$menu_uuid = check_str($_POST["menu_uuid"]);
+		$menu_item_uuid = check_str($_POST["menu_item_uuid"]);
+		$menu_item_title = check_str($_POST["menu_item_title"]);
+		$menu_item_link = check_str($_POST["menu_item_link"]);
+		$menu_item_category = check_str($_POST["menu_item_category"]);
+		$menu_item_description = check_str($_POST["menu_item_description"]);
+		$menu_item_protected = check_str($_POST["menu_item_protected"]);
+		//$menu_item_uuid = check_str($_POST["menu_item_uuid"]);
+		$menu_item_parent_uuid = check_str($_POST["menu_item_parent_uuid"]);
+		$menu_item_order = check_str($_POST["menu_item_order"]);
+	}
+
+//when a HTTP POST is available then process it
+	if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+		if ($action == "update") {
+			$menu_item_uuid = check_str($_POST["menu_item_uuid"]);
+		}
+
+		//check for all required data
+			$msg = '';
+			if (strlen($menu_item_title) == 0) { $msg .= "Please provide: title<br>\n"; }
+			if (strlen($menu_item_category) == 0) { $msg .= "Please provide: category<br>\n"; }
+			//if (strlen($menu_item_link) == 0) { $msg .= "Please provide: menu_item_link<br>\n"; }
+			if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+				require_once "includes/header.php";
+				require_once "includes/persistformvar.php";
+				echo "<div align='center'>\n";
+				echo "<table><tr><td>\n";
+				echo $msg."<br />";
+				echo "</td></tr></table>\n";
+				persistformvar($_POST);
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			}
+
+		//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add" && permission_exists('menu_add')) {
+				$sql = "SELECT menu_item_order FROM v_menu_items ";
+				$sql .= "where menu_uuid = '$menu_uuid' ";
+				$sql .= "and menu_item_parent_uuid  = '$menu_item_parent_uuid' ";
+				$sql .= "order by menu_item_order desc ";
+				$sql .= "limit 1 ";
+				$prep_statement = $db->prepare(check_sql($sql));
+				$prep_statement->execute();
+				$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+				foreach ($result as &$row) {
+					$highest_menu_item_order = $row[menu_item_order];
+				}
+				unset($prep_statement);
+
+				$sql = "insert into v_menu_items ";
+				$sql .= "(";
+				$sql .= "menu_uuid, ";
+				$sql .= "menu_item_title, ";
+				$sql .= "menu_item_link, ";
+				$sql .= "menu_item_category, ";
+				$sql .= "menu_item_description, ";
+				$sql .= "menu_item_protected, ";
+				$sql .= "menu_item_uuid, ";
+				$sql .= "menu_item_parent_uuid, ";
+				$sql .= "menu_item_order, ";
+				$sql .= "menu_item_add_user, ";
+				$sql .= "menu_item_add_date ";
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'$menu_uuid', ";
+				$sql .= "'$menu_item_title', ";
+				$sql .= "'$menu_item_link', ";
+				$sql .= "'$menu_item_category', ";
+				$sql .= "'$menu_item_description', ";
+				$sql .= "'$menu_item_protected', ";
+				$sql .= "'".uuid()."', ";
+				if (strlen($menu_item_parent_uuid) == 0) {
+					$sql .= "null, ";
+				}
+				else {
+					$sql .= "'$menu_item_parent_uuid', ";
+				}
+				$sql .= "'".($highest_menu_item_order+1)."', ";
+				$sql .= "'".$_SESSION["username"]."', ";
+				$sql .= "now() ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=menu_item_edit.php?id=$menu_uuid&menu_item_uuid=$menu_item_uuid&menu_uuid=$menu_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			}
+
+			if ($action == "update" && permission_exists('menu_edit')) {
+				$sql  = "update v_menu_items set ";
+				$sql .= "menu_item_title = '$menu_item_title', ";
+				$sql .= "menu_item_link = '$menu_item_link', ";
+				$sql .= "menu_item_category = '$menu_item_category', ";
+				$sql .= "menu_item_description = '$menu_item_description', ";
+				$sql .= "menu_item_protected = '$menu_item_protected', ";
+				if (strlen($menu_item_parent_uuid) == 0) {
+					$sql .= "menu_item_parent_uuid = null, ";
+				}
+				else {
+					$sql .= "menu_item_parent_uuid = '$menu_item_parent_uuid', ";
+				}
+				$sql .= "menu_item_order = '$menu_item_order', ";
+				$sql .= "menu_item_mod_user = '".$_SESSION["username"]."', ";
+				$sql .= "menu_item_mod_date = now() ";
+				$sql .= "where menu_uuid = '$menu_uuid' ";
+				$sql .= "and menu_item_uuid = '$menu_item_uuid' ";
+				$count = $db->exec(check_sql($sql));
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=menu_item_edit.php?id=$menu_uuid&menu_item_uuid=$menu_item_uuid&menu_uuid=$menu_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Edit Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			}
+		} //if ($_POST["persistformvar"] != "true")
+	} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$menu_item_uuid = $_GET["menu_item_uuid"];
+
+		$sql = "select * from v_menu_items ";
+		$sql .= "where menu_uuid = '$menu_uuid' ";
+		$sql .= "and menu_item_uuid = '$menu_item_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$menu_item_uuid = $row["menu_item_uuid"];
+			$menu_item_title = $row["menu_item_title"];
+			$menu_item_link = $row["menu_item_link"];
+			$menu_item_category = $row["menu_item_category"];
+			$menu_item_description = $row["menu_item_description"];
+			$menu_item_protected = $row["menu_item_protected"];
+			$menu_item_parent_uuid = $row["menu_item_parent_uuid"];
+			$menu_item_order = $row["menu_item_order"];
+			$menu_item_add_user = $row["menu_item_add_user"];
+			$menu_item_add_date = $row["menu_item_add_date"];
+			//$menu_item_del_user = $row["menu_item_del_user"];
+			//$menu_item_del_date = $row["menu_item_del_date"];
+			$menu_item_mod_user = $row["menu_item_mod_user"];
+			$menu_item_mod_date = $row["menu_item_mod_date"];
+			break; //limit to 1 row
+		}
+	}
+
+//show the content
+	require_once "includes/header.php";
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "		<br>";
+
+	echo "<form method='post' action=''>";
+	echo "<table width='100%' cellpadding='6' cellspacing='0'>";
+
+	echo "<tr>\n";
+	echo "<td width='30%' align='left' valign='top' nowrap><b>Menu Item Edit</b></td>\n";
+	echo "<td width='70%' align='right' valign='top'><input type='button' class='btn' name='' alt='back' onclick=\"window.history.back();\" value='Back'><br /><br /></td>\n";
+	echo "</tr>\n";
+
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Title:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='menu_item_title' value='$menu_item_title'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Link:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='menu_item_link' value='$menu_item_link'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Category:</td>";
+	echo "		<td class='vtable'>";
+	echo "            <select name=\"menu_item_category\" class='formfld'>\n";
+	echo "            <option value=\"\"></option>\n";
+	if ($menu_item_category == "internal") { echo "<option value=\"internal\" selected>internal</option>\n"; } else { echo "<option value=\"internal\">internal</option>\n"; }
+	if ($menu_item_category == "external") { echo "<option value=\"external\" selected>external</option>\n"; } else { echo "<option value=\"external\">external</option>\n"; }
+	if ($menu_item_category == "email") { echo "<option value=\"email\" selected>email</option>\n"; } else { echo "<option value=\"email\">email</option>\n"; }
+	echo "            </select>";
+	echo "        </td>";
+	echo "	</tr>";
+
+	echo "	<tr>";
+	echo "		<td class='vncell'>Parent Menu:</td>";
+	echo "		<td class='vtable'>";
+	$sql = "SELECT * FROM v_menu_items ";
+	$sql .= "where menu_uuid = '$menu_uuid' ";
+	$sql .= "order by menu_item_title asc ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	echo "<select name=\"menu_item_parent_uuid\" class='formfld'>\n";
+	echo "<option value=\"\"></option>\n";
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach($result as $field) {
+			if ($menu_item_parent_uuid == $field['menu_item_uuid']) {
+				echo "<option value='".$field['menu_item_uuid']."' selected>".$field['menu_item_title']."</option>\n";
+			}
+			else {
+				echo "<option value='".$field['menu_item_uuid']."'>".$field['menu_item_title']."</option>\n";
+			}
+	}
+	echo "</select>";
+	unset($sql, $result);
+	echo "        </td>";
+	echo "	</tr>";
+
+	echo "	<tr>";
+	echo "		<td class='vncell' valign='top'>Groups:</td>";
+	echo "		<td class='vtable'>";
+
+	echo "<table width='52%'>\n";
+	$sql = "SELECT * FROM v_menu_item_groups ";
+	$sql .= "where menu_uuid=:menu_uuid ";
+	$sql .= "and menu_item_uuid=:menu_item_uuid ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->bindParam(':menu_uuid', $menu_uuid);
+	$prep_statement->bindParam(':menu_item_uuid', $menu_item_uuid);
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$result_count = count($result);
+	foreach($result as $field) {
+		if (strlen($field['group_name']) > 0) {
+			echo "<tr>\n";
+			echo "	<td class='vtable'>".$field['group_name']."</td>\n";
+			echo "	<td>\n";
+			if (permission_exists('group_member_delete') || if_group("superadmin")) {
+				echo "		<a href='menu_item_edit.php?id=".$field['menu_uuid']."&group_name=".$field['group_name']."&menu_item_uuid=".$menu_item_uuid."&menu_item_parent_uuid=".$menu_item_parent_uuid."&a=delete' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			}
+			echo "	</td>\n";
+			echo "</tr>\n";
+		}
+	}
+	echo "</table>\n";
+
+	echo "<br />\n";
+	$sql = "SELECT * FROM v_groups ";
+	$sql .= "where domain_uuid = '".$domain_uuid."' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	echo "<select name=\"group_name\" class='frm'>\n";
+	echo "<option value=\"\"></option>\n";
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach($result as $field) {
+		if ($field['group_name'] == "superadmin") {
+			//only show the superadmin group to other users in the superadmin group
+			if (if_group("superadmin")) {
+				echo "<option value='".$field['group_name']."'>".$field['group_name']."</option>\n";
+			}
+		}
+		else {
+			echo "<option value='".$field['group_name']."'>".$field['group_name']."</option>\n";
+		}
+	}
+	echo "</select>";
+	echo "<input type=\"submit\" class='btn' value=\"Add\">\n";
+	unset($sql, $result);
+	echo "		</td>";
+	echo "	</tr>";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap>\n";
+	echo "    Protected:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "    <select class='formfld' name='menu_item_protected'>\n";
+	echo "    <option value=''></option>\n";
+	if ($menu_item_protected == "true") { 
+		echo "    <option value='true' selected='selected' >true</option>\n";
+	}
+	else {
+		echo "    <option value='true'>true</option>\n";
+	}
+	if ($menu_item_protected == "false") { 
+		echo "    <option value='false' selected='selected' >false</option>\n";
+	}
+	else {
+		echo "    <option value='false'>false</option>\n";
+	}
+	echo "    </select><br />\n";
+	echo "Protect this item in the menu so that is is not removed by 'Restore Default.'<br />\n";
+	echo "\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	if ($action == "update") {
+		echo "	<tr>";
+		echo "		<td class='vncell'>Menu Order:</td>";
+		echo "		<td class='vtable'><input type='text' class='formfld' name='menu_item_order' value='$menu_item_order'></td>";
+		echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>Added By:</td>";
+		//echo "		<td class='vtable'>$menu_item_add_user &nbsp;</td>";
+		//echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>Add Date:</td>";
+		//echo "		<td class='vtable'>$menu_item_add_date &nbsp;</td>";
+		//echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>menu_item_del_user:</td>";
+		//echo "		<td><input type='text' name='menu_item_del_user' value='$menu_item_del_user'></td>";
+		//echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>menu_item_del_date:</td>";
+		//echo "		<td><input type='text' name='menu_item_del_date' value='$menu_item_del_date'></td>";
+		//echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>Modified By:</td>";
+		//echo "		<td class='vtable'>$menu_item_mod_user &nbsp;</td>";
+		//echo "	</tr>";
+		//echo "	<tr>";
+		//echo "		<td class='vncell'>Modified Date:</td>";
+		//echo "		<td class='vtable'>$menu_item_mod_date &nbsp;</td>";
+		//echo "	</tr>";
+	}
+
+	echo "	<tr>";
+	echo "		<td class='vncell'>Description:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='menu_item_description' value='$menu_item_description'></td>";
+	echo "	</tr>";
+
+	if (permission_exists('menu_add') || permission_exists('menu_edit')) {
+		echo "	<tr>\n";
+		echo "		<td colspan='2' align='right'>\n";
+		echo "			<table width='100%'>";
+		echo "			<tr>";
+		echo "			<td align='left'>";
+		echo "			</td>\n";
+		echo "			<td align='right'>";
+		if ($action == "update") {
+			echo "				<input type='hidden' name='menu_item_uuid' value='$menu_item_uuid'>";
+		}
+		echo "				<input type='hidden' name='menu_uuid' value='$menu_uuid'>";
+		echo "				<input type='hidden' name='menu_item_uuid' value='$menu_item_uuid'>";
+		echo "				<input type='submit' class='btn' name='submit' value='Save'>\n";
+		echo "			</td>";
+		echo "			</tr>";
+		echo "			</table>";
+		echo "		</td>";
+		echo "	</tr>";
+	}
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+  require_once "includes/footer.php";
+?>

+ 371 - 0
core/menu/menu_item_list.php

@@ -0,0 +1,371 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_add') || permission_exists('menu_edit')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+$tmp_menu_item_order = 0;
+
+function build_db_child_menu_list ($db, $menu_item_level, $menu_item_uuid, $c) {
+	global $menu_uuid, $tmp_menu_item_order, $v_link_label_edit, $v_link_label_delete;
+
+	//check for sub menus
+		$menu_item_level = $menu_item_level+1;
+		$sql = "select * from v_menu_items ";
+		$sql .= "where menu_uuid = '".$menu_uuid."' ";
+		$sql .= "and menu_item_parent_uuid = '".$menu_item_uuid."' ";
+		$sql .= "order by menu_item_order, menu_item_title asc ";
+		$prep_statement_2 = $db->prepare($sql);
+		$prep_statement_2->execute();
+		$result2 = $prep_statement_2->fetchAll(PDO::FETCH_NAMED);
+
+		$row_style["0"] = "row_style1";
+		$row_style["1"] = "row_style1";
+
+		if (count($result2) > 0) {
+			if ($c == 0) { $c2 = 1; } else { $c2 = 0; }
+			foreach($result2 as $row2) {
+				//set the db values as php variables
+					$menu_item_uuid = $row2['menu_item_uuid'];
+					$menu_item_category = $row2['menu_item_category'];
+					$menu_item_protected = $row2['menu_item_protected'];
+					$menu_item_parent_uuid = $row2['menu_item_parent_uuid'];
+					$menu_item_order = $row2['menu_item_order'];
+					$menu_item_language = $row2['menu_item_language'];
+					$menu_item_title = $row2[menu_item_title];
+					$menu_item_link = $row2[menu_item_link];
+				//get the groups that have been assigned to the menu
+					$sql = "";
+					$sql .= "select group_name from v_menu_item_groups ";
+					$sql .= "where menu_uuid = '$menu_uuid' ";
+					$sql .= "and menu_item_uuid = '".$menu_item_uuid."' ";
+					$sub_prep_statement = $db->prepare(check_sql($sql));
+					$sub_prep_statement->execute();
+					$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+					$group_list = "";
+					$x = 0;
+					foreach ($sub_result as &$sub_row) {
+						if ($x == 0) {
+							$group_list = $sub_row["group_name"];
+						}
+						else {
+							$group_list .= ", ".$sub_row["group_name"];
+						}
+						$x++;
+					}
+					unset ($sub_prep_statement);
+				//display the main body of the list
+					switch ($menu_item_category) {
+						case "internal":
+							$menu_item_title = "<a href='".PROJECT_PATH."/$menu_item_link'>$menu_item_title</a>";
+							break;
+						case "external":
+							if (substr($menu_item_link, 0,1) == "/") {
+								$menu_item_link = PROJECT_PATH . $menu_item_link;
+							}
+							$menu_item_title = "<a href='$menu_item_link' target='_blank'>$menu_item_title</a>";
+							break;
+						case "email":
+							$menu_item_title = "<a href='mailto:$menu_item_link'>$menu_item_title</a>";
+							break;
+					}
+
+				//display the content of the list
+					echo "<tr'>\n";
+					echo "<td valign='top' class='".$row_style[$c]."'>";
+					echo "  <table cellpadding='0' cellspacing='0' border='0'>";
+					echo "  <tr>";
+					echo "      <td nowrap>";
+					$i=0;
+					while($i < $menu_item_level){
+						echo "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;";
+						$i++;
+					}
+					echo "       ".$menu_item_title."&nbsp;";
+
+					echo "      </td>";
+					echo "  </tr>";
+					echo "  </table>";
+					echo "</td>";
+					//echo "<td valign='top'>&nbsp;".$menu_item_link."&nbsp;</td>";
+					echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$group_list."&nbsp;</td>";
+					echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$menu_item_category."&nbsp;</td>";
+					//echo "<td valign='top'>".$row[menu_item_description]."</td>";
+					//echo "<td valign='top'>&nbsp;".$row[menu_item_order]."&nbsp;</td>";
+					if ($menu_item_protected == "true") {
+						echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; <strong>yes</strong> &nbsp;</td>";
+					}
+					else {
+						echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; no &nbsp;</td>";
+					}
+					echo "<td valign='top' align='center' nowrap class='".$row_style[$c]."'>";
+					echo "	&nbsp;";
+					//echo "  ".$row2[menu_item_order]."&nbsp;";
+					echo "</td>";
+
+					//echo "<td valign='top' align='center' class='".$row_style[$c]."'>";
+					//if (permission_exists('menu_edit')) {
+					//	echo "  <input type='button' class='btn' name='' onclick=\"window.location='menu_item_move_up.php?menu_uuid=".$menu_uuid."&menu_item_parent_uuid=".$row2['menu_item_parent_uuid']."&menu_item_uuid=".$row2[menu_item_uuid]."&menu_item_order=".$row2[menu_item_order]."'\" value='<' title='".$row2[menu_item_order].". Move Up'>";
+					//	echo "  <input type='button' class='btn' name='' onclick=\"window.location='menu_item_move_down.php?menu_uuid=".$menu_uuid."&menu_item_parent_uuid=".$row2['menu_item_parent_uuid']."&menu_item_uuid=".$row2[menu_item_uuid]."&menu_item_order=".$row2[menu_item_order]."'\" value='>' title='".$row2[menu_item_order].". Move Down'>";
+					//}
+					//echo "</td>";
+
+					echo "   <td valign='top' align='right' nowrap>\n";
+					if (permission_exists('menu_edit')) {
+						echo "		<a href='menu_item_edit.php?id=".$menu_uuid."&menu_item_uuid=".$row2['menu_item_uuid']."&menu_item_parent_uuid=".$row2['menu_item_parent_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+					}
+					if (permission_exists('menu_delete')) {
+						echo "		<a href='menu_item_delete.php?id=".$menu_uuid."&menu_item_uuid=".$row2['menu_item_uuid']."' onclick=\"return confirm('Do you really want to delete this?')\" alt='delete'>$v_link_label_delete</a>\n";
+					}
+					echo "   </td>\n";
+					echo "</tr>";
+
+				//update the menu order
+					if ($row2[menu_item_order] != $tmp_menu_item_order) {
+						$sql  = "update v_menu_items set ";
+						$sql .= "menu_item_title = '".$row2[menu_item_title]."', ";
+						$sql .= "menu_item_order = '".$tmp_menu_item_order."' ";
+						$sql .= "where menu_uuid = '".$menu_uuid."' ";
+						$sql .= "and menu_item_uuid = '".$row2[menu_item_uuid]."' ";
+						$count = $db->exec(check_sql($sql));
+					}
+					$tmp_menu_item_order++;
+
+				//check for additional sub menus
+					if (strlen($menu_item_uuid)> 0) {
+						$c = build_db_child_menu_list($db, $menu_item_level, $menu_item_uuid, $c);
+					}
+
+				if ($c==0) { $c=1; } else { $c=0; }
+			} //end foreach
+			unset($sql, $result2, $row2);
+		}
+		return $c;
+	//end check for children
+}
+
+require_once "includes/header.php";
+$order_by = $_GET["order_by"];
+$order = $_GET["order"];
+
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+
+	echo "<table width='100%' border='0'><tr>";
+	//echo "<td width='50%'><b>Menu Manager</b></td>";
+	echo "<td width='50%' align='right'>\n";
+	//if (permission_exists('menu_restore')) {
+	//	echo "	<input type='button' class='btn' value='Restore Default' onclick=\"document.location.href='menu_restore_default.php';\" />";
+	//}
+	echo "</td>\n";
+	echo "<td width='35' nowrap></td>\n";
+	echo "</tr></table>";
+
+	$sql = "select * from v_menu_items ";
+	$sql .= "where menu_uuid = '".$menu_uuid."' ";
+	$sql .= "and menu_item_parent_uuid is null ";
+	if (strlen($order_by)> 0) {
+		$sql .= "order by $order_by $order ";
+	}
+	else {
+		$sql .= "order by menu_item_order asc ";
+	}
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$result_count = count($result);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style0";
+
+	echo "<div align='left'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	if ($result_count == 0) {
+		//no results
+		echo "<tr><td>&nbsp;</td></tr>";
+	}
+	else {
+		echo "<tr>";
+		echo "<th align='left' nowrap>&nbsp; Title &nbsp; </th>";
+		echo "<th align='left' nowrap>&nbsp; Groups &nbsp; </th>";
+		echo "<th align='left'nowrap>&nbsp; Category &nbsp; </th>";
+		echo "<th nowrap>&nbsp; Protected &nbsp; </th>";
+		//echo "<th align='left'  width='55' nowrap>&nbsp; Order &nbsp;</th>";
+		echo "<th nowrap width='70'>Order &nbsp; </th>";
+		echo "<td align='right' width='42'>\n";
+		if (permission_exists('menu_add')) {
+			echo "	<a href='menu_item_edit.php?id=".$menu_uuid."' alt='add'>$v_link_label_add</a>\n";
+		}
+		echo "</td>\n";
+		echo "</tr>";
+
+		foreach($result as $row) {
+			//set the db values as php variables
+				$menu_item_uuid = $row['menu_item_uuid'];
+				$menu_item_category = $row['menu_item_category'];
+				$menu_item_title = $row['menu_item_title'];
+				$menu_item_link = $row['menu_item_link'];
+				$menu_item_protected = $row['menu_item_protected'];
+
+			//get the groups that have been assigned to the menu
+				$sql = "";
+				$sql .= "select group_name from v_menu_item_groups ";
+				$sql .= "where menu_uuid = '$menu_uuid' ";
+				$sql .= "and menu_item_uuid = '$menu_item_uuid' ";
+				$sub_prep_statement = $db->prepare(check_sql($sql));
+				$sub_prep_statement->execute();
+				$sub_result = $sub_prep_statement->fetchAll(PDO::FETCH_NAMED);
+				$group_list = "";
+				$x = 0;
+				foreach ($sub_result as &$sub_row) {
+					if ($x == 0) {
+						$group_list = $sub_row["group_name"];
+					}
+					else {
+						$group_list .= ", ".$sub_row["group_name"];
+					}
+					$x++;
+				}
+				unset ($sub_prep_statement);
+
+			//add the type link based on the typd of the menu
+				switch ($menu_item_category) {
+					case "internal":
+						$menu_item_title = "<a href='".PROJECT_PATH."/$menu_item_link'>$menu_item_title</a>";
+						break;
+					case "external":
+						if (substr($menu_item_link, 0,1) == "/") {
+							$menu_item_link = PROJECT_PATH . $menu_item_link;
+						}
+						$menu_item_title = "<a href='$menu_item_link' target='_blank'>$menu_item_title</a>";
+						break;
+					case "email":
+						$menu_item_title = "<a href='mailto:$menu_item_link'>$menu_item_title</a>";
+						break;
+				}
+
+			//display the content of the list
+				echo "<tr style='".$row_style[$c]."'>\n";
+				echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; ".$menu_item_title."&nbsp;</td>";
+				echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; ".$group_list."&nbsp;</td>";
+				//echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$menu_item_link."&nbsp;</td>";
+				echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$menu_item_category."&nbsp;</td>";
+				//echo "<td valign='top' class='".$row_style[$c]."'>".$row[menu_item_description]."</td>";
+				//echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$row['menu_item_parent_uuid']."&nbsp;</td>";
+				//echo "<td valign='top' class='".$row_style[$c]."'>&nbsp;".$row['menu_item_order']."&nbsp;</td>";
+
+				if ($menu_item_protected == "true") {
+					echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; <strong>yes</strong> &nbsp;</td>";
+				}
+				else {
+					echo "<td valign='top' class='".$row_style[$c]."'>&nbsp; no &nbsp;</td>";
+				}
+
+				echo "<td valign='top' align='center' nowrap class='".$row_style[$c]."'>";
+				echo "  ".$row[menu_item_order]."&nbsp;";
+				echo "</td>";
+
+				//echo "<td valign='top' align='center' nowrap class='".$row_style[$c]."'>";
+				//if (permission_exists('menu_edit')) {
+				//	echo "  <input type='button' class='btn' name='' onclick=\"window.location='menu_item_move_up.php?menu_uuid=".$menu_uuid."&menu_item_parent_uuid=".$row['menu_item_parent_uuid']."&menu_item_uuid=".$row['menu_item_uuid']."&menu_item_order=".$row['menu_item_order']."'\" value='<' title='".$row['menu_item_order'].". Move Up'>";
+				//	echo "  <input type='button' class='btn' name='' onclick=\"window.location='menu_item_move_down.php?menu_uuid=".$menu_uuid."&menu_item_parent_uuid=".$row['menu_item_parent_uuid']."&menu_item_uuid=".$row['menu_item_uuid']."&menu_item_order=".$row['menu_item_order']."'\" value='>' title='".$row['menu_item_order'].". Move Down'>";
+				//}
+				//echo "</td>";
+
+				echo "   <td valign='top' align='right' nowrap>\n";
+				if (permission_exists('menu_edit')) {
+					echo "		<a href='menu_item_edit.php?id=".$menu_uuid."&menu_item_uuid=".$row['menu_item_uuid']."&menu_uuid=".$menu_uuid."' alt='edit'>$v_link_label_edit</a>\n";
+				}
+				if (permission_exists('menu_delete')) {
+					echo "		<a href='menu_item_delete.php?id=".$menu_uuid."&menu_item_uuid=".$row['menu_item_uuid']."&menu_uuid=".$menu_uuid."' onclick=\"return confirm('Do you really want to delete this?')\" alt='delete'>$v_link_label_delete</a>\n";
+				}
+				echo "   </td>\n";
+				echo "</tr>";
+
+			//update the menu order
+				if ($row[menu_item_order] != $tmp_menu_item_order) {
+					$sql  = "update v_menu_items set ";
+					$sql .= "menu_item_title = '".$row['menu_item_title']."', ";
+					$sql .= "menu_item_order = '".$tmp_menu_item_order."' ";
+					$sql .= "where menu_uuid = '".$menu_uuid."' ";
+					$sql .= "and menu_item_uuid = '".$row[menu_item_uuid]."' ";
+					//$db->exec(check_sql($sql));
+				}
+				$tmp_menu_item_order++;
+
+			//check for sub menus
+				$menu_item_level = 0;
+				if (strlen($row['menu_item_uuid']) > 0) {
+					$c = build_db_child_menu_list($db, $menu_item_level, $row['menu_item_uuid'], $c);
+				}
+
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='6' align='left'>\n";
+	echo "	<table border='0' width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	if (permission_exists('menu_add')) {
+		echo "			<a href='menu_item_edit.php?id=".$menu_uuid."' alt='add'>$v_link_label_add</a>\n";
+	}
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "	</table>\n";
+
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "</table>\n";
+	echo "</div>\n";
+	echo "<br><br>";
+
+	echo "  </td>\n";
+	echo "</tr>\n";
+	echo "</table>\n";
+	echo "</div>";
+
+	echo "<br><br>";
+	require_once "includes/footer.php";
+
+?>

+ 88 - 0
core/menu/menu_item_move_down.php

@@ -0,0 +1,88 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_edit')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//move down more than one level at a time
+//update v_menu_items set menu_item_order = (menu_item_order+1) where menu_item_order > 2 or menu_item_order = 2
+
+if (count($_GET)>0) {
+	$menu_item_id = check_str($_GET["menu_item_id"]);
+	$menu_item_order = check_str($_GET["menu_item_order"]);
+	$menu_parent_guid = check_str($_GET["menu_parent_guid"]);
+
+	$sql = "SELECT menu_item_order FROM v_menu_items ";
+	$sql .= "where domain_uuid = '".$domain_uuid."' ";
+	$sql .= "order by menu_item_order desc ";
+	$sql .= "limit 1 ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$highestmenu_item_order = $row[menu_item_order];
+	}
+	unset($prep_statement);
+
+	if ($menu_item_order != $highestmenu_item_order) {
+		//clear the menu session so it will rebuild with the update
+			$_SESSION["menu"] = "";
+
+		//move the current item's order number up
+			$sql  = "update v_menu_items set ";
+			$sql .= "menu_item_order = (menu_item_order-1) "; //move down
+			$sql .= "where domain_uuid = '".$domain_uuid."' ";
+			$sql .= "and menu_item_order = ".($menu_item_order+1)." ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+
+		//move the selected item's order number down
+			$sql  = "update v_menu_items set ";
+			$sql .= "menu_item_order = (menu_item_order+1) "; //move up
+			$sql .= "where domain_uuid = '".$domain_uuid."' ";
+			$sql .= "and menu_item_id = '$menu_item_id' ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+	}
+
+	//redirect the user
+		require_once "includes/header.php";
+		echo "<meta http-equiv=\"refresh\" content=\"1;url=menu_list.php?menu_item_id=$menu_item_id\">\n";
+		echo "<div align='center'>";
+		echo "Item Moved Down";
+		echo "</div>";
+		require_once "includes/footer.php";
+		return;
+}
+
+?>

+ 75 - 0
core/menu/menu_item_move_up.php

@@ -0,0 +1,75 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_edit')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//move down more than one level at a time
+//update v_menu_items set menu_order = (menu_order+1) where menu_order > 2 or menu_order = 2
+
+if (count($_GET)>0) {
+	$menu_item_id = check_str($_GET["menu_item_id"]);
+	$menu_order = check_str($_GET["menu_order"]);
+
+	if ($menu_order != 1) {
+		//clear the menu session so it will rebuild with the update
+			$_SESSION["menu"] = ""; 
+
+		//move the current item's order number down
+			$sql  = "update v_menu_items set ";
+			$sql .= "menu_order = (menu_order+1) "; //move down
+			$sql .= "where domain_uuid = '".$domain_uuid."' ";
+			$sql .= "and menu_order = ".($menu_order-1)." ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+
+		//move the selected item's order number up
+			$sql  = "update v_menu_items set ";
+			$sql .= "menu_order = (menu_order-1) "; //move up
+			$sql .= "where domain_uuid = '".$domain_uuid."' ";
+			$sql .= "and menu_item_id = '$menu_item_id' ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+	}
+
+	//redirect the user
+		require_once "includes/header.php";
+		echo "<meta http-equiv=\"refresh\" content=\"1;url=menu_list.php?menu_item_id=$menu_item_id\">\n";
+		echo "<div align='center'>";
+		echo "Item Moved Up";
+		echo "</div>";
+		require_once "includes/footer.php";
+		return;
+}
+
+?>

+ 63 - 0
core/menu/menu_restore_default.php

@@ -0,0 +1,63 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('menu_restore')) {
+	//access granted
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//get the http value and set as a php variable
+	$menu_uuid = check_str($_REQUEST["menu_uuid"]);
+
+//menu restore default
+	require_once "includes/classes/menu.php";
+	$menu = new menu;
+	$menu->db = $db;
+	$menu->menu_uuid = $menu_uuid;
+	$menu->delete();
+	$menu->restore();
+
+//unset the menu session variable
+	$_SESSION["menu"] = "";
+
+//unset the default template
+	$_SESSION["template_content"] = '';
+
+//show a message to the user
+	require_once "includes/header.php";
+	echo "<meta http-equiv=\"refresh\" content=\"2;url=/core/menu/menu_edit.php?id=$menu_uuid\">\n";
+	echo "<div align='center'>\n";
+	echo "Restore Complete\n";
+	echo "</div>\n";
+	require_once "includes/footer.php";
+	return;
+
+?>

+ 50 - 0
core/menu/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 98 - 0
core/servers/app_config.php

@@ -0,0 +1,98 @@
+<?php
+/*
+	//application details
+		$apps[$x]['name'] = 'Servers';
+		$apps[$x]['guid'] = '0f390134-071e-83d7-a79a-ebb7ae139d71';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = '';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Servers';
+		$apps[$x]['menu'][0]['uuid'] = 'f35ee905-1f30-7529-7420-35fc77e47882';
+		$apps[$x]['menu'][0]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/core/servers/v_servers.php';
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+	//permission details
+		$y = 0;
+		$apps[$x]['permissions'][$y]['name'] = 'server_view';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_add';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_edit';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_delete';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_setting_view';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_setting_add';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_setting_edit';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+		$y++;
+		$apps[$x]['permissions'][$y]['name'] = 'server_setting_delete';
+		$apps[$x]['permissions'][$y]['groups'][] = 'superadmin';
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_servers';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the description.';
+		$z++;
+
+		$y = 1; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_category';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the category.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_value';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the value.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_enabled';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'server_setting_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+*/
+?>

+ 50 - 0
core/servers/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 161 - 0
core/servers/v_server_settings.php

@@ -0,0 +1,161 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br />";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' nowrap><b>Server Setting List</b></td>\n";
+	echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2'>\n";
+	echo "			Server settings are assigned to Domains.<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = "";
+		$sql .= " select count(*) as num_rows from v_server_settings ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		$sql .= " and server_uuid = '$server_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 100;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the server list
+		$sql = "";
+		$sql .= " select * from v_server_settings ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		$sql .= " and server_uuid = '$server_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	echo "<tr>\n";
+	echo th_order_by('server_setting_category', 'Category', $order_by, $order);
+	echo th_order_by('server_setting_name', 'Name', $order_by, $order);
+	echo th_order_by('server_setting_value', 'Value', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	echo "	<a href='v_server_settings_edit.php?server_uuid=".$_GET['id']."' alt='add'>$v_link_label_add</a>\n";
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['server_setting_category']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['server_setting_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['server_setting_value']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='v_server_settings_edit.php?server_uuid=".$row['server_uuid']."&id=".$row['server_setting_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='v_server_settings_delete.php?server_uuid=".$row['server_uuid']."&id=".$row['server_setting_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+
+	echo "<tr>\n";
+	echo "<td colspan='6' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='v_server_settings_edit.php?server_uuid=".$_GET['id']."' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+	echo "<br /><br />";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 60 - 0
core/servers/v_server_settings_delete.php

@@ -0,0 +1,60 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+	$server_uuid = check_str($_GET["server_uuid"]);
+}
+
+if (strlen($id)>0) {
+	$sql = "";
+	$sql .= "delete from v_server_settings ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and server_setting_uuid = '$id' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	unset($sql);
+}
+
+require_once "includes/header.php";
+echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers_edit.php?id=$server_uuid\">\n";
+echo "<div align='center'>\n";
+echo "Delete Complete\n";
+echo "</div>\n";
+require_once "includes/footer.php";
+return;
+
+?>

+ 244 - 0
core/servers/v_server_settings_edit.php

@@ -0,0 +1,244 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$server_setting_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+if (strlen($_GET["server_uuid"]) > 0) {
+	$server_uuid = check_str($_GET["server_uuid"]);
+}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$server_uuid = check_str($_POST["server_uuid"]);
+		$server_setting_category = check_str($_POST["server_setting_category"]);
+		$server_setting_value = check_str($_POST["server_setting_value"]);
+		$server_setting_name = check_str($_POST["server_setting_name"]);
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$server_setting_uuid = check_str($_POST["server_setting_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($server_uuid) == 0) { $msg .= "Please provide: server_uuid<br>\n"; }
+		//if (strlen($domain_uuid) == 0) { $msg .= "Please provide: domain_uuid<br>\n"; }
+		//if (strlen($server_setting_category) == 0) { $msg .= "Please provide: Category<br>\n"; }
+		//if (strlen($server_setting_value) == 0) { $msg .= "Please provide: Value<br>\n"; }
+		//if (strlen($server_setting_name) == 0) { $msg .= "Please provide: Name<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add") {
+				$sql = "insert into v_server_settings ";
+				$sql .= "(";
+				$sql .= "domain_uuid, ";
+				$sql .= "server_uuid, ";
+				$sql .= "server_uuid, ";
+				$sql .= "domain_uuid, ";
+				$sql .= "server_setting_category, ";
+				$sql .= "server_setting_value, ";
+				$sql .= "server_setting_name ";
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'$domain_uuid', ";
+				$sql .= "'$server_uuid', ";
+				$sql .= "'$server_uuid', ";
+				$sql .= "'$domain_uuid', ";
+				$sql .= "'$server_setting_category', ";
+				$sql .= "'$server_setting_value', ";
+				$sql .= "'$server_setting_name' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers_edit.php?id=$server_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "add")
+
+			if ($action == "update") {
+				$sql = "update v_server_settings set ";
+				$sql .= "server_uuid = '$server_uuid', ";
+				$sql .= "server_uuid = '$server_uuid', ";
+				$sql .= "domain_uuid = '$domain_uuid', ";
+				$sql .= "server_setting_category = '$server_setting_category', ";
+				$sql .= "server_setting_value = '$server_setting_value', ";
+				$sql .= "server_setting_name = '$server_setting_name' ";
+				$sql .= "where domain_uuid = '$domain_uuid' ";
+				$sql .= "and server_setting_uuid = '$server_setting_uuid'";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers_edit.php?id=$server_uuid\">\n";
+				echo "<div align='center'>\n";
+				echo "Update Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "update")
+		} //if ($_POST["persistformvar"] != "true") 
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$server_setting_uuid = $_GET["id"];
+		$sql = "";
+		$sql .= "select * from v_server_settings ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$sql .= "and server_setting_uuid = '$server_setting_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$server_uuid = $row["server_uuid"];
+			$server_setting_category = $row["server_setting_category"];
+			$server_setting_value = $row["server_setting_value"];
+			$server_setting_name = $row["server_setting_name"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Server Setting Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Server Setting Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'><input type='button' class='btn' name='' alt='back' onclick=\"window.location='v_servers_edit.php?id=$server_uuid'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td colspan='2'>\n";
+	echo "Server settings are assigned to Domains.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Category:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='server_setting_category' maxlength='255' value=\"$server_setting_category\">\n";
+	echo "<br />\n";
+	echo "Enter the category.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='server_setting_name' maxlength='255' value=\"$server_setting_name\">\n";
+	echo "<br />\n";
+	echo "Enter the name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Value:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='server_setting_value' maxlength='255' value=\"$server_setting_value\">\n";
+	echo "<br />\n";
+	echo "Enter the value.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	echo "				<input type='hidden' name='server_uuid' value='$server_uuid'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='server_setting_uuid' value='$server_setting_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 158 - 0
core/servers/v_servers.php

@@ -0,0 +1,158 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get variables used to control the order
+	$order_by = $_GET["order_by"];
+	$order = $_GET["order"];
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br />";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='50%' nowrap><b>Servers</b></td>\n";
+	echo "		<td width='50%' align='right'>&nbsp;</td>\n";
+	echo "	</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2'>\n";
+	echo "			Servers Settings<br /><br />\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	//prepare to page the results
+		$sql = "";
+		$sql .= " select count(*) as num_rows from v_servers ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+		$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$num_rows = $row['num_rows'];
+			}
+			else {
+				$num_rows = '0';
+			}
+		}
+
+	//prepare to page the results
+		$rows_per_page = 10;
+		$param = "";
+		$page = $_GET['page'];
+		if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+		list($paging_controls, $rows_per_page, $var3) = paging($num_rows, $param, $rows_per_page); 
+		$offset = $rows_per_page * $page; 
+
+	//get the  list
+		$sql = "";
+		$sql .= " select * from v_servers ";
+		$sql .= " where domain_uuid = '$domain_uuid' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$sql .= " limit $rows_per_page offset $offset ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		$result_count = count($result);
+		unset ($prep_statement, $sql);
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	echo "<tr>\n";
+	echo th_order_by('server_name', 'Server Name', $order_by, $order);
+	echo th_order_by('server_description', 'Description', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	echo "	<a href='v_servers_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			//print_r( $row );
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['server_name']."&nbsp;</td>\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['server_description']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			echo "		<a href='v_servers_edit.php?id=".$row[server_uuid]."' alt='edit'>$v_link_label_edit</a>\n";
+			echo "		<a href='v_servers_delete.php?id=".$row[server_uuid]."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+
+	echo "<tr>\n";
+	echo "<td colspan='3' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	echo "			<a href='v_servers_edit.php' alt='add'>$v_link_label_add</a>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+ 	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+	echo "<br /><br />";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<br /><br />";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 59 - 0
core/servers/v_servers_delete.php

@@ -0,0 +1,59 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+if (count($_GET)>0) {
+	$id = check_str($_GET["id"]);
+}
+
+if (strlen($id)>0) {
+	$sql = "";
+	$sql .= "delete from v_servers ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and server_uuid = '$id' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	unset($sql);
+}
+
+require_once "includes/header.php";
+echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers.php\">\n";
+echo "<div align='center'>\n";
+echo "Delete Complete\n";
+echo "</div>\n";
+require_once "includes/footer.php";
+return;
+
+?>

+ 212 - 0
core/servers/v_servers_edit.php

@@ -0,0 +1,212 @@
+<?php
+/*
+ FusionPBX
+ Version: MPL 1.1
+
+ The contents of this file are subject to the Mozilla Public License Version
+ 1.1 (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+ http://www.mozilla.org/MPL/
+
+ Software distributed under the License is distributed on an "AS IS" basis,
+ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ for the specific language governing rights and limitations under the
+ License.
+
+ The Original Code is FusionPBX
+
+ The Initial Developer of the Original Code is
+ Mark J Crane <[email protected]>
+ Portions created by the Initial Developer are Copyright (C) 2008-2012
+ the Initial Developer. All Rights Reserved.
+
+ Contributor(s):
+ Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (if_group("admin") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+
+//action add or update
+	if (isset($_REQUEST["id"])) {
+		$action = "update";
+		$server_uuid = check_str($_REQUEST["id"]);
+	}
+	else {
+		$action = "add";
+	}
+
+//get http post variables and set them to php variables
+	if (count($_POST)>0) {
+		$server_name = check_str($_POST["server_name"]);
+		$server_description = check_str($_POST["server_description"]);
+	}
+
+if (count($_POST)>0 && strlen($_POST["persistformvar"]) == 0) {
+
+	$msg = '';
+	if ($action == "update") {
+		$server_uuid = check_str($_POST["server_uuid"]);
+	}
+
+	//check for all required data
+		//if (strlen($server_name) == 0) { $msg .= "Please provide: Server Name<br>\n"; }
+		//if (strlen($server_description) == 0) { $msg .= "Please provide: Description<br>\n"; }
+		if (strlen($msg) > 0 && strlen($_POST["persistformvar"]) == 0) {
+			require_once "includes/header.php";
+			require_once "includes/persistformvar.php";
+			echo "<div align='center'>\n";
+			echo "<table><tr><td>\n";
+			echo $msg."<br />";
+			echo "</td></tr></table>\n";
+			persistformvar($_POST);
+			echo "</div>\n";
+			require_once "includes/footer.php";
+			return;
+		}
+
+	//add or update the database
+		if ($_POST["persistformvar"] != "true") {
+			if ($action == "add") {
+				$sql = "insert into v_servers ";
+				$sql .= "(";
+				$sql .= "domain_uuid, ";
+				$sql .= "server_name, ";
+				$sql .= "server_description ";
+				$sql .= ")";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'$domain_uuid', ";
+				$sql .= "'$server_name', ";
+				$sql .= "'$server_description' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Add Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "add")
+
+			if ($action == "update") {
+				$sql = "update v_servers set ";
+				$sql .= "server_name = '$server_name', ";
+				$sql .= "server_description = '$server_description' ";
+				$sql .= "where domain_uuid = '$domain_uuid' ";
+				$sql .= "and server_uuid = '$server_uuid'";
+				$db->exec(check_sql($sql));
+				unset($sql);
+
+				require_once "includes/header.php";
+				echo "<meta http-equiv=\"refresh\" content=\"2;url=v_servers.php\">\n";
+				echo "<div align='center'>\n";
+				echo "Update Complete\n";
+				echo "</div>\n";
+				require_once "includes/footer.php";
+				return;
+			} //if ($action == "update")
+		} //if ($_POST["persistformvar"] != "true")
+} //(count($_POST)>0 && strlen($_POST["persistformvar"]) == 0)
+
+//pre-populate the form
+	if (count($_GET)>0 && $_POST["persistformvar"] != "true") {
+		$server_uuid = $_GET["id"];
+		$sql = "";
+		$sql .= "select * from v_servers ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$sql .= "and server_uuid = '$server_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach ($result as &$row) {
+			$server_name = $row["server_name"];
+			$server_description = $row["server_description"];
+			break; //limit to 1 row
+		}
+		unset ($prep_statement);
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing=''>\n";
+
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"left\">\n";
+	echo "	  <br>";
+
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>\n";
+	echo "<table width='100%'  border='0' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	if ($action == "add") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Server Add</b></td>\n";
+	}
+	if ($action == "update") {
+		echo "<td align='left' width='30%' nowrap='nowrap'><b>Server Edit</b></td>\n";
+	}
+	echo "<td width='70%' align='right'><input type='button' class='btn' name='' alt='back' onclick=\"window.location='v_servers.php'\" value='Back'></td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td colspan='2'>\n";
+	echo "Servers Settings<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Server Name:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='server_name' maxlength='255' value=\"$server_name\">\n";
+	echo "<br />\n";
+	echo "Enter the name.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncell' valign='top' align='left' nowrap='nowrap'>\n";
+	echo "	Description:\n";
+	echo "</td>\n";
+	echo "<td class='vtable' align='left'>\n";
+	echo "	<input class='formfld' type='text' name='server_description' maxlength='255' value=\"$server_description\">\n";
+	echo "<br />\n";
+	echo "Enter the description.\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "	<tr>\n";
+	echo "		<td colspan='2' align='right'>\n";
+	if ($action == "update") {
+		echo "				<input type='hidden' name='server_uuid' value='$server_uuid'>\n";
+	}
+	echo "				<input type='submit' name='submit' class='btn' value='Save'>\n";
+	echo "		</td>\n";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	if ($action == "update") {
+		require "v_server_settings.php";
+	}
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 71 - 0
core/upgrade/app_config.php

@@ -0,0 +1,71 @@
+<?php
+	//application details
+		$apps[$x]['name'] = "Upgrade Schema";
+		$apps[$x]['uuid'] = '8b1d7eb5-1009-052c-e1a8-d1f4887a3f5c';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'Upgrade the database schema.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Upgrade Schema';
+		$apps[$x]['menu'][0]['uuid'] = '8c826e92-be3c-0944-669a-24e5b915d562';
+		$apps[$x]['menu'][0]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/core/upgrade/upgrade_schema.php';
+		$apps[$x]['menu'][0]['groups'][] = 'superadmin';
+
+	//permission details
+		$apps[$x]['permissions'][0]['name'] = 'upgrade_schema';
+		$apps[$x]['permissions'][0]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][1]['name'] = 'upgrade_svn';
+
+	//schema details
+		/*
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_src';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'src_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'src_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'type';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'last_mod';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'path';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		*/
+?>

+ 132 - 0
core/upgrade/app_defaults.php

@@ -0,0 +1,132 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+if (strlen($_SESSION['switch']['scripts']['dir']) > 0) {
+
+	//if the resource scripts resource directory does not exist then create it
+		if (!is_dir($_SESSION['switch']['scripts']['dir']."/resources")) { mkdir($_SESSION['switch']['scripts']['dir']."/resources",0755,true); }
+
+	//get odbc information
+		$sql = "select count(*) as num_rows from v_databases ";
+		$sql .= "where database_type = 'odbc' ";
+		if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+		$prep_statement = $db->prepare($sql);
+		if ($prep_statement) {
+			$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] > 0) {
+				$odbc_num_rows = $row['num_rows'];
+
+				$sql = "select * from v_databases ";
+				$sql .= "where database_type = 'odbc' ";
+				$prep_statement = $db->prepare(check_sql($sql));
+				$prep_statement->execute();
+				$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+				foreach ($result as &$row) {
+					$dsn_name = $row["database_name"];
+					$dsn_username = $row["database_username"];
+					$dsn_password = $row["database_password"];
+					break; //limit to 1 row
+				}
+				unset ($prep_statement);
+			}
+			else {
+				$odbc_num_rows = '0';
+			}
+		}
+
+	//config.lua
+		$fout = fopen($_SESSION['switch']['scripts']['dir']."/resources/config.lua","w");
+		$tmp = "\n";
+		$tmp .= "--switch directories\n";
+		if (strlen($_SESSION['switch']['sounds']['dir']) > 0) {
+			$tmp .= "	sounds_dir = \"".$_SESSION['switch']['sounds']['dir']."\";\n";
+		}
+		if (strlen($_SESSION['switch']['recordings']['dir']) > 0) {
+			$tmp .= "	recordings_dir = \"".$_SESSION['switch']['recordings']['dir']."\";\n";
+		}
+		$tmp .= "\n";
+		$tmp .= "--database connection info\n";
+		if (strlen($db_type) > 0) {	
+			$tmp .= "	db_type = \"".$db_type."\";\n";
+		}
+		if (strlen($db_name) > 0) {	
+			$tmp .= "	db_name = \"".$db_name."\";\n";
+		}
+		if (strlen($db_path) > 0) {	
+			$tmp .= "	db_path = \"".$db_path."\";\n";
+		}
+		if (strlen($dsn_name) > 0) {	
+			$tmp .= "	dsn_name = \"".$dsn_name."\";\n";
+		}
+		if (strlen($dsn_username) > 0) {	
+			$tmp .= "	dsn_username = \"".$dsn_username."\";\n";
+		}
+		if (strlen($dsn_password) > 0) {	
+			$tmp .= "	dsn_password = \"".$dsn_password."\";\n";
+		}
+		$tmp .= "\n";
+		$tmp .= "--additional info\n";
+		$tmp .= "	tmp_dir = \"".$tmp_dir."\";\n";
+		fwrite($fout, $tmp);
+		unset($tmp);
+		fclose($fout);
+
+	//config.js
+		$fout = fopen($_SESSION['switch']['scripts']['dir']."/resources/config.js","w");
+		$tmp = "\n";
+		$tmp .= "//switch directories\n";
+		$tmp .= "	var admin_pin = \"".$row["admin_pin"]."\";\n";
+		$tmp .= "	var sounds_dir = \"".$_SESSION['switch']['sounds']['dir']."\";\n";
+		$tmp .= "	var recordings_dir = \"".$_SESSION['switch']['recordings']['dir']."\";\n";
+		$tmp .= "\n";
+		$tmp = "//database connection info\n";
+		if (strlen($db_type) > 0) {	
+			$tmp .= "	var db_type = \"".$db_type."\";\n";
+		}
+		if (strlen($db_name) > 0) {	
+			$tmp .= "	var db_name = \"".$db_name."\";\n";
+		}
+		if (strlen($db_path) > 0) {	
+			$tmp .= "	var db_path = \"".$db_path."\";\n";
+		}
+		if (strlen($dsn_name) > 0) {	
+			$tmp .= "	var dsn_name = \"".$dsn_name."\";\n";
+		}
+		if (strlen($dsn_username) > 0) {	
+			$tmp .= "	var dsn_username = \"".$dsn_username."\";\n";
+		}
+		if (strlen($dsn_password) > 0) {	
+			$tmp .= "	var dsn_password = \"".$dsn_password."\";\n";
+		}
+		$tmp .= "\n";
+		$tmp .= "//additional info\n";
+		$tmp .= "	var tmp_dir = \"".$tmp_dir."\";\n";
+		fwrite($fout, $tmp);
+		unset($tmp);
+		fclose($fout);
+}
+?>

+ 50 - 0
core/upgrade/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 101 - 0
core/upgrade/upgrade.php

@@ -0,0 +1,101 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//check the permission
+	if(defined('STDIN')) {
+		$document_root = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
+		preg_match("/^(.*)\/core\/.*$/", $document_root, $matches);
+		$document_root = $matches[1];
+		set_include_path($document_root);
+		require_once "includes/require.php";
+		$_SERVER["DOCUMENT_ROOT"] = $document_root;
+		$display_type = 'text'; //html, text
+	}
+	else {
+		include "root.php";
+		require_once "includes/require.php";
+		require_once "includes/checkauth.php";
+		if (permission_exists('upgrade_schema') || permission_exists('upgrade_svn') || if_group("superadmin")) {
+			//echo "access granted";
+		}
+		else {
+			echo "access denied";
+			exit;
+		}
+	}
+
+//set the default
+	if (!isset($display_results)) {
+		$display_results = false;
+	}
+
+//include the header
+	if ($display_results) {
+		require_once "includes/header.php";
+	}
+
+if ($display_type == 'text') {
+	echo "\n";
+	echo "Upgrade\n";
+	echo "-----------------------------------------\n";
+	echo "\n";
+	echo "Database\n";
+}
+
+//upgrade the database schema
+	require_once "core/upgrade/upgrade_schema.php";
+
+//show the content
+	if ($display_type == 'html') {
+		echo "<div align='center'>\n";
+		echo "<table width='40%'>\n";
+		echo "<tr>\n";
+		echo "<th align='left'>Message</th>\n";
+		echo "</tr>\n";
+		echo "<tr>\n";
+		echo "<td class='row_style1'><strong>Upgrade Completed</strong></td>\n";
+		echo "</tr>\n";
+		echo "</table>\n";
+		echo "</div>\n";
+
+		echo "<br />\n";
+		echo "<br />\n";
+		echo "<br />\n";
+		echo "<br />\n";
+		echo "<br />\n";
+		echo "<br />\n";
+		echo "<br />\n";
+	}
+
+if ($display_type == 'text') {
+	echo "\n";
+}
+
+//include the footer
+	if ($display_results) {
+		require_once "includes/footer.php";
+	}
+?>

+ 188 - 0
core/upgrade/upgrade_domains.php

@@ -0,0 +1,188 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//check the permission
+	if(defined('STDIN')) {
+		$document_root = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
+		preg_match("/^(.*)\/core\/.*$/", $document_root, $matches);
+		$document_root = $matches[1];
+		set_include_path($document_root);
+		require_once "includes/require.php";
+		$_SERVER["DOCUMENT_ROOT"] = $document_root;
+		$display_type = 'text'; //html, text
+	}
+	else {
+		include "root.php";
+		require_once "includes/require.php";
+		require_once "includes/checkauth.php";
+		if (permission_exists('upgrade_schema') || permission_exists('upgrade_svn') || if_group("superadmin")) {
+			//echo "access granted";
+		}
+		else {
+			echo "access denied";
+			exit;
+		}
+	}
+
+//copy the files and directories from includes/install
+	require_once "includes/classes/install.php";
+	$install = new install;
+	$install->domain_uuid = $domain_uuid;
+	$install->domain_name = $domain;
+	$install->switch_conf_dir = $_SESSION['switch']['conf']['dir'];
+	$install->switch_scripts_dir = $_SESSION['switch']['scripts']['dir'];
+	$install->switch_sounds_dir = $_SESSION['switch']['sounds']['dir'];
+	$install->copy();
+	//print_r($install->result);
+
+//get the list of installed apps from the core and mod directories
+	$config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php");
+	$x=0;
+	foreach ($config_list as &$config_path) {
+		include($config_path);
+		$x++;
+	}
+
+//get the domain_uuid
+	$sql = "select * from v_domains ";
+	$prep_statement = $db->prepare($sql);
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach($result as $row) {
+		if (count($result) == 0) {
+			$_SESSION["domain_uuid"] = $row["domain_uuid"];
+			$_SESSION["domain_name"] = $row['domain_name'];
+		}
+		else {
+			if ($row['domain_name'] == $domain_array[0] || $row['domain_name'] == 'www.'.$domain_array[0]) {
+				$_SESSION["domain_uuid"] = $row["domain_uuid"];
+				$_SESSION["domain_name"] = $row['domain_name'];
+			}
+			$_SESSION['domains'][$row['domain_uuid']]['domain_uuid'] = $row['domain_uuid'];
+			$_SESSION['domains'][$row['domain_uuid']]['domain_name'] = $row['domain_name'];
+		}
+	}
+	unset($result, $prep_statement);
+
+//get the default settings
+	$sql = "select * from v_default_settings ";
+	$sql .= "where default_setting_enabled = 'true' ";
+	$prep_statement = $db->prepare($sql);
+	$prep_statement->execute();
+	$result_default_settings = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+
+//get the default recordings directory
+	foreach($result_default_settings as $row) {
+		$name = $row['default_setting_name'];
+		$category = $row['default_setting_category'];
+		$subcategory = $row['default_setting_subcategory'];
+		if ($category == 'switch' && $subcategory == 'recordings' && $name == 'dir') {
+			$switch_recordings_dir = $row['default_setting_value'];
+		}
+	}
+
+//loop through all domains
+	$sql = "select * from v_domains ";
+	$v_prep_statement = $db->prepare(check_sql($sql));
+	$v_prep_statement->execute();
+	$main_result = $v_prep_statement->fetchAll(PDO::FETCH_ASSOC);
+	$domain_count = count($main_result);
+	foreach ($main_result as &$row) {
+		//get the values from database and set them as php variables
+			$domain_uuid = $row["domain_uuid"];
+			$domain_name = $row["domain_name"];
+
+		//get the context
+			if ($domain_count == 1) {
+				$context = "default";
+			}
+			else {
+				$context = $domain_name;
+			}
+
+		//show the domain when display_type is set to text
+			if ($display_type == "text") {
+				echo "\n";
+				echo $domain_name;
+				echo "\n";
+			}
+
+		//get the default settings - this needs to be done to reset the session values back to the defaults for each domain in the loop
+			foreach($result_defaults_settings as $row) {
+				$name = $row['default_setting_name'];
+				$category = $row['default_setting_category'];
+				$subcategory = $row['default_setting_subcategory'];	
+				if (strlen($subcategory) == 0) {
+					$_SESSION[$category][$name] = $row['default_setting_value'];
+				}
+				else {
+					$_SESSION[$category][$subcategory][$name] = $row['default_setting_value'];
+				}
+			}
+
+		//get the domains settings
+			$sql = "select * from v_domain_settings ";
+			$sql .= "where domain_uuid = '".$domain_uuid."' ";
+			$sql .= "and domain_setting_enabled = 'true' ";
+			$prep_statement = $db->prepare($sql);
+			$prep_statement->execute();
+			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+			foreach($result as $row) {
+				$name = $row['domain_setting_name'];
+				$category = $row['domain_setting_category'];
+				$subcategory = $row['domain_setting_subcategory'];	
+				if (strlen($subcategory) == 0) {
+					//$$category[$name] = $row['domain_setting_value'];
+					$_SESSION[$category][$name] = $row['domain_setting_value'];
+				}
+				else {
+					//$$category[$subcategory][$name] = $row['domain_setting_value'];
+					$_SESSION[$category][$subcategory][$name] = $row['domain_setting_value'];
+				}
+			}
+
+		//set the recordings directory
+			if (strlen($switch_recordings_dir) > 1 && count($_SESSION["domains"]) > 1) {
+				$_SESSION['switch']['recordings']['dir'] = $switch_recordings_dir."/".$domain_name;
+			}
+
+		//get the list of installed apps from the core and mod directories and execute the php code in app_defaults.php
+			$default_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_defaults.php");
+			foreach ($default_list as &$default_path) {
+				include($default_path);
+			}
+		// synchronize the dialplan
+			if (function_exists('save_dialplan_xml')) {
+				save_dialplan_xml();
+			}
+	}
+	unset ($v_prep_statement);
+
+//clear the session variables
+	unset($_SESSION['domain']);
+	unset($_SESSION['switch']);
+
+?>

+ 71 - 0
core/upgrade/upgrade_schema.php

@@ -0,0 +1,71 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//check the permission
+	if(defined('STDIN')) {
+		$document_root = str_replace("\\", "/", $_SERVER["PHP_SELF"]);
+		preg_match("/^(.*)\/core\/.*$/", $document_root, $matches);
+		$document_root = $matches[1];
+		set_include_path($document_root);
+		require_once "includes/require.php";
+		$_SERVER["DOCUMENT_ROOT"] = $document_root;
+		$display_type = 'text'; //html, text
+	}
+	else {
+		include "root.php";
+		require_once "includes/require.php";
+		require_once "includes/checkauth.php";
+		if (permission_exists('upgrade_schema') || if_group("superadmin")) {
+			//echo "access granted";
+		}
+		else {
+			echo "access denied";
+			exit;
+		}
+		require_once "includes/header.php";
+		$display_type = 'html'; //html, text
+	}
+
+//set the default
+	if (!isset($display_results)) {
+		$display_results = true;
+	}
+
+//load the default database into memory and compare it with the active database
+	require_once "includes/lib_schema.php";
+	db_upgrade_schema ($db, $db_type, $db_name, $display_results);
+	unset($apps);
+
+//upgrade the domains
+	require_once "core/upgrade/upgrade_domains.php";
+
+if ($display_results && $display_type == "html") {
+	echo "<br />\n";
+	echo "<br />\n";
+	require_once "includes/footer.php";
+}
+
+?>

+ 296 - 0
core/upgrade/upgrade_svn.php

@@ -0,0 +1,296 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+/*
+   $mtime = microtime();
+   $mtime = explode(" ",$mtime);
+   $mtime = $mtime[1] + $mtime[0];
+   $start_time = $mtime;
+*/
+
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/phpsvnclient/phpsvnclient.php";
+
+if (!isset($display_results)) {
+	$display_results = true;
+}
+
+if (strlen($_SERVER['HTTP_USER_AGENT']) > 0) {
+	require_once "includes/checkauth.php";
+	if (permission_exists('upgrade_svn') || if_group("superadmin")) {
+		//echo "access granted";
+	}
+	else {
+		echo "access denied";
+		exit;
+	}
+}
+else {
+	$display_results = false; //true false
+	//$display_type = 'csv'; //html, csv
+}
+
+ini_set('display_errors', '0');
+ini_set(max_execution_time,3600);
+clearstatcache();
+
+if ($display_results) {
+	require_once "includes/header.php";
+}
+
+$svn_url = 'http://fusionpbx.googlecode.com/svn/';
+$svn_path = '/trunk/fusionpbx/';
+
+//set path_array
+	$sql = "";
+	$sql .= "select * from v_src ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$path = trim($row["path"]);
+		$path_array[$path][type] = $row["type"];
+		$path_array[$path][last_mod] = $row["last_mod"];
+	}
+	unset ($prep_statement);
+
+$svn  = new phpsvnclient($svn_url);
+//$svn_version = $svn->getVersion();
+$svn_directory_tree = $svn->getDirectoryTree($svn_path);
+
+if ($display_results) {
+	echo "<table width='100%' border='0' cellpadding='20' cellspacing='0'>\n";
+	echo "<tr>\n";
+	echo "<th>Type</th>\n";
+	echo "<th>Last Modified</th>\n";
+	echo "<th>Path</th>\n";
+	echo "<th>Status/Size</th>\n";
+	echo "<th>MD5 file</th>\n";
+	echo "<th>MD5 xml</th>\n";
+	echo "<th>Action</th>\n";
+	echo "<tr>\n";
+}
+
+//$db->beginTransaction();
+foreach ($svn_directory_tree as &$row) {
+	$md5_match = false;
+	$xml_type = $row[type];
+	$xml_relative_path = trim(str_replace(trim($svn_path,'/'),"",$row[path]));
+	$xml_last_mod = $row[last_mod];
+	$new_path = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH . $xml_relative_path;
+
+	if (file_exists($new_path)) {
+		$exists = true;
+	}
+	else {
+		$exists = false;
+	}	
+	
+	if ( $xml_type == 'file' ) {
+		$xml_file_path = trim($row[path]); //we need this to download the file from svn
+		$md5_xml = $row[md5];
+		if ($exists) {
+			$md5_file = md5_file($new_path);
+			if ($md5_xml == $md5_file){ 
+				$md5_match = true; 
+			}
+		}
+		else { 
+			$md5_match = false;//???
+			$md5_file = '';
+		}
+	}
+	else {
+		$md5_xml = '';//directory has no md5
+	}
+
+	if (strlen($xml_relative_path) > 0) {
+		if ($display_results) {
+			if ($xml_type == 'file' && !$md5_match) {
+				echo "<tr>\n";
+				echo "<td class='row_style1'>$xml_type</td>\n";
+				echo "<td class='row_style1'>$xml_last_mod</td>\n";
+				echo "<td class='row_style1'>$xml_relative_path</td>\n";
+				echo "<td class='row_style1'>$exists</td>\n";
+				//echo "<td class='row_style1'>$xml_size</td>\n";
+				echo "<td class='row_style1'>$md5_file</td>\n";
+				echo "<td class='row_style1'>$md5_xml</td>\n";
+				echo "<td class='row_style1'>$md5_match </td>\n";
+				//file_get_contents($svn_url.$svn_path.$xml_relative_path);</td>\n";
+				echo "<td class='row_style1'>\n";
+			}
+		}
+
+		//update the v_scr data
+		if ($xml_type=='file' && strlen($path_array[$xml_relative_path]['type']) == 0) { 
+			//insert a new record into the src table
+			$sql ="";
+			$sql .= "insert into v_src ";
+			$sql .= "(";
+			$sql .= "domain_uuid, ";
+			$sql .= "type, ";
+			$sql .= "last_mod, ";
+			$sql .= "path ";
+			$sql .= ")";
+			$sql .= "values ";
+			$sql .= "(";
+			$sql .= "'$domain_uuid', ";
+			$sql .= "'$xml_type', ";
+			$sql .= "'$xml_last_mod', ";
+			$sql .= "'$xml_relative_path' ";
+			$sql .= ")";
+			//echo "$sql<br />\n";
+		} 
+		else {
+			if ($xml_type=='file' && !$md5_match) {//update changed files
+				//update the src table
+				$sql =""; 
+				$sql .= "update v_src set ";
+				$sql .= "type = '$xml_type', ";
+				$sql .= "last_mod = '$xml_last_mod' ";
+				$sql .= "where domain_uuid = '$domain_uuid' ";
+				$sql .= "and path = '$xml_relative_path' ";
+			}
+		}
+		//if the path exists and is a file
+		if ($exists && $xml_type == 'file') {
+			//the md5 of the xml file and the local file do not match
+			if ($md5_match) {
+				if ($display_results) {
+					//echo "current "; //the file is up to date
+				}
+			}
+			else {
+/*				if ($xml_file_path == '/core/upgrade/upgrade_svn.php' ) {
+					if ($display_results) {
+						echo "white list"; //the file is up to date
+					}
+					continue;
+				}
+*/				//get the remote file contents
+				$file_content = $svn->getFile($xml_file_path);
+				
+				//the md5 of the local file and the remote content match
+				if (md5_file($new_path) == md5($file_content)) {
+					if ($display_results) {
+						//echo "current 2 "; //the file is up to date
+					}
+				}
+				else {
+					//make sure the string matches the file md5 that was recorded.
+					if (strlen($file_content) > 0) {
+						$tmp_fh = fopen($new_path, 'w');
+						fwrite($tmp_fh, $file_content);
+						fclose($tmp_fh);
+					}
+
+					//display the results
+					if ($display_results) {
+						echo "<strong style='color: #FF0000;'> ";
+						if (is_writable($new_path)) {
+							echo "updated ";
+						}
+						else {
+							echo "not writable ";
+						}
+						echo "</strong>";
+					}
+				}
+			}
+			//unset the variable
+			unset($file_content);
+		}
+		else {
+			
+			//if the path does not exist create it and then add it to the database
+			//echo "file is missing |";
+			if ($xml_type == 'directory' && !$exists) {
+				//make sure the directory exists
+					mkdir (dirname($new_path), 0755, true);
+			}
+			if ($xml_type == 'file') {
+				//make sure the directory exists
+					if (!is_dir(dirname($new_path))){
+						mkdir (dirname($new_path), 0755, true);
+					}
+
+				//get the remote file contents
+					$file_content = $svn->getFile($xml_file_path);
+
+				//make sure we got some data.
+					if (strlen($file_content) > 0) {
+						$tmp_fh = fopen($new_path, 'w');
+						fwrite($tmp_fh, $file_content);
+						fclose($tmp_fh);
+					}
+
+					if ($display_results) {
+						echo "<strong style='color: #FF0000;'> ";
+						if (is_writable($new_path)) {
+							echo "added/restored";
+						}
+						else {
+							echo "not writable ";
+						}
+						echo "</strong>";
+						//echo "<br />\n";
+					}
+				//unset the variable
+					unset($file_content);
+			}
+		}
+
+		if ($display_results) {
+			if ($xml_type == 'file' && !$md5_match) {
+				echo "&nbsp;";
+				echo "</td>\n";
+				echo "<tr>\n";
+			}
+		}
+		//update the database
+		if (strlen($sql) > 0) {
+			$db->exec(check_sql($sql));
+			//echo "$sql<br />\n";
+		}
+		unset($sql);
+	}
+}
+//$db->commit();
+//clearstatcache();
+if ($display_results) {
+	echo "</table>\n";
+	require_once "includes/footer.php";
+}
+/*
+   $mtime = microtime();
+   $mtime = explode(" ",$mtime);
+   $mtime = $mtime[1] + $mtime[0];
+   $end_time = $mtime;
+   $total_time = ($end_time - $start_time);
+   echo "This page was created in ".$total_time." seconds";
+*/
+?>

+ 356 - 0
core/users/app_config.php

@@ -0,0 +1,356 @@
+<?php
+	//application details
+		$apps[$x]['name'] = "User Manager";
+		$apps[$x]['uuid'] = '112124b3-95c2-5352-7e9d-d14c0b88f207';
+		$apps[$x]['category'] = 'Core';
+		$apps[$x]['subcategory'] = '';
+		$apps[$x]['version'] = '';
+		$apps[$x]['license'] = 'Mozilla Public License 1.1';
+		$apps[$x]['url'] = 'http://www.fusionpbx.com';
+		$apps[$x]['description']['en'] = 'Add, edit, delete, and search for users.';
+
+	//menu details
+		$apps[$x]['menu'][0]['title']['en'] = 'Login';
+		$apps[$x]['menu'][0]['uuid'] = 'c85bf816-b88d-40fa-8634-11b456928afa';
+		$apps[$x]['menu'][0]['parent_uuid'] = '';
+		$apps[$x]['menu'][0]['category'] = 'internal';
+		$apps[$x]['menu'][0]['path'] = '/login.php';
+		$apps[$x]['menu'][0]['groups'][] = 'public';
+		$apps[$x]['menu'][0]['order'] = '99';
+
+		$apps[$x]['menu'][1]['title']['en'] = 'Logout';
+		$apps[$x]['menu'][1]['uuid'] = '0d29e9f4-0c9b-9d8d-cd2d-454899dc9bc4';
+		$apps[$x]['menu'][1]['parent_uuid'] = '02194288-6d56-6d3e-0b1a-d53a2bc10788';
+		$apps[$x]['menu'][1]['category'] = 'internal';
+		$apps[$x]['menu'][1]['path'] = '/logout.php';
+		$apps[$x]['menu'][1]['groups'][] = 'user';
+		$apps[$x]['menu'][1]['groups'][] = 'admin';
+		$apps[$x]['menu'][1]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][2]['title']['en'] = 'User Manager';
+		$apps[$x]['menu'][2]['uuid'] = '0d57cc1e-1874-47b9-7ddd-fe1f57cec99b';
+		$apps[$x]['menu'][2]['parent_uuid'] = 'bc96d773-ee57-0cdd-c3ac-2d91aba61b55';
+		$apps[$x]['menu'][2]['category'] = 'internal';
+		$apps[$x]['menu'][2]['path'] = '/core/users/index.php';
+		$apps[$x]['menu'][2]['groups'][] = 'admin';
+		$apps[$x]['menu'][2]['groups'][] = 'superadmin';
+
+		$apps[$x]['menu'][3]['title']['en'] = 'Group Manager';
+		$apps[$x]['menu'][3]['uuid'] = '3b4acc6d-827b-f537-bf21-0093d94ffec7';
+		$apps[$x]['menu'][3]['parent_uuid'] = '594d99c5-6128-9c88-ca35-4b33392cec0f';
+		$apps[$x]['menu'][3]['category'] = 'internal';
+		$apps[$x]['menu'][3]['path'] = '/core/users/grouplist.php';
+		$apps[$x]['menu'][3]['groups'][] = 'superadmin';
+
+	//permission details
+		$apps[$x]['permissions'][0]['name'] = 'user_view';
+		$apps[$x]['permissions'][0]['groups'][] = 'admin';
+		$apps[$x]['permissions'][0]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][1]['name'] = 'user_add';
+		$apps[$x]['permissions'][1]['groups'][] = 'admin';
+		$apps[$x]['permissions'][1]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][2]['name'] = 'user_edit';
+		$apps[$x]['permissions'][2]['groups'][] = 'admin';
+		$apps[$x]['permissions'][2]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][3]['name'] = 'user_delete';
+		$apps[$x]['permissions'][3]['groups'][] = 'admin';
+		$apps[$x]['permissions'][3]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][4]['name'] = 'group_view';
+		$apps[$x]['permissions'][4]['groups'][] = 'admin';
+		$apps[$x]['permissions'][4]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][5]['name'] = 'group_add';
+		$apps[$x]['permissions'][5]['groups'][] = 'admin';
+		$apps[$x]['permissions'][5]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][6]['name'] = 'group_edit';
+		$apps[$x]['permissions'][6]['groups'][] = 'admin';
+		$apps[$x]['permissions'][6]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][7]['name'] = 'group_delete';
+		$apps[$x]['permissions'][7]['groups'][] = 'admin';
+		$apps[$x]['permissions'][7]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][8]['name'] = 'group_member_view';
+		$apps[$x]['permissions'][8]['groups'][] = 'admin';
+		$apps[$x]['permissions'][8]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][9]['name'] = 'group_member_add';
+		$apps[$x]['permissions'][9]['groups'][] = 'admin';
+		$apps[$x]['permissions'][9]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][10]['name'] = 'group_member_delete';
+		$apps[$x]['permissions'][10]['groups'][] = 'admin';
+		$apps[$x]['permissions'][10]['groups'][] = 'superadmin';
+
+		$apps[$x]['permissions'][11]['name'] = 'group_permissions';
+		$apps[$x]['permissions'][11]['groups'][] = 'superadmin';
+
+	//schema details
+		$y = 0; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_users';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'username';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'password';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'salt';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'contact_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_contacts';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'contact_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'user_email';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'useremail';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'user_status';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'userstatus';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'user_time_zone';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'usertimezone';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'user_add_user';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'useradduser';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'user_add_date';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'useradddate';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+		$y = 1; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_groups';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'group_name';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'groupid';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'group_description';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'groupdesc';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+		$y = 2; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_group_users';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_user_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'group_name';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'groupid';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		//$z++;
+		//$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_uuid';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		//$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'username';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+		$y = 3; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_group_permissions';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_permission_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'id';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'group_permission_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'serial';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'integer';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'INT NOT NULL AUTO_INCREMENT';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['table'] = 'v_domains';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['reference']['field'] = 'domain_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'v_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$apps[$x]['db'][$y]['fields'][$z]['deprecated'] = 'true';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name']['text'] = 'permission_name';
+		$apps[$x]['db'][$y]['fields'][$z]['name']['deprecated'] = 'permission_id';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		//$apps[$x]['db'][$y]['fields'][$z]['name'] = 'group_uuid';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		//$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		//$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		//$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+
+		$y = 4; //table array index
+		$z = 0; //field array index
+		$apps[$x]['db'][$y]['table'] = 'v_user_settings';
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'primary';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['pgsql'] = 'uuid';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['sqlite'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['type']['mysql'] = 'char(36)';
+		$apps[$x]['db'][$y]['fields'][$z]['key']['type'] = 'foreign';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_category';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the category.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_subcategory';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the subcategory.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_name';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the name.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_value';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = 'Enter the value.';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_enabled';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+		$z++;
+		$apps[$x]['db'][$y]['fields'][$z]['name'] = 'user_setting_description';
+		$apps[$x]['db'][$y]['fields'][$z]['type'] = 'text';
+		$apps[$x]['db'][$y]['fields'][$z]['description']['en'] = '';
+?>

+ 169 - 0
core/users/app_defaults.php

@@ -0,0 +1,169 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+//if the are no groups add the default groups
+	$sql = "SELECT * FROM v_groups ";
+	$sql .= "WHERE domain_uuid = '$domain_uuid' ";
+	$sub_result = $db->query($sql)->fetch();
+	$prep_statement = $db->prepare(check_sql($sql));
+	if ($prep_statement) {
+		$prep_statement->execute();
+		$sub_result = $prep_statement->fetchAll(PDO::FETCH_ASSOC);
+		if (count($sub_result) == 0) {
+			$x = 0;
+			$tmp[$x]['group_name'] = 'superadmin';
+			$tmp[$x]['group_description'] = 'Super Administrator Group';
+			$x++;
+			$tmp[$x]['group_name'] = 'admin';
+			$tmp[$x]['group_description'] = 'Administrator Group';
+			$x++;
+			$tmp[$x]['group_name'] = 'user';
+			$tmp[$x]['group_description'] = 'User Group';
+			$x++;
+			$tmp[$x]['group_name'] = 'public';
+			$tmp[$x]['group_description'] = 'Public Group';
+			$x++;
+			$tmp[$x]['group_name'] = 'agent';
+			$tmp[$x]['group_description'] = 'Call Center Agent Group';
+			foreach($tmp as $row) {
+				if (strlen($row['group_name']) > 0) {
+					$sql = "insert into v_groups ";
+					$sql .= "(";
+					$sql .= "domain_uuid, ";
+					$sql .= "group_uuid, ";
+					$sql .= "group_name, ";
+					$sql .= "group_description ";
+					$sql .= ")";
+					$sql .= "values ";
+					$sql .= "(";
+					$sql .= "'$domain_uuid', ";
+					$sql .= "'".uuid()."', ";
+					$sql .= "'".$row['group_name']."', ";
+					$sql .= "'".$row['group_description']."' ";
+					$sql .= ")";
+					$db->exec(check_sql($sql));
+					unset($sql);
+				}
+			}
+		}
+	}
+	unset($prep_statement, $sub_result);
+
+//if there are no permissions listed in v_group_permissions then set the default permissions
+	$sql = "select count(*) as count from v_group_permissions ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$prep_statement = $db->prepare($sql);
+	$prep_statement->execute();
+	$sub_result = $prep_statement->fetch(PDO::FETCH_ASSOC);
+	unset ($prep_statement);
+	if ($sub_result['count'] > 0) {
+		if ($display_type == "text") {
+			echo "	Group Permissions:	no change\n";
+		}
+	}
+	else {
+		if ($display_type == "text") {
+			echo "	Group Permissions:	added\n";
+		}
+		//no permissions found add the defaults
+		$db->beginTransaction();
+		foreach($apps as $app) {
+			foreach ($app['permissions'] as $sub_row) {
+				foreach ($sub_row['groups'] as $group) {
+					//add the record
+					$sql = "insert into v_group_permissions ";
+					$sql .= "(";
+					$sql .= "group_permission_uuid, ";
+					$sql .= "domain_uuid, ";
+					$sql .= "permission_name, ";
+					$sql .= "group_name ";
+					$sql .= ")";
+					$sql .= "values ";
+					$sql .= "(";
+					$sql .= "'".uuid()."', ";
+					$sql .= "'$domain_uuid', ";
+					$sql .= "'".$sub_row['name']."', ";
+					$sql .= "'".$group."' ";
+					$sql .= ")";
+					$db->exec($sql);
+					unset($sql);
+				}
+			}
+		}
+		$db->commit();
+	}
+
+//find rows that have a null user_uuid and set the correct user_uuid
+	$sql = "select * from v_group_users ";
+	$sql .= "where domain_uuid = '".$_SESSION['domain_uuid']."' ";
+	$sql .= "and user_uuid is null; ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	if ($prep_statement) {
+			$prep_statement->execute();
+			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+			foreach($result as $row) {
+				if (strlen($row['username']) > 0) {
+					//get the user_uuid
+						$sql = "select user_uuid from v_users ";
+						$sql .= "where username = '".$row['username']."' ";
+						$prep_statement_sub = $db->prepare($sql);
+						$prep_statement_sub->execute();
+						$sub_result = $prep_statement_sub->fetch(PDO::FETCH_ASSOC);
+						unset ($prep_statement_sub);
+						$user_uuid = $sub_result['user_uuid'];
+					//set the user uuid
+						$sql = "update v_group_users set ";
+						$sql .= "user_uuid = '".$user_uuid."' ";
+						$sql .= "where username = '".$row['username']."'; ";
+						$db->exec($sql);
+						unset($sql);
+				}
+				else {
+					//get the number of users
+						$sql = "select count(*) as num_rows from v_users ";
+						$prep_statement_sub = $db->prepare($sql);
+						$prep_statement_sub->execute();
+						$sub_result = $prep_statement_sub->fetch(PDO::FETCH_ASSOC);
+						unset ($prep_statement_sub);
+						$num_rows = $sub_result['num_rows'];
+					if ($num_rows == 1) {
+						//get the user_uuid
+							$sql = "select user_uuid from v_users ";
+							$prep_statement_sub = $db->prepare($sql);
+							$prep_statement_sub->execute();
+							$sub_result = $prep_statement_sub->fetch(PDO::FETCH_ASSOC);
+							unset ($prep_statement_sub);
+							$user_uuid = $sub_result['user_uuid'];
+						//set the user uuid
+							$sql = "update v_group_users set ";
+							$sql .= "user_uuid = '".$user_uuid."' ";
+							$db->exec($sql);
+							unset($sql);
+					}
+				}
+			}
+	}
+?>

+ 275 - 0
core/users/group_permissions.php

@@ -0,0 +1,275 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_permissions') || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+require_once "includes/header.php";
+require_once "includes/paging.php";
+
+//get the list of installed apps from the core and mod directories
+	$config_list = glob($_SERVER["DOCUMENT_ROOT"] . PROJECT_PATH . "/*/*/app_config.php");
+	$x=0;
+	foreach ($config_list as &$config_path) {
+		include($config_path);
+		$x++;
+	}
+
+//if there are no permissions listed in v_group_permissions then set the default permissions
+	$sql = "";
+	$sql .= "select count(*) as count from v_group_permissions ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$group_permission_count = $row["count"];
+		break; //limit to 1 row
+	}
+	unset ($prep_statement);
+	if ($group_permission_count == 0) {
+		//no permissions found add the defaults
+		foreach($apps as $app) {
+			foreach ($app['permissions'] as $row) {
+				foreach ($row['groups'] as $group) {
+					//add the record
+					$sql = "insert into v_group_permissions ";
+					$sql .= "(";
+					$sql .= "group_permission_uuid, ";
+					$sql .= "domain_uuid, ";
+					$sql .= "permission_name, ";
+					$sql .= "group_name ";
+					$sql .= ")";
+					$sql .= "values ";
+					$sql .= "(";
+					$sql .= "'".uuid()."', ";
+					$sql .= "'$domain_uuid', ";
+					$sql .= "'".$row['name']."', ";
+					$sql .= "'".$group."' ";
+					$sql .= ")";
+					$db->exec(check_sql($sql));
+					unset($sql);
+				}
+			}
+		}
+	}
+
+//get the http values and set them as php variables
+	$group_name = $_REQUEST['group_name'];
+	
+//get the permissions assigned to this group
+	$sql = "";
+	$sql .= " select * from v_group_permissions ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and group_name = '$group_name' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$permission_name = $row["permission_name"];
+		$permissions_db[$permission_name] = "true";
+	}
+//show the db checklist
+	//echo "<pre>";
+	//print_r($permissions_db);
+	//echo "</pre>";
+
+//list all the permissions in the database
+	foreach($apps as $app) {
+		foreach ($app['permissions'] as $row) {
+			if ($permissions_db[$row['name']] == "true") {
+				$permissions_db_checklist[$row['name']] = "true";
+			}
+			else {
+				$permissions_db_checklist[$row['name']] = "false";
+			}
+		}
+	}
+//show the db checklist
+	//echo "<pre>";
+	//print_r($permissions_db_checklist);
+	//echo "</pre>";
+
+//process the http post
+	if (count($_POST)>0) {
+		foreach($_POST['permissions_form'] as $permission) {
+			$permissions_form[$permission] = "true";
+		}
+
+		//list all the permissions
+			foreach($apps as $app) {
+				foreach ($app['permissions'] as $row) {
+					if ($permissions_form[$row['name']] == "true") {
+						$permissions_form_checklist[$row['name']] = "true";
+					}
+					else {
+						$permissions_form_checklist[$row['name']] = "false";
+					}
+				}
+			}
+		//show the form db checklist
+			//echo "<pre>";
+			//print_r($permissions_form_checklist);
+			//echo "</pre>";
+		
+		//list all the permissions
+			foreach($apps as $app) {
+				foreach ($app['permissions'] as $row) {
+					$permission = $row['name'];
+					if ($permissions_db_checklist[$permission] == "true" && $permissions_form_checklist[$permission] == "true") {
+						//matched do nothing
+					}
+					if ($permissions_db_checklist[$permission] == "false" && $permissions_form_checklist[$permission] == "false") {
+						//matched do nothing
+					}
+					if ($permissions_db_checklist[$permission] == "true" && $permissions_form_checklist[$permission] == "false") {
+						//delete the record
+							$sql = "delete from v_group_permissions ";
+							$sql .= "where domain_uuid = '$domain_uuid' ";
+							$sql .= "and group_name = '$group_name' ";
+							$sql .= "and permission_name = '$permission' ";
+							$db->exec(check_sql($sql));
+							unset($sql);
+						//set the permission to false in the permissions_db_checklist
+							$permissions_db_checklist[$permission] = "false";
+					}
+					if ($permissions_db_checklist[$permission] == "false" && $permissions_form_checklist[$permission] == "true") {
+						//add the record
+							$sql = "insert into v_group_permissions ";
+							$sql .= "(";
+							$sql .= "group_permission_uuid, ";
+							$sql .= "domain_uuid, ";
+							$sql .= "permission_name, ";
+							$sql .= "group_name ";
+							$sql .= ")";
+							$sql .= "values ";
+							$sql .= "(";
+							$sql .= "'".uuid()."', ";
+							$sql .= "'$domain_uuid', ";
+							$sql .= "'$permission', ";
+							$sql .= "'$group_name' ";
+							$sql .= ")";
+							$db->exec(check_sql($sql));
+							unset($sql);
+						//set the permission to true in the permissions_db_checklist
+							$permissions_db_checklist[$permission] = "true";
+					}
+				}
+			}
+	}
+
+//show the content
+	echo "<form method='post' name='frm' action=''>\n";
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr class='border'>\n";
+	echo "	<td align=\"center\">\n";
+	echo "		<br>";
+
+	echo "<table width='100%' border='0'>\n";
+	echo "<tr>\n";
+	echo "<td width='50%' align=\"left\" nowrap=\"nowrap\"><b>Group Permission List for $group_name</b></td>\n";
+	echo "<td width='50%' align=\"right\">\n";
+	echo "	<input type='button' class='btn' name='' alt='back' onclick=\"window.location='grouplist.php'\" value='Back'> ";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align=\"left\" colspan='2'>\n";
+	echo "	Assign permissions to groups.<br /><br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "</tr></table>\n";
+
+	echo "<br />\n";
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='left'>\n";
+
+	//list all the permissions
+		foreach($apps as $app) {
+			$app_name = $app['name'];
+			$description = $app['description']['en'];
+
+			echo "<strong>".$app_name."</strong><br />\n";
+			echo "".$description."<br /><br />";
+			echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+			echo "<tr>\n";
+			echo "<th>Permissions</th>\n";
+			echo "<th>Description</th>\n";
+			echo "<tr>\n";
+
+			foreach ($app['permissions'] as $row) {
+				echo "<tr >\n";
+				echo "	<td valign='top' style='width:250px' nowrap='nowrap' class='".$row_style[$c]."'>\n";
+				if ($permissions_db_checklist[$row['name']] == "true") {
+					echo "		<input type='checkbox' name='permissions_form[]' checked='checked' value='".$row['name']."'>\n";
+				}
+				else {
+					echo "		<input type='checkbox' name='permissions_form[]' value='".$row['name']."'>\n";
+				}
+				echo "		&nbsp; ".$row['name']."\n";
+				echo "	</td>\n";
+				echo "	<td valign='top' class='".$row_style[$c]."'>\n";
+				echo "		&nbsp; ".$row['description']."\n";
+				echo "	</td>\n";
+				echo "</tr>\n";
+				if ($c==0) { $c=1; } else { $c=0; }
+			}
+			
+			echo "<tr>\n";
+			echo "	<td colspan='3' align='right'>\n";
+			echo "		<input type='submit' name='submit' class='btn' value='Save'>\n";
+			echo "	</td>\n";
+			echo "</tr>\n";
+			echo "</table>";
+			echo "<br />\n";
+		} //end foreach
+		unset($sql, $result, $row_count);
+
+	echo "</div>";
+	echo "<br><br>";
+	echo "<br><br>";
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "<form>\n";
+
+	echo "<br><br>";
+
+//show the footer
+	require_once "includes/footer.php";
+
+?>

+ 134 - 0
core/users/groupadd.php

@@ -0,0 +1,134 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_add')) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//get the http values and set them as variables
+	$path = check_str($_GET["path"]);
+	$msg = check_str($_GET["msg"]);
+	$group_name = check_str($_POST["group_name"]);
+	$group_description = check_str($_POST["group_description"]);
+
+if (strlen($group_name) > 0) {
+	$sql_insert = "insert into v_groups ";
+	$sql_insert .= "(";
+	$sql_insert .= "domain_uuid, ";
+	$sql_insert .= "group_uuid, ";
+	$sql_insert .= "group_name, ";
+	$sql_insert .= "group_description ";
+	$sql_insert .= ")";
+	$sql_insert .= "values ";
+	$sql_insert .= "(";
+	$sql_insert .= "'$domain_uuid', ";
+	$sql_insert .= "'".uuid()."', ";
+	$sql_insert .= "'$group_name', ";
+	$sql_insert .= "'$group_description' ";
+	$sql_insert .= ")";
+	if (!$db->exec($sql_insert)) {
+		//echo $db->errorCode() . "<br>";
+		$info = $db->errorInfo();
+		print_r($info);
+		// $info[0] == $db->errorCode() unified error code
+		// $info[1] is the driver specific error code
+		// $info[2] is the driver specific error string
+	}
+
+	//redirect the user
+		require_once "includes/header.php";
+		echo "<meta http-equiv=\"refresh\" content=\"2;url=grouplist.php\">\n";
+		echo "<div align='center'>\n";
+		echo "Group Added\n";
+		echo "</div>\n";
+		require_once "includes/footer.php";
+		return;
+}
+
+//include the header
+	include "includes/header.php";
+
+//show the content
+	echo "<br><br>";
+	echo "<div align='center'>";
+
+	echo "<table width='100%' cellpadding='6' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td align='left'>\n";
+	echo "			Please choose a group name. ";
+	echo "		</td>\n";
+	echo "		<td align='right'>\n";
+	echo "			<input type='button' class='btn' name='' alt='back' onclick=\"window.location='grouplist.php'\" value='Back'> ";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+	echo "<br>";
+
+	echo "<form name='login' METHOD=\"POST\" action=\"groupadd.php\">\n";
+	echo "<table width='100%' cellpadding='6' cellspacing='0'>\n";
+	echo "<tr>\n";
+	echo "<td width='30%' class='vncellreq'>\n";
+	echo "Group Name:\n";
+	echo "</td>\n";
+	echo "<td width='70%' align='left' class='vtable'>\n";
+	echo "  <input type=\"text\" class='formfld' name=\"group_name\">\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td class='vncellreq'>\n";
+	echo "Description:\n";
+	echo "</td>\n";
+	echo "<td align='left' class='vtable'>\n";
+	echo "<textarea name='group_description' class='formfld'></textarea>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "<tr>\n";
+	echo "<td>\n";
+	echo "</td>\n";
+	echo "<td align=\"right\">\n";
+	echo "  <input type=\"hidden\" name=\"path\" value=\"$path\">\n";
+	echo "  <input type=\"submit\" class='btn' value=\"Save\">\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "</table>\n";
+	echo "</form>";
+	echo "</div>";
+
+	echo "<br><br>";
+	echo "<br><br>";
+
+//include the footer
+	include "includes/footer.php";
+
+?>

+ 56 - 0
core/users/groupdelete.php

@@ -0,0 +1,56 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_delete') || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//get the http value and set as a variable
+	$id = check_str($_GET["id"]);
+
+//delete the group
+	$sqldelete = "delete from v_groups ";
+	$sqldelete .= "where domain_uuid = '$domain_uuid' ";
+	$sqldelete .= "and group_uuid = '$id' ";
+	if (!$db->exec($sqldelete)) {
+		//echo $db->errorCode() . "<br>";
+		$info = $db->errorInfo();
+		print_r($info);
+		// $info[0] == $db->errorCode() unified error code
+		// $info[1] is the driver specific error code
+		// $info[2] is the driver specific error string
+	}
+
+//redirect the user
+	header("Location: grouplist.php");
+
+?>

+ 137 - 0
core/users/grouplist.php

@@ -0,0 +1,137 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+
+//check the permissions
+	require_once "includes/checkauth.php";
+	if (if_group("admin") || if_group("superadmin")) {
+		//access allowed
+	}
+	else {
+		echo "access denied";
+		return;
+	}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div class='' style='padding:0px;'>\n";
+	echo "<table width='100%'>";
+	echo "<td>";
+
+	echo "<table width='100%' border='0'><tr>";
+	echo "<td width='50%'><b>Group List</b></td>";
+	echo "<td width='50%' align='right'>";
+	if (permission_exists('user_view')) {
+		echo "  <input type='button' class='btn' onclick=\"window.location='index.php'\" value='User Manager'>";
+	}
+	echo "</td>\n";
+	echo "</tr></table>";
+
+	$sql = "SELECT * FROM v_groups ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	$strlist = "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+	$strlist .= "<tr class='border'>\n";
+	$strlist .= "	<th align=\"left\" nowrap> &nbsp; Group Name &nbsp; </th>\n";
+	$strlist .= "	<th align=\"left\" nowrap> &nbsp; Group Description &nbsp; </th>\n";
+	$strlist .= "	<th align=\"center\" nowrap>&nbsp;</th>\n";
+
+	$strlist .= "	<td width='22px' align=\"right\" nowrap>\n";
+	if (permission_exists('group_add')) {
+		$strlist .= "	<a href='groupadd.php' alt='add'>$v_link_label_add</a>\n";
+	}
+	$strlist .= "	</td>\n";
+	$strlist .= "</tr>\n";
+
+	$count = 0;
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$group_name = $row["group_name"];
+		$group_uuid = $row["group_uuid"];
+		$group_description = $row["group_description"];
+		if (strlen($group_name) == 0) { $group_name = "&nbsp;"; }
+		if (strlen($group_description) == 0) { $group_description = "&nbsp;"; }
+		$group_description = wordwrap($group_description, 50, "<br />\n");
+
+		if (!if_group("superadmin") && $group_name == "superadmin") {
+			//hide the superadmin group from non superadmin's
+		}
+		else {
+			$strlist .= "<tr>";
+			$strlist .= "<td class='".$row_style[$c]."' align=\"left\" class='' nowrap> &nbsp; $group_name &nbsp; </td>\n";
+			$strlist .= "<td class='".$row_style[$c]."' align=\"left\" class='' nowrap> &nbsp;  $group_description &nbsp; </td>\n";
+
+			$strlist .= "<td class='".$row_style[$c]."' align=\"center\" nowrap>\n";
+			if (permission_exists('group_add') || if_group("superadmin")) {
+				$strlist .= "&nbsp;<a class='' href='group_permissions.php?group_name=$group_name' title='Group Permissions'>Permissions</a>&nbsp;&nbsp;";
+			}
+			if (permission_exists('group_member_view') || if_group("superadmin")) {
+				$strlist .= "&nbsp;<a class='' href='groupmembers.php?group_name=$group_name' title='Group Members'>Members</a>&nbsp;";
+			}
+			$strlist .= "</td>\n";
+
+			$strlist .= "<td align=\"right\" nowrap>\n";
+			$strlist .= "<a href='groupdelete.php?id=$group_uuid' onclick=\"return confirm('Do you really want to delete this?')\" alt='delete'>$v_link_label_delete</a>\n";
+
+			$strlist .= "</td>\n";
+			$strlist .= "</tr>\n";
+		}
+		if ($c==0) { $c=1; } else { $c=0; }
+		$count++;
+	}
+
+	$strlist .= "<tr>\n";
+	$strlist .= "<td colspan='4' align='right' height='20'>\n";
+	if (permission_exists('group_add')) {
+		$strlist .= "	<a href='groupadd.php' alt='add'>$v_link_label_add</a>\n";
+	}
+	$strlist .= "</td>\n";
+	$strlist .= "</tr>\n";
+
+	$strlist .= "</table>\n";
+	if ($count > 0) {
+		echo $strlist;
+	}
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "<br>";
+	echo "</div>";
+
+//show the footer
+	require_once "includes/footer.php";
+
+?>

+ 80 - 0
core/users/groupmemberadd.php

@@ -0,0 +1,80 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_member_add') || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//requires a superadmin to add a user to the superadmin group
+	if (!if_group("superadmin") && $_GET["group_name"] == "superadmin") {
+		echo "access denied";
+		return;
+	}
+
+//get the http values and set them as variables
+	$group_name = check_str($_POST["group_name"]);
+	$user_uuid = check_str($_POST["user_uuid"]);
+
+if (strlen($user_uuid) > 0  && strlen($group_name) > 0)   {
+	$sql_insert = "insert into v_group_users ";
+	$sql_insert .= "(";
+	$sql_insert .= "group_user_uuid, ";
+	$sql_insert .= "domain_uuid, ";
+	$sql_insert .= "group_name, ";
+	$sql_insert .= "user_uuid ";
+	$sql_insert .= ")";
+	$sql_insert .= "values ";
+	$sql_insert .= "(";
+	$sql_insert .= "'".uuid()."', ";
+	$sql_insert .= "'$domain_uuid', ";
+	$sql_insert .= "'$group_name', ";
+	$sql_insert .= "'$user_uuid' ";
+	$sql_insert .= ")";
+	if (!$db->exec($sql_insert)) {
+		//echo $db->errorCode() . "<br>";
+		$info = $db->errorInfo();
+		print_r($info);
+		// $info[0] == $db->errorCode() unified error code
+		// $info[1] is the driver specific error code
+		// $info[2] is the driver specific error string
+	}
+	else {
+		//log the success
+		//$log_type = 'group'; $log_status='add'; $log_add_user=$_SESSION["username"]; $log_desc= "username: ".$username." added to group: ".$group_name;
+		//log_add($db, $log_type, $log_status, $log_desc, $log_add_user, $_SERVER["REMOTE_ADDR"]);
+	}
+}
+
+//redirect the user
+	header("Location: groupmembers.php?group_name=$group_name");
+
+?>

+ 68 - 0
core/users/groupmemberdelete.php

@@ -0,0 +1,68 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_member_delete') || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//requires a superadmin to delete superadmin group
+	if (!if_group("superadmin") && $_GET["group_name"] == "superadmin") {
+		echo "access denied";
+		return;
+	}
+
+//get the http values and set them as variables
+	$group_name = check_str($_GET["group_name"]);
+	$user_uuid = check_str($_GET["user_uuid"]);
+
+//delete the group membership
+	$sql_delete = "delete from v_group_users ";
+	$sql_delete .= "where domain_uuid = '$domain_uuid' ";
+	$sql_delete .= "and user_uuid = '$user_uuid' ";
+	$sql_delete .= "and group_name = '$group_name' ";
+	if (!$db->exec($sql_delete)) {
+		//echo $db->errorCode() . "<br>";
+		$info = $db->errorInfo();
+		print_r($info);
+		// $info[0] == $db->errorCode() unified error code
+		// $info[1] is the driver specific error code
+		// $info[2] is the driver specific error string
+	}
+	else {
+		//$log_type = 'group'; $log_status='remove'; $log_add_user=$_SESSION["username"]; $log_desc= "username: ".$username." removed from group: ".$group_name;
+		//log_add($db, $log_type, $log_status, $log_desc, $log_add_user, $_SERVER["REMOTE_ADDR"]);
+	}
+
+//redirect the user
+	header("Location: groupmembers.php?group_name=$group_name");
+
+?>

+ 166 - 0
core/users/groupmembers.php

@@ -0,0 +1,166 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('group_members_view') || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//requires a superadmin to view members of the superadmin group
+	if (!if_group("superadmin") && $_GET["group_name"] == "superadmin") {
+		echo "access denied";
+		return;
+	}
+
+//get the http value and set as a variable
+	$group_name = $_GET["group_name"];
+
+//define the if group members function
+	function if_group_members($db, $group_name, $user_uuid) {
+		$sql = "select * from v_group_users ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$sql .= "and group_name = '$group_name' ";
+		$sql .= "and user_uuid = '$user_uuid' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		if (count($prep_statement->fetchAll(PDO::FETCH_NAMED)) == 0) { return true; } else { return false; }
+		unset ($sql, $prep_statement);
+	}
+	//$exampledatareturned = example("apples", 1);
+
+//include the header
+	require_once "includes/header.php";
+
+//show the content
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+	echo "<div align='center'>\n";
+	echo "<table width='90%' border='0'><tr><td align='left'>\n";
+	echo "\n";
+
+	echo "<table width='100%' cellpadding='6' cellspacing='1'>\n";
+	echo "	<tr>\n";
+	echo "		<td align='left'>\n";
+	echo "			<span  class=\"\" height='50'>Member list for <b>$group_name</b></span>";
+	echo "		</td>\n";
+	echo "		<td align='right' nowrap='nowrap'>\n";
+	echo "			<input type='button' class='btn' name='' alt='back' onclick=\"window.location='grouplist.php'\" value='Back'>";
+	echo "			&nbsp;&nbsp;&nbsp;\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	$sql = "SELECT u.user_uuid, u.username, g.group_user_uuid FROM v_group_users as g, v_users as u ";
+	$sql .= "where g.user_uuid = u.user_uuid ";
+	$sql .= "and g.domain_uuid = '$domain_uuid' ";
+	$sql .= "and g.group_name = '$group_name' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+
+	$strlist = "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+	$strlist .= "<tr>\n";
+	$strlist .= "	<th align=\"left\" nowrap> &nbsp; Username &nbsp; </th>\n";
+	$strlist .= "	<th align=\"left\" nowrap> &nbsp; &nbsp; </th>\n";
+	$strlist .= "	<td width='22' align=\"right\" nowrap>\n";
+	$strlist .= "		&nbsp;\n";
+	$strlist .= "	</td>\n";
+	$strlist .= "</tr>\n";
+
+	$count = 0;
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$group_user_uuid = $row["group_user_uuid"];
+		$username = $row["username"];
+		$user_uuid = $row["user_uuid"];
+		$strlist .= "<tr'>";
+		$strlist .= "<td align=\"left\"  class='".$row_style[$c]."' nowrap> &nbsp; $username &nbsp; </td>\n";
+		$strlist .= "<td align=\"left\"  class='".$row_style[$c]."' nowrap> &nbsp; </td>\n";
+		$strlist .= "<td align=\"right\" nowrap>\n";
+		if (permission_exists('group_member_delete')) {
+			$strlist .= "	<a href='groupmemberdelete.php?user_uuid=$user_uuid&group_name=$group_name' onclick=\"return confirm('Do you really want to delete this?')\" alt='delete'>$v_link_label_delete</a>\n";
+		}
+		$strlist .= "</td>\n";
+		$strlist .= "</tr>\n";
+
+		if ($c==0) { $c=1; } else { $c=0; }
+		$count++;
+	}
+
+	$strlist .= "</table>\n";
+	echo $strlist;
+
+	echo "</td>";
+	echo "</tr>";
+	echo "</table>";
+	echo "<br>";
+
+	echo "  <div align='center'>";
+	echo "  <form method='post' action='groupmemberadd.php'>";
+	echo "  <table width='250'>";
+	echo "	<tr>";
+	echo "		<td width='60%' align='right'>";
+
+	$sql = "SELECT * FROM v_users ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "order by username ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+
+	echo "<select name=\"user_uuid\" style='width: 200px;' class='formfld'>\n";
+	echo "<option value=\"\"></option>\n";
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach($result as $field) {
+		$username = $field['username'];
+		if (if_group_members($db, $group_name, $field['user_uuid'])) {
+			echo "<option value='".$field['user_uuid']."'>".$field['username']."</option>\n";
+		}
+	}
+	echo "</select>";
+	unset($sql, $result);
+
+	echo "		</td>";
+	echo "		<td align='right'>";
+	if (permission_exists('group_member_add')) {
+		echo "          <input type='hidden' name='group_name' value='$group_name'>";
+		echo "          <input type='submit' class='btn' value='Add Member'>";
+	}
+	echo "      </td>";
+	echo "	</tr>";
+	echo "  </table>";
+	echo "  </form>";
+	echo "  </div>";
+	echo "<br><br>";
+
+//include the footer
+	require_once "includes/footer.php";
+?>

+ 57 - 0
core/users/index.php

@@ -0,0 +1,57 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('user_view') || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//include the header
+	require_once "includes/header.php";
+
+//show the user list
+	echo "<div align='center'>";
+	echo "	<table width='100%' border='0'>";
+	echo "		<tr>";
+	echo "		<td align='left' width='100%'>";
+	require_once "userlist.php";
+	echo "				<br />";
+	echo "				<br />";
+	echo "				<br />";
+	echo "			</td>";
+	echo "		</tr>";
+	echo "	</table>";
+	echo "</div>";
+
+//include the footer
+	include "includes/footer.php";
+
+?>

+ 50 - 0
core/users/root.php

@@ -0,0 +1,50 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = realpath($_SERVER["DOCUMENT_ROOT"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', '/fusionpbx'); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		if(!defined('PROJECT_PATH')) { define('PROJECT_PATH', ''); }
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 258 - 0
core/users/signup.php

@@ -0,0 +1,258 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+
+if (if_group("admin") || if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+$username = check_str($_POST["username"]);
+$password = check_str($_POST["password"]);
+$confirmpassword = check_str($_POST["confirmpassword"]);
+$contact_organization = check_str($_POST["contact_organization"]);
+$contact_name_given = check_str($_POST["contact_name_given"]);
+$contact_name_family = check_str($_POST["contact_name_family"]);
+$user_email = check_str($_POST["user_email"]);
+
+if (count($_POST)>0 && check_str($_POST["persistform"]) != "1") {
+
+	$msgerror = '';
+
+	//--- begin captcha verification ---------------------
+		//session_start(); //make sure sessions are started
+		if (strtolower($_SESSION["captcha"]) != strtolower($_REQUEST["captcha"]) || strlen($_SESSION["captcha"]) == 0) {
+			//$msgerror .= "Captcha Verification Failed<br>\n";
+		}
+		else {
+			//echo "verified";
+		}
+	//--- end captcha verification -----------------------
+
+	//username is already used.
+	if (strlen($username) == 0) {
+		$msgerror .= "Please provide a Username.<br>\n";
+	}
+	else {
+		$sql = "SELECT * FROM v_users ";
+		$sql .= "where domain_uuid = '$domain_uuid' ";
+		$sql .= "and username = '$username' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		$prep_statement->execute();
+		if (count($prep_statement->fetchAll(PDO::FETCH_NAMED)) > 0) {
+			$msgerror .= "Please choose a different Username.<br>\n";
+		}
+	}
+
+	if (strlen($password) == 0) { $msgerror .= "Password cannot be blank.<br>\n"; }
+	if ($password != $confirmpassword) { $msgerror .= "Passwords did not match.<br>\n"; }
+	//if (strlen($contact_organization) == 0) { $msgerror .= "Please provide a organization name.<br>\n"; }
+	//if (strlen($contact_name_given) == 0) { $msgerror .= "Please provide a first name.<br>\n"; }
+	//if (strlen($contact_name_family) == 0) { $msgerror .= "Please provide a last name $user_last_name.<br>\n"; }
+	if (strlen($user_email) == 0) { $msgerror .= "Please provide an email.<br>\n"; }
+
+	if (strlen($msgerror) > 0) {
+		require_once "includes/header.php";
+		echo "<div align='center'>";
+		echo "<table><tr><td>";
+		echo $msgerror;
+		echo "</td></tr></table>";
+		require_once "includes/persistform.php";
+		echo persistform($_POST);
+		echo "</div>";
+		require_once "includes/footer.php";
+		return;
+	}
+
+	//salt used with the password to create a one way hash
+	$salt = generate_password('20', '4');
+
+	//prepare the uuids
+	$user_uuid = uuid();
+	$contact_uuid = uuid();
+
+	//add the user
+	$sql = "insert into v_users ";
+	$sql .= "(";
+	$sql .= "domain_uuid, ";
+	$sql .= "user_uuid, ";
+	$sql .= "contact_uuid, ";
+	$sql .= "username, ";
+	$sql .= "password, ";
+	$sql .= "salt, ";
+	$sql .= "user_add_date, ";
+	$sql .= "user_add_user ";
+	$sql .= ") ";
+	$sql .= "values ";
+	$sql .= "(";
+	$sql .= "'$domain_uuid', ";
+	$sql .= "'$user_uuid', ";
+	$sql .= "'$contact_uuid', ";
+	$sql .= "'$username', ";
+	$sql .= "'".md5($salt.$password)."', ";
+	$sql .= "'".$salt."', ";
+	$sql .= "now(), ";
+	$sql .= "'".$_SESSION["username"]."' ";
+	$sql .= ")";
+	$db->exec(check_sql($sql));
+	unset($sql);
+
+	//add to contacts
+	$sql = "insert into v_contacts ";
+	$sql .= "(";
+	$sql .= "domain_uuid, ";
+	$sql .= "contact_uuid, ";
+	$sql .= "contact_type, ";
+	$sql .= "contact_organization, ";
+	$sql .= "contact_name_given, ";
+	$sql .= "contact_name_family, ";
+	$sql .= "contact_nickname, ";
+	$sql .= "contact_email ";
+	$sql .= ") ";
+	$sql .= "values ";
+	$sql .= "(";
+	$sql .= "'$domain_uuid', ";
+	$sql .= "'$contact_uuid', ";
+	$sql .= "'user', ";
+	$sql .= "'$contact_organization', ";
+	$sql .= "'$contact_name_given', ";
+	$sql .= "'$contact_name_family', ";
+	$sql .= "'$username', ";
+	$sql .= "'$user_email' ";
+	$sql .= ")";
+	$db->exec(check_sql($sql));
+	unset($sql);
+
+	//log the success
+	//$log_type = 'user'; $log_status='add'; $log_add_user=$_SESSION["username"]; $log_desc= "username: ".$username." user added.";
+	//log_add($db, $log_type, $log_status, $log_desc, $log_add_user, $_SERVER["REMOTE_ADDR"]);
+
+	$group_name = 'user';
+	$sql = "insert into v_group_users ";
+	$sql .= "(";
+	$sql .= "group_user_uuid, ";
+	$sql .= "domain_uuid, ";
+	$sql .= "group_name, ";
+	$sql .= "user_uuid ";
+	$sql .= ")";
+	$sql .= "values ";
+	$sql .= "(";
+	$sql .= "'".uuid()."', ";
+	$sql .= "'$domain_uuid', ";
+	$sql .= "'$group_name', ";
+	$sql .= "'$user_uuid' ";
+	$sql .= ")";
+	$db->exec(check_sql($sql));
+	unset($sql);
+
+	require_once "includes/header.php";
+	echo "<meta http-equiv=\"refresh\" content=\"3;url=index.php\">\n";
+	echo "<div align='center'>Add Complete</div>";
+	require_once "includes/footer.php";
+	return;
+}
+
+//show the header
+	require_once "includes/header.php";
+
+//show the content
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr>\n";
+	echo "	<td align=\"left\">\n";
+	echo "      <br>";
+
+	$tablewidth ='width="100%"';
+	echo "<form method='post' action=''>";
+	echo "<div class='borderlight' style='padding:10px;'>\n";
+
+	echo "<table border='0' $tablewidth cellpadding='6' cellspacing='0'>";
+	echo "	<tr>\n";
+	echo "		<td width='80%'>\n";
+	echo "			<b>To add a user, please fill out this form completely. All fields are required. </b><br>";
+	echo "		</td>\n";
+	echo "		<td width='20%' align='right'>\n";
+	echo "			<input type='button' class='btn' name='back' alt='back' onclick=\"window.history.back()\" value='Back'>\n";
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "</table>\n";
+
+	echo "<table border='0' $tablewidth cellpadding='6' cellspacing='0'>";
+	echo "	<tr>";
+	echo "		<td class='vncellreq' width='40%'>Username:</td>";
+	echo "		<td class='vtable' width='60%'><input type='text' class='formfld' autocomplete='off' name='username' value='$username'></td>";
+	echo "	</tr>";
+
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Password:</td>";
+	echo "		<td class='vtable'><input type='password' class='formfld' autocomplete='off' name='password' value='$password'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Confirm Password:</td>";
+	echo "		<td class='vtable'><input type='password' class='formfld' autocomplete='off' name='confirmpassword' value='$confirmpassword'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncellreq'>Email:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='user_email' value='$user_email'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncell'>First Name:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='contact_name_given' value='$contact_name_given'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncell'>Last Name:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='contact_name_family' value='$contact_name_family'></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncell'>Company Name:</td>";
+	echo "		<td class='vtable'><input type='text' class='formfld' name='contact_organization' value='$contact_organization'></td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+	echo "<div class='' style='padding:10px;'>\n";
+	echo "<table $tablewidth>";
+	echo "	<tr>";
+	echo "		<td colspan='2' align='right'>";
+	echo "       <input type='submit' name='submit' class='btn' value='Create Account'>";
+	echo "		</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</form>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+
+//show the footer
+	require_once "includes/footer.php";
+?>

+ 87 - 0
core/users/userdelete.php

@@ -0,0 +1,87 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists('user_delete')) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//get the id
+	$user_uuid = check_str($_GET["id"]);
+
+//get the username from v_users
+	$sql = "";
+	$sql .= "select * from v_users ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and user_uuid = '$user_uuid' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$username = $row["username"];
+		break; //limit to 1 row
+	}
+	unset ($prep_statement);
+
+//required to be a superadmin to delete a member of the superadmin group
+	$superadmin_list = superadmin_list($db);
+	if (if_superadmin($superadmin_list, $_SESSION['user_uuid'])) {
+		if (!if_group("superadmin")) { 
+			echo "access denied";
+			return;
+		}
+	}
+//delete the user
+	$sql_delete = "delete from v_users ";
+	$sql_delete .= "where domain_uuid = '$domain_uuid' ";
+	$sql_delete .= "and user_uuid = '$user_uuid' ";
+	if (!$db->exec($sql_delete)) {
+		//echo $db->errorCode() . "<br>";
+		$info = $db->errorInfo();
+		print_r($info);
+		// $info[0] == $db->errorCode() unified error code
+		// $info[1] is the driver specific error code
+		// $info[2] is the driver specific error string
+	}
+
+//delete the groups the user is assigned to
+	$sql_delete = "delete from v_group_users ";
+	$sql_delete .= "where domain_uuid = '$domain_uuid' ";
+	$sql_delete .= "and user_uuid = '$user_uuid' ";
+	if (!$db->exec($sql_delete)) {
+		$info = $db->errorInfo();
+		print_r($info);
+	}
+
+//redirect the user
+	header("Location: index.php");
+
+?>

+ 192 - 0
core/users/userlist.php

@@ -0,0 +1,192 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists("user_view") || if_group("superadmin")) {
+	//access granted
+}
+else {
+	echo "access denied";
+	exit;
+}
+//require_once "includes/header.php";
+	require_once "includes/paging.php";
+
+$order_by = $_GET["order_by"];
+$order = $_GET["order"];
+$field_name = $_REQUEST["field_name"];
+$field_value = $_REQUEST["field_value"];
+
+echo "<div align='center'>";
+echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+echo "<tr class='border'>\n";
+echo "	<td align=\"center\">\n";
+
+//page title and description
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+	echo "<form method='post' action=''>";
+	echo "<tr>\n";
+	echo "<td align='left' width='90%' nowrap><b>User Manager</b></td>\n";
+	echo "<td align='right' nowrap='nowrap'>Search by:&nbsp;</td>";
+	echo "<td align='left'>\n";
+	echo "	<select name='field_name' style='width:150px' class='frm'>\n";
+	echo "	<option value=''></option>\n";
+	if ($field_name == "username") {
+		echo "	<option value='username' selected='selected'>Username</option>\n";
+	}
+	else {
+		echo "	<option value='username'>Username</option>\n";
+	}
+	//if ($field_name == "user_email") {
+	//	echo "	<option value='user_email' selected='selected'>Email</option>\n";
+	//}
+	//else {
+	//	echo "	<option value='user_email'>Email</option>\n";
+	//}
+	echo "	</select>\n";
+	echo "</td>\n";
+	echo "<td align='left' width='3px'>&nbsp;</td>";
+	echo "<td align='left'><input type='text' class='txt' style='width: 150px' name='field_value' value='$field_value'></td>";
+	echo "<td align='left' width='60px'><input type='submit' class='btn' name='submit' value='search'></td>";
+	//echo "	<input type='button' class='btn' name='' alt='view' onclick=\"window.location='user_search.php'\" value='advanced'>&nbsp;\n";
+	echo "</tr>\n";
+	echo "</form>";
+
+	echo "<tr>\n";
+	echo "<td align='left' colspan='4'>\n";
+	echo "Add, edit, delete, and search for users. \n";
+	echo "<br />\n";
+	echo "<br />\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+//get the user list from the database
+	$sql = "";
+	$sql .= " select * from v_users ";
+	$sql .= " where domain_uuid = '$domain_uuid' ";
+	if (strlen($field_name) > 0 && strlen($field_value) > 0) {
+		$sql .= " and $field_name = '$field_value' ";
+	}
+	if (strlen($order_by)> 0) { $sql .= "order by $order_by $order "; }
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$num_rows = count($result);
+	unset ($prep_statement, $result, $sql);
+	$rows_per_page = 200;
+	$param = "";
+	$page = $_GET['page'];
+	if (strlen($page) == 0) { $page = 0; $_GET['page'] = 0; } 
+	list($paging_controls, $rows_per_page, $var_3) = paging($num_rows, $param, $rows_per_page); 
+	$offset = $rows_per_page * $page; 
+
+	$sql = "";
+	$sql .= " select * from v_users ";
+	$sql .= " where domain_uuid = '".$_SESSION['domain_uuid']."' ";
+	if (strlen($field_name) > 0 && strlen($field_value) > 0) {
+		$sql .= " and $field_name like '%$field_value%' ";
+	}
+	if (strlen($order_by)> 0) { 
+		$sql .= "order by $order_by $order "; 
+	}
+	else {
+		$sql .= "order by username ";
+	}
+	$sql .= " limit $rows_per_page offset $offset ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$result_count = count($result);
+	unset ($prep_statement, $sql);
+
+//alternate the row style
+	$c = 0;
+	$row_style["0"] = "row_style0";
+	$row_style["1"] = "row_style1";
+
+//show the data
+	echo "<div align='center'>\n";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='0'>\n";
+
+	echo "<tr>\n";
+	echo th_order_by('username', 'Username', $order_by, $order);
+	//echo th_order_by('user_email', 'Email', $order_by, $order);
+	//echo th_order_by('user_template_name', 'Template', $order_by, $order);
+	echo "<td align='right' width='42'>\n";
+	if (permission_exists('user_add')) {
+		echo "	<a href='signup.php' alt='add'>$v_link_label_add</a>\n";
+	}
+	echo "</td>\n";
+	echo "<tr>\n";
+
+	if ($result_count > 0) {
+		foreach($result as $row) {
+			echo "<tr >\n";
+			echo "	<td valign='top' class='".$row_style[$c]."'>".$row['username']."&nbsp;</td>\n";
+			//echo "	<td valign='top' class='".$row_style[$c]."'>".$row['user_email']."&nbsp;</td>\n";
+			echo "	<td valign='top' align='right'>\n";
+			if (permission_exists('user_edit')) {
+				echo "		<a href='usersupdate.php?id=".$row['user_uuid']."' alt='edit'>$v_link_label_edit</a>\n";
+			}
+			if (permission_exists('user_delete')) {
+				echo "		<a href='userdelete.php?id=".$row['user_uuid']."' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			}
+			echo "	</td>\n";
+			echo "</tr>\n";
+			if ($c==0) { $c=1; } else { $c=0; }
+		} //end foreach
+		unset($sql, $result, $row_count);
+	} //end if results
+
+	echo "<tr>\n";
+	echo "<td colspan='49' align='left'>\n";
+	echo "	<table width='100%' cellpadding='0' cellspacing='0'>\n";
+	echo "	<tr>\n";
+	echo "		<td width='33.3%' nowrap>&nbsp;</td>\n";
+	echo "		<td width='33.3%' align='center' nowrap>$paging_controls</td>\n";
+	echo "		<td width='33.3%' align='right'>\n";
+	if (permission_exists('user_add')) {
+		echo "			<a href='signup.php' alt='add'>$v_link_label_add</a>\n";
+	}
+	echo "		</td>\n";
+	echo "	</tr>\n";
+	echo "	</table>\n";
+	echo "</td>\n";
+	echo "</tr>\n";
+
+	echo "</table>";
+	echo "</div>";
+	echo "<br><br>";
+	echo "<br><br>";
+
+echo "</td>";
+echo "</tr>";
+echo "</table>";
+echo "</div>";
+echo "<br><br>";
+
+?>

+ 612 - 0
core/users/usersupdate.php

@@ -0,0 +1,612 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "includes/require.php";
+require_once "includes/checkauth.php";
+if (permission_exists("user_add") ||
+	permission_exists("user_edit") || 
+	permission_exists("user_delete") ||
+	if_group("superadmin")) {
+	//access allowed
+}
+else {
+	echo "access denied";
+	return;
+}
+
+//get data from the db
+	if (strlen($_REQUEST["id"])> 0) {
+		$user_uuid = $_REQUEST["id"];
+	}
+	else {
+		if (strlen($_SESSION["username"]) > 0) {
+			$username = $_SESSION["username"];
+		}
+	}
+
+//get the username from v_users
+	$sql = "select * from v_users ";
+	$sql .= "where domain_uuid = '$domain_uuid' ";
+	$sql .= "and user_uuid = '$user_uuid' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$username = $row["username"];
+		break; //limit to 1 row
+	}
+	unset ($prep_statement);
+
+//required to be a superadmin to update an account that is a member of the superadmin group
+	$superadmin_list = superadmin_list($db);
+	if (if_superadmin($superadmin_list, $_SESSION['user_uuid'])) {
+		if (!if_group("superadmin")) { 
+			echo "access denied";
+			return;
+		}
+	}
+
+//delete the group from the user
+	if ($_GET["a"] == "delete" && permission_exists("user_delete")) {
+		//set the variables
+			$group_name = check_str($_GET["group_name"]);
+		//delete the group from the users
+			$sql = "delete from v_group_users ";
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and group_name = '$group_name' ";
+			$sql .= "and user_uuid = '$user_uuid' ";
+			$db->exec(check_sql($sql));
+		//redirect the user
+			require_once "includes/header.php";
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=usersupdate.php?id=$user_uuid\">\n";
+			echo "<div align='center'>Update Complete</div>";
+			require_once "includes/footer.php";
+			return;
+	}
+
+//get the user settings
+	$sql = "select * from v_user_settings ";
+	$sql .= "where user_uuid = '".$_SESSION["user_uuid"]."' ";
+	$sql .= "and user_setting_enabled = 'true' ";
+	$prep_statement = $db->prepare($sql);
+	if ($prep_statement) {
+		$prep_statement->execute();
+		$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+		foreach($result as $row) {
+			$name = $row['user_setting_name'];
+			$category = $row['user_setting_category'];
+			$subcategory = $row['user_setting_subcategory'];
+			if (strlen($subcategory) == 0) {
+				//$$category[$name] = $row['domain_setting_value'];
+				$user_settings[$category][$name] = $row['user_setting_value'];
+			}
+			else {
+				$user_settings[$category][$subcategory][$name] = $row['user_setting_value'];
+			}
+		}
+	}
+
+if (count($_POST)>0 && $_POST["persistform"] != "1") {
+	$user_uuid = $_REQUEST["id"];
+	$password = check_str($_POST["password"]);
+	$confirm_password = check_str($_POST["confirm_password"]);
+	$user_status = check_str($_POST["user_status"]);
+	//$user_template_name = check_str($_POST["user_template_name"]);
+	$user_time_zone = check_str($_POST["user_time_zone"]);
+	$contact_uuid = check_str($_POST["contact_uuid"]);
+	$group_member = check_str($_POST["group_member"]);
+
+	//if (strlen($password) == 0) { $msg_error .= "Password cannot be blank.<br>\n"; }
+	//if (strlen($username) == 0) { $msg_error .= "Please provide the username.<br>\n"; }
+	if ($password != $confirm_password) { $msg_error .= "Passwords did not match.<br>\n"; }
+	//if (strlen($contact_uuid) == 0) { $msg_error .= "Please provide an email.<br>\n"; }
+	//if (strlen($user_time_zone) == 0) { $msg_error .= "Please provide an time zone.<br>\n"; }
+	if ($msg_error) {
+		require_once "includes/header.php";
+		echo "<div align='center'>";
+		echo "<table><tr><td>";
+		echo $msg_error;
+		echo "</td></tr></table>";
+		echo "<br />\n";
+		require_once "includes/persistform.php";
+		echo persistform($_POST);
+		echo "</div>";
+		require_once "includes/footer.php";
+		return;
+	}
+
+	//get the number of rows in v_user_settings 
+		$sql = "select count(*) as num_rows from v_user_settings ";
+		$sql .= "where user_setting_category = 'domain' ";
+		$sql .= "and user_setting_subcategory = 'time_zone' ";
+		$sql .= "and user_uuid = '".$user_uuid."' ";
+		$prep_statement = $db->prepare(check_sql($sql));
+		if ($prep_statement) {
+			$prep_statement->execute();
+			$row = $prep_statement->fetch(PDO::FETCH_ASSOC);
+			if ($row['num_rows'] == 0) {
+				$user_setting_uuid = uuid();
+				$sql = "insert into v_user_settings ";
+				$sql .= "(";
+				$sql .= "user_setting_uuid, ";
+				$sql .= "user_setting_category, ";
+				$sql .= "user_setting_subcategory, ";
+				$sql .= "user_setting_name, ";
+				$sql .= "user_setting_value, ";
+				$sql .= "user_setting_enabled, ";
+				$sql .= "user_uuid ";
+				$sql .= ") ";
+				$sql .= "values ";
+				$sql .= "(";
+				$sql .= "'".$user_setting_uuid."', ";
+				$sql .= "'domain', ";
+				$sql .= "'time_zone', ";
+				$sql .= "'name', ";
+				$sql .= "'".$user_time_zone."', ";
+				$sql .= "'true', ";
+				$sql .= "'".$user_uuid."' ";
+				$sql .= ")";
+				$db->exec(check_sql($sql));
+			}
+			else {
+				if (strlen($user_time_zone) == 0) {
+					$sql = "delete from v_user_settings ";
+					$sql .= "where user_setting_category = 'domain' ";
+					$sql .= "and user_setting_subcategory = 'time_zone' ";
+					$sql .= "and user_uuid = '".$user_uuid."' ";
+					$db->exec(check_sql($sql));
+					unset($sql);
+				}
+				else {
+					$sql  = "update v_user_settings set ";
+					$sql .= "user_setting_value = '".$user_time_zone."', ";
+					$sql .= "user_setting_enabled = 'true' ";
+					$sql .= "where user_setting_category = 'domain' ";
+					$sql .= "and user_setting_subcategory = 'time_zone' ";
+					$sql .= "and user_uuid = '".$user_uuid."' ";
+					$db->exec(check_sql($sql));
+				}
+			}
+		}
+
+	//assign the user to the group
+		if (strlen($_REQUEST["group_name"]) > 0) {
+			$sql_insert = "insert into v_group_users ";
+			$sql_insert .= "(";
+			$sql_insert .= "group_user_uuid, ";
+			$sql_insert .= "domain_uuid, ";
+			$sql_insert .= "group_name, ";
+			$sql_insert .= "user_uuid ";
+			$sql_insert .= ")";
+			$sql_insert .= "values ";
+			$sql_insert .= "(";
+			$sql_insert .= "'".uuid()."', ";
+			$sql_insert .= "'$domain_uuid', ";
+			$sql_insert .= "'".$_REQUEST["group_name"]."', ";
+			$sql_insert .= "'$user_uuid' ";
+			$sql_insert .= ")";
+			if ($_REQUEST["group_name"] == "superadmin") {
+				//only a user in the superadmin group can add other users to that group
+				if (if_group("superadmin")) {
+					$db->exec($sql_insert);
+				}
+			}
+			else {
+				$db->exec($sql_insert);
+			}
+		}
+
+	//if the template has not been assigned by the superadmin
+		//if (strlen($_SESSION['domain']['template']['name']) == 0) {
+			//set the session theme for the active user
+		//	if ($_SESSION["username"] == $username) {
+		//		$_SESSION['domain']['template']['name'] = $user_template_name;
+		//	}
+		//}
+
+	//sql update
+		$sql  = "update v_users set ";
+		if (if_group("admin") && strlen($_POST["username"])> 0) {
+			$sql .= "username = '$username', ";
+		}
+		if (strlen($password) > 0 && $confirm_password == $password) {
+			//salt used with the password to create a one way hash
+				$salt = generate_password('20', '4');
+			//set the password
+				$sql .= "password = '".md5($salt.$password)."', ";
+				$sql .= "salt = '".$salt."', ";
+		}
+		$sql .= "user_status = '$user_status', ";
+		if (strlen($contact_uuid) == 0) {
+			$sql .= "contact_uuid = null ";
+		}
+		else {
+			$sql .= "contact_uuid = '$contact_uuid' ";
+		}
+		if (strlen($user_uuid)> 0) {
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and user_uuid = '$user_uuid' ";
+		}
+		else {
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and username = '$username' ";
+		}
+		$db->exec(check_sql($sql));
+
+	//update the user_status
+		$fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']);
+		$switch_cmd .= "callcenter_config agent set status ".$username."@".$_SESSION['domain_name']." '".$user_status."'";
+		$switch_result = event_socket_request($fp, 'api '.$switch_cmd);
+
+	//update the user state
+		$cmd = "api callcenter_config agent set state ".$username."@".$_SESSION['domain_name']." Waiting";
+		$response = event_socket_request($fp, $cmd);
+
+	//clear the template so it will rebuild in case the template was changed
+		//$_SESSION["template_content"] = '';
+
+	//redirect the browser
+		require_once "includes/header.php";
+		if (if_group("admin")) {
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=usersupdate.php?id=$user_uuid\">\n";
+		}
+		else {
+			echo "<meta http-equiv=\"refresh\" content=\"2;url=usersupdate.php?id=$user_uuid\">\n";
+		}
+		echo "<div align='center'>Update Complete</div>";
+		require_once "includes/footer.php";
+		return;
+}
+else {
+	$sql = "select * from v_users ";
+	//allow admin access
+	if (if_group("admin") || if_group("superadmin")) {
+		if (strlen($user_uuid)> 0) {
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and user_uuid = '$user_uuid' ";
+		}
+		else {
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and username = '$username' ";
+		}
+	}
+	else {
+			$sql .= "where domain_uuid = '$domain_uuid' ";
+			$sql .= "and username = '$username' ";
+	}
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach ($result as &$row) {
+		$user_uuid = $row["user_uuid"];
+		if (if_group("admin")) {
+			$username = $row["username"];
+		}
+		$password = $row["password"];
+		$contact_uuid = $row["contact_uuid"];
+		$user_status = $row["user_status"];
+		break; //limit to 1 row
+	}
+
+	//get the groups the user is a member of
+	//group_members function defined in config.php
+	$group_members = group_members($db, $user_uuid);
+}
+
+//include the header
+	require_once "includes/header.php";
+
+//show the content
+	$table_width ='width="100%"';
+	echo "<form method='post' action=''>";
+	echo "<br />\n";
+
+	echo "<div align='center'>";
+	echo "<table width='100%' border='0' cellpadding='0' cellspacing='2'>\n";
+	echo "<tr>\n";
+	echo "<td>\n";
+
+	echo "<table $table_width cellpadding='3' cellspacing='0' border='0'>";
+	echo "<td align='left' width='90%' nowrap><b>User Manager</b></td>\n";
+	echo "<td nowrap='nowrap'>\n";
+	echo "	<input type='submit' name='submit' class='btn' value='Save'>";
+	echo "	<input type='button' class='btn' onclick=\"window.location='index.php'\" value='Back'>";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "<tr>\n";
+	echo "<td align='left' colspan='2'>\n";
+	echo "	Edit user information and group membership. \n";
+	echo "</td>\n";
+	echo "</tr>\n";
+	echo "</table>\n";
+
+	echo "<br />\n";
+
+	echo "<table $table_width cellpadding='6' cellspacing='0' border='0'>";
+	echo "<tr>\n";
+	echo "	<th class='th' colspan='2' align='left'>User Info</th>\n";
+	echo "</tr>\n";
+
+	echo "	<tr>";
+	echo "		<td width='30%' class='vncellreq'>Username:</td>";
+	echo "		<td width='70%' class='vtable'>$username</td>";
+	echo "	</tr>";
+
+	echo "	<tr>";
+	echo "		<td class='vncell'>Password:</td>";
+	echo "		<td class='vtable'><input type='password' autocomplete='off' class='formfld' name='password' value=\"\"></td>";
+	echo "	</tr>";
+	echo "	<tr>";
+	echo "		<td class='vncell'>Confirm Password:</td>";
+	echo "		<td class='vtable'><input type='password' autocomplete='off' class='formfld' name='confirm_password' value=\"\"></td>";
+	echo "	</tr>";
+
+	echo "	<tr>";
+	echo "		<td class='vncell' valign='top'>Groups:</td>";
+	echo "		<td class='vtable'>";
+
+	echo "<table width='52%'>\n";
+	$sql = "SELECT * FROM v_group_users ";
+	$sql .= "where domain_uuid=:domain_uuid ";
+	$sql .= "and user_uuid=:user_uuid ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->bindParam(':domain_uuid', $domain_uuid);
+	$prep_statement->bindParam(':user_uuid', $user_uuid);
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	$result_count = count($result);
+	foreach($result as $field) {
+		if (strlen($field['group_name']) > 0) {
+			echo "<tr>\n";
+			echo "	<td class='vtable'>".$field['group_name']."</td>\n";
+			echo "	<td>\n";
+			if (permission_exists('group_member_delete') || if_group("superadmin")) {
+				echo "		<a href='usersupdate.php?id=".$user_uuid."&domain_uuid=".$domain_uuid."&group_name=".$field['group_name']."&a=delete' alt='delete' onclick=\"return confirm('Do you really want to delete this?')\">$v_link_label_delete</a>\n";
+			}
+			echo "	</td>\n";
+			echo "</tr>\n";
+		}
+	}
+	echo "</table>\n";
+
+	echo "<br />\n";
+	$sql = "SELECT * FROM v_groups ";
+	$sql .= "where domain_uuid = '".$domain_uuid."' ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	echo "<select name=\"group_name\" class='frm'>\n";
+	echo "<option value=\"\"></option>\n";
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	foreach($result as $field) {
+		if ($field['group_name'] == "superadmin") {
+			//only show the superadmin group to other users in the superadmin group
+			if (if_group("superadmin")) {
+				echo "<option value='".$field['group_name']."'>".$field['group_name']."</option>\n";
+			}
+		}
+		else {
+			echo "<option value='".$field['group_name']."'>".$field['group_name']."</option>\n";
+		}
+	}
+	echo "</select>";
+	echo "<input type=\"submit\" class='btn' value=\"Add\">\n";
+	unset($sql, $result);
+	echo "		</td>";
+	echo "	</tr>";
+	echo "</table>";
+
+	echo "<br>";
+	echo "<br>";
+
+	echo "<table $table_width cellpadding='6' cellspacing='0'>";
+	echo "	<tr>\n";
+	echo "	<th class='th' colspan='2' align='left'>Additional Info</th>\n";
+	echo "	</tr>\n";
+
+	echo "	<tr>";
+	echo "		<td width='30%' class='vncell'>Contact:</td>";
+	echo "		<td width='70%' class='vtable'>\n";
+	$sql = " select contact_uuid, contact_organization, contact_name_given, contact_name_family from v_contacts ";
+	$sql .= " where domain_uuid = '".$_SESSION['domain_uuid']."' ";
+	$sql .= " order by contact_organization asc ";
+	$prep_statement = $db->prepare(check_sql($sql));
+	$prep_statement->execute();
+	$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+	unset ($prep_statement, $sql);
+	echo "<select name=\"contact_uuid\" id=\"contact_uuid\" class=\"formfld\">\n";
+	echo "<option value=\"\"></option>\n";
+	foreach($result as $row) {
+			$contact_name = '';
+			if (strlen($row['contact_organization']) > 0) {
+					$contact_name = $row['contact_organization'];
+			}
+			if (strlen($row['contact_name_family']) > 0) {
+					if (strlen($contact_name) > 0) { $contact_name .= ", "; }
+					$contact_name .= $row['contact_name_family'];
+			}
+			if (strlen($row['contact_name_given']) > 0) {
+					if (strlen($contact_name) > 0) { $contact_name .= ", "; }
+					$contact_name .= $row['contact_name_given'];
+			}
+			if ($row['contact_uuid'] == $contact_uuid) {
+					echo "<option value=\"".$row['contact_uuid']."\" selected=\"selected\">".$contact_name."</option>\n";
+			}
+			else {
+					echo "<option value=\"".$row['contact_uuid']."\">".$contact_name."</option>\n";
+			}
+	}
+	unset($sql, $result, $row_count);
+	echo "</select>\n";
+	echo "<br />\n";
+	echo "Assign a contact to this user account.\n";
+	if (strlen($contact_uuid) > 0) {
+		echo "			<a href=\"/app/contacts/contacts_edit.php?id=$contact_uuid\">View</a>\n";
+	}
+	echo "		</td>";
+	echo "	</tr>";
+
+	if ($_SESSION['user_status_display'] == "false") {
+		//hide the user_status when it is set to false
+	}
+	else {
+		echo "	<tr>\n";
+		echo "	<td width='20%' class=\"vncell\" style='text-align: left;'>\n";
+		echo "		Status:\n";
+		echo "	</td>\n";
+		echo "	<td class=\"vtable\">\n";
+		$cmd = "'".PROJECT_PATH."/app/calls_active/v_calls_exec.php?cmd=callcenter_config+agent+set+status+".$_SESSION['username']."@".$_SESSION['domain_name']."+'+this.value";
+		echo "		<select id='user_status' name='user_status' class='formfld' style='' onchange=\"send_cmd($cmd);\">\n";
+		echo "		<option value=''></option>\n";
+		if ($user_status == "Available") {
+			echo "		<option value='Available' selected='selected'>Available</option>\n";
+		}
+		else {
+			echo "		<option value='Available'>Available</option>\n";
+		}
+		if ($user_status == "Available (On Demand)") {
+			echo "		<option value='Available (On Demand)' selected='selected'>Available (On Demand)</option>\n";
+		}
+		else {
+			echo "		<option value='Available (On Demand)'>Available (On Demand)</option>\n";
+		}
+		if ($user_status == "Logged Out") {
+			echo "		<option value='Logged Out' selected='selected'>Logged Out</option>\n";
+		}
+		else {
+			echo "		<option value='Logged Out'>Logged Out</option>\n";
+		}
+		if ($user_status == "On Break") {
+			echo "		<option value='On Break' selected='selected'>On Break</option>\n";
+		}
+		else {
+			echo "		<option value='On Break'>On Break</option>\n";
+		}
+		if ($user_status == "Do Not Disturb") {
+			echo "		<option value='Do Not Disturb' selected='selected'>Do Not Disturb</option>\n";
+		}
+		else {
+			echo "		<option value='Do Not Disturb'>Do Not Disturb</option>\n";
+		}
+		echo "		</select>\n";
+		echo "		<br />\n";
+		echo "		Select a the user status.<br />\n";
+		echo "	</td>\n";
+		echo "	</tr>\n";
+	}
+
+	//if the template has not been assigned by the superadmin
+		/*
+		if (strlen($_SESSION['domain']['template']['name']) == 0) {
+			echo "	<tr>\n";
+			echo "	<td width='20%' class=\"vncell\" style='text-align: left;'>\n";
+			echo "		Template: \n";
+			echo "	</td>\n";
+			echo "	<td class=\"vtable\">\n";
+			echo "		<select id='user_template_name' name='user_template_name' class='formfld' style=''>\n";
+			echo "		<option value=''></option>\n";
+			$theme_dir = $_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes';
+			if ($handle = opendir($_SERVER["DOCUMENT_ROOT"].PROJECT_PATH.'/themes')) {
+				while (false !== ($dir_name = readdir($handle))) {
+					if ($dir_name != "." && $dir_name != ".." && $dir_name != ".svn" && is_dir($theme_dir.'/'.$dir_name)) {
+						$dir_label = str_replace('_', ' ', $dir_name);
+						$dir_label = str_replace('-', ' ', $dir_label);
+						if ($dir_name == $user_settings['domain']['template']['name']) {
+							echo "		<option value='$dir_name' selected='selected'>$dir_label</option>\n";
+						}
+						else {
+							echo "		<option value='$dir_name'>$dir_label</option>\n";
+						}
+					}
+				}
+				closedir($handle);
+			}
+			echo "	</select>\n";
+			echo "	<br />\n";
+			echo "	Select a template to set as the default and then press save.<br />\n";
+			echo "	</td>\n";
+			echo "	</tr>\n";
+		}
+		*/
+
+	echo "	<tr>\n";
+	echo "	<td width='20%' class=\"vncell\" style='text-align: left;'>\n";
+	echo "		Time Zone: \n";
+	echo "	</td>\n";
+	echo "	<td class=\"vtable\" align='left'>\n";
+	echo "		<select id='user_time_zone' name='user_time_zone' class='formfld' style=''>\n";
+	echo "		<option value=''></option>\n";
+	//$list = DateTimeZone::listAbbreviations();
+    $time_zone_identifiers = DateTimeZone::listIdentifiers();
+	$previous_category = '';
+	$x = 0;
+	foreach ($time_zone_identifiers as $key => $row) {
+		$time_zone = explode("/", $row);
+		$category = $time_zone[0];
+		if ($category != $previous_category) {
+			if ($x > 0) {
+				echo "		</optgroup>\n";
+			}
+			echo "		<optgroup label='".$category."'>\n";
+		}
+		if ($row == $user_settings['domain']['time_zone']['name']) {
+			echo "			<option value='".$row."' selected='selected'>".$row."</option>\n";
+		}
+		else {
+			echo "			<option value='".$row."'>".$row."</option>\n";
+		}
+		$previous_category = $category;
+		$x++;
+	}
+	echo "		</select>\n";
+	echo "		<br />\n";
+	echo "		Select the default time zone.<br />\n";
+	echo "	</td>\n";
+	echo "	</tr>\n";
+
+	echo "	</table>";
+	echo "<br>";
+
+	echo "<div class='' style='padding:10px;'>\n";
+	echo "<table $table_width>";
+	echo "	<tr>";
+	echo "		<td colspan='2' align='right'>";
+	echo "			<input type='hidden' name='id' value=\"$user_uuid\">";
+	echo "			<input type='hidden' name='username' value=\"$username\">";
+	echo "			<input type='submit' name='submit' class='btn' value='Save'>";
+	echo "		</td>";
+	echo "	</tr>";
+	echo "</table>";
+
+	echo "	</td>";
+	echo "	</tr>";
+	echo "</table>";
+	echo "</div>";
+	echo "</form>";
+
+//include the footer
+	require_once "includes/footer.php";
+
+?>


BIN
images/background_cell_active.gif


BIN
images/background_cell_conference.gif


BIN
images/background_cell_fifo.gif


BIN
images/background_cell_light.gif


BIN
images/blank.gif


BIN
images/icon_cal.gif


BIN
images/icon_e.gif


BIN
images/icon_e.png


BIN
images/icon_plus.gif


BIN
images/icon_plus.png


BIN
images/icon_restart.gif


BIN
images/icon_start.gif


BIN
images/icon_stop.gif


BIN
images/icon_up.gif


BIN
images/icon_view.gif


BIN
images/icon_x.gif


BIN
images/icon_x.png


+ 189 - 0
includes/calendar_lw_layers.js

@@ -0,0 +1,189 @@
+//	written	by Tan Ling Wee
+//	last updated 20 June 2003
+//	email :	[email protected]
+
+//////////////////////////////////////////////////////////////////////////////////
+// Layers 
+//////////////////////////////////////////////////////////////////////////////////
+
+var layerQueue=new Array()
+var layerIndex=-1
+
+/* hides <select> and <applet> objects (for IE only) */
+function hideElement( elmID, overDiv )
+{
+  if( ie )
+  {
+	for( i = 0; i < document.getElementsByTagName( elmID ).length; i++ )
+	{
+	  obj = document.getElementsByTagName( elmID )[i];
+	  if( !obj || !obj.offsetParent )
+	  {
+		continue;
+	  }
+  
+	  // Find the element's offsetTop and offsetLeft relative to the BODY tag.
+	  objLeft   = obj.offsetLeft;
+	  objTop    = obj.offsetTop;
+	  objParent = obj.offsetParent;
+	  
+	  while( objParent.tagName.toUpperCase() != "BODY" )
+	  {
+		objLeft  += objParent.offsetLeft;
+		objTop   += objParent.offsetTop;
+		objParent = objParent.offsetParent;
+	  }
+  
+	  objHeight = obj.offsetHeight;
+	  objWidth = obj.offsetWidth;
+  
+	  if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
+	  else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
+	  else if( overDiv.offsetTop >= ( objTop + objHeight ));
+	  else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
+	  else
+	  {
+		obj.style.visibility = "hidden";
+	  }
+	}
+  }
+}
+ 
+/*
+* unhides <select> and <applet> objects (for IE only)
+*/
+function showElement( elmID )
+{
+  if( ie )
+  {
+	for( i = 0; i < document.getElementsByTagName( elmID ).length; i++ )
+	{
+	  obj = document.getElementsByTagName( elmID )[i];
+	  
+	  if( !obj || !obj.offsetParent )
+	  {
+		continue;
+	  }
+	
+	  obj.style.visibility = "";
+	}
+  }
+}
+
+function lw_createLayer (layerName, top_pos, left_pos, width, height, bgcolor, bordercolor, z_index) {
+	document.write("<div ONCLICK='event.cancelBubble=true' id='"+layerName+"' style='z-index:" + z_index + ";position:absolute;top:"+top_pos+";left:"+left_pos+";visibility:hidden;'><table bgcolor='"+bgcolor+"' style='border-width:1px;border-style:solid;border-color:" + bordercolor + "' cellpadding=2 cellspacing=0 width=0><tr><td valign=top width='"+width+"' height='"+height+"'><span id='"+layerName+"_content'></span></td></tr></table></div>")
+}
+
+function lw_getObj (objName) {
+	return (dom)?document.getElementById(objName).style:ie?eval("document.all."+objName) :eval("document."+objName)
+}
+
+function lw_showLayer (layerName) {
+
+	found=false
+	for (i=0;i<=layerIndex;i++)
+	{
+		if (layerQueue[i]==layerName)
+		{
+			found=true
+		}
+	}
+
+	if ((lw_getObj(layerName).visibility!="visible")&&(lw_getObj(layerName).visibility!="show"))
+	{
+		lw_getObj(layerName).visibility = (dom||ie)?"visible":"show"
+		layerQueue[++layerIndex] = layerName
+
+		hideElement( 'SELECT', document.getElementById(layerName) );
+		hideElement( 'APPLET', document.getElementById(layerName) );
+	}	
+}
+
+function lw_hideLayer () {
+	showElement( 'SELECT', document.getElementById(layerQueue[layerIndex]) );
+	showElement( 'APPLET', document.getElementById(layerQueue[layerIndex]) );
+
+	lw_getObj(layerQueue[layerIndex--]).visibility = "hidden"
+}
+
+function lw_hideLayerName (layerName) {
+	var i
+	var tmpQueue=new Array()
+	var newIndex=-1
+
+	showElement( 'SELECT', document.getElementById(layerName) );
+	showElement( 'APPLET', document.getElementById(layerName) );
+
+	lw_getObj(layerName).visibility = "hidden"
+
+	for (i=0;i<=layerIndex;i++)
+	{
+		if ((layerQueue[i]!="")&&(layerQueue[i]!=layerName))
+		{
+			tmpQueue [++newIndex] = layerQueue[i]			
+			hideElement( 'SELECT', document.getElementById(layerQueue[i]) );
+			hideElement( 'APPLET', document.getElementById(layerQueue[i]) );
+		}
+		
+	}
+
+	layerQueue = tmpQueue
+	layerIndex = newIndex
+}
+
+function lw_closeAllLayers() {
+	while (layerIndex >= 0)
+	{
+		lw_hideLayer()
+	}
+}
+
+function lw_closeLastLayer() {
+	if (layerIndex >= 0)
+	{
+		while ((lw_getObj(layerQueue[layerIndex]).visibility!="visible") && (layerIndex>0))
+		{
+			layerIndex--;
+		}
+		lw_hideLayer()
+	}
+}
+
+function lw_escLayer (e) {
+	if (navigator.appName=="Netscape")
+	{
+		var keyCode = e.keyCode?e.keyCode:e.which?e.which:e.charCode;
+		if ((keyCode==27)||(keyCode==1))
+		{
+			lw_closeLastLayer()
+		}
+	}
+	else
+	if ((event.keyCode==0)||(event.keyCode==27))
+	{
+		lw_closeLastLayer()		
+	}
+}
+
+
+var lw_leftpos = 0
+var lw_toppos = 0
+var lw_width = 0
+var lw_height = 0
+
+function lw_calcpos(obj) {
+	lw_leftpos=0
+	lw_toppos=0
+	lw_width = obj.offsetWidth
+	lw_height = obj.offsetHeight
+
+	var aTag = obj
+	do {
+		lw_leftpos += aTag.offsetLeft;
+		lw_toppos += aTag.offsetTop;
+		aTag = aTag.offsetParent;
+	} while(aTag.tagName!="BODY");
+}
+
+document.onkeypress = lw_escLayer;
+document.onclick = lw_closeAllLayers;

+ 376 - 0
includes/calendar_lw_menu.js

@@ -0,0 +1,376 @@
+//	written	by Tan Ling Wee
+//	last updated 20 June 2003
+//	email :	[email protected]
+
+var orientation=0	// 0-horizontal 1-vertical
+var imgPath = "js/"
+
+var mainItemForeground = "#000000"
+var mainItemBorder = "#f0f0f0"
+var mainItemBackground = "#f0f0f0"
+
+var mainItemHoverForeground = "#000000"
+var mainItemHoverBorder = "#a0a0a0"
+var mainItemHoverBackground = "#d0d0d0"
+
+var subItemForeground = "#000000"
+var subItemBorder = "#ffffff"
+var subItemBackground = "#ffffff"
+
+var subItemHoverForeground = "#000000"
+var subItemHoverBorder = "#a0a0a0"
+var subItemHoverBackground = "#d0d0d0"
+
+var menuFont = "verdana"
+var menuSize = "11px"
+
+
+/////////////////////////////////////////////////////////////////////////////
+
+var	ie=(navigator.appName=='Microsoft Internet Explorer')
+var	ns=(navigator.appName=='Netscape')
+var	dom=document.getElementById
+var lw_menuId, lw_trigger, to1
+var s1
+
+/////////////////////////////////////////////////////////////////////////////
+
+function Tmenu (id, parentId, url, description, img) {
+	this.id = id
+	this.parentId = parentId
+	this.url = url
+	this.description = description
+	this.numChild = 0
+	this.levelId = 0
+	this.img = img
+}
+
+/////////////////////////////////////////////////////////////////////////////
+
+var menu = new Array()
+var menuCounter = 0
+var numLevel = 0
+var prevMenuId = -1
+var nNowAt = 0
+
+function displayMenuItem(menuId) {
+	var sHTML
+	
+	if (menu[menuId].parentId>0)
+	{
+		ItemForeground = subItemForeground 
+		Border = subItemBorder 
+		Background = subItemBackground 
+
+		HoverForeground = subItemHoverForeground 
+		HoverBorder = subItemHoverBorder 
+		HoverBackground = subItemHoverBackground 
+	}
+	else
+	{
+		ItemForeground = mainItemForeground 
+		Border = mainItemBorder 
+		Background = mainItemBackground 
+
+		HoverForeground = mainItemHoverForeground 
+		HoverBorder = mainItemHoverBorder 
+		HoverBackground = mainItemHoverBackground 
+	}
+
+	if ((orientation==1)||(menu[menuId].levelId>0))
+	{
+		sHTML += "<tr>"
+	}	
+
+	if (menu[menuId].description!='-')
+	{
+		sHTML = "<td valign='top' id='menu_"+menuId+"' style='cursor:pointer;cursor:hand;border-style:solid;border-width:1px;background-color:"+ Background +";color=\""+ ItemForeground +"\";border-color:"+ Border +"' onmouseover='clearInterval(s1);this.style.backgroundColor=\"" + HoverBackground + "\";this.style.color=\"" + HoverForeground + "\";this.style.borderColor=\"" + HoverBorder + "\";"
+
+		if (menu[menuId].numChild!=0) {
+			sHTML += "showSubmenu("+menu[menuId].id+",this);hideSubmenu(menu["+menuId+"].levelId+1);"
+		}
+		else
+		{
+			sHTML += "prevMenuId = "+menuId+";hideSubmenu(menu["+menuId+"].levelId);"
+		}
+
+		sHTML += ";nNowAt="+menuId+";clearAll("+menu[menuId].levelId+","+menu[menuId].parentId+")' onclick='document.location.href=\""+menu[menuId].url+"\"' onmouseout='s1=setInterval(\"resetMenu();hideSubmenu(0)\",1000);'><table cellpadding=0 cellspacing=0 border=0 width='100%'><tr>"
+
+		if (menu[menuId].levelId>0)
+		{
+			sHTML += "<td  valign='bottom' style='padding-left:3px' width=20><img src='"
+			if (menu[menuId].img=="")
+			{
+				sHTML += imgPath + "trans.gif"
+			}
+			else
+			{
+				sHTML += imgPath + menu[menuId].img
+			}
+			sHTML += "' width=16 height=16 border=0></td>"
+		}
+
+		if ((orientation==0) && (menu[menuId].levelId==0))
+		{
+			nArrowWidth = 0
+		}
+		else
+		{
+			nArrowWidth = 25
+		}
+
+		sHTML += "<td  valign='bottom' style='padding-left:5px;padding-right:5px' align=left>" + menu[menuId].description.replace(" ","&nbsp;") + "</td><td style='padding-right:2px' align=right width="+nArrowWidth+">"
+		if (menu[menuId].numChild>0)
+		{
+			if ((orientation==0)&&(menu[menuId].levelId==0))
+			{
+				sHTML += "<img src='" + imgPath + "arrow_down.gif'>"
+			}
+			else
+			{
+				sHTML += "<img src='" + imgPath + "arrow_right.gif'>"
+			}
+		}
+		else
+		{
+			sHTML += "&nbsp;"
+		}
+		sHTML += "</td></tr></table></td>"
+	}
+	else
+	{
+		sHTML = "<td valign='bottom'><img src='" + imgPath + "trans.gif' height=2></td></tr><tr><td onmouseover='' bgcolor='#d0d0d0'><img src='" + imgPath + "trans.gif' height=1></td></tr><tr><td><img src='" + imgPath + "trans.gif' height=2></td>"
+	}
+
+	if ((orientation==1)||(menu[menuId].levelId>0))
+	{
+		sHTML += "</tr>"
+	}	
+	return sHTML
+}
+
+function clearAll(levelId, parentId) {
+
+	if (levelId>0)
+	{
+		Border = subItemBorder 
+		Background = subItemBackground 
+	}
+	else
+	{
+		Border = mainItemBorder 
+		Background = mainItemBackground 
+	}
+
+	for (i=0;i<menuCounter;i++)
+	{
+		if (menu[i].levelId==levelId)
+		{
+			if ((i!=nNowAt) && (menu[i].parentId==parentId) && (menu[i].description!="-")) {
+				lw_getObj("menu_"+i).backgroundColor=Background;
+				lw_getObj("menu_"+i).borderColor=Border
+			}
+		}
+	}
+
+}
+
+function mapID (id) {
+	for (var i=0;i<menuCounter;i++)
+	{
+		if (menu[i].id==id)
+		{
+			return i
+		}
+	}
+	return -1
+}
+
+function showSubmenu(menuId,trigger) {
+	lw_menuId = menuId
+	lw_trigger = trigger
+
+	if (ns)
+	{
+		to1 = setTimeout("showActualSubmenu(lw_menuId,lw_trigger)",50)
+	}
+	else
+	{
+		showActualSubmenu(lw_menuId,lw_trigger)
+	}
+}
+
+function showActualSubmenu(menuId,trigger) {
+	var nLevel = 0
+	var leftpos = 0 
+	var nIndex=0
+
+	if (menuId>0)
+	{
+		lw_calcpos(trigger)
+
+		for (var i=0;i<menuCounter;i++)
+		{
+			if (menu[i].id==menuId)
+			{	
+				nLevel = menu[i].levelId
+				nIndex = i
+			}
+		}
+
+		if ((orientation==1)||(menu[nIndex].parentId>0))
+		{
+			lw_getObj("menu_level_"+nLevel).top=lw_toppos
+			leftpos = lw_leftpos + lw_width + 5
+
+			if (nLevel==0) {
+				leftpos -= 3
+			}
+		}
+		else {
+			lw_getObj("menu_level_"+nLevel).top = lw_toppos + lw_height + 2
+			leftpos = lw_leftpos
+		}
+
+		lw_getObj("menu_level_"+nLevel).left=leftpos
+
+		sHTML = "<table cellpadding=0 cellspacing=0 border=1>"
+		for (var i=0;i<menuCounter;i++)
+		{
+			if (menu[i].parentId==menuId)
+			{
+				sHTML += displayMenuItem (i)
+			}
+		}
+		sHTML += "</table>"
+
+		document.getElementById("menu_level_"+nLevel+"_content").innerHTML=sHTML
+		lw_showLayer('menu_level_'+nLevel)
+	} 
+}
+
+function hideSubmenu(levelId) {
+	for (var cnt=levelId; cnt<numLevel; cnt++)
+	{
+		lw_hideLayerName("menu_level_"+cnt)
+	}
+}
+
+function DrawMenu ()  {
+
+	for (var i=0; i<numLevel ; i++)
+	{
+		lw_createLayer("menu_level_"+i,0,0,0,0,"#ffffff","#d0d0d0",100)
+	}
+	
+	sHTML="<table width=100% cellpadding=2 cellspacing=0>"
+	for (var i=0; i<menuCounter; i++)
+	{
+		if (menu[i].parentId==0)
+		{		
+			sHTML += displayMenuItem (i)
+		}
+		else if (menu[i].parentId==-1)
+		{		
+			sHTML += "<tr><td valign='top'><img src='trans' height=2></td></tr><tr bgcolor='"+mainItemBackground+"'><td style='padding:5px'><b>" + menu[i].description + "</b></td></tr>"
+		}
+	}
+	sHTML += "</table>"
+
+	document.writeln(sHTML)
+
+}
+
+function getLevel (menuId) {
+	var pId=menuId
+	var nLevel=0
+
+	while (pId!=0)
+	{
+		nLevel++
+		for (var i=0;i<menuCounter;i++)
+		{
+			if (menu[i].id==pId)
+			{	
+				pId = menu[i].parentId
+			}
+		}
+	}
+
+	return nLevel
+}
+
+function AddMenuItem (id, parentId, url, description, img)  {
+
+	menu[menuCounter++] = new Tmenu (id, parentId, url, description, img)
+
+	if (parentId>0)
+	{
+		for (i=0;i<menuCounter;i++)
+		{
+			if (menu[i].id==parentId)
+			{
+				menu[i].numChild++
+			}
+		}
+		menu[menuCounter-1].levelId = getLevel(parentId)
+
+		if ( numLevel < menu[menuCounter-1].levelId)
+		{	
+			numLevel = menu[menuCounter-1].levelId
+		}
+	}	 
+	else if (parentId==0)
+	{
+		menu[menuCounter-1].levelId = 0
+	}
+	else
+	{
+		menu[menuCounter-1].levelId = -1
+	}
+}
+
+function handleonclick() {
+	if (ns)
+	{
+		lw_closeAllLayers()
+	}
+	else
+	{
+		lw_closeAllLayers(event)
+	}
+
+	resetMenu()
+}
+
+function handlekeypress(e) {
+	if (ns)
+	{
+		var keyCode = e.keyCode?e.keyCode:e.which?e.which:e.charCode;
+		if ((keyCode==27)||(keyCode==1))
+		{
+			handleonclick()
+		}
+	}
+	else
+	if ((event.keyCode==0)||(event.keyCode==27))
+	{
+		handleonclick()
+	}
+	resetMenu()
+}
+
+function resetMenu () {
+	for (i=0;i<menuCounter;i++)
+	{
+		if (menu[i].levelId==0)
+		{
+			lw_getObj("menu_"+i).backgroundColor=mainItemBackground
+			lw_getObj("menu_"+i).borderColor=mainItemBorder
+		}
+	}
+}
+
+document.onkeypress = handlekeypress
+document.onclick = handleonclick
+

+ 637 - 0
includes/calendar_popcalendar.js

@@ -0,0 +1,637 @@
+//	written	by Tan Ling	Wee	on 2 Dec 2001
+//	last updated 20 June 2003
+//	email :	[email protected]
+
+	var	fixedX = -1			// x position (-1 if to appear below control)
+	var	fixedY = -1			// y position (-1 if to appear below control)
+	var startAt = 1			// 0 - sunday ; 1 - monday
+	var showWeekNumber = 1	// 0 - don't show; 1 - show
+	var showToday = 1		// 0 - don't show; 1 - show
+	var imgDir = "/images/"			// directory for images ... e.g. var imgDir="/img/"
+
+	var gotoString = "Go To Current Month"
+	var todayString = "Today is"
+	var weekString = "Wk"
+	var scrollLeftMessage = "Click to scroll to previous month. Hold mouse button to scroll automatically."
+	var scrollRightMessage = "Click to scroll to next month. Hold mouse button to scroll automatically."
+	var selectMonthMessage = "Click to select a month."
+	var selectYearMessage = "Click to select a year."
+	var selectDateMessage = "Select [date] as date." // do not replace [date], it will be replaced by date.
+
+	var	crossobj, crossMonthObj, crossYearObj, monthSelected, yearSelected, dateSelected, omonthSelected, oyearSelected, odateSelected, monthConstructed, yearConstructed, intervalID1, intervalID2, timeoutID1, timeoutID2, ctlToPlaceValue, ctlNow, dateFormat, nStartingYear
+
+	var	bPageLoaded=false
+	var	ie=document.all
+	var	dom=document.getElementById
+
+	var	ns4=document.layers
+	var	today =	new	Date()
+	var	dateNow	 = today.getDate()
+	var	monthNow = today.getMonth()
+	var	yearNow	 = today.getYear()
+	var	imgsrc = new Array("caldrop.png","caldrop.png","calleft.png","calleft.png","calright.png","calright.png")
+	var	img	= new Array()
+
+	var bShow = false;
+
+    /* hides <select> and <applet> objects (for IE only) */
+    function hideElement( elmID, overDiv )
+    {
+      if( ie )
+      {
+        for( i = 0; i < document.all.tags( elmID ).length; i++ )
+        {
+          obj = document.all.tags( elmID )[i];
+          if( !obj || !obj.offsetParent )
+          {
+            continue;
+          }
+      
+          // Find the element's offsetTop and offsetLeft relative to the BODY tag.
+          objLeft   = obj.offsetLeft;
+          objTop    = obj.offsetTop;
+          objParent = obj.offsetParent;
+          
+          while( objParent.tagName.toUpperCase() != "BODY" )
+          {
+            objLeft  += objParent.offsetLeft;
+            objTop   += objParent.offsetTop;
+            objParent = objParent.offsetParent;
+          }
+      
+          objHeight = obj.offsetHeight;
+          objWidth = obj.offsetWidth;
+      
+          if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
+          else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
+          else if( overDiv.offsetTop >= ( objTop + objHeight ));
+          else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
+          else
+          {
+            obj.style.visibility = "hidden";
+          }
+        }
+      }
+    }
+     
+    /*
+    * unhides <select> and <applet> objects (for IE only)
+    */
+    function showElement( elmID )
+    {
+      if( ie )
+      {
+        for( i = 0; i < document.all.tags( elmID ).length; i++ )
+        {
+          obj = document.all.tags( elmID )[i];
+          
+          if( !obj || !obj.offsetParent )
+          {
+            continue;
+          }
+        
+          obj.style.visibility = "";
+        }
+      }
+    }
+
+	function HolidayRec (d, m, y, desc)
+	{
+		this.d = d
+		this.m = m
+		this.y = y
+		this.desc = desc
+	}
+
+	var HolidaysCounter = 0
+	var Holidays = new Array()
+
+	function addHoliday (d, m, y, desc)
+	{
+		Holidays[HolidaysCounter++] = new HolidayRec ( d, m, y, desc )
+	}
+
+	if (dom)
+	{
+		for	(i=0;i<imgsrc.length;i++)
+		{
+			img[i] = new Image
+			img[i].src = imgDir + imgsrc[i]
+		}
+		document.write ("<div onclick='bShow=true' id='calendar'	style='z-index:+999;position:absolute;visibility:hidden;'><table width="+((showWeekNumber==1)?250:220)+" style='font-family:arial;font-size:11px;border-width:1;border-style:solid;border-color:#287FB5;font-family:arial; font-size:11px}' bgcolor='#FFFFFF'><tr class='calmenubar'><td valign='top'><table border='0' cellpadding='0' cellspacing='0' width='"+((showWeekNumber==1)?248:218)+"'><tr><td valign='middle' style='font-family:arial; font-size:11px;'><font color='#287FB5' class='menubartxt'><B><span id='caption'></span></B></font></td><td align=right valign='middle'><input type='button' class='btn' onclick='javascript:hideCalendar();' name='x' value='x'></td></tr></table></td></tr><tr><td style='padding:0px' bgcolor=#ffffff><span id='content'></span></td></tr>")
+		//document.write ("<div onclick='bShow=true' id='calendar'	style='z-index:+999;position:absolute;visibility:hidden;'><table	width="+((showWeekNumber==1)?250:220)+" style='font-family:arial;font-size:11px;border-width:1;border-style:solid;border-color:#a0a0a0;font-family:arial; font-size:11px}' bgcolor='#ffffff'><tr bgcolor='#FF00aa' class='calmenubar'><td valign='top'><table cellpadding='0' cellspacing='0' width='"+((showWeekNumber==1)?248:218)+"'><tr><td style='padding:1px;font-family:arial; font-size:11px;'><font color='#ffffff' class='menubartxt'><B><span id='caption'></span></B></font></td><td align=right><a href='javascript:hideCalendar()'><IMG SRC='"+imgDir+"close.gif' WIDTH='10' HEIGHT='10' BORDER='0' ALT='Close the Calendar'></a></td></tr></table></td></tr><tr><td style='padding:0px' bgcolor=#ffffff><span id='content'></span></td></tr>")
+
+		if (showToday==1)
+		{
+            //bottom background
+			document.write ("<tr bgcolor=#f0f0f0><td style='padding:5px' align=center><span id='lblToday'></span></td></tr>")
+		}
+			
+		document.write ("</table></div><div id='selectMonth' style='z-index:+999;position:absolute;visibility:hidden;'></div><div id='selectYear' style='z-index:+999;position:absolute;visibility:hidden;'></div>");
+	}
+
+	var	monthName =	new	Array("January","February","March","April","May","June","July","August","September","October","November","December")
+	var	monthName2 = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")
+	if (startAt==0)
+	{
+		dayName = new Array	("Sun","Mon","Tue","Wed","Thu","Fri","Sat")
+	}
+	else
+	{
+		dayName = new Array	("Mon","Tue","Wed","Thu","Fri","Sat","Sun")
+	}
+	var	styleAnchor="text-decoration:none;color:black;"
+	var	styleLightBorder="border-style:solid;border-width:1px;border-color:#a0a0a0;"
+
+	function swapImage(srcImg, destImg){
+		if (ie)	{ document.getElementById(srcImg).setAttribute("src",imgDir + destImg) }
+	}
+
+	function init()	{
+		if (!ns4)
+		{
+			if (!ie) { yearNow += 1900	}
+
+			crossobj=(dom)?document.getElementById("calendar").style : ie? document.all.calendar : document.calendar
+			hideCalendar()
+
+			crossMonthObj=(dom)?document.getElementById("selectMonth").style : ie? document.all.selectMonth	: document.selectMonth
+
+			crossYearObj=(dom)?document.getElementById("selectYear").style : ie? document.all.selectYear : document.selectYear
+
+			monthConstructed=false;
+			yearConstructed=false;
+
+			if (showToday==1)
+			{
+				document.getElementById("lblToday").innerHTML =	todayString + " <a onmousemove='window.status=\""+gotoString+"\"' onmouseout='window.status=\"\"' title='"+gotoString+"' style='"+styleAnchor+"' href='javascript:monthSelected=monthNow;yearSelected=yearNow;constructCalendar();'>"+dayName[(today.getDay()-startAt==-1)?6:(today.getDay()-startAt)]+", " + dateNow + " " + monthName[monthNow].substring(0,3)	+ "	" +	yearNow	+ "</a>"
+			}
+
+			sHTML1="<span id='spanLeft'	style='border-style:solid;border-width:0;border-color:#D3DCE4;cursor:pointer' onmouseover='swapImage(\"changeLeft\",\"calleft.png\");window.status=\""+scrollLeftMessage+"\"' onclick='javascript:decMonth()' onmouseout='clearInterval(intervalID1);swapImage(\"changeLeft\",\"calleft.png\");window.status=\"\"' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartDecMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp<IMG id='changeLeft' SRC='"+imgDir+"calleft.png' BORDER=0>&nbsp</span>&nbsp;"
+			sHTML1+="<span id='spanRight' style='border-style:solid;border-width:0;border-color:#D3DCE4;cursor:pointer'	onmouseover='swapImage(\"changeRight\",\"calright.png\");window.status=\""+scrollRightMessage+"\"' onmouseout='clearInterval(intervalID1);swapImage(\"changeRight\",\"calright.png\");window.status=\"\"' onclick='incMonth()' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartIncMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp<IMG id='changeRight' SRC='"+imgDir+"calright.png'	BORDER=0>&nbsp</span>&nbsp"
+			sHTML1+="<span id='spanMonth' style='border-style:solid;border-width:0;border-color:#D3DCE4;cursor:pointer'	onmouseover='swapImage(\"changeMonth\",\"caldrop.png\");window.status=\""+selectMonthMessage+"\"' onmouseout='swapImage(\"changeMonth\",\"caldrop.png\");window.status=\"\"' onclick='popUpMonth()'></span>&nbsp;"
+			sHTML1+="<span id='spanYear' style='border-style:solid;border-width:0;border-color:#D3DCE4;cursor:pointer' onmouseover='swapImage(\"changeYear\",\"caldrop.png\");window.status=\""+selectYearMessage+"\"'	onmouseout='swapImage(\"changeYear\",\"caldrop.png\");window.status=\"\"'	onclick='popUpYear()'></span>&nbsp;"
+			
+			document.getElementById("caption").innerHTML  =	sHTML1
+
+			bPageLoaded=true
+		}
+	}
+
+	function hideCalendar()	{
+		crossobj.visibility="hidden"
+		if (crossMonthObj != null){crossMonthObj.visibility="hidden"}
+		if (crossYearObj !=	null){crossYearObj.visibility="hidden"}
+
+	    showElement( 'SELECT' );
+		showElement( 'APPLET' );
+	}
+
+	function padZero(num) {
+		return (num	< 10)? '0' + num : num ;
+	}
+
+	function constructDate(d,m,y)
+	{
+		sTmp = dateFormat
+		sTmp = sTmp.replace	("dd","<e>")
+		sTmp = sTmp.replace	("d","<d>")
+		sTmp = sTmp.replace	("<e>",padZero(d))
+		sTmp = sTmp.replace	("<d>",d)
+		sTmp = sTmp.replace	("mmmm","<p>")
+		sTmp = sTmp.replace	("mmm","<o>")
+		sTmp = sTmp.replace	("mm","<n>")
+		sTmp = sTmp.replace	("m","<m>")
+		sTmp = sTmp.replace	("<m>",m+1)
+		sTmp = sTmp.replace	("<n>",padZero(m+1))
+		sTmp = sTmp.replace	("<o>",monthName[m])
+		sTmp = sTmp.replace	("<p>",monthName2[m])
+		sTmp = sTmp.replace	("yyyy",y)
+		return sTmp.replace ("yy",padZero(y%100))
+	}
+
+	function closeCalendar() {
+		var	sTmp
+
+		hideCalendar();
+		ctlToPlaceValue.value =	constructDate(dateSelected,monthSelected,yearSelected)
+	}
+
+	/*** Month Pulldown	***/
+
+	function StartDecMonth()
+	{
+		intervalID1=setInterval("decMonth()",80)
+	}
+
+	function StartIncMonth()
+	{
+		intervalID1=setInterval("incMonth()",80)
+	}
+
+	function incMonth () {
+		monthSelected++
+		if (monthSelected>11) {
+			monthSelected=0
+			yearSelected++
+		}
+		constructCalendar()
+	}
+
+	function decMonth () {
+		monthSelected--
+		if (monthSelected<0) {
+			monthSelected=11
+			yearSelected--
+		}
+		constructCalendar()
+	}
+
+	function constructMonth() {
+		popDownYear()
+		if (!monthConstructed) {
+			sHTML =	""
+			for	(i=0; i<12;	i++) {
+				sName =	monthName[i];
+				if (i==monthSelected){
+					sName =	"<B>" +	sName +	"</B>"
+				}
+				sHTML += "<tr><td id='m" + i + "' onmouseover='this.style.backgroundColor=\"#D3DCE4\"' onmouseout='this.style.backgroundColor=\"\"' style='cursor:pointer' onclick='monthConstructed=false;monthSelected=" + i + ";constructCalendar();popDownMonth();event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>"
+			}
+
+			document.getElementById("selectMonth").innerHTML = "<table width=70	style='font-family:arial; font-size:11px; border-width:1; border-style:solid; border-color:#a0a0a0;' bgcolor='#F1F4F6' cellspacing=0 onmouseover='clearTimeout(timeoutID1)'	onmouseout='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"popDownMonth()\",100);event.cancelBubble=true'>" +	sHTML +	"</table>"
+
+			monthConstructed=true
+		}
+	}
+
+	function popUpMonth() {
+		constructMonth()
+		crossMonthObj.visibility = (dom||ie)? "visible"	: "show"
+		crossMonthObj.left = parseInt(crossobj.left) + 50
+		crossMonthObj.top =	parseInt(crossobj.top) + 26
+
+		hideElement( 'SELECT', document.getElementById("selectMonth") );
+		hideElement( 'APPLET', document.getElementById("selectMonth") );			
+	}
+
+	function popDownMonth()	{
+		crossMonthObj.visibility= "hidden"
+	}
+
+	/*** Year Pulldown ***/
+
+	function incYear() {
+		for	(i=0; i<7; i++){
+			newYear	= (i+nStartingYear)+1
+			if (newYear==yearSelected)
+			{ txtYear =	"&nbsp;<B>"	+ newYear +	"</B>&nbsp;" }
+			else
+			{ txtYear =	"&nbsp;" + newYear + "&nbsp;" }
+			document.getElementById("y"+i).innerHTML = txtYear
+		}
+		nStartingYear ++;
+		bShow=true
+	}
+
+	function decYear() {
+		for	(i=0; i<7; i++){
+			newYear	= (i+nStartingYear)-1
+			if (newYear==yearSelected)
+			{ txtYear =	"&nbsp;<B>"	+ newYear +	"</B>&nbsp;" }
+			else
+			{ txtYear =	"&nbsp;" + newYear + "&nbsp;" }
+			document.getElementById("y"+i).innerHTML = txtYear
+		}
+		nStartingYear --;
+		bShow=true
+	}
+
+	function selectYear(nYear) {
+		yearSelected=parseInt(nYear+nStartingYear);
+		yearConstructed=false;
+		constructCalendar();
+		popDownYear();
+	}
+
+	function constructYear() {
+		popDownMonth()
+		sHTML =	""
+		if (!yearConstructed) {
+
+			sHTML =	"<tr><td align='center'	onmouseover='this.style.backgroundColor=\"#D3DCE4\"' onmouseout='clearInterval(intervalID1);this.style.backgroundColor=\"\"' style='cursor:pointer'	onmousedown='clearInterval(intervalID1);intervalID1=setInterval(\"decYear()\",30)' onmouseup='clearInterval(intervalID1)'>-</td></tr>"
+
+			j =	0
+			nStartingYear =	yearSelected-3
+			for	(i=(yearSelected-3); i<=(yearSelected+3); i++) {
+				sName =	i;
+				if (i==yearSelected){
+					sName =	"<B>" +	sName +	"</B>"
+				}
+
+				sHTML += "<tr><td id='y" + j + "' onmouseover='this.style.backgroundColor=\"#D3DCE4\"' onmouseout='this.style.backgroundColor=\"\"' style='cursor:pointer' onclick='selectYear("+j+");event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>"
+				j ++;
+			}
+
+			sHTML += "<tr><td align='center' onmouseover='this.style.backgroundColor=\"#D3DCE4\"' onmouseout='clearInterval(intervalID2);this.style.backgroundColor=\"\"' style='cursor:pointer' onmousedown='clearInterval(intervalID2);intervalID2=setInterval(\"incYear()\",30)'	onmouseup='clearInterval(intervalID2)'>+</td></tr>"
+
+			document.getElementById("selectYear").innerHTML	= "<table width=44 style='font-family:arial; font-size:11px; border-width:1; border-style:solid; border-color:#a0a0a0;'	bgcolor='#F1F4F6' onmouseover='clearTimeout(timeoutID2)' onmouseout='clearTimeout(timeoutID2);timeoutID2=setTimeout(\"popDownYear()\",100)' cellspacing=0>"	+ sHTML	+ "</table>"
+
+			yearConstructed	= true
+		}
+	}
+
+	function popDownYear() {
+		clearInterval(intervalID1)
+		clearTimeout(timeoutID1)
+		clearInterval(intervalID2)
+		clearTimeout(timeoutID2)
+		crossYearObj.visibility= "hidden"
+	}
+
+	function popUpYear() {
+		var	leftOffset
+
+		constructYear()
+		crossYearObj.visibility	= (dom||ie)? "visible" : "show"
+		leftOffset = parseInt(crossobj.left) + document.getElementById("spanYear").offsetLeft
+		if (ie)
+		{
+			leftOffset += 6
+		}
+		crossYearObj.left =	leftOffset
+		crossYearObj.top = parseInt(crossobj.top) +	26
+	}
+
+	/*** calendar ***/
+   function WeekNbr(n) {
+      // Algorithm used:
+      // From Klaus Tondering's Calendar document (The Authority/Guru)
+      // hhtp://www.tondering.dk/claus/calendar.html
+      // a = (14-month) / 12
+      // y = year + 4800 - a
+      // m = month + 12a - 3
+      // J = day + (153m + 2) / 5 + 365y + y / 4 - y / 100 + y / 400 - 32045
+      // d4 = (J + 31741 - (J mod 7)) mod 146097 mod 36524 mod 1461
+      // L = d4 / 1460
+      // d1 = ((d4 - L) mod 365) + L
+      // WeekNumber = d1 / 7 + 1
+ 
+      year = n.getFullYear();
+      month = n.getMonth() + 1;
+      if (startAt == 0) {
+         day = n.getDate() + 1;
+      }
+      else {
+         day = n.getDate();
+      }
+ 
+      a = Math.floor((14-month) / 12);
+      y = year + 4800 - a;
+      m = month + 12 * a - 3;
+      b = Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400);
+      J = day + Math.floor((153 * m + 2) / 5) + 365 * y + b - 32045;
+      d4 = (((J + 31741 - (J % 7)) % 146097) % 36524) % 1461;
+      L = Math.floor(d4 / 1460);
+      d1 = ((d4 - L) % 365) + L;
+      week = Math.floor(d1/7) + 1;
+ 
+      return week;
+   }
+
+	function constructCalendar () {
+		var aNumDays = Array (31,0,31,30,31,30,31,31,30,31,30,31)
+
+		var dateMessage
+		var	startDate =	new	Date (yearSelected,monthSelected,1)
+		var endDate
+
+		if (monthSelected==1)
+		{
+			endDate	= new Date (yearSelected,monthSelected+1,1);
+			endDate	= new Date (endDate	- (24*60*60*1000));
+			numDaysInMonth = endDate.getDate()
+		}
+		else
+		{
+			numDaysInMonth = aNumDays[monthSelected];
+		}
+
+		datePointer	= 0
+		dayPointer = startDate.getDay() - startAt
+		
+		if (dayPointer<0)
+		{
+			dayPointer = 6
+		}
+
+		sHTML =	"<table	border=0 style='font-family:verdana;font-size:10px;'><tr>"
+
+		if (showWeekNumber==1)
+		{
+			sHTML += "<td width=27><b>" + weekString + "</b></td><td width=1 rowspan=7 bgcolor='#d0d0d0' style='padding:0px'><img src='"+imgDir+"divider.gif' width=1></td>"
+		}
+
+		for	(i=0; i<7; i++)	{
+			sHTML += "<td width='27' align='right'><B>"+ dayName[i]+"</B></td>"
+		}
+		sHTML +="</tr><tr>"
+		
+		if (showWeekNumber==1)
+		{
+			sHTML += "<td align=right>" + WeekNbr(startDate) + "&nbsp;</td>"
+		}
+
+		for	( var i=1; i<=dayPointer;i++ )
+		{
+			sHTML += "<td>&nbsp;</td>"
+		}
+	
+		for	( datePointer=1; datePointer<=numDaysInMonth; datePointer++ )
+		{
+			dayPointer++;
+			sHTML += "<td align=right>"
+			sStyle=styleAnchor
+			if ((datePointer==odateSelected) &&	(monthSelected==omonthSelected)	&& (yearSelected==oyearSelected))
+			{ sStyle+=styleLightBorder }
+
+			sHint = ""
+			for (k=0;k<HolidaysCounter;k++)
+			{
+				if ((parseInt(Holidays[k].d)==datePointer)&&(parseInt(Holidays[k].m)==(monthSelected+1)))
+				{
+					if ((parseInt(Holidays[k].y)==0)||((parseInt(Holidays[k].y)==yearSelected)&&(parseInt(Holidays[k].y)!=0)))
+					{
+						sStyle+="background-color:#FFDDDD;"
+						sHint+=sHint==""?Holidays[k].desc:"\n"+Holidays[k].desc
+					}
+				}
+			}
+
+			var regexp= /\"/g
+			sHint=sHint.replace(regexp,"&quot;")
+
+			dateMessage = "onmousemove='window.status=\""+selectDateMessage.replace("[date]",constructDate(datePointer,monthSelected,yearSelected))+"\"' onmouseout='window.status=\"\"' "
+
+			if ((datePointer==dateNow)&&(monthSelected==monthNow)&&(yearSelected==yearNow))
+			{ sHTML += "<b><a "+dateMessage+" title=\"" + sHint + "\" style='"+sStyle+"' href='javascript:dateSelected="+datePointer+";closeCalendar();'><font color=#ff0000>&nbsp;" + datePointer + "</font>&nbsp;</a></b>"}
+			else if	(dayPointer % 7 == (startAt * -1)+1)
+			{ sHTML += "<a "+dateMessage+" title=\"" + sHint + "\" style='"+sStyle+"' href='javascript:dateSelected="+datePointer + ";closeCalendar();'>&nbsp;<font color=#909090>" + datePointer + "</font>&nbsp;</a>" }
+			else
+			{ sHTML += "<a "+dateMessage+" title=\"" + sHint + "\" style='"+sStyle+"' href='javascript:dateSelected="+datePointer + ";closeCalendar();'>&nbsp;" + datePointer + "&nbsp;</a>" }
+
+			sHTML += ""
+			if ((dayPointer+startAt) % 7 == startAt) { 
+				sHTML += "</tr><tr>" 
+				if ((showWeekNumber==1)&&(datePointer<numDaysInMonth))
+				{
+					sHTML += "<td align=right>" + (WeekNbr(new Date(yearSelected,monthSelected,datePointer+1))) + "&nbsp;</td>"
+				}
+			}
+		}
+
+		document.getElementById("content").innerHTML   = sHTML
+		document.getElementById("spanMonth").innerHTML = "&nbsp;" +	monthName[monthSelected] + "&nbsp;<IMG id='changeMonth' SRC='"+imgDir+"caldrop.png' BORDER=0>"
+		document.getElementById("spanYear").innerHTML =	"&nbsp;" + yearSelected	+ "&nbsp;<IMG id='changeYear' SRC='"+imgDir+"caldrop.png' BORDER=0>"
+	}
+
+	function popUpCalendar(ctl,	ctl2, format) {
+		var	leftpos=0
+		var	toppos=0
+
+		if (bPageLoaded)
+		{
+			if ( crossobj.visibility ==	"hidden" ) {
+				ctlToPlaceValue	= ctl2
+				dateFormat=format;
+
+				formatChar = " "
+				aFormat	= dateFormat.split(formatChar)
+				if (aFormat.length<3)
+				{
+					formatChar = "/"
+					aFormat	= dateFormat.split(formatChar)
+					if (aFormat.length<3)
+					{
+						formatChar = "."
+						aFormat	= dateFormat.split(formatChar)
+						if (aFormat.length<3)
+						{
+							formatChar = "-"
+							aFormat	= dateFormat.split(formatChar)
+							if (aFormat.length<3)
+							{
+								// invalid date	format
+								formatChar=""
+							}
+						}
+					}
+				}
+
+				tokensChanged =	0
+				if ( formatChar	!= "" )
+				{
+					// use user's date
+					aData =	ctl2.value.split(formatChar)
+
+					for	(i=0;i<3;i++)
+					{
+						if ((aFormat[i]=="d") || (aFormat[i]=="dd"))
+						{
+							dateSelected = parseInt(aData[i], 10)
+							tokensChanged ++
+						}
+						else if	((aFormat[i]=="m") || (aFormat[i]=="mm"))
+						{
+							monthSelected =	parseInt(aData[i], 10) - 1
+							tokensChanged ++
+						}
+						else if	(aFormat[i]=="yyyy")
+						{
+							yearSelected = parseInt(aData[i], 10)
+							tokensChanged ++
+						}
+						else if	(aFormat[i]=="mmm")
+						{
+							for	(j=0; j<12;	j++)
+							{
+								if (aData[i]==monthName[j])
+								{
+									monthSelected=j
+									tokensChanged ++
+								}
+							}
+						}
+						else if	(aFormat[i]=="mmmm")
+						{
+							for	(j=0; j<12;	j++)
+							{
+								if (aData[i]==monthName2[j])
+								{
+									monthSelected=j
+									tokensChanged ++
+								}
+							}
+						}
+					}
+				}
+
+				if ((tokensChanged!=3)||isNaN(dateSelected)||isNaN(monthSelected)||isNaN(yearSelected))
+				{
+					dateSelected = dateNow
+					monthSelected =	monthNow
+					yearSelected = yearNow
+				}
+
+				odateSelected=dateSelected
+				omonthSelected=monthSelected
+				oyearSelected=yearSelected
+
+				aTag = ctl
+				do {
+					aTag = aTag.offsetParent;
+					leftpos	+= aTag.offsetLeft;
+					toppos += aTag.offsetTop;
+				} while(aTag.tagName!="BODY");
+
+				crossobj.left =	fixedX==-1 ? ctl.offsetLeft	+ leftpos :	fixedX
+				crossobj.top = fixedY==-1 ?	ctl.offsetTop +	toppos + ctl.offsetHeight +	2 :	fixedY
+				constructCalendar (1, monthSelected, yearSelected);
+				crossobj.visibility=(dom||ie)? "visible" : "show"
+
+				hideElement( 'SELECT', document.getElementById("calendar") );
+				hideElement( 'APPLET', document.getElementById("calendar") );			
+
+				bShow = true;
+			}
+			else
+			{
+				hideCalendar()
+				if (ctlNow!=ctl) {popUpCalendar(ctl, ctl2, format)}
+			}
+			ctlNow = ctl
+		}
+	}
+
+	document.onkeypress = function hidecal1 () { 
+		if (event.keyCode==27) 
+		{
+			hideCalendar()
+		}
+	}
+	document.onclick = function hidecal2 () { 		
+		if (!bShow)
+		{
+			hideCalendar()
+		}
+		bShow = false
+	}
+
+	if(ie)
+	{
+		init()
+	}
+	else
+	{
+		window.onload=init
+	}

+ 108 - 0
includes/captcha/config.php

@@ -0,0 +1,108 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+$pathtofonts = "/captcha/fonts/"; //path from the root of the website
+
+/*
+//How to use this Captcha
+
+    //Option1: add this to the html form
+        <table width='100%' border='0' cellpadding="3" cellspacing="0">
+        <tr>
+          <td colspan='2'>Please type the code you see from the image into the text box below.</td>
+        </tr>
+        <tr>
+          <td align='right'><img src='/captcha/img.php'></td>
+          <td align='right'><input type="text" name="captcha" size="15"></td>
+        </tr>
+        </table>
+        
+    //Option2:  or add this to the html form
+				<br>
+					<script language="JavaScript" type="text/javascript">
+						function genNewCaptcha(imgObj) {
+							var randnum = Math.floor((1-1000)*Math.random()+1000);
+							imgObj.src='/captcha/img.php?x=' + randnum;
+						}
+					</script>
+					<table cellpadding="0" cellspacing="0" border="0" width="100%">
+						<tr>
+							<td align="center" colspan="2" style="font-size: 11px;">Please enter the text you see from the image below...</td>
+						</tr>
+						<tr>
+
+							<td align="center" valign="bottom" width="50%"><img id="captchaimg" src="/captcha/img.php" onclick="genNewCaptcha(this); document.getElementById('captcha').focus();" onmouseover="this.style.cursor='hand';" alt="Click for a new image."></td>
+							<td align="center" valign="bottom" width="50%"><input type="text" class="txt" style="text-align: center;" name="captcha" id="captcha" size="15" style="margin-top: 15px;"></td>
+						</tr>
+						<td align="center" colspan="2" style="font-size: 9px;"><br>Can't read the image text?  Click the image for a new one.</td>
+					</table>
+					<br>
+
+    //add this to the top of the page where the form is submitted to
+
+        //--- begin captcha verification ---------------------
+          //session_start(); //make sure sessions are started
+          if (strtolower($_SESSION["captcha"]) != strtolower($_REQUEST["captcha"]) || strlen($_SESSION["captcha"]) == 0) {
+
+              echo "       <span class=\"h2\">Sorry!</span>\n";
+              //echo "              <br><br>\n";
+              //echo "\n";
+              //echo "              <b>Your e-mail was NOT sent.</b>\n";
+              echo "              <br><br>\n";
+              echo "              <b>Error: <span style=\"color: red;\">Captcha Image Verification Failed</span></b><br>\n";
+              echo "              <img src=\"/images/spacer.gif\" width=\"325\" height=\"1\" border=\"0\">\n";
+              echo "              <br><br>\n";
+              echo "              <a href=\"contact.php\">Try Again?</a>";
+
+              exit;
+          }
+          else {
+              //echo "verified";
+          }
+        //--- end captcha verification -----------------------
+
+//notes
+    A diverse collection of unique fonts can improve the captcha.
+    If bots get past the captcha try changing fonts.
+
+    Ideas that may be implemented in the future...
+    1. randomize the background with texture, color and/or gradient
+    2. distort the image
+    3. rotate the characters with different rotations.
+    4. use audio, svg, or flash
+
+//additional fonts can be obtained from
+    http://simplythebest.net/fonts/
+    http://www.1001freefonts.com/afonts.htm
+
+//Usefull Links
+    http://sam.zoy.org/pwntcha/
+    http://en.wikipedia.org/wiki/Captcha
+
+*/
+
+
+
+?>

BIN
includes/captcha/fonts/ROUGD.TTF


BIN
includes/captcha/fonts/Zebra.ttf


BIN
includes/captcha/fonts/hanshand.ttf


+ 123 - 0
includes/captcha/img.php

@@ -0,0 +1,123 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+require_once "config.php";
+error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ); //hide notices and warnings
+session_start();
+
+
+// Captcha verification image -----------------------
+// Description this page is used to verify the captcha
+
+$_SESSION["captcha"] = substr(md5(date('r')), 0, 6);
+$text = $_SESSION["captcha"];
+//echo $text;
+exit;
+
+
+function isfile($filename) {
+    if (@filesize($filename) > 0) { return true; } else { return false; }
+}
+
+function dircontents($dir) {
+  clearstatcache();
+  $htmldirlist = '';
+  $htmlfilelist = '';
+  $dirlist = opendir($dir);
+  while ($file = readdir ($dirlist)) {
+      if ($file != '.' && $file != '..') {
+          $newpath = $dir.'/'.$file;
+           $level = explode('/',$newpath);
+
+           if (is_dir($newpath)) {
+                //do nothing
+           }
+           else {
+                $mod_array[] = end($level);
+           }
+       }
+   }
+
+   closedir($dirlist);
+   return $mod_array;
+}
+
+$fontarray = dircontents($pathtofonts);
+//print_r($fontarray);
+
+function make_seed()
+{
+  list($usec, $sec) = explode(' ', microtime());
+  return (float) $sec + ((float) $usec * 100000);
+}
+srand(make_seed());
+$random = (rand()%count($fontarray));
+$font = $pathtofonts.$fontarray[$random];
+//echo $font;
+
+//echo phpinfo();
+//exit;
+
+$fontsize = 16;
+if(@$_GET['fontsize']) {
+	$fontsize = $_GET['fontsize'];
+}
+
+//picked up from a note at http://www.php.net/imagettfbbox
+function imagettfbbox_custom($size, $angle, $font, $text) {
+  $dummy = imagecreate(1, 1);
+  $black = imagecolorallocate($dummy, 0, 0, 0);
+  $bbox = imagettftext($dummy, $size, $angle, 0, 0, $black, $font, $text);
+  imagedestroy($dummy);
+  return $bbox;
+}
+
+
+// Create the image
+$size = imagettfbbox_custom($fontsize, 0, $font, $text);
+$width = $size[2] + $size[0] + 8;
+$height = abs($size[1]) + abs($size[7]);
+//$width = 200;
+//$height =  200;
+
+$im = imagecreate($width, $height);
+
+$colourBlack = imagecolorallocate($im, 255, 255, 255);
+imagecolortransparent($im, $colourBlack);
+
+// Create some colors
+$white = imagecolorallocate($im, 255, 255, 255);
+$black = imagecolorallocate($im, 0, 0, 0);
+
+// Add the text
+imagefttext($im, $fontsize, 0, 0, abs($size[5]), $black, $font, $text);
+
+// Set the content-type
+header("Content-type: image/png");
+// Using imagepng() results in clearer text compared with
+imagepng($im);
+imagedestroy($im);
+?>

+ 48 - 0
includes/captcha/root.php

@@ -0,0 +1,48 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+// make sure the PATH_SEPARATOR is defined
+	if (!defined("PATH_SEPARATOR")) {
+		if ( strpos( $_ENV[ "OS" ], "Win" ) !== false ) { define("PATH_SEPARATOR", ";"); } else { define("PATH_SEPARATOR", ":"); }
+	}
+
+// make sure the document_root is set
+	$_SERVER["SCRIPT_FILENAME"] = str_replace("\\", "/", $_SERVER["SCRIPT_FILENAME"]);
+	$_SERVER["DOCUMENT_ROOT"] = str_replace($_SERVER["PHP_SELF"], "", $_SERVER["SCRIPT_FILENAME"]);
+	//echo "DOCUMENT_ROOT: ".$_SERVER["DOCUMENT_ROOT"]."<br />\n";
+	//echo "PHP_SELF: ".$_SERVER["PHP_SELF"]."<br />\n";
+	//echo "SCRIPT_FILENAME: ".$_SERVER["SCRIPT_FILENAME"]."<br />\n";
+
+// if the project directory exists then add it to the include path otherwise add the document root to the include path
+	if (is_dir($_SERVER["DOCUMENT_ROOT"].'/fusionpbx')){
+		define('PROJECT_PATH', '/fusionpbx');
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER["DOCUMENT_ROOT"].'/fusionpbx' );
+	}
+	else {
+		define('PROJECT_PATH', '');
+		set_include_path( get_include_path() . PATH_SEPARATOR . $_SERVER['DOCUMENT_ROOT'] );
+	}
+
+?>

+ 159 - 0
includes/checkauth.php

@@ -0,0 +1,159 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+require_once "includes/require.php";
+session_start();
+
+//if the username session is not set the check username and password
+	if (strlen($_SESSION["username"]) == 0) {
+		//clear the menu
+			$_SESSION["menu"] = "";
+
+		//clear the template only if the template has not been assigned by the superadmin
+			if (strlen($_SESSION['domain']['template']['name']) == 0) {
+				$_SESSION["template_content"] = '';
+			}
+
+		//if the username from the form is not provided then send to login.php
+			if (strlen(check_str($_REQUEST["username"])) == 0) {
+				$php_self = $_SERVER["PHP_SELF"];
+				$msg = "username required";
+				header("Location: ".PROJECT_PATH."/login.php?path=".urlencode($php_self)."&msg=".urlencode($msg));
+				exit;
+			}
+
+		//check the username and password if they don't match then redirect to the login
+			$sql = "select * from v_users ";
+			$sql .= "where domain_uuid=:domain_uuid ";
+			$sql .= "and username=:username ";
+			$prep_statement = $db->prepare(check_sql($sql));
+			$prep_statement->bindParam(':domain_uuid', $domain_uuid);
+			$prep_statement->bindParam(':username', check_str($_REQUEST["username"]));
+			$prep_statement->execute();
+			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+			if (count($result) == 0) {
+				$auth_failed = true;
+			}
+			else {
+				foreach ($result as &$row) {
+					//get the salt from the database
+						$salt = $row["salt"];
+					//if salt is not defined then use the default salt for backwards compatibility
+						if (strlen($salt) == 0) {
+							$salt = 'e3.7d.12';
+						}
+					//compare the password provided by the user with the one in the database
+						if (md5($salt.check_str($_REQUEST["password"])) != $row["password"]) {
+							$auth_failed = true;
+						}
+					//end the loop
+						break;
+				}
+			}
+			if ($auth_failed) {
+				//log the failed auth attempt to the system, to be available for fail2ban.
+					openlog('FusionPBX', LOG_NDELAY, LOG_AUTH);
+					syslog(LOG_WARNING, '['.$_SERVER['REMOTE_ADDR']."] authentication failed for ".$_REQUEST["username"]);
+					closelog();
+				//redirect the user to the login page
+					$php_self = $_SERVER["PHP_SELF"];
+					$msg = "incorrect account information";
+					header("Location: ".PROJECT_PATH."/login.php?path=".urlencode($php_self)."&msg=".urlencode($msg));
+					exit;
+			}
+			$_SESSION["username"] = check_str($_REQUEST["username"]);
+			foreach ($result as &$row) {
+				//allow the user to choose a template only if the template has not been assigned by the superadmin
+				if (strlen($_SESSION['domain']['template']['name']) == 0) {
+					$_SESSION['domain']['template']['name'] = $row["user_template_name"];
+				}
+				$_SESSION["time_zone"]["user"] = '';
+				if (strlen($row["user_time_zone"]) > 0) {
+					//user defined time zone
+					$_SESSION["time_zone"]["user"] = $row["user_time_zone"];
+				}
+				// add the user_uuid to the session
+				$_SESSION['user_uuid'] = $row['user_uuid'];
+				break;
+			}
+			//echo "username: ".$_SESSION["username"]." and password are correct";
+
+		//get the groups assigned to the user and then set the groups in $_SESSION["groups"]
+			$sql = "SELECT * FROM v_group_users ";
+			$sql .= "where domain_uuid=:domain_uuid ";
+			$sql .= "and user_uuid=:user_uuid ";
+			$prep_statement = $db->prepare(check_sql($sql));
+			$prep_statement->bindParam(':domain_uuid', $domain_uuid);
+			$prep_statement->bindParam(':user_uuid', $_SESSION["user_uuid"]);
+			$prep_statement->execute();
+			$result = $prep_statement->fetchAll(PDO::FETCH_NAMED);
+			$_SESSION["groups"] = $result;
+			unset($sql, $row_count, $prep_statement);
+
+		//get the permissions assigned to the groups that the user is a member of set the permissions in $_SESSION['permissions']
+			$x = 0;
+			$sql = "select distinct(permission_name) from v_group_permissions ";
+			foreach($_SESSION["groups"] as $field) {
+				if (strlen($field['group_name']) > 0) {
+					if ($x == 0) {
+						$sql .= "where (domain_uuid = '".$domain_uuid."' and group_name = '".$field['group_name']."') ";
+					}
+					else {
+						$sql .= "or (domain_uuid = '".$domain_uuid."' and group_name = '".$field['group_name']."') ";
+					}
+					$x++;
+				}
+			}
+			$prep_statement_sub = $db->prepare($sql);
+			$prep_statement_sub->execute();
+			$_SESSION['permissions'] = $prep_statement_sub->fetchAll(PDO::FETCH_NAMED);
+			unset($sql, $prep_statement_sub);
+
+		//redirect the user
+			if (check_str($_REQUEST["rdr"]) !== 'n'){
+				$path = check_str($_POST["path"]);
+				if(isset($path) && !empty($path) && $path!="index2.php" && $path!="/install.php") {
+					header("Location: ".$path);
+					exit();
+				}
+			}
+	}
+
+//set the time zone
+	if (strlen($_SESSION["time_zone"]["user"]) == 0) {
+		//set the domain time zone as the default time zone
+		date_default_timezone_set($_SESSION['domain']['time_zone']['name']);
+	}
+	else {
+		//set the user defined time zone
+		date_default_timezone_set($_SESSION["time_zone"]["user"]);
+	}
+
+//hide the path unless logged in as a superadmin.
+	if (!if_group("superadmin")) {
+		$v_path_show = false;
+	}
+
+?>

+ 30 - 0
includes/checkstring.php

@@ -0,0 +1,30 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Portions created by the Initial Developer are Copyright (C) 2008-2012
+	the Initial Developer. All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+function check_string($str) {
+    $str = str_replace ("\'", "''", $str); //escape the single quote
+    return $str;
+}
+?>

+ 1896 - 0
includes/class.phpmailer.php

@@ -0,0 +1,1896 @@
+<?php
+/*~ class.phpmailer.php
+.---------------------------------------------------------------------------.
+|  Software: PHPMailer - PHP email class                                    |
+|   Version: 2.0.2                                                          |
+|   Contact: via sourceforge.net support pages (also www.codeworxtech.com)  |
+|      Info: http://phpmailer.sourceforge.net                               |
+|   Support: http://sourceforge.net/projects/phpmailer/                     |
+| ------------------------------------------------------------------------- |
+|    Author: Andy Prevost (project admininistrator)                         |
+|    Author: Brent R. Matzelle (original founder)                           |
+| Copyright (c) 2004-2007, Andy Prevost. All Rights Reserved.               |
+| Copyright (c) 2001-2003, Brent R. Matzelle                                |
+| ------------------------------------------------------------------------- |
+|   License: Distributed under the Lesser General Public License (LGPL)     |
+|            http://www.gnu.org/copyleft/lesser.html                        |
+| This program is distributed in the hope that it will be useful - WITHOUT  |
+| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
+| FITNESS FOR A PARTICULAR PURPOSE.                                         |
+| ------------------------------------------------------------------------- |
+| We offer a number of paid services (www.codeworxtech.com):                |
+| - Web Hosting on highly optimized fast and secure servers                 |
+| - Technology Consulting                                                   |
+| - Oursourcing (highly qualified programmers and graphic designers)        |
+'---------------------------------------------------------------------------'
+
+/**
+ * PHPMailer - PHP email transport class
+ * @package PHPMailer
+ * @author Andy Prevost
+ * @copyright 2004 - 2008 Andy Prevost
+ */
+
+class PHPMailer {
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PUBLIC
+  /////////////////////////////////////////////////
+
+  /**
+   * Email priority (1 = High, 3 = Normal, 5 = low).
+   * @var int
+   */
+  var $Priority          = 3;
+
+  /**
+   * Sets the CharSet of the message.
+   * @var string
+   */
+  var $CharSet           = 'iso-8859-1';
+
+  /**
+   * Sets the Content-type of the message.
+   * @var string
+   */
+  var $ContentType        = 'text/plain';
+
+  /**
+   * Sets the Encoding of the message. Options for this are "8bit",
+   * "7bit", "binary", "base64", and "quoted-printable".
+   * @var string
+   */
+  var $Encoding          = '8bit';
+
+  /**
+   * Holds the most recent mailer error message.
+   * @var string
+   */
+  var $ErrorInfo         = '';
+
+  /**
+   * Sets the From email address for the message.
+   * @var string
+   */
+  var $From              = 'root@localhost';
+
+  /**
+   * Sets the From name of the message.
+   * @var string
+   */
+  var $FromName          = 'Root User';
+
+  /**
+   * Sets the Sender email (Return-Path) of the message.  If not empty,
+   * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
+   * @var string
+   */
+  var $Sender            = '';
+
+  /**
+   * Sets the Subject of the message.
+   * @var string
+   */
+  var $Subject           = '';
+
+  /**
+   * Sets the Body of the message.  This can be either an HTML or text body.
+   * If HTML then run IsHTML(true).
+   * @var string
+   */
+  var $Body              = '';
+
+  /**
+   * Sets the text-only body of the message.  This automatically sets the
+   * email to multipart/alternative.  This body can be read by mail
+   * clients that do not have HTML email capability such as mutt. Clients
+   * that can read HTML will view the normal Body.
+   * @var string
+   */
+  var $AltBody           = '';
+
+  /**
+   * Sets word wrapping on the body of the message to a given number of
+   * characters.
+   * @var int
+   */
+  var $WordWrap          = 0;
+
+  /**
+   * Method to send mail: ("mail", "sendmail", or "smtp").
+   * @var string
+   */
+  var $Mailer            = 'mail';
+
+  /**
+   * Sets the path of the sendmail program.
+   * @var string
+   */
+  var $Sendmail          = '/usr/sbin/sendmail';
+
+  /**
+   * Path to PHPMailer plugins.  This is now only useful if the SMTP class
+   * is in a different directory than the PHP include path.
+   * @var string
+   */
+  var $PluginDir         = '';
+
+  /**
+   * Holds PHPMailer version.
+   * @var string
+   */
+  var $Version           = "2.0.2";
+
+  /**
+   * Sets the email address that a reading confirmation will be sent.
+   * @var string
+   */
+  var $ConfirmReadingTo  = '';
+
+  /**
+   * Sets the hostname to use in Message-Id and Received headers
+   * and as default HELO string. If empty, the value returned
+   * by SERVER_NAME is used or 'localhost.localdomain'.
+   * @var string
+   */
+  var $Hostname          = '';
+
+  /**
+   * Sets the message ID to be used in the Message-Id header.
+   * If empty, a unique id will be generated.
+   * @var string
+   */
+  var $MessageID         = '';
+
+  /////////////////////////////////////////////////
+  // PROPERTIES FOR SMTP
+  /////////////////////////////////////////////////
+
+  /**
+   * Sets the SMTP hosts.  All hosts must be separated by a
+   * semicolon.  You can also specify a different port
+   * for each host by using this format: [hostname:port]
+   * (e.g. "smtp1.example.com:25;smtp2.example.com").
+   * Hosts will be tried in order.
+   * @var string
+   */
+  var $Host        = 'localhost';
+
+  /**
+   * Sets the default SMTP server port.
+   * @var int
+   */
+  var $Port        = 25;
+
+  /**
+   * Sets the SMTP HELO of the message (Default is $Hostname).
+   * @var string
+   */
+  var $Helo        = '';
+
+  /**
+   * Sets connection prefix.
+   * Options are "", "ssl" or "tls"
+   * @var string
+   */
+  var $SMTPSecure = "";
+
+  /**
+   * Sets SMTP authentication. Utilizes the Username and Password variables.
+   * @var bool
+   */
+  var $SMTPAuth     = false;
+
+  /**
+   * Sets SMTP username.
+   * @var string
+   */
+  var $Username     = '';
+
+  /**
+   * Sets SMTP password.
+   * @var string
+   */
+  var $Password     = '';
+
+  /**
+   * Sets the SMTP server timeout in seconds. This function will not
+   * work with the win32 version.
+   * @var int
+   */
+  var $Timeout      = 10;
+
+  /**
+   * Sets SMTP class debugging on or off.
+   * @var bool
+   */
+  var $SMTPDebug    = false;
+
+  /**
+   * Prevents the SMTP connection from being closed after each mail
+   * sending.  If this is set to true then to close the connection
+   * requires an explicit call to SmtpClose().
+   * @var bool
+   */
+  var $SMTPKeepAlive = false;
+
+  /**
+   * Provides the ability to have the TO field process individual
+   * emails, instead of sending to entire TO addresses
+   * @var bool
+   */
+  var $SingleTo = false;
+
+  /////////////////////////////////////////////////
+  // PROPERTIES, PRIVATE
+  /////////////////////////////////////////////////
+
+  var $smtp            = NULL;
+  var $to              = array();
+  var $cc              = array();
+  var $bcc             = array();
+  var $ReplyTo         = array();
+  var $attachment      = array();
+  var $CustomHeader    = array();
+  var $message_type    = '';
+  var $boundary        = array();
+  var $language        = array();
+  var $error_count     = 0;
+  var $LE              = "\n";
+  var $sign_key_file   = "";
+  var $sign_key_pass   = "";
+
+  /////////////////////////////////////////////////
+  // METHODS, VARIABLES
+  /////////////////////////////////////////////////
+
+  /**
+   * Sets message type to HTML.
+   * @param bool $bool
+   * @return void
+   */
+  function IsHTML($bool) {
+    if($bool == true) {
+      $this->ContentType = 'text/html';
+    } else {
+      $this->ContentType = 'text/plain';
+    }
+  }
+
+  /**
+   * Sets Mailer to send message using SMTP.
+   * @return void
+   */
+  function IsSMTP() {
+    $this->Mailer = 'smtp';
+  }
+
+  /**
+   * Sets Mailer to send message using PHP mail() function.
+   * @return void
+   */
+  function IsMail() {
+    $this->Mailer = 'mail';
+  }
+
+  /**
+   * Sets Mailer to send message using the $Sendmail program.
+   * @return void
+   */
+  function IsSendmail() {
+    $this->Mailer = 'sendmail';
+  }
+
+  /**
+   * Sets Mailer to send message using the qmail MTA.
+   * @return void
+   */
+  function IsQmail() {
+    $this->Sendmail = '/var/qmail/bin/sendmail';
+    $this->Mailer = 'sendmail';
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, RECIPIENTS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds a "To" address.
+   * @param string $address
+   * @param string $name
+   * @return void
+   */
+  function AddAddress($address, $name = '') {
+    $cur = count($this->to);
+    $this->to[$cur][0] = trim($address);
+    $this->to[$cur][1] = $name;
+  }
+
+  /**
+   * Adds a "Cc" address. Note: this function works
+   * with the SMTP mailer on win32, not with the "mail"
+   * mailer.
+   * @param string $address
+   * @param string $name
+   * @return void
+   */
+  function AddCC($address, $name = '') {
+    $cur = count($this->cc);
+    $this->cc[$cur][0] = trim($address);
+    $this->cc[$cur][1] = $name;
+  }
+
+  /**
+   * Adds a "Bcc" address. Note: this function works
+   * with the SMTP mailer on win32, not with the "mail"
+   * mailer.
+   * @param string $address
+   * @param string $name
+   * @return void
+   */
+  function AddBCC($address, $name = '') {
+    $cur = count($this->bcc);
+    $this->bcc[$cur][0] = trim($address);
+    $this->bcc[$cur][1] = $name;
+  }
+
+  /**
+   * Adds a "Reply-To" address.
+   * @param string $address
+   * @param string $name
+   * @return void
+   */
+  function AddReplyTo($address, $name = '') {
+    $cur = count($this->ReplyTo);
+    $this->ReplyTo[$cur][0] = trim($address);
+    $this->ReplyTo[$cur][1] = $name;
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, MAIL SENDING
+  /////////////////////////////////////////////////
+
+  /**
+   * Creates message and assigns Mailer. If the message is
+   * not sent successfully then it returns false.  Use the ErrorInfo
+   * variable to view description of the error.
+   * @return bool
+   */
+  function Send() {
+    $header = '';
+    $body = '';
+    $result = true;
+
+    if((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
+      $this->SetError($this->Lang('provide_address'));
+      return false;
+    }
+
+    /* Set whether the message is multipart/alternative */
+    if(!empty($this->AltBody)) {
+      $this->ContentType = 'multipart/alternative';
+    }
+
+    $this->error_count = 0; // reset errors
+    $this->SetMessageType();
+    $header .= $this->CreateHeader();
+    $body = $this->CreateBody();
+
+    if($body == '') {
+      return false;
+    }
+
+    /* Choose the mailer */
+    switch($this->Mailer) {
+      case 'sendmail':
+        $result = $this->SendmailSend($header, $body);
+        break;
+      case 'smtp':
+        $result = $this->SmtpSend($header, $body);
+        break;
+      case 'mail':
+        $result = $this->MailSend($header, $body);
+        break;
+      default:
+        $result = $this->MailSend($header, $body);
+        break;
+        //$this->SetError($this->Mailer . $this->Lang('mailer_not_supported'));
+        //$result = false;
+        //break;
+    }
+
+    return $result;
+  }
+
+  /**
+   * Sends mail using the $Sendmail program.
+   * @access private
+   * @return bool
+   */
+  function SendmailSend($header, $body) {
+    if ($this->Sender != '') {
+      $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+    } else {
+      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
+    }
+
+    if(!@$mail = popen($sendmail, 'w')) {
+      $this->SetError($this->Lang('execute') . $this->Sendmail);
+      return false;
+    }
+
+    fputs($mail, $header);
+    fputs($mail, $body);
+
+    $result = pclose($mail);
+    if (version_compare(phpversion(), '4.2.3') == -1) {
+      $result = $result >> 8 & 0xFF;
+    }
+    if($result != 0) {
+      $this->SetError($this->Lang('execute') . $this->Sendmail);
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends mail using the PHP mail() function.
+   * @access private
+   * @return bool
+   */
+  function MailSend($header, $body) {
+
+    $to = '';
+    for($i = 0; $i < count($this->to); $i++) {
+      if($i != 0) { $to .= ', '; }
+      $to .= $this->AddrFormat($this->to[$i]);
+    }
+
+    $toArr = split(',', $to);
+
+    $params = sprintf("-oi -f %s", $this->Sender);
+    if ($this->Sender != '' && strlen(ini_get('safe_mode')) < 1) {
+      $old_from = ini_get('sendmail_from');
+      ini_set('sendmail_from', $this->Sender);
+      if ($this->SingleTo === true && count($toArr) > 1) {
+        foreach ($toArr as $key => $val) {
+          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
+        }
+      } else {
+        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
+      }
+    } else {
+      if ($this->SingleTo === true && count($toArr) > 1) {
+        foreach ($toArr as $key => $val) {
+          $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
+        }
+      } else {
+        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
+      }
+    }
+
+    if (isset($old_from)) {
+      ini_set('sendmail_from', $old_from);
+    }
+
+    if(!$rt) {
+      $this->SetError($this->Lang('instantiate'));
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Sends mail via SMTP using PhpSMTP (Author:
+   * Chris Ryan).  Returns bool.  Returns false if there is a
+   * bad MAIL FROM, RCPT, or DATA input.
+   * @access private
+   * @return bool
+   */
+  function SmtpSend($header, $body) {
+    include_once($this->PluginDir . 'class.smtp.php');
+    $error = '';
+    $bad_rcpt = array();
+
+    if(!$this->SmtpConnect()) {
+      return false;
+    }
+
+    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
+    if(!$this->smtp->Mail($smtp_from)) {
+      $error = $this->Lang('from_failed') . $smtp_from;
+      $this->SetError($error);
+      $this->smtp->Reset();
+      return false;
+    }
+
+    /* Attempt to send attach all recipients */
+    for($i = 0; $i < count($this->to); $i++) {
+      if(!$this->smtp->Recipient($this->to[$i][0])) {
+        $bad_rcpt[] = $this->to[$i][0];
+      }
+    }
+    for($i = 0; $i < count($this->cc); $i++) {
+      if(!$this->smtp->Recipient($this->cc[$i][0])) {
+        $bad_rcpt[] = $this->cc[$i][0];
+      }
+    }
+    for($i = 0; $i < count($this->bcc); $i++) {
+      if(!$this->smtp->Recipient($this->bcc[$i][0])) {
+        $bad_rcpt[] = $this->bcc[$i][0];
+      }
+    }
+
+    if(count($bad_rcpt) > 0) { // Create error message
+      for($i = 0; $i < count($bad_rcpt); $i++) {
+        if($i != 0) {
+          $error .= ', ';
+        }
+        $error .= $bad_rcpt[$i];
+      }
+      $error = $this->Lang('recipients_failed') . $error;
+      $this->SetError($error);
+      $this->smtp->Reset();
+      return false;
+    }
+
+    if(!$this->smtp->Data($header . $body)) {
+      $this->SetError($this->Lang('data_not_accepted'));
+      $this->smtp->Reset();
+      return false;
+    }
+    if($this->SMTPKeepAlive == true) {
+      $this->smtp->Reset();
+    } else {
+      $this->SmtpClose();
+    }
+
+    return true;
+  }
+
+  /**
+   * Initiates a connection to an SMTP server.  Returns false if the
+   * operation failed.
+   * @access private
+   * @return bool
+   */
+  function SmtpConnect() {
+    if($this->smtp == NULL) {
+      $this->smtp = new SMTP();
+    }
+
+    $this->smtp->do_debug = $this->SMTPDebug;
+    $hosts = explode(';', $this->Host);
+    $index = 0;
+    $connection = ($this->smtp->Connected());
+
+    /* Retry while there is no connection */
+    while($index < count($hosts) && $connection == false) {
+      $hostinfo = array();
+      if(eregi('^(.+):([0-9]+)$', $hosts[$index], $hostinfo)) {
+        $host = $hostinfo[1];
+        $port = $hostinfo[2];
+      } else {
+        $host = $hosts[$index];
+        $port = $this->Port;
+      }
+
+      if($this->smtp->Connect(((!empty($this->SMTPSecure))?$this->SMTPSecure.'://':'').$host, $port, $this->Timeout)) {
+        if ($this->Helo != '') {
+          $this->smtp->Hello($this->Helo);
+        } else {
+          $this->smtp->Hello($this->ServerHostname());
+        }
+
+        $connection = true;
+        if($this->SMTPAuth) {
+          if(!$this->smtp->Authenticate($this->Username, $this->Password)) {
+            $this->SetError($this->Lang('authenticate'));
+            $this->smtp->Reset();
+            $connection = false;
+          }
+        }
+      }
+      $index++;
+    }
+    if(!$connection) {
+      $this->SetError($this->Lang('connect_host'));
+    }
+
+    return $connection;
+  }
+
+  /**
+   * Closes the active SMTP session if one exists.
+   * @return void
+   */
+  function SmtpClose() {
+    if($this->smtp != NULL) {
+      if($this->smtp->Connected()) {
+        $this->smtp->Quit();
+        $this->smtp->Close();
+      }
+    }
+  }
+
+  /**
+   * Sets the language for all class error messages.  Returns false
+   * if it cannot load the language file.  The default language type
+   * is English.
+   * @param string $lang_type Type of language (e.g. Portuguese: "br")
+   * @param string $lang_path Path to the language file directory
+   * @access public
+   * @return bool
+   */
+  function SetLanguage($lang_type, $lang_path = 'language/') {
+    if(file_exists($lang_path.'phpmailer.lang-'.$lang_type.'.php')) {
+      include($lang_path.'phpmailer.lang-'.$lang_type.'.php');
+    } elseif (file_exists($lang_path.'phpmailer.lang-en.php')) {
+      include($lang_path.'phpmailer.lang-en.php');
+    } else {
+      $this->SetError('Could not load language file');
+      return false;
+    }
+    $this->language = $PHPMAILER_LANG;
+
+    return true;
+  }
+
+  /////////////////////////////////////////////////
+  // METHODS, MESSAGE CREATION
+  /////////////////////////////////////////////////
+
+  /**
+   * Creates recipient headers.
+   * @access private
+   * @return string
+   */
+  function AddrAppend($type, $addr) {
+    $addr_str = $type . ': ';
+    $addr_str .= $this->AddrFormat($addr[0]);
+    if(count($addr) > 1) {
+      for($i = 1; $i < count($addr); $i++) {
+        $addr_str .= ', ' . $this->AddrFormat($addr[$i]);
+      }
+    }
+    $addr_str .= $this->LE;
+
+    return $addr_str;
+  }
+
+  /**
+   * Formats an address correctly.
+   * @access private
+   * @return string
+   */
+  function AddrFormat($addr) {
+    if(empty($addr[1])) {
+      $formatted = $this->SecureHeader($addr[0]);
+    } else {
+      $formatted = $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
+    }
+
+    return $formatted;
+  }
+
+  /**
+   * Wraps message for use with mailers that do not
+   * automatically perform wrapping and for quoted-printable.
+   * Original written by philippe.
+   * @access private
+   * @return string
+   */
+  function WrapText($message, $length, $qp_mode = false) {
+    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
+    // If utf-8 encoding is used, we will need to make sure we don't
+    // split multibyte characters when we wrap
+    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
+
+    $message = $this->FixEOL($message);
+    if (substr($message, -1) == $this->LE) {
+      $message = substr($message, 0, -1);
+    }
+
+    $line = explode($this->LE, $message);
+    $message = '';
+    for ($i=0 ;$i < count($line); $i++) {
+      $line_part = explode(' ', $line[$i]);
+      $buf = '';
+      for ($e = 0; $e<count($line_part); $e++) {
+        $word = $line_part[$e];
+        if ($qp_mode and (strlen($word) > $length)) {
+          $space_left = $length - strlen($buf) - 1;
+          if ($e != 0) {
+            if ($space_left > 20) {
+              $len = $space_left;
+              if ($is_utf8) {
+                $len = $this->UTF8CharBoundary($word, $len);
+              } elseif (substr($word, $len - 1, 1) == "=") {
+                $len--;
+              } elseif (substr($word, $len - 2, 1) == "=") {
+                $len -= 2;
+              }
+              $part = substr($word, 0, $len);
+              $word = substr($word, $len);
+              $buf .= ' ' . $part;
+              $message .= $buf . sprintf("=%s", $this->LE);
+            } else {
+              $message .= $buf . $soft_break;
+            }
+            $buf = '';
+          }
+          while (strlen($word) > 0) {
+            $len = $length;
+            if ($is_utf8) {
+              $len = $this->UTF8CharBoundary($word, $len);
+            } elseif (substr($word, $len - 1, 1) == "=") {
+              $len--;
+            } elseif (substr($word, $len - 2, 1) == "=") {
+              $len -= 2;
+            }
+            $part = substr($word, 0, $len);
+            $word = substr($word, $len);
+
+            if (strlen($word) > 0) {
+              $message .= $part . sprintf("=%s", $this->LE);
+            } else {
+              $buf = $part;
+            }
+          }
+        } else {
+          $buf_o = $buf;
+          $buf .= ($e == 0) ? $word : (' ' . $word);
+
+          if (strlen($buf) > $length and $buf_o != '') {
+            $message .= $buf_o . $soft_break;
+            $buf = $word;
+          }
+        }
+      }
+      $message .= $buf . $this->LE;
+    }
+
+    return $message;
+  }
+
+  /**
+   * Finds last character boundary prior to maxLength in a utf-8
+   * quoted (printable) encoded string.
+   * Original written by Colin Brown.
+   * @access private
+   * @param string $encodedText utf-8 QP text
+   * @param int    $maxLength   find last character boundary prior to this length
+   * @return int
+   */
+  function UTF8CharBoundary($encodedText, $maxLength) {
+    $foundSplitPos = false;
+    $lookBack = 3;
+    while (!$foundSplitPos) {
+      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
+      $encodedCharPos = strpos($lastChunk, "=");
+      if ($encodedCharPos !== false) {
+        // Found start of encoded character byte within $lookBack block.
+        // Check the encoded byte value (the 2 chars after the '=')
+        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
+        $dec = hexdec($hex);
+        if ($dec < 128) { // Single byte character.
+          // If the encoded char was found at pos 0, it will fit
+          // otherwise reduce maxLength to start of the encoded char
+          $maxLength = ($encodedCharPos == 0) ? $maxLength :
+          $maxLength - ($lookBack - $encodedCharPos);
+          $foundSplitPos = true;
+        } elseif ($dec >= 192) { // First byte of a multi byte character
+          // Reduce maxLength to split at start of character
+          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
+          $foundSplitPos = true;
+        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
+          $lookBack += 3;
+        }
+      } else {
+        // No encoded character found
+        $foundSplitPos = true;
+      }
+    }
+    return $maxLength;
+  }
+
+  /**
+   * Set the body wrapping.
+   * @access private
+   * @return void
+   */
+  function SetWordWrap() {
+    if($this->WordWrap < 1) {
+      return;
+    }
+
+    switch($this->message_type) {
+      case 'alt':
+        /* fall through */
+      case 'alt_attachments':
+        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
+        break;
+      default:
+        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
+        break;
+    }
+  }
+
+  /**
+   * Assembles message header.
+   * @access private
+   * @return string
+   */
+  function CreateHeader() {
+    $result = '';
+
+    /* Set the boundaries */
+    $uniq_id = md5(uniqid(time()));
+    $this->boundary[1] = 'b1_' . $uniq_id;
+    $this->boundary[2] = 'b2_' . $uniq_id;
+
+    $result .= $this->HeaderLine('Date', $this->RFCDate());
+    if($this->Sender == '') {
+      $result .= $this->HeaderLine('Return-Path', trim($this->From));
+    } else {
+      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
+    }
+
+    /* To be created automatically by mail() */
+    if($this->Mailer != 'mail') {
+      if(count($this->to) > 0) {
+        $result .= $this->AddrAppend('To', $this->to);
+      } elseif (count($this->cc) == 0) {
+        $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
+      }
+      if(count($this->cc) > 0) {
+        $result .= $this->AddrAppend('Cc', $this->cc);
+      }
+    }
+
+    $from = array();
+    $from[0][0] = trim($this->From);
+    $from[0][1] = $this->FromName;
+    $result .= $this->AddrAppend('From', $from);
+
+    /* sendmail and mail() extract Cc from the header before sending */
+    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->cc) > 0)) {
+      $result .= $this->AddrAppend('Cc', $this->cc);
+    }
+
+    /* sendmail and mail() extract Bcc from the header before sending */
+    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
+      $result .= $this->AddrAppend('Bcc', $this->bcc);
+    }
+
+    if(count($this->ReplyTo) > 0) {
+      $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
+    }
+
+    /* mail() sets the subject itself */
+    if($this->Mailer != 'mail') {
+      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
+    }
+
+    if($this->MessageID != '') {
+      $result .= $this->HeaderLine('Message-ID',$this->MessageID);
+    } else {
+      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
+    }
+    $result .= $this->HeaderLine('X-Priority', $this->Priority);
+    $result .= $this->HeaderLine('X-Mailer', 'PHPMailer (phpmailer.sourceforge.net) [version ' . $this->Version . ']');
+
+    if($this->ConfirmReadingTo != '') {
+      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
+    }
+
+    // Add custom headers
+    for($index = 0; $index < count($this->CustomHeader); $index++) {
+      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
+    }
+    if (!$this->sign_key_file) {
+      $result .= $this->HeaderLine('MIME-Version', '1.0');
+      $result .= $this->GetMailMIME();
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns the message MIME.
+   * @access private
+   * @return string
+   */
+  function GetMailMIME() {
+    $result = '';
+    switch($this->message_type) {
+      case 'plain':
+        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
+        $result .= sprintf("Content-Type: %s; charset=\"%s\"", $this->ContentType, $this->CharSet);
+        break;
+      case 'attachments':
+        /* fall through */
+      case 'alt_attachments':
+        if($this->InlineImageExists()){
+          $result .= sprintf("Content-Type: %s;%s\ttype=\"text/html\";%s\tboundary=\"%s\"%s", 'multipart/related', $this->LE, $this->LE, $this->boundary[1], $this->LE);
+        } else {
+          $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
+          $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+        }
+        break;
+      case 'alt':
+        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
+        break;
+    }
+
+    if($this->Mailer != 'mail') {
+      $result .= $this->LE.$this->LE;
+    }
+
+    return $result;
+  }
+
+  /**
+   * Assembles the message body.  Returns an empty string on failure.
+   * @access private
+   * @return string
+   */
+  function CreateBody() {
+    $result = '';
+    if ($this->sign_key_file) {
+      $result .= $this->GetMailMIME();
+    }
+
+    $this->SetWordWrap();
+
+    switch($this->message_type) {
+      case 'alt':
+        $result .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+        $result .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $result .= $this->LE.$this->LE;
+        $result .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
+        $result .= $this->EncodeString($this->Body, $this->Encoding);
+        $result .= $this->LE.$this->LE;
+        $result .= $this->EndBoundary($this->boundary[1]);
+        break;
+      case 'plain':
+        $result .= $this->EncodeString($this->Body, $this->Encoding);
+        break;
+      case 'attachments':
+        $result .= $this->GetBoundary($this->boundary[1], '', '', '');
+        $result .= $this->EncodeString($this->Body, $this->Encoding);
+        $result .= $this->LE;
+        $result .= $this->AttachAll();
+        break;
+      case 'alt_attachments':
+        $result .= sprintf("--%s%s", $this->boundary[1], $this->LE);
+        $result .= sprintf("Content-Type: %s;%s" . "\tboundary=\"%s\"%s", 'multipart/alternative', $this->LE, $this->boundary[2], $this->LE.$this->LE);
+        $result .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '') . $this->LE; // Create text body
+        $result .= $this->EncodeString($this->AltBody, $this->Encoding);
+        $result .= $this->LE.$this->LE;
+        $result .= $this->GetBoundary($this->boundary[2], '', 'text/html', '') . $this->LE; // Create the HTML body
+        $result .= $this->EncodeString($this->Body, $this->Encoding);
+        $result .= $this->LE.$this->LE;
+        $result .= $this->EndBoundary($this->boundary[2]);
+        $result .= $this->AttachAll();
+        break;
+    }
+
+    if($this->IsError()) {
+      $result = '';
+    } else if ($this->sign_key_file) {
+      $file = tempnam("", "mail");
+      $fp = fopen($file, "w");
+      fwrite($fp, $result);
+      fclose($fp);
+      $signed = tempnam("", "signed");
+
+      if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_key_file, array("file://".$this->sign_key_file, $this->sign_key_pass), null)) {
+        $fp = fopen($signed, "r");
+        $result = fread($fp, filesize($this->sign_key_file));
+        fclose($fp);
+      } else {
+        $this->SetError($this->Lang("signing").openssl_error_string());
+        $result = '';
+      }
+
+      unlink($file);
+      unlink($signed);
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns the start of a message boundary.
+   * @access private
+   */
+  function GetBoundary($boundary, $charSet, $contentType, $encoding) {
+    $result = '';
+    if($charSet == '') {
+      $charSet = $this->CharSet;
+    }
+    if($contentType == '') {
+      $contentType = $this->ContentType;
+    }
+    if($encoding == '') {
+      $encoding = $this->Encoding;
+    }
+    $result .= $this->TextLine('--' . $boundary);
+    $result .= sprintf("Content-Type: %s; charset = \"%s\"", $contentType, $charSet);
+    $result .= $this->LE;
+    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
+    $result .= $this->LE;
+
+    return $result;
+  }
+
+  /**
+   * Returns the end of a message boundary.
+   * @access private
+   */
+  function EndBoundary($boundary) {
+    return $this->LE . '--' . $boundary . '--' . $this->LE;
+  }
+
+  /**
+   * Sets the message type.
+   * @access private
+   * @return void
+   */
+  function SetMessageType() {
+    if(count($this->attachment) < 1 && strlen($this->AltBody) < 1) {
+      $this->message_type = 'plain';
+    } else {
+      if(count($this->attachment) > 0) {
+        $this->message_type = 'attachments';
+      }
+      if(strlen($this->AltBody) > 0 && count($this->attachment) < 1) {
+        $this->message_type = 'alt';
+      }
+      if(strlen($this->AltBody) > 0 && count($this->attachment) > 0) {
+        $this->message_type = 'alt_attachments';
+      }
+    }
+  }
+
+  /* Returns a formatted header line.
+   * @access private
+   * @return string
+   */
+  function HeaderLine($name, $value) {
+    return $name . ': ' . $value . $this->LE;
+  }
+
+  /**
+   * Returns a formatted mail line.
+   * @access private
+   * @return string
+   */
+  function TextLine($value) {
+    return $value . $this->LE;
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, ATTACHMENTS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds an attachment from a path on the filesystem.
+   * Returns false if the file could not be found
+   * or accessed.
+   * @param string $path Path to the attachment.
+   * @param string $name Overrides the attachment name.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return bool
+   */
+  function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
+    if(!@is_file($path)) {
+      $this->SetError($this->Lang('file_access') . $path);
+      return false;
+    }
+
+    $filename = basename($path);
+    if($name == '') {
+      $name = $filename;
+    }
+
+    $cur = count($this->attachment);
+    $this->attachment[$cur][0] = $path;
+    $this->attachment[$cur][1] = $filename;
+    $this->attachment[$cur][2] = $name;
+    $this->attachment[$cur][3] = $encoding;
+    $this->attachment[$cur][4] = $type;
+    $this->attachment[$cur][5] = false; // isStringAttachment
+    $this->attachment[$cur][6] = 'attachment';
+    $this->attachment[$cur][7] = 0;
+
+    return true;
+  }
+
+  /**
+   * Attaches all fs, string, and binary attachments to the message.
+   * Returns an empty string on failure.
+   * @access private
+   * @return string
+   */
+  function AttachAll() {
+    /* Return text of body */
+    $mime = array();
+
+    /* Add all attachments */
+    for($i = 0; $i < count($this->attachment); $i++) {
+      /* Check for string attachment */
+      $bString = $this->attachment[$i][5];
+      if ($bString) {
+        $string = $this->attachment[$i][0];
+      } else {
+        $path = $this->attachment[$i][0];
+      }
+
+      $filename    = $this->attachment[$i][1];
+      $name        = $this->attachment[$i][2];
+      $encoding    = $this->attachment[$i][3];
+      $type        = $this->attachment[$i][4];
+      $disposition = $this->attachment[$i][6];
+      $cid         = $this->attachment[$i][7];
+
+      $mime[] = sprintf("--%s%s", $this->boundary[1], $this->LE);
+      $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $name, $this->LE);
+      $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
+
+      if($disposition == 'inline') {
+        $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
+      }
+
+      $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $name, $this->LE.$this->LE);
+
+      /* Encode as string attachment */
+      if($bString) {
+        $mime[] = $this->EncodeString($string, $encoding);
+        if($this->IsError()) {
+          return '';
+        }
+        $mime[] = $this->LE.$this->LE;
+      } else {
+        $mime[] = $this->EncodeFile($path, $encoding);
+        if($this->IsError()) {
+          return '';
+        }
+        $mime[] = $this->LE.$this->LE;
+      }
+    }
+
+    $mime[] = sprintf("--%s--%s", $this->boundary[1], $this->LE);
+
+    return join('', $mime);
+  }
+
+  /**
+   * Encodes attachment in requested format.  Returns an
+   * empty string on failure.
+   * @access private
+   * @return string
+   */
+  function EncodeFile ($path, $encoding = 'base64') {
+    if(!@$fd = fopen($path, 'rb')) {
+      $this->SetError($this->Lang('file_open') . $path);
+      return '';
+    }
+    $magic_quotes = get_magic_quotes_runtime();
+    set_magic_quotes_runtime(0);
+    $file_buffer = fread($fd, filesize($path));
+    $file_buffer = $this->EncodeString($file_buffer, $encoding);
+    fclose($fd);
+    set_magic_quotes_runtime($magic_quotes);
+
+    return $file_buffer;
+  }
+
+  /**
+   * Encodes string to requested format. Returns an
+   * empty string on failure.
+   * @access private
+   * @return string
+   */
+  function EncodeString ($str, $encoding = 'base64') {
+    $encoded = '';
+    switch(strtolower($encoding)) {
+      case 'base64':
+        /* chunk_split is found in PHP >= 3.0.6 */
+        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
+        break;
+      case '7bit':
+      case '8bit':
+        $encoded = $this->FixEOL($str);
+        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
+          $encoded .= $this->LE;
+        break;
+      case 'binary':
+        $encoded = $str;
+        break;
+      case 'quoted-printable':
+        $encoded = $this->EncodeQP($str);
+        break;
+      default:
+        $this->SetError($this->Lang('encoding') . $encoding);
+        break;
+    }
+    return $encoded;
+  }
+
+  /**
+   * Encode a header string to best of Q, B, quoted or none.
+   * @access private
+   * @return string
+   */
+  function EncodeHeader ($str, $position = 'text') {
+    $x = 0;
+
+    switch (strtolower($position)) {
+      case 'phrase':
+        if (!preg_match('/[\200-\377]/', $str)) {
+          /* Can't use addslashes as we don't know what value has magic_quotes_sybase. */
+          $encoded = addcslashes($str, "\0..\37\177\\\"");
+          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
+            return ($encoded);
+          } else {
+            return ("\"$encoded\"");
+          }
+        }
+        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
+        break;
+      case 'comment':
+        $x = preg_match_all('/[()"]/', $str, $matches);
+        /* Fall-through */
+      case 'text':
+      default:
+        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
+        break;
+    }
+
+    if ($x == 0) {
+      return ($str);
+    }
+
+    $maxlen = 75 - 7 - strlen($this->CharSet);
+    /* Try to select the encoding which should produce the shortest output */
+    if (strlen($str)/3 < $x) {
+      $encoding = 'B';
+      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
+     // Use a custom function which correctly encodes and wraps long
+     // multibyte strings without breaking lines within a character
+        $encoded = $this->Base64EncodeWrapMB($str);
+      } else {
+        $encoded = base64_encode($str);
+        $maxlen -= $maxlen % 4;
+        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
+      }
+    } else {
+      $encoding = 'Q';
+      $encoded = $this->EncodeQ($str, $position);
+      $encoded = $this->WrapText($encoded, $maxlen, true);
+      $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
+    }
+
+    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
+    $encoded = trim(str_replace("\n", $this->LE, $encoded));
+
+    return $encoded;
+  }
+
+  /**
+   * Checks if a string contains multibyte characters.
+   * @access private
+   * @param string $str multi-byte text to wrap encode
+   * @return bool
+   */
+  function HasMultiBytes($str) {
+    if (function_exists('mb_strlen')) {
+      return (strlen($str) > mb_strlen($str, $this->CharSet));
+    } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
+      return False;
+    }
+  }
+
+  /**
+   * Correctly encodes and wraps long multibyte strings for mail headers
+   * without breaking lines within a character.
+   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
+   * @access private
+   * @param string $str multi-byte text to wrap encode
+   * @return string
+   */
+  function Base64EncodeWrapMB($str) {
+    $start = "=?".$this->CharSet."?B?";
+    $end = "?=";
+    $encoded = "";
+
+    $mb_length = mb_strlen($str, $this->CharSet);
+    // Each line must have length <= 75, including $start and $end
+    $length = 75 - strlen($start) - strlen($end);
+    // Average multi-byte ratio
+    $ratio = $mb_length / strlen($str);
+    // Base64 has a 4:3 ratio
+    $offset = $avgLength = floor($length * $ratio * .75);
+
+    for ($i = 0; $i < $mb_length; $i += $offset) {
+      $lookBack = 0;
+
+      do {
+        $offset = $avgLength - $lookBack;
+        $chunk = mb_substr($str, $i, $offset, $this->CharSet);
+        $chunk = base64_encode($chunk);
+        $lookBack++;
+      }
+      while (strlen($chunk) > $length);
+
+      $encoded .= $chunk . $this->LE;
+    }
+
+    // Chomp the last linefeed
+    $encoded = substr($encoded, 0, -strlen($this->LE));
+    return $encoded;
+  }
+
+  /**
+   * Encode string to quoted-printable.
+   * @access private
+   * @return string
+   */
+  function EncodeQP( $input = '', $line_max = 76, $space_conv = false ) {
+    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
+    $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
+    $eol = "\r\n";
+    $escape = '=';
+    $output = '';
+    while( list(, $line) = each($lines) ) {
+      $linlen = strlen($line);
+      $newline = '';
+      for($i = 0; $i < $linlen; $i++) {
+        $c = substr( $line, $i, 1 );
+        $dec = ord( $c );
+        if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E
+          $c = '=2E';
+        }
+        if ( $dec == 32 ) {
+          if ( $i == ( $linlen - 1 ) ) { // convert space at eol only
+            $c = '=20';
+          } else if ( $space_conv ) {
+            $c = '=20';
+          }
+        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
+          $h2 = floor($dec/16);
+          $h1 = floor($dec%16);
+          $c = $escape.$hex[$h2].$hex[$h1];
+        }
+        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
+          $output .= $newline.$escape.$eol; //  soft line break; " =\r\n" is okay
+          $newline = '';
+          // check if newline first character will be point or not
+          if ( $dec == 46 ) {
+            $c = '=2E';
+          }
+        }
+        $newline .= $c;
+      } // end of for
+      $output .= $newline.$eol;
+    } // end of while
+    return trim($output);
+  }
+
+  /**
+   * Encode string to q encoding.
+   * @access private
+   * @return string
+   */
+  function EncodeQ ($str, $position = 'text') {
+    /* There should not be any EOL in the string */
+    $encoded = preg_replace("[\r\n]", '', $str);
+
+    switch (strtolower($position)) {
+      case 'phrase':
+        $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
+        break;
+      case 'comment':
+        $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
+      case 'text':
+      default:
+        /* Replace every high ascii, control =, ? and _ characters */
+        $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
+              "'='.sprintf('%02X', ord('\\1'))", $encoded);
+        break;
+    }
+
+    /* Replace every spaces to _ (more readable than =20) */
+    $encoded = str_replace(' ', '_', $encoded);
+
+    return $encoded;
+  }
+
+  /**
+   * Adds a string or binary attachment (non-filesystem) to the list.
+   * This method can be used to attach ascii or binary data,
+   * such as a BLOB record from a database.
+   * @param string $string String attachment data.
+   * @param string $filename Name of the attachment.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return void
+   */
+  function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
+    /* Append to $attachment array */
+    $cur = count($this->attachment);
+    $this->attachment[$cur][0] = $string;
+    $this->attachment[$cur][1] = $filename;
+    $this->attachment[$cur][2] = $filename;
+    $this->attachment[$cur][3] = $encoding;
+    $this->attachment[$cur][4] = $type;
+    $this->attachment[$cur][5] = true; // isString
+    $this->attachment[$cur][6] = 'attachment';
+    $this->attachment[$cur][7] = 0;
+  }
+
+  /**
+   * Adds an embedded attachment.  This can include images, sounds, and
+   * just about any other document.  Make sure to set the $type to an
+   * image type.  For JPEG images use "image/jpeg" and for GIF images
+   * use "image/gif".
+   * @param string $path Path to the attachment.
+   * @param string $cid Content ID of the attachment.  Use this to identify
+   *        the Id for accessing the image in an HTML form.
+   * @param string $name Overrides the attachment name.
+   * @param string $encoding File encoding (see $Encoding).
+   * @param string $type File extension (MIME) type.
+   * @return bool
+   */
+  function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
+
+    if(!@is_file($path)) {
+      $this->SetError($this->Lang('file_access') . $path);
+      return false;
+    }
+
+    $filename = basename($path);
+    if($name == '') {
+      $name = $filename;
+    }
+
+    /* Append to $attachment array */
+    $cur = count($this->attachment);
+    $this->attachment[$cur][0] = $path;
+    $this->attachment[$cur][1] = $filename;
+    $this->attachment[$cur][2] = $name;
+    $this->attachment[$cur][3] = $encoding;
+    $this->attachment[$cur][4] = $type;
+    $this->attachment[$cur][5] = false;
+    $this->attachment[$cur][6] = 'inline';
+    $this->attachment[$cur][7] = $cid;
+
+    return true;
+  }
+
+  /**
+   * Returns true if an inline attachment is present.
+   * @access private
+   * @return bool
+   */
+  function InlineImageExists() {
+    $result = false;
+    for($i = 0; $i < count($this->attachment); $i++) {
+      if($this->attachment[$i][6] == 'inline') {
+        $result = true;
+        break;
+      }
+    }
+
+    return $result;
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, MESSAGE RESET
+  /////////////////////////////////////////////////
+
+  /**
+   * Clears all recipients assigned in the TO array.  Returns void.
+   * @return void
+   */
+  function ClearAddresses() {
+    $this->to = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the CC array.  Returns void.
+   * @return void
+   */
+  function ClearCCs() {
+    $this->cc = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the BCC array.  Returns void.
+   * @return void
+   */
+  function ClearBCCs() {
+    $this->bcc = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the ReplyTo array.  Returns void.
+   * @return void
+   */
+  function ClearReplyTos() {
+    $this->ReplyTo = array();
+  }
+
+  /**
+   * Clears all recipients assigned in the TO, CC and BCC
+   * array.  Returns void.
+   * @return void
+   */
+  function ClearAllRecipients() {
+    $this->to = array();
+    $this->cc = array();
+    $this->bcc = array();
+  }
+
+  /**
+   * Clears all previously set filesystem, string, and binary
+   * attachments.  Returns void.
+   * @return void
+   */
+  function ClearAttachments() {
+    $this->attachment = array();
+  }
+
+  /**
+   * Clears all custom headers.  Returns void.
+   * @return void
+   */
+  function ClearCustomHeaders() {
+    $this->CustomHeader = array();
+  }
+
+  /////////////////////////////////////////////////
+  // CLASS METHODS, MISCELLANEOUS
+  /////////////////////////////////////////////////
+
+  /**
+   * Adds the error message to the error container.
+   * Returns void.
+   * @access private
+   * @return void
+   */
+  function SetError($msg) {
+    $this->error_count++;
+    $this->ErrorInfo = $msg;
+  }
+
+  /**
+   * Returns the proper RFC 822 formatted date.
+   * @access private
+   * @return string
+   */
+  function RFCDate() {
+    $tz = date('Z');
+    $tzs = ($tz < 0) ? '-' : '+';
+    $tz = abs($tz);
+    $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
+    $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
+
+    return $result;
+  }
+
+  /**
+   * Returns the appropriate server variable.  Should work with both
+   * PHP 4.1.0+ as well as older versions.  Returns an empty string
+   * if nothing is found.
+   * @access private
+   * @return mixed
+   */
+  function ServerVar($varName) {
+    global $HTTP_SERVER_VARS;
+    global $HTTP_ENV_VARS;
+
+    if(!isset($_SERVER)) {
+      $_SERVER = $HTTP_SERVER_VARS;
+      if(!isset($_SERVER['REMOTE_ADDR'])) {
+        $_SERVER = $HTTP_ENV_VARS; // must be Apache
+      }
+    }
+
+    if(isset($_SERVER[$varName])) {
+      return $_SERVER[$varName];
+    } else {
+      return '';
+    }
+  }
+
+  /**
+   * Returns the server hostname or 'localhost.localdomain' if unknown.
+   * @access private
+   * @return string
+   */
+  function ServerHostname() {
+    if ($this->Hostname != '') {
+      $result = $this->Hostname;
+    } elseif ($this->ServerVar('SERVER_NAME') != '') {
+      $result = $this->ServerVar('SERVER_NAME');
+    } else {
+      $result = 'localhost.localdomain';
+    }
+
+    return $result;
+  }
+
+  /**
+   * Returns a message in the appropriate language.
+   * @access private
+   * @return string
+   */
+  function Lang($key) {
+    if(count($this->language) < 1) {
+      $this->SetLanguage('en'); // set the default language
+    }
+
+    if(isset($this->language[$key])) {
+      return $this->language[$key];
+    } else {
+      return 'Language string failed to load: ' . $key;
+    }
+  }
+
+  /**
+   * Returns true if an error occurred.
+   * @return bool
+   */
+  function IsError() {
+    return ($this->error_count > 0);
+  }
+
+  /**
+   * Changes every end of line from CR or LF to CRLF.
+   * @access private
+   * @return string
+   */
+  function FixEOL($str) {
+    $str = str_replace("\r\n", "\n", $str);
+    $str = str_replace("\r", "\n", $str);
+    $str = str_replace("\n", $this->LE, $str);
+    return $str;
+  }
+
+  /**
+   * Adds a custom header.
+   * @return void
+   */
+  function AddCustomHeader($custom_header) {
+    $this->CustomHeader[] = explode(':', $custom_header, 2);
+  }
+
+  /**
+   * Evaluates the message and returns modifications for inline images and backgrounds
+   * @access public
+   * @return $message
+   */
+  function MsgHTML($message,$basedir='') {
+    preg_match_all("/(src|background)=\"(.*)\"/Ui", $message, $images);
+    if(isset($images[2])) {
+      foreach($images[2] as $i => $url) {
+        // do not change urls for absolute images (thanks to corvuscorax)
+        if (!preg_match('/^[A-z][A-z]*:\/\//',$url)) {
+          $filename = basename($url);
+          $directory = dirname($url);
+          ($directory == '.')?$directory='':'';
+          $cid = 'cid:' . md5($filename);
+          $fileParts = split("\.", $filename);
+          $ext = $fileParts[1];
+          $mimeType = $this->_mime_types($ext);
+          if ( strlen($basedir) > 1 && substr($basedir,-1) != '/') { $basedir .= '/'; }
+          if ( strlen($directory) > 1 && substr($basedir,-1) != '/') { $directory .= '/'; }
+          $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType);
+          if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64',$mimeType) ) {
+            $message = preg_replace("/".$images[1][$i]."=\"".preg_quote($url, '/')."\"/Ui", $images[1][$i]."=\"".$cid."\"", $message);
+          }
+        }
+      }
+    }
+    $this->IsHTML(true);
+    $this->Body = $message;
+    $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$message)));
+    if ( !empty($textMsg) && empty($this->AltBody) ) {
+      $this->AltBody = $textMsg;
+    }
+    if ( empty($this->AltBody) ) {
+      $this->AltBody = 'To view this email message, open the email in with HTML compatibility!' . "\n\n";
+    }
+  }
+
+  /**
+   * Gets the mime type of the embedded or inline image
+   * @access private
+   * @return mime type of ext
+   */
+  function _mime_types($ext = '') {
+    $mimes = array(
+      'hqx'  =>  'application/mac-binhex40',
+      'cpt'   =>  'application/mac-compactpro',
+      'doc'   =>  'application/msword',
+      'bin'   =>  'application/macbinary',
+      'dms'   =>  'application/octet-stream',
+      'lha'   =>  'application/octet-stream',
+      'lzh'   =>  'application/octet-stream',
+      'exe'   =>  'application/octet-stream',
+      'class' =>  'application/octet-stream',
+      'psd'   =>  'application/octet-stream',
+      'so'    =>  'application/octet-stream',
+      'sea'   =>  'application/octet-stream',
+      'dll'   =>  'application/octet-stream',
+      'oda'   =>  'application/oda',
+      'pdf'   =>  'application/pdf',
+      'ai'    =>  'application/postscript',
+      'eps'   =>  'application/postscript',
+      'ps'    =>  'application/postscript',
+      'smi'   =>  'application/smil',
+      'smil'  =>  'application/smil',
+      'mif'   =>  'application/vnd.mif',
+      'xls'   =>  'application/vnd.ms-excel',
+      'ppt'   =>  'application/vnd.ms-powerpoint',
+      'wbxml' =>  'application/vnd.wap.wbxml',
+      'wmlc'  =>  'application/vnd.wap.wmlc',
+      'dcr'   =>  'application/x-director',
+      'dir'   =>  'application/x-director',
+      'dxr'   =>  'application/x-director',
+      'dvi'   =>  'application/x-dvi',
+      'gtar'  =>  'application/x-gtar',
+      'php'   =>  'application/x-httpd-php',
+      'php4'  =>  'application/x-httpd-php',
+      'php3'  =>  'application/x-httpd-php',
+      'phtml' =>  'application/x-httpd-php',
+      'phps'  =>  'application/x-httpd-php-source',
+      'js'    =>  'application/x-javascript',
+      'swf'   =>  'application/x-shockwave-flash',
+      'sit'   =>  'application/x-stuffit',
+      'tar'   =>  'application/x-tar',
+      'tgz'   =>  'application/x-tar',
+      'xhtml' =>  'application/xhtml+xml',
+      'xht'   =>  'application/xhtml+xml',
+      'zip'   =>  'application/zip',
+      'mid'   =>  'audio/midi',
+      'midi'  =>  'audio/midi',
+      'mpga'  =>  'audio/mpeg',
+      'mp2'   =>  'audio/mpeg',
+      'mp3'   =>  'audio/mpeg',
+      'aif'   =>  'audio/x-aiff',
+      'aiff'  =>  'audio/x-aiff',
+      'aifc'  =>  'audio/x-aiff',
+      'ram'   =>  'audio/x-pn-realaudio',
+      'rm'    =>  'audio/x-pn-realaudio',
+      'rpm'   =>  'audio/x-pn-realaudio-plugin',
+      'ra'    =>  'audio/x-realaudio',
+      'rv'    =>  'video/vnd.rn-realvideo',
+      'wav'   =>  'audio/x-wav',
+      'bmp'   =>  'image/bmp',
+      'gif'   =>  'image/gif',
+      'jpeg'  =>  'image/jpeg',
+      'jpg'   =>  'image/jpeg',
+      'jpe'   =>  'image/jpeg',
+      'png'   =>  'image/png',
+      'tiff'  =>  'image/tiff',
+      'tif'   =>  'image/tiff',
+      'css'   =>  'text/css',
+      'html'  =>  'text/html',
+      'htm'   =>  'text/html',
+      'shtml' =>  'text/html',
+      'txt'   =>  'text/plain',
+      'text'  =>  'text/plain',
+      'log'   =>  'text/plain',
+      'rtx'   =>  'text/richtext',
+      'rtf'   =>  'text/rtf',
+      'xml'   =>  'text/xml',
+      'xsl'   =>  'text/xml',
+      'mpeg'  =>  'video/mpeg',
+      'mpg'   =>  'video/mpeg',
+      'mpe'   =>  'video/mpeg',
+      'qt'    =>  'video/quicktime',
+      'mov'   =>  'video/quicktime',
+      'avi'   =>  'video/x-msvideo',
+      'movie' =>  'video/x-sgi-movie',
+      'doc'   =>  'application/msword',
+      'word'  =>  'application/msword',
+      'xl'    =>  'application/excel',
+      'eml'   =>  'message/rfc822'
+    );
+    return ( ! isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
+  }
+
+  /**
+   * Set (or reset) Class Objects (variables)
+   *
+   * Usage Example:
+   * $page->set('X-Priority', '3');
+   *
+   * @access public
+   * @param string $name Parameter Name
+   * @param mixed $value Parameter Value
+   * NOTE: will not work with arrays, there are no arrays to set/reset
+   */
+  function set ( $name, $value = '' ) {
+    if ( isset($this->$name) ) {
+      $this->$name = $value;
+    } else {
+      $this->SetError('Cannot set or reset variable ' . $name);
+      return false;
+    }
+  }
+
+  /**
+   * Read a file from a supplied filename and return it.
+   *
+   * @access public
+   * @param string $filename Parameter File Name
+   */
+  function getFile($filename) {
+    $return = '';
+    if ($fp = fopen($filename, 'rb')) {
+      while (!feof($fp)) {
+        $return .= fread($fp, 1024);
+      }
+      fclose($fp);
+      return $return;
+    } else {
+      return false;
+    }
+  }
+
+  /**
+   * Strips newlines to prevent header injection.
+   * @access private
+   * @param string $str String
+   * @return string
+   */
+  function SecureHeader($str) {
+    $str = trim($str);
+    $str = str_replace("\r", "", $str);
+    $str = str_replace("\n", "", $str);
+    return $str;
+  }
+
+  /**
+   * Set the private key file and password to sign the message.
+   *
+   * @access public
+   * @param string $key_filename Parameter File Name
+   * @param string $key_pass Password for private key
+   */
+  function Sign($key_filename, $key_pass) {
+    $this->sign_key_file = $key_filename;
+    $this->sign_key_pass = $key_pass;
+  }
+
+}
+
+?>

+ 1062 - 0
includes/class.smtp.php

@@ -0,0 +1,1062 @@
+<?php
+/*~ class.smtp.php
+.---------------------------------------------------------------------------.
+|  Software: PHPMailer - PHP email class                                    |
+|   Version: 2.0.2                                                          |
+|   Contact: via sourceforge.net support pages (also www.codeworxtech.com)  |
+|      Info: http://phpmailer.sourceforge.net                               |
+|   Support: http://sourceforge.net/projects/phpmailer/                     |
+| ------------------------------------------------------------------------- |
+|    Author: Andy Prevost (project admininistrator)                         |
+|    Author: Brent R. Matzelle (original founder)                           |
+| Copyright (c) 2004-2007, Andy Prevost. All Rights Reserved.               |
+| Copyright (c) 2001-2003, Brent R. Matzelle                                |
+| ------------------------------------------------------------------------- |
+|   License: Distributed under the Lesser General Public License (LGPL)     |
+|            http://www.gnu.org/copyleft/lesser.html                        |
+| This program is distributed in the hope that it will be useful - WITHOUT  |
+| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
+| FITNESS FOR A PARTICULAR PURPOSE.                                         |
+| ------------------------------------------------------------------------- |
+| We offer a number of paid services (www.codeworxtech.com):                |
+| - Web Hosting on highly optimized fast and secure servers                 |
+| - Technology Consulting                                                   |
+| - Oursourcing (highly qualified programmers and graphic designers)        |
+'---------------------------------------------------------------------------'
+
+/**
+ * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
+ * commands except TURN which will always return a not implemented
+ * error. SMTP also provides some utility methods for sending mail
+ * to an SMTP server.
+ * @package PHPMailer
+ * @author Chris Ryan
+ */
+
+class SMTP
+{
+  /**
+   *  SMTP server port
+   *  @var int
+   */
+  var $SMTP_PORT = 25;
+
+  /**
+   *  SMTP reply line ending
+   *  @var string
+   */
+  var $CRLF = "\r\n";
+
+  /**
+   *  Sets whether debugging is turned on
+   *  @var bool
+   */
+  var $do_debug;       # the level of debug to perform
+
+  /**
+   *  Sets VERP use on/off (default is off)
+   *  @var bool
+   */
+  var $do_verp = false;
+
+  /**#@+
+   * @access private
+   */
+  var $smtp_conn;      # the socket to the server
+  var $error;          # error if any on the last call
+  var $helo_rply;      # the reply the server sent to us for HELO
+  /**#@-*/
+
+  /**
+   * Initialize the class so that the data is in a known state.
+   * @access public
+   * @return void
+   */
+  function SMTP() {
+    $this->smtp_conn = 0;
+    $this->error = null;
+    $this->helo_rply = null;
+
+    $this->do_debug = 0;
+  }
+
+  /*************************************************************
+   *                    CONNECTION FUNCTIONS                  *
+   ***********************************************************/
+
+  /**
+   * Connect to the server specified on the port specified.
+   * If the port is not specified use the default SMTP_PORT.
+   * If tval is specified then a connection will try and be
+   * established with the server for that number of seconds.
+   * If tval is not specified the default is 30 seconds to
+   * try on the connection.
+   *
+   * SMTP CODE SUCCESS: 220
+   * SMTP CODE FAILURE: 421
+   * @access public
+   * @return bool
+   */
+  function Connect($host,$port=0,$tval=30) {
+    # set the error val to null so there is no confusion
+    $this->error = null;
+
+    # make sure we are __not__ connected
+    if($this->connected()) {
+      # ok we are connected! what should we do?
+      # for now we will just give an error saying we
+      # are already connected
+      $this->error = array("error" => "Already connected to a server");
+      return false;
+    }
+
+    if(empty($port)) {
+      $port = $this->SMTP_PORT;
+    }
+
+    #connect to the smtp server
+    $this->smtp_conn = fsockopen($host,    # the host of the server
+                                 $port,    # the port to use
+                                 $errno,   # error number if any
+                                 $errstr,  # error message if any
+                                 $tval);   # give up after ? secs
+    # verify we connected properly
+    if(empty($this->smtp_conn)) {
+      $this->error = array("error" => "Failed to connect to server",
+                           "errno" => $errno,
+                           "errstr" => $errstr);
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": $errstr ($errno)" . $this->CRLF;
+      }
+      return false;
+    }
+
+    # sometimes the SMTP server takes a little longer to respond
+    # so we will give it a longer timeout for the first read
+    // Windows still does not have support for this timeout function
+    if(substr(PHP_OS, 0, 3) != "WIN")
+     socket_set_timeout($this->smtp_conn, $tval, 0);
+
+    # get any announcement stuff
+    $announce = $this->get_lines();
+
+    # set the timeout  of any socket functions at 1/10 of a second
+    //if(function_exists("socket_set_timeout"))
+    //   socket_set_timeout($this->smtp_conn, 0, 100000);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce;
+    }
+
+    return true;
+  }
+
+  /**
+   * Performs SMTP authentication.  Must be run after running the
+   * Hello() method.  Returns true if successfully authenticated.
+   * @access public
+   * @return bool
+   */
+  function Authenticate($username, $password) {
+    // Start authentication
+    fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($code != 334) {
+      $this->error =
+        array("error" => "AUTH not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    // Send encoded username
+    fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($code != 334) {
+      $this->error =
+        array("error" => "Username not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    // Send encoded password
+    fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($code != 235) {
+      $this->error =
+        array("error" => "Password not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Returns true if connected to a server otherwise false
+   * @access private
+   * @return bool
+   */
+  function Connected() {
+    if(!empty($this->smtp_conn)) {
+      $sock_status = socket_get_status($this->smtp_conn);
+      if($sock_status["eof"]) {
+        # hmm this is an odd situation... the socket is
+        # valid but we are not connected anymore
+        if($this->do_debug >= 1) {
+            echo "SMTP -> NOTICE:" . $this->CRLF .
+                 "EOF caught while checking if connected";
+        }
+        $this->Close();
+        return false;
+      }
+      return true; # everything looks good
+    }
+    return false;
+  }
+
+  /**
+   * Closes the socket and cleans up the state of the class.
+   * It is not considered good to use this function without
+   * first trying to use QUIT.
+   * @access public
+   * @return void
+   */
+  function Close() {
+    $this->error = null; # so there is no confusion
+    $this->helo_rply = null;
+    if(!empty($this->smtp_conn)) {
+      # close the connection and cleanup
+      fclose($this->smtp_conn);
+      $this->smtp_conn = 0;
+    }
+  }
+
+  /***************************************************************
+   *                        SMTP COMMANDS                       *
+   *************************************************************/
+
+  /**
+   * Issues a data command and sends the msg_data to the server
+   * finializing the mail transaction. $msg_data is the message
+   * that is to be send with the headers. Each header needs to be
+   * on a single line followed by a <CRLF> with the message headers
+   * and the message body being seperated by and additional <CRLF>.
+   *
+   * Implements rfc 821: DATA <CRLF>
+   *
+   * SMTP CODE INTERMEDIATE: 354
+   *     [data]
+   *     <CRLF>.<CRLF>
+   *     SMTP CODE SUCCESS: 250
+   *     SMTP CODE FAILURE: 552,554,451,452
+   * SMTP CODE FAILURE: 451,554
+   * SMTP CODE ERROR  : 500,501,503,421
+   * @access public
+   * @return bool
+   */
+  function Data($msg_data) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Data() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"DATA" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 354) {
+      $this->error =
+        array("error" => "DATA command not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    # the server is ready to accept data!
+    # according to rfc 821 we should not send more than 1000
+    # including the CRLF
+    # characters on a single line so we will break the data up
+    # into lines by \r and/or \n then if needed we will break
+    # each of those into smaller lines to fit within the limit.
+    # in addition we will be looking for lines that start with
+    # a period '.' and append and additional period '.' to that
+    # line. NOTE: this does not count towards are limit.
+
+    # normalize the line breaks so we know the explode works
+    $msg_data = str_replace("\r\n","\n",$msg_data);
+    $msg_data = str_replace("\r","\n",$msg_data);
+    $lines = explode("\n",$msg_data);
+
+    # we need to find a good way to determine is headers are
+    # in the msg_data or if it is a straight msg body
+    # currently I am assuming rfc 822 definitions of msg headers
+    # and if the first field of the first line (':' sperated)
+    # does not contain a space then it _should_ be a header
+    # and we can process all lines before a blank "" line as
+    # headers.
+    $field = substr($lines[0],0,strpos($lines[0],":"));
+    $in_headers = false;
+    if(!empty($field) && !strstr($field," ")) {
+      $in_headers = true;
+    }
+
+    $max_line_length = 998; # used below; set here for ease in change
+
+    while(list(,$line) = @each($lines)) {
+      $lines_out = null;
+      if($line == "" && $in_headers) {
+        $in_headers = false;
+      }
+      # ok we need to break this line up into several
+      # smaller lines
+      while(strlen($line) > $max_line_length) {
+        $pos = strrpos(substr($line,0,$max_line_length)," ");
+
+        # Patch to fix DOS attack
+        if(!$pos) {
+          $pos = $max_line_length - 1;
+        }
+
+        $lines_out[] = substr($line,0,$pos);
+        $line = substr($line,$pos + 1);
+        # if we are processing headers we need to
+        # add a LWSP-char to the front of the new line
+        # rfc 822 on long msg headers
+        if($in_headers) {
+          $line = "\t" . $line;
+        }
+      }
+      $lines_out[] = $line;
+
+      # now send the lines to the server
+      while(list(,$line_out) = @each($lines_out)) {
+        if(strlen($line_out) > 0)
+        {
+          if(substr($line_out, 0, 1) == ".") {
+            $line_out = "." . $line_out;
+          }
+        }
+        fputs($this->smtp_conn,$line_out . $this->CRLF);
+      }
+    }
+
+    # ok all the message data has been sent so lets get this
+    # over with aleady
+    fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "DATA not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Expand takes the name and asks the server to list all the
+   * people who are members of the _list_. Expand will return
+   * back and array of the result or false if an error occurs.
+   * Each value in the array returned has the format of:
+   *     [ <full-name> <sp> ] <path>
+   * The definition of <path> is defined in rfc 821
+   *
+   * Implements rfc 821: EXPN <SP> <string> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE FAILURE: 550
+   * SMTP CODE ERROR  : 500,501,502,504,421
+   * @access public
+   * @return string array
+   */
+  function Expand($name) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+            "error" => "Called Expand() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "EXPN not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    # parse the reply and place in our array to return to user
+    $entries = explode($this->CRLF,$rply);
+    while(list(,$l) = @each($entries)) {
+      $list[] = substr($l,4);
+    }
+
+    return $list;
+  }
+
+  /**
+   * Sends the HELO command to the smtp server.
+   * This makes sure that we and the server are in
+   * the same known state.
+   *
+   * Implements from rfc 821: HELO <SP> <domain> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE ERROR  : 500, 501, 504, 421
+   * @access public
+   * @return bool
+   */
+  function Hello($host="") {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+            "error" => "Called Hello() without being connected");
+      return false;
+    }
+
+    # if a hostname for the HELO was not specified determine
+    # a suitable one to send
+    if(empty($host)) {
+      # we need to determine some sort of appopiate default
+      # to send to the server
+      $host = "localhost";
+    }
+
+    // Send extended hello first (RFC 2821)
+    if(!$this->SendHello("EHLO", $host))
+    {
+      if(!$this->SendHello("HELO", $host))
+          return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Sends a HELO/EHLO command.
+   * @access private
+   * @return bool
+   */
+  function SendHello($hello, $host) {
+    fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER: " . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => $hello . " not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    $this->helo_rply = $rply;
+
+    return true;
+  }
+
+  /**
+   * Gets help information on the keyword specified. If the keyword
+   * is not specified then returns generic help, ussually contianing
+   * A list of keywords that help is available on. This function
+   * returns the results back to the user. It is up to the user to
+   * handle the returned data. If an error occurs then false is
+   * returned with $this->error set appropiately.
+   *
+   * Implements rfc 821: HELP [ <SP> <string> ] <CRLF>
+   *
+   * SMTP CODE SUCCESS: 211,214
+   * SMTP CODE ERROR  : 500,501,502,504,421
+   * @access public
+   * @return string
+   */
+  function Help($keyword="") {
+    $this->error = null; # to avoid confusion
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Help() without being connected");
+      return false;
+    }
+
+    $extra = "";
+    if(!empty($keyword)) {
+      $extra = " " . $keyword;
+    }
+
+    fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 211 && $code != 214) {
+      $this->error =
+        array("error" => "HELP not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    return $rply;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command.
+   *
+   * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,421
+   * @access public
+   * @return bool
+   */
+  function Mail($from) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Mail() without being connected");
+      return false;
+    }
+
+    $useVerp = ($this->do_verp ? "XVERP" : "");
+    fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "MAIL not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the command NOOP to the SMTP server.
+   *
+   * Implements from rfc 821: NOOP <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE ERROR  : 500, 421
+   * @access public
+   * @return bool
+   */
+  function Noop() {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Noop() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"NOOP" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "NOOP not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the quit command to the server and then closes the socket
+   * if there is no error or the $close_on_error argument is true.
+   *
+   * Implements from rfc 821: QUIT <CRLF>
+   *
+   * SMTP CODE SUCCESS: 221
+   * SMTP CODE ERROR  : 500
+   * @access public
+   * @return bool
+   */
+  function Quit($close_on_error=true) {
+    $this->error = null; # so there is no confusion
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Quit() without being connected");
+      return false;
+    }
+
+    # send the quit command to the server
+    fputs($this->smtp_conn,"quit" . $this->CRLF);
+
+    # get any good-bye messages
+    $byemsg = $this->get_lines();
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg;
+    }
+
+    $rval = true;
+    $e = null;
+
+    $code = substr($byemsg,0,3);
+    if($code != 221) {
+      # use e as a tmp var cause Close will overwrite $this->error
+      $e = array("error" => "SMTP server rejected quit command",
+                 "smtp_code" => $code,
+                 "smtp_rply" => substr($byemsg,4));
+      $rval = false;
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $e["error"] . ": " .
+                 $byemsg . $this->CRLF;
+      }
+    }
+
+    if(empty($e) || $close_on_error) {
+      $this->Close();
+    }
+
+    return $rval;
+  }
+
+  /**
+   * Sends the command RCPT to the SMTP server with the TO: argument of $to.
+   * Returns true if the recipient was accepted false if it was rejected.
+   *
+   * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250,251
+   * SMTP CODE FAILURE: 550,551,552,553,450,451,452
+   * SMTP CODE ERROR  : 500,501,503,421
+   * @access public
+   * @return bool
+   */
+  function Recipient($to) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Recipient() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250 && $code != 251) {
+      $this->error =
+        array("error" => "RCPT not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Sends the RSET command to abort and transaction that is
+   * currently in progress. Returns true if successful false
+   * otherwise.
+   *
+   * Implements rfc 821: RSET <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE ERROR  : 500,501,504,421
+   * @access public
+   * @return bool
+   */
+  function Reset() {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Reset() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"RSET" . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "RSET failed",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+
+    return true;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command. This command
+   * will send the message to the users terminal if they are logged
+   * in.
+   *
+   * Implements rfc 821: SEND <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,502,421
+   * @access public
+   * @return bool
+   */
+  function Send($from) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Send() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "SEND not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command. This command
+   * will send the message to the users terminal if they are logged
+   * in and send them an email.
+   *
+   * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,502,421
+   * @access public
+   * @return bool
+   */
+  function SendAndMail($from) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+          "error" => "Called SendAndMail() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "SAML not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Starts a mail transaction from the email address specified in
+   * $from. Returns true if successful or false otherwise. If True
+   * the mail transaction is started and then one or more Recipient
+   * commands may be called followed by a Data command. This command
+   * will send the message to the users terminal if they are logged
+   * in or mail it to them if they are not.
+   *
+   * Implements rfc 821: SOML <SP> FROM:<reverse-path> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE SUCCESS: 552,451,452
+   * SMTP CODE SUCCESS: 500,501,502,421
+   * @access public
+   * @return bool
+   */
+  function SendOrMail($from) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+          "error" => "Called SendOrMail() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250) {
+      $this->error =
+        array("error" => "SOML not accepted from server",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * This is an optional command for SMTP that this class does not
+   * support. This method is here to make the RFC821 Definition
+   * complete for this class and __may__ be implimented in the future
+   *
+   * Implements from rfc 821: TURN <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250
+   * SMTP CODE FAILURE: 502
+   * SMTP CODE ERROR  : 500, 503
+   * @access public
+   * @return bool
+   */
+  function Turn() {
+    $this->error = array("error" => "This method, TURN, of the SMTP ".
+                                    "is not implemented");
+    if($this->do_debug >= 1) {
+      echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF;
+    }
+    return false;
+  }
+
+  /**
+   * Verifies that the name is recognized by the server.
+   * Returns false if the name could not be verified otherwise
+   * the response from the server is returned.
+   *
+   * Implements rfc 821: VRFY <SP> <string> <CRLF>
+   *
+   * SMTP CODE SUCCESS: 250,251
+   * SMTP CODE FAILURE: 550,551,553
+   * SMTP CODE ERROR  : 500,501,502,421
+   * @access public
+   * @return int
+   */
+  function Verify($name) {
+    $this->error = null; # so no confusion is caused
+
+    if(!$this->connected()) {
+      $this->error = array(
+              "error" => "Called Verify() without being connected");
+      return false;
+    }
+
+    fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF);
+
+    $rply = $this->get_lines();
+    $code = substr($rply,0,3);
+
+    if($this->do_debug >= 2) {
+      echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
+    }
+
+    if($code != 250 && $code != 251) {
+      $this->error =
+        array("error" => "VRFY failed on name '$name'",
+              "smtp_code" => $code,
+              "smtp_msg" => substr($rply,4));
+      if($this->do_debug >= 1) {
+        echo "SMTP -> ERROR: " . $this->error["error"] .
+                 ": " . $rply . $this->CRLF;
+      }
+      return false;
+    }
+    return $rply;
+  }
+
+  /*******************************************************************
+   *                       INTERNAL FUNCTIONS                       *
+   ******************************************************************/
+
+  /**
+   * Read in as many lines as possible
+   * either before eof or socket timeout occurs on the operation.
+   * With SMTP we can tell if we have more lines to read if the
+   * 4th character is '-' symbol. If it is a space then we don't
+   * need to read anything else.
+   * @access private
+   * @return string
+   */
+  function get_lines() {
+    $data = "";
+    while($str = @fgets($this->smtp_conn,515)) {
+      if($this->do_debug >= 4) {
+        echo "SMTP -> get_lines(): \$data was \"$data\"" .
+                 $this->CRLF;
+        echo "SMTP -> get_lines(): \$str is \"$str\"" .
+                 $this->CRLF;
+      }
+      $data .= $str;
+      if($this->do_debug >= 4) {
+        echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF;
+      }
+      # if the 4th character is a space then we are done reading
+      # so just break the loop
+      if(substr($str,3,1) == " ") { break; }
+    }
+    return $data;
+  }
+
+}
+
+
+ ?>

+ 198 - 0
includes/class_vcard.php

@@ -0,0 +1,198 @@
+<?php
+/*
+* Filename.......: class_vcard.php
+* Author.........: Troy Wolf [[email protected]]
+* Last Modified..: 2005/07/14 13:30:00
+* Description....: A class to generate vCards for contact data.
+*/
+class vcard {
+	var $log;
+	var $data;  //array of this vcard's contact data
+	var $filename; //filename for download file naming
+	var $class; //PUBLIC, PRIVATE, CONFIDENTIAL
+	var $revision_date;
+	var $card;
+
+	/*
+	The class constructor. You can set some defaults here if desired.
+	*/
+	function vcard() {
+	$this->log = "New vcard() called<br />";
+	$this->data = array(
+		"display_name"=>null
+		,"first_name"=>null
+		,"last_name"=>null
+		,"additional_name"=>null
+		,"name_prefix"=>null
+		,"name_suffix"=>null
+		,"nickname"=>null
+		,"title"=>null
+		,"role"=>null
+		,"department"=>null
+		,"company"=>null
+		,"work_po_box"=>null
+		,"work_extended_address"=>null
+		,"work_address"=>null
+		,"work_city"=>null
+		,"work_state"=>null
+		,"work_postal_code"=>null
+		,"work_country"=>null
+		,"home_po_box"=>null
+		,"home_extended_address"=>null
+		,"home_address"=>null
+		,"home_city"=>null
+		,"home_state"=>null
+		,"home_postal_code"=>null
+		,"home_country"=>null
+		,"office_tel"=>null
+		,"home_tel"=>null
+		,"cell_tel"=>null
+		,"fax_tel"=>null
+		,"pager_tel"=>null
+		,"email1"=>null
+		,"email2"=>null
+		,"url"=>null
+		,"photo"=>null
+		,"birthday"=>null
+		,"timezone"=>null
+		,"sort_string"=>null
+		,"note"=>null
+		);
+	return true;
+	}
+
+	/*
+	build() method checks all the values, builds appropriate defaults for
+	missing values, generates the vcard data string.
+	*/  
+	function build() {
+		$this->log .= "vcard build() called<br />";
+		/*
+		For many of the values, if they are not passed in, we set defaults or
+		build them based on other values.
+		*/
+		if (!$this->class) { $this->class = "PUBLIC"; }
+		if (!$this->data['display_name']) {
+			$this->data['display_name'] = trim($this->data['first_name']." ".$this->data['last_name']);
+		}
+		if (!$this->data['sort_string']) { $this->data['sort_string'] = $this->data['last_name']; }
+		if (!$this->data['sort_string']) { $this->data['sort_string'] = $this->data['company']; }
+		if (!$this->data['timezone']) { $this->data['timezone'] = date("O"); }
+		if (!$this->revision_date) { $this->revision_date = date('Y-m-d H:i:s'); }
+
+		$this->card = "BEGIN:VCARD\r\n";
+		$this->card .= "VERSION:3.0\r\n";
+		//$this->card .= "CLASS:".$this->class."\r\n";
+		//$this->card .= "PRODID:-//class_vcard from TroyWolf.com//NONSGML Version 1//EN\r\n";
+		$this->card .= "REV:".$this->revision_date."\r\n";
+		$this->card .= "FN:".$this->data['display_name']."\r\n";
+		$this->card .= "N:";
+		$this->card .= $this->data['last_name'].";";
+		$this->card .= $this->data['first_name'].";";
+		if (strlen($this->data['additional_name']) > 0) {
+			$this->card .= $this->data['additional_name'].";";
+		}
+		if (strlen($this->data['name_prefix']) > 0) {
+			$this->card .= $this->data['name_prefix'].";";
+		}
+		if (strlen($this->data['name_suffix']) > 0) {
+			$this->card .= $this->data['name_suffix']."\r\n";
+		}
+		if ($this->data['nickname']) { $this->card .= "NICKNAME:".$this->data['contact_nickname']."\r\n"; }
+		if ($this->data['title']) { $this->card .= "TITLE:".$this->data['title']."\r\n"; }
+		if ($this->data['company']) { $this->card .= "ORG:".$this->data['company']; }
+		if ($this->data['department']) { $this->card .= ";".$this->data['department']; }
+		$this->card .= "\r\n";
+
+		if ($this->data['work_po_box']
+		|| $this->data['work_extended_address']
+		|| $this->data['work_address']
+		|| $this->data['work_city']
+		|| $this->data['work_state']
+		|| $this->data['work_postal_code']
+		|| $this->data['work_country']) {
+			$this->card .= "ADR;TYPE=work:";
+			if (strlen($this->data['work_po_box']) > 0) {
+				$this->card .= $this->data['work_po_box'].";";
+			}
+			if (strlen($this->data['work_extended_address']) > 0) {
+				$this->card .= $this->data['work_extended_address'].";";
+			}
+			if (strlen($this->data['work_address']) > 0) {
+				$this->card .= $this->data['work_address'].";";
+			}
+			if (strlen($this->data['work_city']) > 0) {
+				$this->card .= $this->data['work_city'].";";
+			}
+			if (strlen($this->data['work_state']) > 0) {
+				$this->card .= $this->data['work_state'].";";
+			}
+			if (strlen($this->data['work_postal_code']) > 0) {
+				$this->card .= $this->data['work_postal_code'].";";
+			}
+			if (strlen($this->data['work_country']) > 0) {
+				$this->card .= $this->data['work_country']."";
+			}
+			$this->card .= "\r\n";
+		}
+		if ($this->data['home_po_box']
+		|| $this->data['home_extended_address']
+		|| $this->data['home_address']
+		|| $this->data['home_city']
+		|| $this->data['home_state']
+		|| $this->data['home_postal_code']
+		|| $this->data['home_country']) {
+			$this->card .= "ADR;TYPE=home:";
+			if (strlen($this->data['home_po_box']) > 0) {
+				$this->card .= $this->data['home_po_box'].";";
+			}
+			if (strlen($this->data['home_extended_address']) > 0) {
+				$this->card .= $this->data['home_extended_address'].";";
+			}
+			if (strlen($this->data['home_address']) > 0) {
+				$this->card .= $this->data['home_address'].";";
+			}
+			if (strlen($this->data['home_city']) > 0) {
+				$this->card .= $this->data['home_city'].";";
+			}
+			if (strlen($this->data['home_state']) > 0) {
+				$this->card .= $this->data['home_state']."";
+			}
+			if (strlen($this->data['home_postal_code']) > 0) {
+				$this->card .= $this->data['home_postal_code'].";";
+			}
+			if (strlen($this->data['home_country']) > 0) {
+				$this->card .= $this->data['home_country'];
+			}
+			$this->card .= "\r\n";
+		}
+		if ($this->data['email1']) { $this->card .= "EMAIL;TYPE=internet,pref:".$this->data['email1']."\r\n"; }
+		if ($this->data['email2']) { $this->card .= "EMAIL;TYPE=internet:".$this->data['email2']."\r\n"; }
+		if ($this->data['office_tel']) { $this->card .= "TEL;TYPE=work,voice:".$this->data['office_tel']."\r\n"; }
+		if ($this->data['home_tel']) { $this->card .= "TEL;TYPE=home,voice:".$this->data['home_tel']."\r\n"; }
+		if ($this->data['cell_tel']) { $this->card .= "TEL;TYPE=cell,voice:".$this->data['cell_tel']."\r\n"; }
+		if ($this->data['fax_tel']) { $this->card .= "TEL;TYPE=work,fax:".$this->data['fax_tel']."\r\n"; }
+		if ($this->data['pager_tel']) { $this->card .= "TEL;TYPE=work,pager:".$this->data['pager_tel']."\r\n"; }
+		if ($this->data['url']) { $this->card .= "URL;TYPE=work:".$this->data['url']."\r\n"; }
+		if ($this->data['birthday']) { $this->card .= "BDAY:".$this->data['birthday']."\r\n"; }
+		if ($this->data['role']) { $this->card .= "ROLE:".$this->data['role']."\r\n"; }
+		if ($this->data['note']) { $this->card .= "NOTE:".$this->data['note']."\r\n"; }
+		$this->card .= "TZ:".$this->data['timezone']."\r\n";
+		$this->card .= "END:VCARD\r\n";
+	}
+
+	/*
+	download() method streams the vcard to the browser client.
+	*/
+	function download() {
+		$this->log .= "vcard download() called<br />";
+		if (!$this->card) { $this->build(); }
+		if (!$this->filename) { $this->filename = trim($this->data['display_name']); }
+		$this->filename = str_replace(" ", "_", $this->filename);
+		header("Content-type: text/directory");
+		header("Content-Disposition: attachment; filename=".$this->filename.".vcf");
+		header("Pragma: public");
+		echo $this->card;
+		return true;
+	}
+}

+ 45 - 0
includes/classes/array_order.php

@@ -0,0 +1,45 @@
+<?php
+class array_order {
+
+	var $sort_fields;
+	var $backwards = false;
+	var $numeric = false;
+
+	function sort() {
+		$args = func_get_args();
+		$array = $args[0];
+		if (!$array) return array();
+		$this->sort_fields = array_slice($args, 1);
+		if (!$this->sort_fields) return $array();
+
+		if ($this->numeric) {
+			usort($array, array($this, 'numericCompare'));
+		} else {
+			usort($array, array($this, 'stringCompare'));
+		}
+		return $array;
+	}
+
+	function numericCompare($a, $b) {
+		foreach($this->sort_fields as $sort_field) {
+			if ($a[$sort_field] == $b[$sort_field]) {
+				continue;
+			}
+			return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
+		}
+		return 0;
+	}
+
+	function stringCompare($a, $b) {
+		foreach($this->sort_fields as $sort_field) {
+			$cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
+			if ($cmp_result == 0) continue;
+			return ($this->backwards ? -$cmp_result : $cmp_result);
+		}
+		return 0;
+	}
+}
+//$order = new array_order();
+//$registrations = $order->sort($registrations, 'domain', 'user');
+
+?>

+ 195 - 0
includes/classes/call_forward.php

@@ -0,0 +1,195 @@
+<?php
+/*
+	FusionPBX
+	Version: MPL 1.1
+
+	The contents of this file are subject to the Mozilla Public License Version
+	1.1 (the "License"); you may not use this file except in compliance with
+	the License. You may obtain a copy of the License at
+	http://www.mozilla.org/MPL/
+
+	Software distributed under the License is distributed on an "AS IS" basis,
+	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+	for the specific language governing rights and limitations under the
+	License.
+
+	The Original Code is FusionPBX
+
+	The Initial Developer of the Original Code is
+	Mark J Crane <[email protected]>
+	Copyright (C) 2010
+	All Rights Reserved.
+
+	Contributor(s):
+	Mark J Crane <[email protected]>
+*/
+include "root.php";
+
+//define the call_forward class
+	class call_forward {
+		public $domain_uuid;
+		public $db_type;
+		public $call_forward_uuid;
+		public $extension;
+		public $call_forward_enabled;
+		public $call_forward_number;
+
+		public function call_forward_add() {
+			global $db;
+			$hunt_group_extension = $this->extension;
+			$huntgroup_name = 'call_forward_'.$this->extension;
+			$hunt_group_type = 'call_forward';
+			$hunt_group_context = $_SESSION['context'];
+			$hunt_group_timeout_destination = $this->extension;
+			$hunt_group_timeout_type = 'voicemail';
+			$hunt_group_ring_back = 'us-ring';
+			$hunt_group_cid_name_prefix = '';
+			$hunt_group_pin = '';
+			$huntgroup_caller_announce = 'false';
+			$hunt_group_user_list = '';
+			$hunt_group_enabled = $this->call_forward_enabled;
+			$hunt_group_description = 'call forward '.$this->extension;
+
+			$sql = "insert into v_hunt_groups ";
+			$sql .= "(";
+			$sql .= "domain_uuid, ";
+			$sql .= "hunt_group_uuid, ";
+			$sql .= "hunt_group_extension, ";
+			$sql .= "hunt_group_name, ";
+			$sql .= "hunt_group_type, ";
+			$sql .= "hunt_group_context, ";
+			$sql .= "hunt_group_timeout, ";
+			$sql .= "hunt_group_timeout_destination, ";
+			$sql .= "hunt_group_timeout_type, ";
+			$sql .= "hunt_group_ringback, ";
+			$sql .= "hunt_group_cid_name_prefix, ";
+			$sql .= "hunt_group_pin, ";
+			$sql .= "hunt_group_call_prompt, ";
+			$sql .= "hunt_group_caller_announce, ";
+			$sql .= "hunt_group_user_list, ";
+			$sql .= "hunt_group_enabled, ";
+			$sql .= "hunt_group_description ";
+			$sql .= ")";
+			$sql .= "values ";
+			$sql .= "(";
+			$sql .= "'$this->domain_uuid', ";
+			$sql .= "'".$this->call_forward_uuid."', ";
+			$sql .= "'$hunt_group_extension', ";
+			$sql .= "'$huntgroup_name', ";
+			$sql .= "'$hunt_group_type', ";
+			$sql .= "'$hunt_group_context', ";
+			$sql .= "'$hunt_group_timeout', ";
+			$sql .= "'$hunt_group_timeout_destination', ";
+			$sql .= "'$hunt_group_timeout_type', ";
+			$sql .= "'$hunt_group_ring_back', ";
+			$sql .= "'$hunt_group_cid_name_prefix', ";
+			$sql .= "'$hunt_group_pin', ";
+			$sql .= "'$hunt_group_call_prompt', ";
+			$sql .= "'$huntgroup_caller_announce', ";
+			$sql .= "'$hunt_group_user_list', ";
+			$sql .= "'$hunt_group_enabled', ";
+			$sql .= "'$hunt_group_description' ";
+			$sql .= ")";
+			if ($v_debug) {
+				echo "add: ".$sql."<br />";
+			}
+			$db->exec(check_sql($sql));
+			unset($sql);
+			$this->call_forward_destination();
+		}
+
+		public function call_forward_update() {
+			global $db;
+			$hunt_group_extension = $this->extension;
+			$huntgroup_name = 'call_forward_'.$this->extension;
+			$hunt_group_type = 'call_forward';
+			$hunt_group_context = $_SESSION['context'];
+			$hunt_group_timeout_destination = $this->extension;
+			$hunt_group_timeout_type = 'voicemail';
+			$hunt_group_ring_back = 'us-ring';
+			$hunt_group_cid_name_prefix = '';
+			$hunt_group_pin = '';
+			$huntgroup_caller_announce = 'false';
+			$hunt_group_user_list = '';
+			$hunt_group_enabled = $this->call_forward_enabled;
+			$hunt_group_description = 'call forward '.$this->extension;
+
+			$sql = "update v_hunt_groups set ";
+			$sql .= "hunt_group_extension = '$hunt_group_extension', ";
+			$sql .= "hunt_group_name = '$huntgroup_name', ";
+			$sql .= "hunt_group_type = '$hunt_group_type', ";
+			$sql .= "hunt_group_context = '$hunt_group_context', ";
+			$sql .= "hunt_group_timeout = '$hunt_group_timeout', ";
+			$sql .= "hunt_group_timeout_destination = '$hunt_group_timeout_destination', ";
+			$sql .= "hunt_group_timeout_type = '$hunt_group_timeout_type', ";
+			$sql .= "hunt_group_ringback = '$hunt_group_ring_back', ";
+			$sql .= "hunt_group_cid_name_prefix = '$hunt_group_cid_name_prefix', ";
+			$sql .= "hunt_group_pin = '$hunt_group_pin', ";
+			$sql .= "hunt_group_call_prompt = '$hunt_group_call_prompt', ";
+			$sql .= "hunt_group_caller_announce = '$huntgroup_caller_announce', ";
+			$sql .= "hunt_group_user_list = '$hunt_group_user_list', ";
+			$sql .= "hunt_group_enabled = '$hunt_group_enabled', ";
+			$sql .= "hunt_group_description = '$hunt_group_description' ";
+			$sql .= "where domain_uuid = '$this->domain_uuid' ";
+			$sql .= "and hunt_group_uuid = '$this->call_forward_uuid' ";
+			$db->exec(check_sql($sql));
+			unset($sql);
+			$this->call_forward_destination();
+		} //end function
+
+		public function call_forward_destination() {
+			global $db;
+			//delete related v_hunt_group_destinations
+				$sql = "delete from v_hunt_group_destinations where hunt_group_uuid = '$this->call_forward_uuid' ";
+				$db->exec(check_sql($sql));
+			//check whether the number is an extension or external number
+				if (strlen($this->call_forward_number) > 7) {
+					$destination_type = 'sip uri';
+					$destination_profile = '';
+				}
+				else {
+					$destination_type = 'extension';
+					$destination_profile = 'internal';
+				}
+			//prepare the variables
+				$destination_data = $this->call_forward_number;
+				$destination_timeout = '';
+				$destination_order = '1';
+				$destination_enabled = 'true';
+				$destination_description = 'call forward';
+			//add the hunt group destination
+				if ($this->call_forward_uuid) {
+					$sql = "insert into v_hunt_group_destinations ";
+					$sql .= "(";
+					$sql .= "hunt_group_destination_uuid, ";
+					$sql .= "domain_uuid, ";
+					$sql .= "hunt_group_uuid, ";
+					$sql .= "destination_data, ";
+					$sql .= "destination_type, ";
+					$sql .= "destination_profile, ";
+					$sql .= "destination_timeout, ";
+					$sql .= "destination_order, ";
+					$sql .= "destination_enabled, ";
+					$sql .= "destination_description ";
+					$sql .= ") ";
+					$sql .= "values ";
+					$sql .= "(";
+					$sql .= "'".uuid()."', ";
+					$sql .= "'$this->domain_uuid', ";
+					$sql .= "'$this->call_forward_uuid', ";
+					$sql .= "'$destination_data', ";
+					$sql .= "'$destination_type', ";
+					$sql .= "'$destination_profile', ";
+					$sql .= "'$destination_timeout', ";
+					$sql .= "'$destination_order', ";
+					$sql .= "'$destination_enabled', ";
+					$sql .= "'$destination_description' ";
+					$sql .= ")";
+
+					$db->exec(check_sql($sql));
+					unset($sql);
+				}
+		} //end function
+	}
+
+?>

Некоторые файлы не были показаны из-за большого количества измененных файлов