Fork of FusionPBX but with LDAP kinda working
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2173 lines
68 KiB

2 years ago
  1. <?php
  2. /*
  3. FusionPBX
  4. Version: MPL 1.1
  5. The contents of this file are subject to the Mozilla Public License Version
  6. 1.1 (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.mozilla.org/MPL/
  9. Software distributed under the License is distributed on an "AS IS" basis,
  10. WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. for the specific language governing rights and limitations under the
  12. License.
  13. The Original Code is FusionPBX
  14. The Initial Developer of the Original Code is
  15. Mark J Crane <markjcrane@fusionpbx.com>
  16. Portions created by the Initial Developer are Copyright (C) 2008-2022
  17. the Initial Developer. All Rights Reserved.
  18. Contributor(s):
  19. Mark J Crane <markjcrane@fusionpbx.com>
  20. Luis Daniel Lucio Quiroz <dlucio@okay.com.mx>
  21. */
  22. if (!function_exists('mb_strtoupper')) {
  23. function mb_strtoupper($string) {
  24. return strtoupper($string);
  25. }
  26. }
  27. if (!function_exists('check_float')) {
  28. function check_float($string) {
  29. $string = str_replace(",",".",$string);
  30. return trim($string);
  31. }
  32. }
  33. if (!function_exists('check_str')) {
  34. function check_str($string, $trim = true) {
  35. global $db_type, $db;
  36. //when code in db is urlencoded the ' does not need to be modified
  37. if ($db_type == "sqlite") {
  38. if (function_exists('sqlite_escape_string')) {
  39. $string = sqlite_escape_string($string);
  40. }
  41. else {
  42. $string = str_replace("'","''",$string);
  43. }
  44. }
  45. if ($db_type == "pgsql") {
  46. $string = str_replace("'","''",$string);
  47. }
  48. if ($db_type == "mysql") {
  49. if(function_exists('mysql_real_escape_string')){
  50. $tmp_str = mysql_real_escape_string($string);
  51. }
  52. else {
  53. $tmp_str = mysqli_real_escape_string($db, $string);
  54. }
  55. if (strlen($tmp_str)) {
  56. $string = $tmp_str;
  57. }
  58. else {
  59. $search = array("\x00", "\n", "\r", "\\", "'", "\"", "\x1a");
  60. $replace = array("\\x00", "\\n", "\\r", "\\\\" ,"\'", "\\\"", "\\\x1a");
  61. $string = str_replace($search, $replace, $string);
  62. }
  63. }
  64. $string = ($trim) ? trim($string) : $string;
  65. return $string;
  66. }
  67. }
  68. if (!function_exists('check_sql')) {
  69. function check_sql($string) {
  70. return trim($string); //remove white space
  71. }
  72. }
  73. if (!function_exists('check_cidr')) {
  74. function check_cidr($cidr, $ip_address) {
  75. if (isset($cidr) && strlen($cidr) > 0) {
  76. list ($subnet, $mask) = explode ('/', $cidr);
  77. return ( ip2long ($ip_address) & ~((1 << (32 - $mask)) - 1) ) == ip2long ($subnet);
  78. }
  79. else {
  80. return false;
  81. }
  82. }
  83. }
  84. if (!function_exists('fix_postback')) {
  85. function fix_postback($post_array) {
  86. foreach ($post_array as $index => $value) {
  87. if (is_array($value)) { fix_postback($value); }
  88. else {
  89. $value = str_replace('"', "&#34;", $value);
  90. $value = str_replace("'", "&#39;", $value);
  91. $post_array[$index] = $value;
  92. }
  93. }
  94. return $post_array;
  95. }
  96. }
  97. if (!function_exists('uuid')) {
  98. function uuid() {
  99. $uuid = null;
  100. if (PHP_OS === 'FreeBSD') {
  101. $uuid = trim(shell_exec("uuid -v 4"));
  102. if (is_uuid($uuid)) {
  103. return $uuid;
  104. }
  105. else {
  106. echo "Please install the following package.\n";
  107. echo "pkg install ossp-uuid\n";
  108. exit;
  109. }
  110. }
  111. if (PHP_OS === 'Linux') {
  112. $uuid = trim(file_get_contents('/proc/sys/kernel/random/uuid'));
  113. if (is_uuid($uuid)) {
  114. return $uuid;
  115. }
  116. else {
  117. $uuid = trim(shell_exec("uuidgen"));
  118. if (is_uuid($uuid)) {
  119. return $uuid;
  120. }
  121. else {
  122. echo "Please install the uuidgen.\n";
  123. exit;
  124. }
  125. }
  126. }
  127. if ((strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') && function_exists('com_create_guid')) {
  128. $uuid = trim(com_create_guid(), '{}');
  129. if (is_uuid($uuid)) {
  130. return $uuid;
  131. }
  132. else {
  133. echo "The com_create_guid() function failed to create a uuid.\n";
  134. exit;
  135. }
  136. }
  137. }
  138. }
  139. if (!function_exists('is_uuid')) {
  140. function is_uuid($uuid) {
  141. if (gettype($uuid) == 'string') {
  142. $regex = '/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i';
  143. return preg_match($regex, $uuid);
  144. }
  145. return false;
  146. }
  147. }
  148. if (!function_exists('recursive_copy')) {
  149. if (file_exists('/bin/cp')) {
  150. function recursive_copy($source, $destination, $options = '') {
  151. if (strtoupper(substr(PHP_OS, 0, 3)) === 'SUN') {
  152. //copy -R recursive, preserve attributes for SUN
  153. $cmd = 'cp -Rp '.$source.'/* '.$destination;
  154. }
  155. else {
  156. //copy -R recursive, -L follow symbolic links, -p preserve attributes for other Posix systemss
  157. $cmd = 'cp -RLp '.$options.' '.$source.'/* '.$destination;
  158. }
  159. exec ($cmd);
  160. }
  161. }
  162. elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  163. function recursive_copy($source, $destination, $options = '') {
  164. $source = normalize_path_to_os($source);
  165. $destination = normalize_path_to_os($destination);
  166. exec("xcopy /E /Y \"$source\" \"$destination\"");
  167. }
  168. }
  169. else {
  170. function recursive_copy($source, $destination, $options = '') {
  171. $dir = opendir($source);
  172. if (!$dir) {
  173. throw new Exception("recursive_copy() source directory '".$source."' does not exist.");
  174. }
  175. if (!is_dir($destination)) {
  176. if (!mkdir($destination,02770,true)) {
  177. throw new Exception("recursive_copy() failed to create destination directory '".$destination."'");
  178. }
  179. }
  180. while(false !== ( $file = readdir($dir)) ) {
  181. if (( $file != '.' ) && ( $file != '..' )) {
  182. if ( is_dir($source . '/' . $file) ) {
  183. recursive_copy($source . '/' . $file,$destination . '/' . $file);
  184. }
  185. else {
  186. copy($source . '/' . $file,$destination . '/' . $file);
  187. }
  188. }
  189. }
  190. closedir($dir);
  191. }
  192. }
  193. }
  194. if (!function_exists('recursive_delete')) {
  195. if (file_exists('/usr/bin/find')) {
  196. function recursive_delete($directory) {
  197. if (isset($directory) && strlen($directory) > 8) {
  198. exec('/usr/bin/find '.$directory.'/* -name "*" -delete');
  199. //exec('rm -Rf '.$directory.'/*');
  200. clearstatcache();
  201. }
  202. }
  203. }
  204. elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  205. function recursive_delete($directory) {
  206. $directory = normalize_path_to_os($directory);
  207. //$this->write_debug("del /S /F /Q \"$dir\"");
  208. exec("del /S /F /Q \"$directory\"");
  209. clearstatcache();
  210. }
  211. }
  212. else {
  213. function recursive_delete($directory) {
  214. foreach (glob($directory) as $file) {
  215. if (is_dir($file)) {
  216. //$this->write_debug("rm dir: ".$file);
  217. recursive_delete("$file/*");
  218. rmdir($file);
  219. }
  220. else {
  221. //$this->write_debug("delete file: ".$file);
  222. unlink($file);
  223. }
  224. }
  225. clearstatcache();
  226. }
  227. }
  228. }
  229. if (!function_exists('if_group')) {
  230. function if_group($group) {
  231. //set default false
  232. $result = false;
  233. //search for the permission
  234. if (count($_SESSION["groups"]) > 0) {
  235. foreach($_SESSION["groups"] as $row) {
  236. if ($row['group_name'] == $group) {
  237. $result = true;
  238. break;
  239. }
  240. }
  241. }
  242. //return the result
  243. return $result;
  244. }
  245. }
  246. if (!function_exists('permission_exists')) {
  247. function permission_exists($permission) {
  248. //set default false
  249. $result = false;
  250. //find the permission
  251. if (is_array($_SESSION["permissions"]) && $_SESSION["permissions"][$permission] == true) {
  252. $result = true;
  253. }
  254. //return the result
  255. return $result;
  256. }
  257. }
  258. if (!function_exists('if_group_member')) {
  259. function if_group_member($group_members, $group) {
  260. if (stripos($group_members, "||".$group."||") === false) {
  261. return false; //group does not exist
  262. }
  263. else {
  264. return true; //group exists
  265. }
  266. }
  267. }
  268. if (!function_exists('superadmin_list')) {
  269. function superadmin_list() {
  270. global $domain_uuid;
  271. $sql = "select * from v_user_groups ";
  272. $sql .= "where group_name = 'superadmin' ";
  273. $database = new database;
  274. $result = $database->select($sql, null, 'all');
  275. $superadmin_list = "||";
  276. if (is_array($result) && @sizeof($result) != 0) {
  277. foreach ($result as $field) {
  278. //get the list of superadmins
  279. $superadmin_list .= $field['user_uuid']."||";
  280. }
  281. }
  282. unset($sql, $result, $field);
  283. return $superadmin_list;
  284. }
  285. }
  286. if (!function_exists('if_superadmin')) {
  287. function if_superadmin($superadmin_list, $user_uuid) {
  288. if (stripos($superadmin_list, "||".$user_uuid."||") === false) {
  289. return false;
  290. }
  291. else {
  292. return true; //user_uuid exists
  293. }
  294. }
  295. }
  296. if (!function_exists('html_select_other')) {
  297. function html_select_other($table_name, $field_name, $sql_where_optional, $field_current_value) {
  298. //html select other: build a select box from distinct items in db with option for other
  299. global $domain_uuid;
  300. $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name);
  301. $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name);
  302. $html = "<table border='0' cellpadding='1' cellspacing='0'>\n";
  303. $html .= "<tr>\n";
  304. $html .= "<td id=\"cell".escape($field_name)."1\">\n";
  305. $html .= "\n";
  306. $html .= "<select id=\"".escape($field_name)."\" name=\"".escape($field_name)."\" class='formfld' onchange=\"if (document.getElementById('".$field_name."').value == 'Other') { /*enabled*/ document.getElementById('".$field_name."_other').style.display=''; document.getElementById('".$field_name."_other').className='formfld'; document.getElementById('".$field_name."_other').focus(); } else { /*disabled*/ document.getElementById('".$field_name."_other').value = ''; document.getElementById('".$field_name."_other').style.display='none'; } \">\n";
  307. $html .= "<option value=''></option>\n";
  308. $sql = "select distinct(".$field_name.") as ".$field_name." ";
  309. $sql .= "from ".$table_name." ".$sql_where_optional." ";
  310. $database = new database;
  311. $result = $database->select($sql, null, 'all');
  312. if (is_array($result) && @sizeof($result) != 0) {
  313. foreach($result as $field) {
  314. if (strlen($field[$field_name]) > 0) {
  315. $html .= "<option value=\"".escape($field[$field_name])."\" ".($field_current_value == $field[$field_name] ? "selected='selected'" : null).">".escape($field[$field_name])."</option>\n";
  316. }
  317. }
  318. }
  319. unset($sql, $result, $field);
  320. $html .= "<option value='Other'>Other</option>\n";
  321. $html .= "</select>\n";
  322. $html .= "</td>\n";
  323. $html .= "<td id=\"cell".$field_name."2\" width='5'>\n";
  324. $html .= "<input id=\"".$field_name."_other\" name=\"".$field_name."_other\" value='' type='text' class='formfld' style='display: none;'>\n";
  325. $html .= "</td>\n";
  326. $html .= "</tr>\n";
  327. $html .= "</table>";
  328. return $html;
  329. }
  330. }
  331. if (!function_exists('html_select')) {
  332. function html_select($table_name, $field_name, $sql_where_optional, $field_current_value, $field_value = '', $style = '', $on_change = '') {
  333. //html select: build a select box from distinct items in db
  334. global $domain_uuid;
  335. $table_name = preg_replace("#[^a-zA-Z0-9_]#", "", $table_name);
  336. $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name);
  337. $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value);
  338. if (strlen($field_value) > 0) {
  339. $html .= "<select id=\"".$field_value."\" name=\"".$field_value."\" class='formfld' style='".$style."' ".($on_change != '' ? "onchange=\"".$on_change."\"" : null).">\n";
  340. $html .= " <option value=\"\"></option>\n";
  341. $sql = "select distinct(".$field_name.") as ".$field_name.", ".$field_value." from ".$table_name." ".$sql_where_optional." order by ".$field_name." asc ";
  342. }
  343. else {
  344. $html .= "<select id=\"".$field_name."\" name=\"".$field_name."\" class='formfld' style='".$style."' ".($on_change != '' ? "onchange=\"".$on_change."\"" : null).">\n";
  345. $html .= " <option value=\"\"></option>\n";
  346. $sql = "select distinct(".$field_name.") as ".$field_name." from ".$table_name." ".$sql_where_optional." ";
  347. }
  348. $database = new database;
  349. $result = $database->select($sql, null, 'all');
  350. if (is_array($result) && @sizeof($result) != 0) {
  351. foreach($result as $field) {
  352. if (strlen($field[$field_name]) > 0) {
  353. $selected = $field_current_value == $field[$field_name] ? "selected='selected'" : null;
  354. $array_key = strlen($field_value) > 0 ? $field_value : $field_name;
  355. $html .= "<option value=\"".urlencode($field[$array_key])."\" ".$selected.">".urlencode($field[$field_name])."</option>\n";
  356. }
  357. }
  358. }
  359. unset($sql, $result, $field);
  360. $html .= "</select>\n";
  361. return $html;
  362. }
  363. }
  364. if (!function_exists('th_order_by')) {
  365. //html table header order by
  366. function th_order_by($field_name, $column_title, $order_by, $order, $app_uuid = '', $css = '', $http_get_params = '', $description = '') {
  367. global $text;
  368. if (is_uuid($app_uuid) > 0) { $app_uuid = "&app_uuid=".urlencode($app_uuid); } // accomodate need to pass app_uuid where necessary (inbound/outbound routes lists)
  369. $field_name = preg_replace("#[^a-zA-Z0-9_]#", "", $field_name);
  370. $field_value = preg_replace("#[^a-zA-Z0-9_]#", "", $field_value);
  371. $sanitized_parameters = '';
  372. if (isset($http_get_params) && strlen($http_get_params) > 0) {
  373. $parameters = explode('&', $http_get_params);
  374. if (is_array($parameters)) {
  375. foreach ($parameters as $parameter) {
  376. if (substr_count($parameter, '=') != 0) {
  377. $array = explode('=', $parameter);
  378. $key = preg_replace('#[^a-zA-Z0-9_\-]#', '', $array['0']);
  379. $value = urldecode($array['1']);
  380. if ($key == 'order_by' && strlen($value) > 0) {
  381. //validate order by
  382. $sanitized_parameters .= "&order_by=". preg_replace('#[^a-zA-Z0-9_\-]#', '', $value);
  383. }
  384. else if ($key == 'order' && strlen($value) > 0) {
  385. //validate order
  386. switch ($value) {
  387. case 'asc':
  388. $sanitized_parameters .= "&order=asc";
  389. break;
  390. case 'desc':
  391. $sanitized_parameters .= "&order=desc";
  392. break;
  393. }
  394. }
  395. else if (strlen($value) > 0 && is_numeric($value)) {
  396. $sanitized_parameters .= "&".$key."=".$value;
  397. }
  398. else {
  399. $sanitized_parameters .= "&".$key."=".urlencode($value);
  400. }
  401. }
  402. }
  403. }
  404. }
  405. $html = "<th ".$css." nowrap='nowrap'>";
  406. $description = (strlen($description) > 0) ? $description . ', ': '';
  407. if (strlen($order_by) == 0) {
  408. $order = 'asc';
  409. }
  410. if ($order_by == $field_name) {
  411. if ($order == "asc") {
  412. $description .= $text['label-order'].' '.$text['label-descending'];
  413. $html .= "<a href='?order_by=".urlencode($field_name)."&order=desc".$app_uuid.$sanitized_parameters."' title=\"".escape($description)."\">".escape($column_title)."</a>";
  414. }
  415. else {
  416. $description .= $text['label-order'].' '.$text['label-ascending'];
  417. $html .= "<a href='?order_by=".urlencode($field_name)."&order=asc".$app_uuid.$sanitized_parameters."' title=\"".escape($description)."\">".escape($column_title)."</a>";
  418. }
  419. }
  420. else {
  421. $description .= $text['label-order'].' '.$text['label-ascending'];
  422. $html .= "<a href='?order_by=".urlencode($field_name)."&order=asc".$app_uuid.$sanitized_parameters."' title=\"".escape($description)."\">".escape($column_title)."</a>";
  423. }
  424. $html .= "</th>";
  425. return $html;
  426. }
  427. }
  428. if (!function_exists('get_ext')) {
  429. function get_ext($filename) {
  430. preg_match('/[^?]*/', $filename, $matches);
  431. $string = $matches[0];
  432. $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
  433. // check if there is any extension
  434. if(count($pattern) == 1){
  435. //echo 'No File Extension Present';
  436. return '';
  437. }
  438. if(count($pattern) > 1) {
  439. $filenamepart = $pattern[count($pattern)-1][0];
  440. preg_match('/[^?]*/', $filenamepart, $matches);
  441. return $matches[0];
  442. }
  443. }
  444. //echo "ext: ".get_ext('test.txt');
  445. }
  446. if (!function_exists('file_upload')) {
  447. function file_upload($field = '', $file_type = '', $dest_dir = '') {
  448. $uploadtempdir = $_ENV["TEMP"]."\\";
  449. ini_set('upload_tmp_dir', $uploadtempdir);
  450. $tmp_name = $_FILES[$field]["tmp_name"];
  451. $file_name = $_FILES[$field]["name"];
  452. $file_type = $_FILES[$field]["type"];
  453. $file_size = $_FILES[$field]["size"];
  454. $file_ext = get_ext($file_name);
  455. $file_name_orig = $file_name;
  456. $file_name_base = substr($file_name, 0, (strlen($file_name) - (strlen($file_ext)+1)));
  457. //$dest_dir = '/tmp';
  458. if ($file_size == 0) {
  459. return;
  460. }
  461. if (!is_dir($dest_dir)) {
  462. echo "dest_dir not found<br />\n";
  463. return;
  464. }
  465. //check if allowed file type
  466. if ($file_type == "img") {
  467. switch (strtolower($file_ext)) {
  468. case "jpg":
  469. case "png":
  470. case "gif":
  471. case "bmp":
  472. case "psd":
  473. case "tif": break;
  474. default: return false;
  475. }
  476. }
  477. if ($file_type == "file") {
  478. switch (strtolower($file_ext)) {
  479. case "doc":
  480. case "pdf":
  481. case "ppt":
  482. case "xls":
  483. case "zip":
  484. case "exe": break;
  485. default: return false;
  486. }
  487. }
  488. //find unique filename: check if file exists if it does then increment the filename
  489. $i = 1;
  490. while( file_exists($dest_dir.'/'.$file_name)) {
  491. if (strlen($file_ext)> 0) {
  492. $file_name = $file_name_base . $i .'.'. $file_ext;
  493. }
  494. else {
  495. $file_name = $file_name_orig . $i;
  496. }
  497. $i++;
  498. }
  499. //echo "file_type: ".$file_type."<br />\n";
  500. //echo "tmp_name: ".$tmp_name."<br />\n";
  501. //echo "file_name: ".$file_name."<br />\n";
  502. //echo "file_ext: ".$file_ext."<br />\n";
  503. //echo "file_name_orig: ".$file_name_orig."<br />\n";
  504. //echo "file_name_base: ".$file_name_base."<br />\n";
  505. //echo "dest_dir: ".$dest_dir."<br />\n";
  506. //move the file to upload directory
  507. //bool move_uploaded_file ( string $filename, string $destination )
  508. if (move_uploaded_file($tmp_name, $dest_dir.'/'.$file_name)) {
  509. return $file_name;
  510. }
  511. else {
  512. echo "File upload failed! Here's some debugging info:\n";
  513. return false;
  514. }
  515. exit;
  516. }
  517. }
  518. if (!function_exists('sys_get_temp_dir')) {
  519. function sys_get_temp_dir() {
  520. if ($temp = getenv('TMP')) { return $temp; }
  521. if ($temp = getenv('TEMP')) { return $temp; }
  522. if ($temp = getenv('TMPDIR')) { return $temp; }
  523. $temp = tempnam(__FILE__,'');
  524. if (file_exists($temp)) {
  525. unlink($temp);
  526. return dirname($temp);
  527. }
  528. return null;
  529. }
  530. }
  531. //echo realpath(sys_get_temp_dir());
  532. if (!function_exists('normalize_path')) {
  533. //don't use DIRECTORY_SEPARATOR as it will change on a per platform basis and we need consistency
  534. function normalize_path($path) {
  535. return str_replace(array('/','\\'), '/', $path);
  536. }
  537. }
  538. if (!function_exists('normalize_path_to_os')) {
  539. function normalize_path_to_os($path) {
  540. return str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $path);
  541. }
  542. }
  543. if (!function_exists('username_exists')) {
  544. function username_exists($username) {
  545. global $domain_uuid;
  546. $sql = "select count(*) from v_users ";
  547. $sql .= "where domain_uuid = :domain_uuid ";
  548. $sql .= "and username = :username ";
  549. $parameters['domain_uuid'] = $domain_uuid;
  550. $parameters['username'] = $username;
  551. $database = new database;
  552. $num_rows = $database->select($sql, $parameters, 'column');
  553. return $num_rows > 0 ? true : false;
  554. }
  555. }
  556. if (!function_exists('add_extension_user')) {
  557. function add_extension_user($extension_uuid, $username) {
  558. global $domain_uuid;
  559. //get the user_uuid by using the username
  560. $sql = "select user_uuid from v_users ";
  561. $sql .= "where domain_uuid = :domain_uuid ";
  562. $sql .= "and username = :username ";
  563. $parameters['domain_uuid'] = $domain_uuid;
  564. $parameters['username'] = $username;
  565. $database = new database;
  566. $user_uuid = $database->select($sql, $parameters, 'column');
  567. unset($sql, $parameters);
  568. if (is_uuid($user_uuid)) {
  569. //check if the user_uuid exists in v_extension_users
  570. $sql = "select count(*) from v_extension_users ";
  571. $sql .= "where domain_uuid = :domain_uuid ";
  572. $sql .= "and user_uuid = :user_uuid ";
  573. $parameters['domain_uuid'] = $domain_uuid;
  574. $parameters['user_uuid'] = $user_uuid;
  575. $database = new database;
  576. $num_rows = $database->select($sql, $parameters, 'column');
  577. unset($sql, $parameters);
  578. //assign the extension to the user
  579. if ($num_rows == 0) {
  580. //build insert array
  581. $extension_user_uuid = uuid();
  582. $array['extension_users'][$x]['extension_user_uuid'] = $extension_user_uuid;
  583. $array['extension_users'][$x]['domain_uuid'] = $domain_uuid;
  584. $array['extension_users'][$x]['extension_uuid'] = $extension_uuid;
  585. $array['extension_users'][$x]['user_uuid'] = $row["user_uuid"];
  586. //grant temporary permissions
  587. $p = new permissions;
  588. $p->add('extension_user_add', 'temp');
  589. //execute insert
  590. $database = new database;
  591. $database->app_name = 'function-add_extension_user';
  592. $database->app_uuid = 'e68d9689-2769-e013-28fa-6214bf47fca3';
  593. $database->save($array);
  594. unset($array);
  595. //revoke temporary permissions
  596. $p->delete('extension_user_add', 'temp');
  597. }
  598. }
  599. }
  600. }
  601. if (!function_exists('user_add')) {
  602. function user_add($username, $password, $user_email = '') {
  603. global $domain_uuid;
  604. if (strlen($username) == 0) { return false; }
  605. if (strlen($password) == 0) { return false; }
  606. if (!username_exists($username)) {
  607. //build user insert array
  608. $user_uuid = uuid();
  609. $salt = generate_password('20', '4');
  610. $array['users'][0]['user_uuid'] = $user_uuid;
  611. $array['users'][0]['domain_uuid'] = $domain_uuid;
  612. $array['users'][0]['username'] = $username;
  613. $array['users'][0]['password'] = md5($salt.$password);
  614. $array['users'][0]['salt'] = $salt;
  615. if (valid_email($user_email)) {
  616. $array['users'][0]['user_email'] = $user_email;
  617. }
  618. $array['users'][0]['add_date'] = 'now()';
  619. $array['users'][0]['add_user'] = $_SESSION["username"];
  620. //build user group insert array
  621. $user_group_uuid = uuid();
  622. $array['user_groups'][0]['user_group_uuid'] = $user_group_uuid;
  623. $array['user_groups'][0]['domain_uuid'] = $domain_uuid;
  624. $array['user_groups'][0]['group_name'] = 'user';
  625. $array['user_groups'][0]['user_uuid'] = $user_uuid;
  626. //grant temporary permissions
  627. $p = new permissions;
  628. $p->add('user_add', 'temp');
  629. $p->add('user_group_add', 'temp');
  630. //execute insert
  631. $database = new database;
  632. $database->app_name = 'function-user_add';
  633. $database->app_uuid = '15a8d74b-ac7e-4468-add4-3e6ebdcb8e22';
  634. $database->save($array);
  635. unset($array);
  636. //revoke temporary permissions
  637. $p->delete('user_add', 'temp');
  638. $p->delete('user_group_add', 'temp');
  639. }
  640. }
  641. }
  642. function switch_module_is_running($fp, $mod) {
  643. if (!$fp) {
  644. //if the handle does not exist create it
  645. $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']);
  646. //if the handle still does not exist show an error message
  647. if (!$fp) {
  648. $msg = "<div align='center'>Connection to Event Socket failed.<br /></div>";
  649. }
  650. }
  651. if ($fp) {
  652. //send the api command to check if the module exists
  653. $switchcmd = "module_exists $mod";
  654. $switch_result = event_socket_request($fp, 'api '.$switchcmd);
  655. unset($switchcmd);
  656. if (trim($switch_result) == "true") {
  657. return true;
  658. }
  659. else {
  660. return false;
  661. }
  662. }
  663. else {
  664. return false;
  665. }
  666. }
  667. //switch_module_is_running('mod_spidermonkey');
  668. //format a number (n) replace with a number (r) remove the number
  669. function format_string($format, $data) {
  670. //preset values
  671. $x=0;
  672. $tmp = '';
  673. //count the characters
  674. $format_count = substr_count($format, 'x');
  675. $format_count = $format_count + substr_count($format, 'R');
  676. $format_count = $format_count + substr_count($format, 'r');
  677. //format the string if it matches
  678. if ($format_count == strlen($data)) {
  679. for ($i = 0; $i <= strlen($format); $i++) {
  680. $tmp_format = strtolower(substr($format, $i, 1));
  681. if ($tmp_format == 'x') {
  682. $tmp .= substr($data, $x, 1);
  683. $x++;
  684. }
  685. elseif ($tmp_format == 'r') {
  686. $x++;
  687. }
  688. else {
  689. $tmp .= $tmp_format;
  690. }
  691. }
  692. }
  693. if (strlen($tmp) == 0) {
  694. return $data;
  695. }
  696. else {
  697. return $tmp;
  698. }
  699. }
  700. //get the format and use it to format the phone number
  701. function format_phone($phone_number) {
  702. if (is_numeric(trim($phone_number, ' +'))) {
  703. if (isset($_SESSION["format"]["phone"])) {
  704. $phone_number = trim($phone_number, ' +');
  705. foreach ($_SESSION["format"]["phone"] as &$format) {
  706. $format_count = substr_count($format, 'x');
  707. $format_count = $format_count + substr_count($format, 'R');
  708. $format_count = $format_count + substr_count($format, 'r');
  709. if ($format_count == strlen($phone_number)) {
  710. //format the number
  711. $phone_number = format_string($format, $phone_number);
  712. }
  713. }
  714. }
  715. }
  716. return $phone_number;
  717. }
  718. //format seconds into hh:mm:ss
  719. function format_hours($seconds) {
  720. $hours = floor($seconds / 3600);
  721. $minutes = floor(($seconds / 60) % 60);
  722. $seconds = $seconds % 60;
  723. if (strlen($minutes) == 1) { $minutes = '0'.$minutes; }
  724. if (strlen($seconds) == 1) { $seconds = '0'.$seconds; }
  725. return "$hours:$minutes:$seconds";
  726. }
  727. //browser detection without browscap.ini dependency
  728. function http_user_agent($info = '') {
  729. //set default values
  730. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  731. $browser_name = 'Unknown';
  732. $platform = 'Unknown';
  733. $version = '';
  734. $mobile = false;
  735. //get the platform
  736. if (preg_match('/linux/i', $user_agent)) {
  737. $platform = 'Linux';
  738. }
  739. elseif (preg_match('/macintosh|mac os x/i', $user_agent)) {
  740. $platform = 'Apple';
  741. }
  742. elseif (preg_match('/windows|win32/i', $user_agent)) {
  743. $platform = 'Windows';
  744. }
  745. //set mobile to true or false
  746. if (preg_match('/mobile/i', $user_agent)) {
  747. $platform = 'Mobile';
  748. $mobile = true;
  749. }
  750. elseif (preg_match('/android/i', $user_agent)) {
  751. $platform = 'Android';
  752. $mobile = true;
  753. }
  754. //get the name of the useragent
  755. if (preg_match('/MSIE/i',$user_agent) || preg_match('/Trident/i',$user_agent)) {
  756. $browser_name = 'Internet Explorer';
  757. $browser_name_short = 'MSIE';
  758. }
  759. elseif (preg_match('/Firefox/i',$user_agent)) {
  760. $browser_name = 'Mozilla Firefox';
  761. $browser_name_short = 'Firefox';
  762. }
  763. elseif (preg_match('/Chrome/i',$user_agent)) {
  764. $browser_name = 'Google Chrome';
  765. $browser_name_short = 'Chrome';
  766. }
  767. elseif (preg_match('/Safari/i',$user_agent)) {
  768. $browser_name = 'Apple Safari';
  769. $browser_name_short = 'Safari';
  770. }
  771. elseif (preg_match('/Opera/i',$user_agent)) {
  772. $browser_name = 'Opera';
  773. $browser_name_short = 'Opera';
  774. }
  775. elseif (preg_match('/Netscape/i',$user_agent)) {
  776. $browser_name = 'Netscape';
  777. $browser_name_short = 'Netscape';
  778. }
  779. else {
  780. $browser_name = 'Unknown';
  781. $browser_name_short = 'Unknown';
  782. }
  783. //finally get the correct version number
  784. $known = array('Version', $browser_name_short, 'other');
  785. $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
  786. if (!preg_match_all($pattern, $user_agent, $matches)) {
  787. //we have no matching number just continue
  788. }
  789. //see how many we have
  790. $i = count($matches['browser']);
  791. if ($i != 1) {
  792. //we will have two since we are not using 'other' argument yet
  793. //see if version is before or after the name
  794. if (strripos($user_agent,"Version") < strripos($user_agent,$browser_name_short)) {
  795. $version= $matches['version'][0];
  796. }
  797. else {
  798. $version= $matches['version'][1];
  799. }
  800. }
  801. else {
  802. $version= $matches['version'][0];
  803. }
  804. //check if we have a number
  805. if ($version == null || $version == "") { $version = "?"; }
  806. //return the data
  807. switch ($info) {
  808. case "agent": return $user_agent; break;
  809. case "name": return $browser_name; break;
  810. case "name_short": return $browser_name_short; break;
  811. case "version": return $version; break;
  812. case "platform": return $platform; break;
  813. case "mobile": return $mobile; break;
  814. case "pattern": return $pattern; break;
  815. default :
  816. return array(
  817. 'user_agent' => $user_agent,
  818. 'name' => $browser_name,
  819. 'name_short' => $browser_name_short,
  820. 'version' => $version,
  821. 'platform' => $platform,
  822. 'mobile' => $mobile,
  823. 'pattern' => $pattern
  824. );
  825. }
  826. }
  827. //tail php function for non posix systems
  828. function tail($file, $num_to_get=10) {
  829. $fp = fopen($file, 'r');
  830. $position = filesize($file);
  831. $chunklen = 4096;
  832. if($position-$chunklen<=0) {
  833. fseek($fp,0);
  834. }
  835. else {
  836. fseek($fp, $position-$chunklen);
  837. }
  838. $data="";$ret="";$lc=0;
  839. while($chunklen > 0) {
  840. $data = fread($fp, $chunklen);
  841. $dl=strlen($data);
  842. for($i=$dl-1;$i>=0;$i--){
  843. if($data[$i]=="\n"){
  844. if($lc==0 && $ret!="")$lc++;
  845. $lc++;
  846. if($lc>$num_to_get)return $ret;
  847. }
  848. $ret=$data[$i].$ret;
  849. }
  850. if($position-$chunklen<=0){
  851. fseek($fp,0);
  852. $chunklen=$chunklen-abs($position-$chunklen);
  853. }
  854. else {
  855. fseek($fp, $position-$chunklen);
  856. }
  857. $position = $position - $chunklen;
  858. }
  859. fclose($fp);
  860. return $ret;
  861. }
  862. //generate a random password with upper, lowercase and symbols
  863. function generate_password($length = 0, $strength = 0) {
  864. $password = '';
  865. $chars = '';
  866. if ($length === 0 && $strength === 0) { //set length and strenth if specified in default settings and strength isn't numeric-only
  867. $length = (is_numeric($_SESSION["users"]["password_length"]["numeric"])) ? $_SESSION["users"]["password_length"]["numeric"] : 20;
  868. $strength = (is_numeric($_SESSION["users"]["password_strength"]["numeric"])) ? $_SESSION["users"]["password_strength"]["numeric"] : 4;
  869. }
  870. if ($strength >= 1) { $chars .= "0123456789"; }
  871. if ($strength >= 2) { $chars .= "abcdefghijkmnopqrstuvwxyz"; }
  872. if ($strength >= 3) { $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ"; }
  873. if ($strength >= 4) { $chars .= "!^$%*?."; }
  874. for ($i = 0; $i < $length; $i++) {
  875. $password .= $chars[random_int(0, strlen($chars)-1)];
  876. }
  877. return $password;
  878. }
  879. //check password strength against requirements (if any)
  880. function check_password_strength($password, $text, $type = 'default') {
  881. if ($password != '') {
  882. if ($type == 'default') {
  883. $req['length'] = $_SESSION['extension']['password_length']['numeric'];
  884. $req['number'] = ($_SESSION['extension']['password_number']['boolean'] == 'true') ? true : false;
  885. $req['lowercase'] = ($_SESSION['extension']['password_lowercase']['boolean'] == 'true') ? true : false;
  886. $req['uppercase'] = ($_SESSION['extension']['password_uppercase']['boolean'] == 'true') ? true : false;
  887. $req['special'] = ($_SESSION['extension']['password_special']['boolean'] == 'true') ? true : false;
  888. } elseif ($type == 'user') {
  889. $req['length'] = $_SESSION['user']['password_length']['numeric'];
  890. $req['number'] = ($_SESSION['user']['password_number']['boolean'] == 'true') ? true : false;
  891. $req['lowercase'] = ($_SESSION['user']['password_lowercase']['boolean'] == 'true') ? true : false;
  892. $req['uppercase'] = ($_SESSION['user']['password_uppercase']['boolean'] == 'true') ? true : false;
  893. $req['special'] = ($_SESSION['user']['password_special']['boolean'] == 'true') ? true : false;
  894. }
  895. if (is_numeric($req['length']) && $req['length'] != 0 && !preg_match_all('$\S*(?=\S{'.$req['length'].',})\S*$', $password)) { // length
  896. $msg_errors[] = $req['length'].'+ '.$text['label-characters'];
  897. }
  898. if ($req['number'] && !preg_match_all('$\S*(?=\S*[\d])\S*$', $password)) { //number
  899. $msg_errors[] = '1+ '.$text['label-numbers'];
  900. }
  901. if ($req['lowercase'] && !preg_match_all('$\S*(?=\S*[a-z])\S*$', $password)) { //lowercase
  902. $msg_errors[] = '1+ '.$text['label-lowercase_letters'];
  903. }
  904. if ($req['uppercase'] && !preg_match_all('$\S*(?=\S*[A-Z])\S*$', $password)) { //uppercase
  905. $msg_errors[] = '1+ '.$text['label-uppercase_letters'];
  906. }
  907. if ($req['special'] && !preg_match_all('$\S*(?=\S*[\W])\S*$', $password)) { //special
  908. $msg_errors[] = '1+ '.$text['label-special_characters'];
  909. }
  910. if (is_array($msg_errors) && sizeof($msg_errors) > 0) {
  911. message::add($_SESSION["message"] = $text['message-password_requirements'].': '.implode(', ', $msg_errors), 'negative', 6000);
  912. return false;
  913. }
  914. else {
  915. return true;
  916. }
  917. }
  918. return true;
  919. }
  920. //based on Wez Furlong do_post_request
  921. if (!function_exists('send_http_request')) {
  922. function send_http_request($url, $data, $method = "POST", $optional_headers = null) {
  923. $params = array('http' => array(
  924. 'method' => $method,
  925. 'content' => $data
  926. ));
  927. if ($optional_headers !== null) {
  928. $params['http']['header'] = $optional_headers;
  929. }
  930. $ctx = stream_context_create($params);
  931. $fp = @fopen($url, 'rb', false, $ctx);
  932. if (!$fp) {
  933. throw new Exception("Problem with $url, $php_errormsg");
  934. }
  935. $response = @stream_get_contents($fp);
  936. if ($response === false) {
  937. throw new Exception("Problem reading data from $url, $php_errormsg");
  938. }
  939. return $response;
  940. }
  941. }
  942. //convert the string to a named array
  943. if(!function_exists('csv_to_named_array')) {
  944. function csv_to_named_array($tmp_str, $tmp_delimiter) {
  945. $tmp_array = explode ("\n", $tmp_str);
  946. $result = array();
  947. if (trim(strtoupper($tmp_array[0])) !== "+OK") {
  948. $tmp_field_name_array = explode ($tmp_delimiter, $tmp_array[0]);
  949. $x = 0;
  950. foreach ($tmp_array as $row) {
  951. if ($x > 0) {
  952. $tmp_field_value_array = explode ($tmp_delimiter, $tmp_array[$x]);
  953. $y = 0;
  954. foreach ($tmp_field_value_array as $tmp_value) {
  955. $tmp_name = $tmp_field_name_array[$y];
  956. if (trim(strtoupper($tmp_value)) !== "+OK") {
  957. $result[$x][$tmp_name] = $tmp_value;
  958. }
  959. $y++;
  960. }
  961. }
  962. $x++;
  963. }
  964. unset($row);
  965. }
  966. return $result;
  967. }
  968. }
  969. function get_time_zone_offset($remote_tz, $origin_tz = 'UTC') {
  970. $origin_dtz = new DateTimeZone($origin_tz);
  971. $remote_dtz = new DateTimeZone($remote_tz);
  972. $origin_dt = new DateTime("now", $origin_dtz);
  973. $remote_dt = new DateTime("now", $remote_dtz);
  974. $offset = $remote_dtz->getOffset($remote_dt) - $origin_dtz->getOffset($origin_dt);
  975. return $offset;
  976. }
  977. function number_pad($number,$n) {
  978. return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
  979. }
  980. // validate email address syntax
  981. if(!function_exists('valid_email')) {
  982. function valid_email($email) {
  983. return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false;
  984. }
  985. }
  986. //function to convert hexidecimal color value to rgb string/array value
  987. if (!function_exists('hex_to_rgb')) {
  988. function hex_to_rgb($hex, $delim = '') {
  989. $hex = str_replace("#", "", $hex);
  990. if (strlen($hex) == 3) {
  991. $r = hexdec(substr($hex,0,1).substr($hex,0,1));
  992. $g = hexdec(substr($hex,1,1).substr($hex,1,1));
  993. $b = hexdec(substr($hex,2,1).substr($hex,2,1));
  994. }
  995. else {
  996. $r = hexdec(substr($hex,0,2));
  997. $g = hexdec(substr($hex,2,2));
  998. $b = hexdec(substr($hex,4,2));
  999. }
  1000. $rgb = array($r, $g, $b);
  1001. if ($delim != '') {
  1002. return implode($delim, $rgb); // return rgb delimited string
  1003. }
  1004. else {
  1005. return $rgb; // return array of rgb values
  1006. }
  1007. }
  1008. }
  1009. //function to get a color's luminence level -- dependencies: rgb_to_hsl()
  1010. if (!function_exists('get_color_luminence')) {
  1011. function get_color_luminence($color) {
  1012. //convert hex to rgb
  1013. if (substr_count($color, ',') == 0) {
  1014. $color = str_replace(' ', '', $color);
  1015. $color = str_replace('#', '', $color);
  1016. if (strlen($color) == 3) {
  1017. $r = hexdec(substr($color,0,1).substr($color,0,1));
  1018. $g = hexdec(substr($color,1,1).substr($color,1,1));
  1019. $b = hexdec(substr($color,2,1).substr($color,2,1));
  1020. }
  1021. else {
  1022. $r = hexdec(substr($color,0,2));
  1023. $g = hexdec(substr($color,2,2));
  1024. $b = hexdec(substr($color,4,2));
  1025. }
  1026. $color = $r.','.$g.','.$b;
  1027. }
  1028. //color to array, pop alpha
  1029. if (substr_count($color, ',') > 0) {
  1030. $color = str_replace(' ', '', $color);
  1031. $color = str_replace('rgb', '', $color);
  1032. $color = str_replace('a(', '', $color);
  1033. $color = str_replace(')', '', $color);
  1034. $color = explode(',', $color);
  1035. $hsl = rgb_to_hsl($color[0], $color[1], $color[2]);
  1036. }
  1037. //return luminence value
  1038. return (is_array($hsl) && is_numeric($hsl[2])) ? $hsl[2] : null;
  1039. }
  1040. }
  1041. //function to lighten or darken a hexidecimal, rgb, or rgba color value by a percentage -- dependencies: rgb_to_hsl(), hsl_to_rgb()
  1042. if (!function_exists('color_adjust')) {
  1043. function color_adjust($color, $percent) {
  1044. /*
  1045. USAGE
  1046. 20% Lighter
  1047. color_adjust('#3f4265', 0.2);
  1048. color_adjust('234,120,6,0.3', 0.2);
  1049. 20% Darker
  1050. color_adjust('#3f4265', -0.2); //
  1051. color_adjust('rgba(234,120,6,0.3)', -0.2);
  1052. RETURNS
  1053. Same color format provided (hex in = hex out, rgb(a) in = rgb(a) out)
  1054. */
  1055. //convert hex to rgb
  1056. if (substr_count($color, ',') == 0) {
  1057. $color = str_replace(' ', '', $color);
  1058. if (substr_count($color, '#') > 0) {
  1059. $color = str_replace('#', '', $color);
  1060. $hash = '#';
  1061. }
  1062. if (strlen($color) == 3) {
  1063. $r = hexdec(substr($color,0,1).substr($color,0,1));
  1064. $g = hexdec(substr($color,1,1).substr($color,1,1));
  1065. $b = hexdec(substr($color,2,1).substr($color,2,1));
  1066. }
  1067. else {
  1068. $r = hexdec(substr($color,0,2));
  1069. $g = hexdec(substr($color,2,2));
  1070. $b = hexdec(substr($color,4,2));
  1071. }
  1072. $color = $r.','.$g.','.$b;
  1073. }
  1074. //color to array, pop alpha
  1075. if (substr_count($color, ',') > 0) {
  1076. $color = str_replace(' ', '', $color);
  1077. $wrapper = false;
  1078. if (substr_count($color, 'rgb') != 0) {
  1079. $color = str_replace('rgb', '', $color);
  1080. $color = str_replace('a(', '', $color);
  1081. $color = str_replace(')', '', $color);
  1082. $wrapper = true;
  1083. }
  1084. $colors = explode(',', $color);
  1085. $alpha = (sizeof($colors) == 4) ? array_pop($colors) : null;
  1086. $color = $colors;
  1087. unset($colors);
  1088. //adjust color using rgb > hsl > rgb conversion
  1089. $hsl = rgb_to_hsl($color[0], $color[1], $color[2]);
  1090. $hsl[2] = $hsl[2] + $percent;
  1091. $color = hsl_to_rgb($hsl[0], $hsl[1], $hsl[2]);
  1092. //return adjusted color in format received
  1093. if (isset($hash) && $hash == '#') { //hex
  1094. for ($i = 0; $i <= 2; $i++) {
  1095. $hex_color = dechex($color[$i]);
  1096. if (strlen($hex_color) == 1) { $hex_color = '0'.$hex_color; }
  1097. $hex .= $hex_color;
  1098. }
  1099. return $hash.$hex;
  1100. }
  1101. else { //rgb(a)
  1102. $rgb = implode(',', $color);
  1103. if ($alpha != '') { $rgb .= ','.$alpha; $a = 'a'; }
  1104. if ($wrapper) { $rgb = 'rgb'.$a.'('.$rgb.')'; }
  1105. return $rgb;
  1106. }
  1107. }
  1108. return $color;
  1109. }
  1110. }
  1111. //function to convert an rgb color array to an hsl color array
  1112. if (!function_exists('rgb_to_hsl')) {
  1113. function rgb_to_hsl($r, $g, $b) {
  1114. $r /= 255;
  1115. $g /= 255;
  1116. $b /= 255;
  1117. $max = max($r, $g, $b);
  1118. $min = min($r, $g, $b);
  1119. $h;
  1120. $s;
  1121. $l = ($max + $min) / 2;
  1122. $d = $max - $min;
  1123. if ($d == 0) {
  1124. $h = $s = 0; // achromatic
  1125. }
  1126. else {
  1127. $s = $d / (1 - abs((2 * $l) - 1));
  1128. switch($max){
  1129. case $r:
  1130. $h = 60 * fmod((($g - $b) / $d), 6);
  1131. if ($b > $g) { $h += 360; }
  1132. break;
  1133. case $g:
  1134. $h = 60 * (($b - $r) / $d + 2);
  1135. break;
  1136. case $b:
  1137. $h = 60 * (($r - $g) / $d + 4);
  1138. break;
  1139. }
  1140. }
  1141. return array(round($h, 2), round($s, 2), round($l, 2));
  1142. }
  1143. }
  1144. //function to convert an hsl color array to an rgb color array
  1145. if (!function_exists('hsl_to_rgb')) {
  1146. function hsl_to_rgb($h, $s, $l){
  1147. $r;
  1148. $g;
  1149. $b;
  1150. $c = (1 - abs((2 * $l) - 1)) * $s;
  1151. $x = $c * (1 - abs(fmod(($h / 60), 2) - 1));
  1152. $m = $l - ($c / 2);
  1153. if ($h < 60) {
  1154. $r = $c;
  1155. $g = $x;
  1156. $b = 0;
  1157. }
  1158. else if ($h < 120) {
  1159. $r = $x;
  1160. $g = $c;
  1161. $b = 0;
  1162. }
  1163. else if ($h < 180) {
  1164. $r = 0;
  1165. $g = $c;
  1166. $b = $x;
  1167. }
  1168. else if ($h < 240) {
  1169. $r = 0;
  1170. $g = $x;
  1171. $b = $c;
  1172. }
  1173. else if ($h < 300) {
  1174. $r = $x;
  1175. $g = 0;
  1176. $b = $c;
  1177. }
  1178. else {
  1179. $r = $c;
  1180. $g = 0;
  1181. $b = $x;
  1182. }
  1183. $r = ($r + $m) * 255;
  1184. $g = ($g + $m) * 255;
  1185. $b = ($b + $m) * 255;
  1186. if ($r > 255) { $r = 255; }
  1187. if ($g > 255) { $g = 255; }
  1188. if ($b > 255) { $b = 255; }
  1189. if ($r < 0) { $r = 0; }
  1190. if ($g < 0) { $g = 0; }
  1191. if ($b < 0) { $b = 0; }
  1192. return array(floor($r), floor($g), floor($b));
  1193. }
  1194. }
  1195. //function to send email
  1196. if (!function_exists('send_email')) {
  1197. function send_email($email_recipients, $email_subject, $email_body, &$email_error = '', $email_from_address = '', $email_from_name = '', $email_priority = 3, $email_debug_level = 0, $email_attachments = '', $email_read_confirmation = false) {
  1198. /*
  1199. RECIPIENTS NOTE:
  1200. Pass in a single email address...
  1201. user@domain.com
  1202. Pass in a comma or semi-colon delimited string of e-mail addresses...
  1203. user@domain.com,user2@domain2.com,user3@domain3.com
  1204. user@domain.com;user2@domain2.com;user3@domain3.com
  1205. Pass in a simple array of email addresses...
  1206. Array (
  1207. [0] => user@domain.com
  1208. [1] => user2@domain2.com
  1209. [2] => user3@domain3.com
  1210. )
  1211. Pass in a multi-dimentional array of addresses (delivery, address, name)...
  1212. Array (
  1213. [0] => Array (
  1214. [delivery] => to
  1215. [address] => user@domain.com
  1216. [name] => user 1
  1217. )
  1218. [1] => Array (
  1219. [delivery] => cc
  1220. [address] => user2@domain2.com
  1221. [name] => user 2
  1222. )
  1223. [2] => Array (
  1224. [delivery] => bcc
  1225. [address] => user3@domain3.com
  1226. [name] => user 3
  1227. )
  1228. )
  1229. ATTACHMENTS NOTE:
  1230. Pass in as many files as necessary in an array in the following format...
  1231. Array (
  1232. [0] => Array (
  1233. [type] => file (or 'path')
  1234. [name] => filename.ext
  1235. [value] => /folder/filename.ext
  1236. )
  1237. [1] => Array (
  1238. [type] => string
  1239. [name] => filename.ext
  1240. [value] => (string of file contents - if base64, will be decoded automatically)
  1241. )
  1242. )
  1243. ERROR RESPONSE:
  1244. Error messages are stored in the variable passed into $email_error BY REFERENCE
  1245. */
  1246. //add the email recipients
  1247. $address_found = false;
  1248. if (!is_array($email_recipients)) { // must be a single or delimited recipient address(s)
  1249. $email_recipients = str_replace(' ', '', $email_recipients);
  1250. $email_recipients = str_replace(',', ';', $email_recipients);
  1251. $email_recipients = explode(';', $email_recipients); // convert to array of addresses
  1252. }
  1253. foreach ($email_recipients as $email_recipient) {
  1254. if (is_array($email_recipient)) { // check if each recipient has multiple fields
  1255. if ($email_recipient["address"] != '' && valid_email($email_recipient["address"])) { // check if valid address
  1256. $recipients = $email_recipient["address"];
  1257. $address_found = true;
  1258. }
  1259. }
  1260. else if ($email_recipient != '' && valid_email($email_recipient)) { // check if recipient value is simply (only) an address
  1261. $email_recipients = $email_recipient;
  1262. $address_found = true;
  1263. }
  1264. }
  1265. if (is_array($recipients)) {
  1266. $email_recipients = implode(",", $recipients);
  1267. }
  1268. if (!$address_found) {
  1269. $email_error = "No valid e-mail address provided.";
  1270. return false;
  1271. }
  1272. //get the from address and name
  1273. $email_from_address = ($email_from_address != '') ? $email_from_address : $_SESSION['email']['smtp_from']['text'];
  1274. $email_from_name = ($email_from_name != '') ? $email_from_name : $_SESSION['email']['smtp_from_name']['text'];
  1275. //send email
  1276. $email = new email;
  1277. $email->recipients = $email_recipients;
  1278. $email->subject = $email_subject;
  1279. $email->body = $email_body;
  1280. $email->from_address = $email_from_address;
  1281. $email->from_name = $email_from_name;
  1282. $email->attachments = $email_attachments;
  1283. $email->debug_level = 3;
  1284. $sent = $email->send();
  1285. //$email_error = $email->email_error;
  1286. }
  1287. }
  1288. //encrypt a string
  1289. if (!function_exists('encrypt')) {
  1290. function encrypt($key, $data) {
  1291. $encryption_key = base64_decode($key);
  1292. $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
  1293. $encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);
  1294. return base64_encode($encrypted.'::'.$iv);
  1295. }
  1296. }
  1297. //decrypt a string
  1298. if (!function_exists('decrypt')) {
  1299. function decrypt($key, $data) {
  1300. $encryption_key = base64_decode($key);
  1301. list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
  1302. return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
  1303. }
  1304. }
  1305. //json detection
  1306. if (!function_exists('is_json')) {
  1307. function is_json($str) {
  1308. return (is_string($str) && is_object(json_decode($str))) ? true : false;
  1309. }
  1310. }
  1311. //mac detection
  1312. if (!function_exists('is_mac')) {
  1313. function is_mac($str) {
  1314. return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $str) == 1) ? true : false;
  1315. }
  1316. }
  1317. //detect if php is running as command line interface
  1318. if (!function_exists('is_cli')) {
  1319. function is_cli() {
  1320. if (defined('STDIN')) {
  1321. return true;
  1322. }
  1323. if (php_sapi_name() == 'cli' && !isset($_SERVER['HTTP_USER_AGENT']) && is_numeric($_SERVER['argc'])) {
  1324. return true;
  1325. }
  1326. return false;
  1327. }
  1328. }
  1329. //format mac address
  1330. if (!function_exists('format_mac')) {
  1331. function format_mac($str, $delim = '-', $case = 'lower') {
  1332. if (is_mac($str)) {
  1333. $str = join($delim, str_split($str, 2));
  1334. $str = ($case == 'upper') ? strtoupper($str) : strtolower($str);
  1335. }
  1336. return $str;
  1337. }
  1338. }
  1339. //transparent gif
  1340. if (!function_exists('img_spacer')) {
  1341. function img_spacer($width = '1px', $height = '1px', $custom = null) {
  1342. return "<img src='data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7' style='width: ".$width."; height: ".$height."; ".$custom."'>";
  1343. }
  1344. }
  1345. //lower case
  1346. function lower_case($string) {
  1347. if (function_exists('mb_strtolower')) {
  1348. return mb_strtolower($string, 'UTF-8');
  1349. }
  1350. else {
  1351. return strtolower($string);
  1352. }
  1353. }
  1354. //upper case
  1355. function upper_case($string) {
  1356. if (function_exists('mb_strtoupper')) {
  1357. return mb_strtoupper($string, 'UTF-8');
  1358. }
  1359. else {
  1360. return strtoupper($string);
  1361. }
  1362. }
  1363. //write javascript function that detects select key combinations to perform designated actions
  1364. if (!function_exists('key_press')) {
  1365. function key_press($key, $direction = 'up', $subject = 'document', $exceptions = array(), $prompt = null, $action = null, $script_wrapper = true) {
  1366. //determine key code
  1367. switch (strtolower($key)) {
  1368. case 'escape':
  1369. $key_code = '(e.which == 27)';
  1370. break;
  1371. case 'delete':
  1372. $key_code = '(e.which == 46)';
  1373. break;
  1374. case 'enter':
  1375. $key_code = '(e.which == 13)';
  1376. break;
  1377. case 'backspace':
  1378. $key_code = '(e.which == 8)';
  1379. break;
  1380. case 'space':
  1381. $key_code = '(e.which == 32)';
  1382. break;
  1383. case 'ctrl+s':
  1384. $key_code = '(((e.which == 115 || e.which == 83) && (e.ctrlKey || e.metaKey)) || (e.which == 19))';
  1385. break;
  1386. case 'ctrl+q':
  1387. $key_code = '(((e.which == 113 || e.which == 81) && (e.ctrlKey || e.metaKey)) || (e.which == 19))';
  1388. break;
  1389. case 'ctrl+a':
  1390. $key_code = '(((e.which == 97 || e.which == 65) && (e.ctrlKey || e.metaKey)) || (e.which == 19))';
  1391. break;
  1392. case 'ctrl+c':
  1393. $key_code = '(((e.which == 99 || e.which == 67) && (e.ctrlKey || e.metaKey)) || (e.which == 19))';
  1394. break;
  1395. case 'ctrl+enter':
  1396. $key_code = '(((e.which == 13 || e.which == 10) && (e.ctrlKey || e.metaKey)) || (e.which == 19))';
  1397. break;
  1398. default:
  1399. return;
  1400. }
  1401. //filter direction
  1402. switch ($direction) {
  1403. case 'down': $direction = 'keydown'; break;
  1404. case 'press': $direction = 'keypress'; break;
  1405. case 'up': $direction = 'keyup'; break;
  1406. }
  1407. //check for element exceptions
  1408. if (is_array($exceptions)) {
  1409. if (sizeof($exceptions) > 0) {
  1410. $exceptions = "!$(e.target).is('".implode(',', $exceptions)."') && ";
  1411. }
  1412. }
  1413. //quote if selector is id or class
  1414. $subject = ($subject != 'window' && $subject != 'document') ? "'".$subject."'" : $subject;
  1415. //output script
  1416. echo "\n\n\n";
  1417. if ($script_wrapper) {
  1418. echo "<script language='JavaScript' type='text/javascript'>\n";
  1419. }
  1420. echo " $(".$subject.").on('".$direction."', function(e) {\n";
  1421. echo " if (".$exceptions.$key_code.") {\n";
  1422. if ($prompt != '') {
  1423. $action = ($action != '') ? $action : "alert('".$key."');";
  1424. echo " if (confirm('".$prompt."')) {\n";
  1425. echo " e.preventDefault();\n";
  1426. echo " ".$action."\n";
  1427. echo " }\n";
  1428. }
  1429. else {
  1430. echo " e.preventDefault();\n";
  1431. echo " ".$action."\n";
  1432. }
  1433. echo " }\n";
  1434. echo " });\n";
  1435. if ($script_wrapper) {
  1436. echo "</script>\n";
  1437. }
  1438. echo "\n\n\n";
  1439. }
  1440. }
  1441. //format border radius values
  1442. if (!function_exists('format_border_radius')) {
  1443. function format_border_radius($radius_value, $default = 5) {
  1444. $radius_value = ($radius_value != '') ? $radius_value : $default;
  1445. $br_a = explode(' ', $radius_value);
  1446. foreach ($br_a as $index => $br) {
  1447. if (substr_count($br, '%') > 0) {
  1448. $br_b[$index]['number'] = str_replace('%', '', $br);
  1449. $br_b[$index]['unit'] = '%';
  1450. }
  1451. else {
  1452. $br_b[$index]['number'] = str_replace('px', '', strtolower($br));
  1453. $br_b[$index]['unit'] = 'px';
  1454. }
  1455. }
  1456. unset($br_a, $br);
  1457. if (sizeof($br_b) == 4) {
  1458. $br['tl']['n'] = $br_b[0]['number'];
  1459. $br['tr']['n'] = $br_b[1]['number'];
  1460. $br['br']['n'] = $br_b[2]['number'];
  1461. $br['bl']['n'] = $br_b[3]['number'];
  1462. $br['tl']['u'] = $br_b[0]['unit'];
  1463. $br['tr']['u'] = $br_b[1]['unit'];
  1464. $br['br']['u'] = $br_b[2]['unit'];
  1465. $br['bl']['u'] = $br_b[3]['unit'];
  1466. }
  1467. else if (sizeof($br_b) == 2) {
  1468. $br['tl']['n'] = $br_b[0]['number'];
  1469. $br['tr']['n'] = $br_b[0]['number'];
  1470. $br['br']['n'] = $br_b[1]['number'];
  1471. $br['bl']['n'] = $br_b[1]['number'];
  1472. $br['tl']['u'] = $br_b[0]['unit'];
  1473. $br['tr']['u'] = $br_b[0]['unit'];
  1474. $br['br']['u'] = $br_b[1]['unit'];
  1475. $br['bl']['u'] = $br_b[1]['unit'];
  1476. }
  1477. else {
  1478. $br['tl']['n'] = $br_b[0]['number'];
  1479. $br['tr']['n'] = $br_b[0]['number'];
  1480. $br['br']['n'] = $br_b[0]['number'];
  1481. $br['bl']['n'] = $br_b[0]['number'];
  1482. $br['tl']['u'] = $br_b[0]['unit'];
  1483. $br['tr']['u'] = $br_b[0]['unit'];
  1484. $br['br']['u'] = $br_b[0]['unit'];
  1485. $br['bl']['u'] = $br_b[0]['unit'];
  1486. }
  1487. unset($br_b);
  1488. return $br; //array
  1489. }
  1490. }
  1491. //converts a string to a regular expression
  1492. if (!function_exists('string_to_regex')) {
  1493. function string_to_regex($string, $prefix='') {
  1494. $original_string = $string;
  1495. //escape the plus
  1496. if (substr($string, 0, 1) == "+") {
  1497. $string = "^\\+(".substr($string, 1).")$";
  1498. }
  1499. //add prefix
  1500. if (strlen($prefix) > 0) {
  1501. if (strlen($prefix) > 0 && strlen($prefix) < 4) {
  1502. $plus = (substr($string, 0, 1) == "+") ? '' : '\+?';
  1503. $prefix = $plus.$prefix.'?';
  1504. }
  1505. else {
  1506. $prefix = '(?:'.$prefix.')?';
  1507. }
  1508. }
  1509. //convert N,X,Z syntax to regex
  1510. if (preg_match('/^[NnXxZz]+$/', $original_string)) {
  1511. $string = str_ireplace("N", "[2-9]", $string);
  1512. $string = str_ireplace("X", "[0-9]", $string);
  1513. $string = str_ireplace("Z", "[1-9]", $string);
  1514. }
  1515. //add ^ to the start of the string if missing
  1516. if (substr($string, 0, 1) != "^") {
  1517. $string = "^".$string;
  1518. }
  1519. //add $ to the end of the string if missing
  1520. if (substr($string, -1) != "$") {
  1521. $string = $string."$";
  1522. }
  1523. //add the round brackets
  1524. if (!strstr($string, '(')) {
  1525. if (strstr($string, '^')) {
  1526. $string = str_replace("^", "^".$prefix."(", $string);
  1527. }
  1528. else {
  1529. $string = '^('.$string;
  1530. }
  1531. if (strstr($string, '$')) {
  1532. $string = str_replace("$", ")$", $string);
  1533. }
  1534. else {
  1535. $string = $string.')$';
  1536. }
  1537. }
  1538. //return the result
  1539. return $string;
  1540. }
  1541. //$string = "+12089068227"; echo $string." ".string_to_regex($string)."\n";
  1542. //$string = "12089068227"; echo $string." ".string_to_regex($string)."\n";
  1543. //$string = "2089068227"; echo $string." ".string_to_regex($string)."\n";
  1544. //$string = "^(20890682[0-9][0-9])$"; echo $string." ".string_to_regex($string)."\n";
  1545. //$string = "1208906xxxx"; echo $string." ".string_to_regex($string)."\n";
  1546. //$string = "nxxnxxxxxxx"; echo $string." ".string_to_regex($string)."\n";
  1547. //$string = "208906xxxx"; echo $string." ".string_to_regex($string)."\n";
  1548. //$string = "^(2089068227"; echo $string." ".string_to_regex($string)."\n";
  1549. //$string = "^2089068227)"; echo $string." ".string_to_regex($string)."\n";
  1550. //$string = "2089068227$"; echo $string." ".string_to_regex($string)."\n";
  1551. //$string = "2089068227)$"; echo $string." ".string_to_regex($string)."\n";
  1552. }
  1553. //dynamically load available web fonts
  1554. if (!function_exists('get_available_fonts')) {
  1555. function get_available_fonts($sort = 'alpha') {
  1556. if ($_SESSION['theme']['font_source_key']['text'] != '') {
  1557. if (!is_array($_SESSION['fonts_available']) || sizeof($_SESSION['fonts_available']) == 0) {
  1558. /*
  1559. sort options:
  1560. alpha - alphabetically
  1561. date - by date added (most recent font added or updated first)
  1562. popularity - by popularity (most popular family first)
  1563. style - by number of styles available (family with most styles first)
  1564. trending - by families seeing growth in usage (family seeing the most growth first)
  1565. */
  1566. $google_api_url = 'https://www.googleapis.com/webfonts/v1/webfonts?key='.$_SESSION['theme']['font_source_key']['text'].'&sort='.$sort;
  1567. $response = file_get_contents($google_api_url);
  1568. if ($response != '') {
  1569. $data = json_decode($response, true);
  1570. $items = $data['items'];
  1571. foreach ($items as $item) {
  1572. $fonts[] = $item['family'];
  1573. }
  1574. //echo "<pre>".print_r($font_list, true)."</pre>";
  1575. }
  1576. $_SESSION['fonts_available'] = $fonts;
  1577. unset($fonts);
  1578. }
  1579. return (is_array($_SESSION['fonts_available']) && sizeof($_SESSION['fonts_available']) > 0) ? $_SESSION['fonts_available'] : array();
  1580. }
  1581. else {
  1582. return false;
  1583. }
  1584. }
  1585. }
  1586. //dynamically import web fonts (by reading static css file)
  1587. if (!function_exists('import_fonts')) {
  1588. function import_fonts($file_to_parse, $line_styles_begin = null) {
  1589. /*
  1590. This function reads the contents of $file_to_parse, beginning at $line_styles_begin (if set),
  1591. and attempts to parse the specified google fonts used. The assumption is that each curly brace
  1592. will be on its own line, each CSS style (attribute: value;) will be on its own line, a single
  1593. Google Fonts name will be used per selector, and that it will be surrounded by SINGLE quotes,
  1594. as shown in the example below:
  1595. .class_name {
  1596. font-family: 'Google Font';
  1597. font-weight: 300;
  1598. font-style: italic;
  1599. }
  1600. If the CSS styles are formatted as described, the necessary @import string should be generated
  1601. correctly.
  1602. */
  1603. $file = file_get_contents($_SERVER["DOCUMENT_ROOT"].$file_to_parse);
  1604. $lines = explode("\n", $file);
  1605. $style_counter = 0;
  1606. foreach ($lines as $line_number => $line) {
  1607. if ($line_styles_begin != '' && $line_number < $line_styles_begin - 1) { continue; }
  1608. if (substr_count($line, "{") > 0) {
  1609. $style_lines[$style_counter]['begins'] = $line_number;
  1610. }
  1611. if (substr_count($line, "}") > 0) {
  1612. $style_lines[$style_counter]['ends'] = $line_number;
  1613. $style_counter++;
  1614. }
  1615. }
  1616. //echo "\n\n".print_r($style_lines, true)."\n\n";
  1617. if (is_array($style_lines) && sizeof($style_lines) > 0) {
  1618. foreach ($style_lines as $index => $style_line) {
  1619. for ($l = $style_line['begins']+1; $l < $style_line['ends']; $l++) {
  1620. $tmp[] = $lines[$l];
  1621. }
  1622. $style_groups[] = $tmp;
  1623. unset($tmp);
  1624. }
  1625. //echo "\n\n".print_r($style_groups, true)."\n\n";
  1626. if (is_array($style_groups) && sizeof($style_groups) > 0) {
  1627. foreach ($style_groups as $style_group_index => $style_group) {
  1628. foreach ($style_group as $style_index => $style) {
  1629. $tmp = explode(':', $style);
  1630. $attribute = trim($tmp[0]);
  1631. $value = trim(trim($tmp[1]),';');
  1632. $style_array[$attribute] = $value;
  1633. }
  1634. $style_groups[$style_group_index] = $style_array;
  1635. unset($style_array);
  1636. }
  1637. //echo "\n\n".print_r($style_groups, true)."\n\n";
  1638. foreach ($style_groups as $style_group_index => $style_group) {
  1639. $style_value = $style_group['font-family'];
  1640. if (substr_count($style_value, "'") > 0) {
  1641. //determine font
  1642. $font_begin = strpos($style_value, "'")+1;
  1643. $font_end = strpos($style_value, "'", $font_begin);
  1644. $font_name = substr($style_value, $font_begin, $font_end - $font_begin);
  1645. //determine modifiers
  1646. $weight = (is_numeric($style_group['font-weight']) || strtolower($style_group['font-weight']) == 'bold') ? strtolower($style_group['font-weight']) : null;
  1647. $italic = (strtolower($style_group['font-style']) == 'italic') ? 'italic' : null;
  1648. //add font to array
  1649. $fonts[$font_name][] = $weight.$italic;
  1650. }
  1651. }
  1652. //echo "\n\n/*".print_r($fonts, true)."*/\n\n";
  1653. if (is_array($fonts)) {
  1654. foreach ($fonts as $font_name => $modifiers) {
  1655. $modifiers = array_unique($modifiers);
  1656. $import_font_string = str_replace(' ', '+', $font_name);
  1657. if (is_array($modifiers) && sizeof($modifiers) > 0) {
  1658. $import_font_string .= ':'.implode(',', $modifiers);
  1659. }
  1660. $import_fonts[] = $import_font_string;
  1661. }
  1662. //echo "\n\n/*".print_r($import_fonts, true)."*/\n\n";
  1663. $import_string = "@import url(//fonts.googleapis.com/css?family=".implode('|', $import_fonts).");";
  1664. echo $import_string."\n";
  1665. }
  1666. }
  1667. }
  1668. }
  1669. }
  1670. //retrieve array of countries
  1671. if (!function_exists('get_countries')) {
  1672. function get_countries() {
  1673. $sql = "select * from v_countries order by country asc";
  1674. $database = new database;
  1675. $result = $database->select($sql, null, 'all');
  1676. unset($sql);
  1677. return is_array($result) && @sizeof($result) != 0 ? $result : false;
  1678. }
  1679. }
  1680. //make directory with event socket
  1681. function event_socket_mkdir($dir) {
  1682. //connect to fs
  1683. $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']);
  1684. if (!$fp) {
  1685. return false;
  1686. }
  1687. //send the mkdir command to freeswitch
  1688. if ($fp) {
  1689. //build and send the mkdir command to freeswitch
  1690. $switch_cmd = "lua mkdir.lua ".escapeshellarg($dir);
  1691. $switch_result = event_socket_request($fp, 'api '.$switch_cmd);
  1692. fclose($fp);
  1693. //check result
  1694. if (trim($switch_result) == "-ERR no reply") {
  1695. return true;
  1696. }
  1697. }
  1698. //can not create directory
  1699. return false;
  1700. }
  1701. //escape user data
  1702. function escape($string) {
  1703. if (is_array($string)) {
  1704. return false;
  1705. }
  1706. elseif (isset($string) && strlen($string)) {
  1707. return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  1708. }
  1709. else {
  1710. return false;
  1711. }
  1712. //return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
  1713. }
  1714. //output pre-formatted array keys and values
  1715. if (!function_exists('view_array')) {
  1716. function view_array($array, $exit = true, $return = false) {
  1717. $html = "<br><pre style='text-align: left;'>".print_r($array, true).'</pre><br>';
  1718. if ($return) {
  1719. return $html;
  1720. }
  1721. else {
  1722. echo $html;
  1723. }
  1724. $exit and exit();
  1725. }
  1726. }
  1727. //format db date and/or time to local date and/or time
  1728. if (!function_exists('format_when_local')) {
  1729. function format_when_local($when, $format = 'dt', $include_seconds = false) {
  1730. if ($when != '') {
  1731. // determine when format
  1732. if (substr_count($when, ' ') > 0) { // date and time
  1733. $tmp = explode(' ', $when);
  1734. $date = $tmp[0];
  1735. $time = $tmp[1];
  1736. }
  1737. else if (substr_count($when, '-') > 0) { // date only
  1738. $date = $when;
  1739. }
  1740. else if (substr_count($when, ':') > 0) { // time only
  1741. $time = $when;
  1742. }
  1743. unset($when, $tmp);
  1744. // format date
  1745. if ($date != '') {
  1746. $tmp = explode('-', $date);
  1747. $date = $tmp[1].'-'.$tmp[2].'-'.$tmp[0];
  1748. }
  1749. // format time
  1750. if ($time != '') {
  1751. $tmp = explode(':', $time);
  1752. if ($tmp[0] >= 0 && $tmp[0] <= 11) {
  1753. $meridiem = 'AM';
  1754. $hour = ($tmp[0] == 0) ? 12 : $tmp[0];
  1755. }
  1756. else {
  1757. $meridiem = 'PM';
  1758. $hour = ($tmp[0] > 12) ? ($tmp[0] - 12) : $tmp[0];
  1759. }
  1760. $minute = $tmp[1];
  1761. $second = $tmp[2];
  1762. }
  1763. // structure requested time format
  1764. $time = $hour.':'.$minute;
  1765. if ($include_seconds) { $time .= ':'.$second; }
  1766. $time .= ' '.$meridiem;
  1767. $return['d'] = $date;
  1768. $return['t'] = $time;
  1769. $return['dt'] = $date.' '.$time;
  1770. return $return[$format];
  1771. }
  1772. else {
  1773. return false;
  1774. }
  1775. }
  1776. }
  1777. //define email button (src: https://buttons.cm)
  1778. if (!function_exists('email_button')) {
  1779. function email_button($text = 'Click Here!', $link = URL, $bg_color = '#dddddd', $fg_color = '#000000', $radius = '') {
  1780. // default button radius
  1781. $radius = $radius != '' ? $radius : '3px';
  1782. // retrieve single/first numeric radius value for ms arc
  1783. $tmp = $radius;
  1784. if (substr_count($radius, ' ') > 0) {
  1785. $tmp = explode(' ', $radius);
  1786. $tmp = $tmp[0];
  1787. }
  1788. $tmp = preg_replace("/[^0-9,.]/", '', $tmp); // remove non-numeric characters
  1789. $arc = floor($tmp / 35 * 100); // calculate percentage
  1790. // create button code
  1791. $btn = "
  1792. <div>
  1793. <!--[if mso]>
  1794. <v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='".$link."' style='height: 35px; v-text-anchor: middle; width: 140px;' arcsize='".$arc."%' stroke='f' fillcolor='".$bg_color."'>
  1795. <w:anchorlock/>
  1796. <center>
  1797. <![endif]-->
  1798. <a href='".$link."' style='background-color: ".$bg_color."; border-radius: ".$radius."; color: ".$fg_color."; display: inline-block; font-family: sans-serif; font-size: 13px; font-weight: bold; line-height: 35px; text-align: center; text-decoration: none; width: 140px; -webkit-text-size-adjust: none;'>".$text."</a>
  1799. <!--[if mso]>
  1800. </center>
  1801. </v:roundrect>
  1802. <![endif]-->
  1803. </div>
  1804. ";
  1805. return $btn;
  1806. }
  1807. }
  1808. //validate and format order by clause of select statement
  1809. if (!function_exists('order_by')) {
  1810. function order_by($col, $dir, $col_default = '', $dir_default = 'asc') {
  1811. $order_by = ' order by ';
  1812. $col = preg_replace('#[^a-zA-Z0-9-_.]#', '', $col);
  1813. $dir = strtolower($dir) == 'desc' ? 'desc' : 'asc';
  1814. if ($col != '') {
  1815. return $order_by.$col.' '.$dir.' ';
  1816. }
  1817. else if (is_array($col_default) || $col_default != '') {
  1818. if (is_array($col_default) && @sizeof($col_default) != 0) {
  1819. foreach ($col_default as $k => $column) {
  1820. $direction = (is_array($dir_default) && @sizeof($dir_default) != 0 && (strtolower($dir_default[$k]) == 'asc' || strtolower($dir_default[$k]) == 'desc')) ? $dir_default[$k] : 'asc';
  1821. $order_bys[] = $column.' '.$direction.' ';
  1822. }
  1823. if (is_array($order_bys) && @sizeof($order_bys) != 0) {
  1824. return $order_by.implode(', ', $order_bys);
  1825. }
  1826. }
  1827. else {
  1828. return $order_by.$col_default.' '.$dir_default.' ';
  1829. }
  1830. }
  1831. }
  1832. }
  1833. //validate and format limit and offset clause of select statement
  1834. if (!function_exists('limit_offset')) {
  1835. function limit_offset($limit, $offset = 0) {
  1836. $regex = '#[^0-9]#';
  1837. $limit = preg_replace($regex, '', $limit);
  1838. $offset = preg_replace($regex, '', $offset);
  1839. if (is_numeric($limit) && $limit > 0) {
  1840. $clause = ' limit '.$limit;
  1841. $offset = is_numeric($offset) ? $offset : 0;
  1842. $clause .= ' offset '.$offset;
  1843. }
  1844. return $clause.' ';
  1845. }
  1846. }
  1847. //add a random_bytes function when it doesn't exist for old versions of PHP
  1848. if (!function_exists('random_bytes')) {
  1849. function random_bytes($length) {
  1850. $chars .= "0123456789";
  1851. $chars .= "abcdefghijkmnopqrstuvwxyz";
  1852. $chars .= "ABCDEFGHIJKLMNPQRSTUVWXYZ";
  1853. for ($i = 0; $i < $length; $i++) {
  1854. $string .= $chars[random_int(0, strlen($chars)-1)];
  1855. }
  1856. return $string.' ';
  1857. }
  1858. }
  1859. //add a hash_equals function when it doesn't exist for old versions of PHP
  1860. if (!function_exists('hash_equals')) {
  1861. function hash_equals($var1, $var2) {
  1862. if ($var1 == $var2) {
  1863. return true;
  1864. }
  1865. else {
  1866. return false;
  1867. }
  1868. }
  1869. }
  1870. //convert bytes to readable human format
  1871. if (!function_exists('byte_convert')) {
  1872. function byte_convert($bytes, $precision = 2) {
  1873. static $units = array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
  1874. $step = 1024;
  1875. $i = 0;
  1876. while (($bytes / $step) > 0.9) {
  1877. $bytes = $bytes / $step;
  1878. $i++;
  1879. }
  1880. return round($bytes, $precision).' '.$units[$i];
  1881. }
  1882. }
  1883. //convert bytes to readable human format
  1884. if (!function_exists('random_int')) {
  1885. function random_int($min, $max) {
  1886. return rand ($min, $max);
  1887. }
  1888. }
  1889. //manage submitted form values in a session array
  1890. if (!function_exists('persistent_form_values')) {
  1891. function persistent_form_values($action, $array = null) {
  1892. switch ($action) {
  1893. case 'store':
  1894. // $array is expected to be an array of key / value pairs to store in the session
  1895. if (is_array($array) && @sizeof($array) != 0) {
  1896. $_SESSION['persistent'][$_SERVER['PHP_SELF']] = $array;
  1897. }
  1898. break;
  1899. case 'exists':
  1900. return is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0 ? true : false;
  1901. break;
  1902. case 'load':
  1903. // $array is expected to be the name of the array to create containing the key / value pairs
  1904. if ($array && !is_array($array)) {
  1905. global $$array;
  1906. }
  1907. if (is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) {
  1908. foreach ($_SESSION['persistent'][$_SERVER['PHP_SELF']] as $key => $value) {
  1909. if ($key != 'XID' && $key != 'ACT' && $key != 'RET') {
  1910. if ($array && !is_array($array)) {
  1911. $$array[$key] = $value;
  1912. }
  1913. else {
  1914. global $$key;
  1915. $$key = $value;
  1916. }
  1917. }
  1918. }
  1919. global $unsaved;
  1920. $unsaved = true;
  1921. }
  1922. break;
  1923. case 'view':
  1924. if (is_array($_SESSION['persistent'][$_SERVER['PHP_SELF']]) && @sizeof($_SESSION['persistent'][$_SERVER['PHP_SELF']]) != 0) {
  1925. view_array($_SESSION['persistent'][$_SERVER['PHP_SELF']], false);
  1926. }
  1927. break;
  1928. case 'clear':
  1929. unset($_SESSION['persistent'][$_SERVER['PHP_SELF']]);
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. //add alternative array_key_first for older verisons of PHP
  1935. if (!function_exists('array_key_first')) {
  1936. function array_key_first(array $arr) {
  1937. foreach($arr as $key => $unused) {
  1938. return $key;
  1939. }
  1940. return NULL;
  1941. }
  1942. }
  1943. //get accountcode
  1944. if (!function_exists('get_accountcode')) {
  1945. function get_accountcode() {
  1946. if (strlen($accountcode = $_SESSION['domain']['accountcode']['text']) > 0) {
  1947. if ($accountcode == "none") {
  1948. return;
  1949. }
  1950. }
  1951. else {
  1952. $accountcode = $_SESSION['domain_name'];
  1953. }
  1954. return $accountcode;
  1955. }
  1956. }
  1957. // User exists
  1958. if (!function_exists('user_exists')) {
  1959. function user_exists($login, $domain_name = null) {
  1960. //connect to freeswitch
  1961. $fp = event_socket_create($_SESSION['event_socket_ip_address'], $_SESSION['event_socket_port'], $_SESSION['event_socket_password']);
  1962. if (!$fp) {
  1963. return false;
  1964. }
  1965. //send the user_exists command to freeswitch
  1966. if ($fp) {
  1967. if (is_null($domain_name)) {
  1968. $domain_name = $_SESSION['domain_name'];
  1969. }
  1970. $switch_cmd = "user_exists id '$login' '$domain_name'";
  1971. $switch_result = event_socket_request($fp, 'api '.$switch_cmd);
  1972. fclose($fp);
  1973. return ($switch_result == 'true' ? true: false);
  1974. }
  1975. //can not create directory
  1976. return null;
  1977. }
  1978. }
  1979. //include additional functions
  1980. $functions = glob("{".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/resources/functions/*.php,".$_SERVER["DOCUMENT_ROOT"].PROJECT_PATH."/*/*/resources/functions/*.php}", GLOB_BRACE);
  1981. foreach($functions as $function) {
  1982. $path = pathinfo($function);
  1983. if ($path['filename'] != 'transcribe') {
  1984. require($function);
  1985. }
  1986. }
  1987. ?>