functions.php 67 KB

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