PageRenderTime 864ms CodeModel.GetById 44ms RepoModel.GetById 0ms app.codeStats 1ms

/common/lib/Misc.inc.php

https://github.com/xrg/a2billing
PHP | 1311 lines | 981 code | 150 blank | 180 comment | 249 complexity | 69cffa226a2ad7ebe4ef2e42e60efc95 MD5 | raw file
Possible License(s): AGPL-1.0
  1. <?php
  2. /***************************************************************************
  3. * Misc.php
  4. *
  5. * GPL : Belaid Arezqui
  6. * Email : areski _atl_ gmail
  7. ****************************************************************************/
  8. /*
  9. * a2b_mail
  10. */
  11. function a2b_mail ($to, $subject, $mail_content, $from = 'root@localhost', $fromname = '', $contenttype = 'multipart/alternative')
  12. {
  13. $mail = new phpmailer();
  14. $mail -> From = $from;
  15. $mail -> FromName = $fromname;
  16. //$mail -> IsSendmail();
  17. //$mail -> IsSMTP();
  18. $mail -> Subject = $subject;
  19. $mail -> Body = nl2br($mail_content); //$HTML;
  20. $mail -> AltBody = $mail_content; // Plain text body (for mail clients that cannot read HTML)
  21. // if ContentType = multipart/alternative -> HTML will be send
  22. $mail -> ContentType = $contenttype;
  23. $mail -> AddAddress ($to);
  24. $mail -> Send();
  25. }
  26. /*
  27. * get_currencies
  28. */
  29. function get_currencies($handle = null)
  30. {
  31. if (empty($handle)){
  32. $handle = DbConnect();
  33. }
  34. $instance_table = new Table();
  35. $QUERY = "SELECT id,currency,name,value from cc_currencies order by id";
  36. $result = $instance_table -> SQLExec ($handle, $QUERY);
  37. /*
  38. $currencies_list['ADF'][1]="Andorran Franc";
  39. $currencies_list['ADF'][2]="0.1339";
  40. [ADF] => Array ( [1] => Andorran Franc (ADF), [2] => 0.1339 )
  41. */
  42. if (is_array($result)){
  43. $num_cur = count($result);
  44. for ($i=0;$i<$num_cur;$i++){
  45. $currencies_list[$result[$i][1]] = array (1 => $result[$i][2], 2 => $result[$i][3]);
  46. }
  47. }
  48. if ((isset($currencies_list)) && (is_array($currencies_list))) sort_currencies_list($currencies_list);
  49. return $currencies_list;
  50. }
  51. /**
  52. * Do Currency Conversion.
  53. * @param $currencies_list the List of currencies.
  54. * @param $amount the amount to be converted.
  55. * @param $from_cur Source Currency
  56. * @param $to_cur Destination Currecny
  57. */
  58. function convert_currency ($currencies_list, $amount, $from_cur, $to_cur)
  59. {
  60. if (!is_numeric($amount) || ($amount == 0)) {
  61. return 0;
  62. }
  63. if ($from_cur == $to_cur) {
  64. return $amount;
  65. }
  66. // EUR -> 1.19175 : MAD -> 0.10897
  67. // FROM -> 2 - TO -> 0.5 =>>>> multiply 4
  68. $mycur_tobase = $currencies_list[strtoupper($from_cur)][2];
  69. $mycur = $currencies_list[strtoupper($to_cur)][2];
  70. if ($mycur == 0) return 0;
  71. $amount = $amount * ($mycur_tobase / $mycur);
  72. // echo "\n \n AMOUNT CONVERTED IN NEW CURRENCY $to_cur -> VALUE =".$amount;
  73. return $amount;
  74. }
  75. /*
  76. * sort_currencies_list
  77. */
  78. function sort_currencies_list(&$currencies_list)
  79. {
  80. $first_array = array (strtoupper(BASE_CURRENCY), 'USD', 'EUR','GBP','AUD','HKD', 'JPY', 'NZD', 'SGD', 'TWD', 'PLN', 'SEK', 'DKK', 'CHF', 'COP', 'MXN', 'CLP');
  81. foreach ($first_array as $element_first_array){
  82. if (isset($currencies_list[$element_first_array])){
  83. $currencies_list2[$element_first_array]=$currencies_list[$element_first_array];
  84. unset($currencies_list[$element_first_array]);
  85. }
  86. }
  87. $currencies_list = array_merge($currencies_list2,$currencies_list);
  88. }
  89. /*
  90. * Write log into file
  91. */
  92. function write_log($logfile, $output)
  93. {
  94. if (strlen($logfile) > 1){
  95. $string_log = "[".date("d/m/Y H:i:s")."]:[$output]\n";
  96. error_log ($string_log."\n", 3, $logfile);
  97. }
  98. }
  99. /*
  100. * function sanitize_data
  101. */
  102. function sanitize_data($data)
  103. {
  104. $lowerdata = strtolower ($data);
  105. $data = str_replace('--', '', $data);
  106. $data = str_replace("'", '', $data);
  107. $data = str_replace('=', '', $data);
  108. $data = str_replace(';', '', $data);
  109. //$lowerdata = str_replace('table', '', $lowerdata);
  110. //$lowerdata = str_replace(' or ', '', $data);
  111. if (!(strpos($lowerdata, ' or ')===FALSE)){ return false;}
  112. if (!(strpos($lowerdata, 'table')===FALSE)){ return false;}
  113. return $data;
  114. }
  115. /*
  116. * function getpost_ifset
  117. */
  118. function getpost_ifset($test_vars)
  119. {
  120. if (!is_array($test_vars)) {
  121. $test_vars = array($test_vars);
  122. }
  123. foreach($test_vars as $test_var) {
  124. if (isset($_POST[$test_var])) {
  125. global $$test_var;
  126. $$test_var = $_POST[$test_var];
  127. $$test_var = sanitize_data($$test_var);
  128. } elseif (isset($_GET[$test_var])) {
  129. global $$test_var;
  130. $$test_var = $_GET[$test_var];
  131. $$test_var = sanitize_data($$test_var);
  132. }
  133. }
  134. }
  135. /** Return a single variable from the post/get data */
  136. function getpost_single($vname)
  137. {
  138. if (isset($_POST[$vname]))
  139. return sanitize_data($_POST[$vname]);
  140. elseif (isset($_GET[$vname]))
  141. return sanitize_data($_GET[$vname]);
  142. else
  143. return null;
  144. }
  145. /** The opposite of getpost_ifset: create an array with those post vars
  146. @param arr Array of ("var name", ...)
  147. @param empty_null If true, treat empty vars as null
  148. @return array( var => val, ...)
  149. BIG NOTE: It doesn't work, because GLOBALS here may not be the same..
  150. */
  151. function putpost_arr($test_vars, $empty_null = false){
  152. $ret = array();
  153. if (!is_array($test_vars)) {
  154. $test_vars = array($test_vars);
  155. }
  156. foreach($test_vars as $test_var) {
  157. if (isset($GLOBALS[$test_var]) && ($GLOBALS[$test_var] != null) &&
  158. ((!$empty_null) || $GLOBALS[$test_var] != '') )
  159. $ret[$test_var] = $GLOBALS[$test_var];
  160. }
  161. return $ret;
  162. }
  163. /** Convert params in array to url string
  164. @param arr An array like (var1 => value1, ...)
  165. @return A url like var1=value1
  166. */
  167. function arr2url ($arr) {
  168. if (!is_array($arr))
  169. return;
  170. $rar = array();
  171. foreach($arr as $key => $value) {
  172. if ($value === null)
  173. continue;
  174. if (is_array($value)){
  175. foreach($value as $arr_val)
  176. $rar[] = "$key" . '[]=' . rawurlencode($arr_val);
  177. }else
  178. $rar[] = "$key" . '=' . rawurlencode($value);
  179. }
  180. return implode('&',$rar);
  181. }
  182. /** Generate an html combo, with selected values etc. */
  183. function gen_Combo($name, $value, $option_array,$multiple=false){
  184. $tmp_name=$name;
  185. if ($multiple){
  186. $tmp_name.='[]';
  187. $tmp_size=count($option_array);
  188. if ($tmp_size>20)
  189. $tmp_size=15;
  190. $opts .= ' class="form_enter" multiple="multiple" size='.$tmp_size;
  191. }else
  192. $opts .=' size=1 class="form_enter"';
  193. ?> <select name="<?= $tmp_name?>" <?=$opts ?>>
  194. <?php
  195. if (is_array($option_array))
  196. foreach($option_array as $option){ ?>
  197. <option value="<?= $option[0] ?>"<?php
  198. if (($value == $option[0]) || ($multiple && is_array($value) && in_array($option[0],$value)))
  199. echo ' selected';
  200. ?>><?= htmlspecialchars($option[1])?></option>
  201. <?php }
  202. ?>
  203. </select>
  204. <?php
  205. }
  206. /*
  207. * function display_money
  208. */
  209. function display_money($value, $currency = BASE_CURRENCY){
  210. echo $value.' '.$currency;
  211. }
  212. /*
  213. * function display_dateformat
  214. */
  215. function display_dateformat($mydate){
  216. if (DB_TYPE == "mysql"){
  217. if (strlen($mydate)==14){
  218. // YYYY-MM-DD HH:MM:SS 20300331225242
  219. echo substr($mydate,0,4).'-'.substr($mydate,4,2).'-'.substr($mydate,6,2);
  220. echo ' '.substr($mydate,8,2).':'.substr($mydate,10,2).':'.substr($mydate,12,2);
  221. return;
  222. }
  223. }
  224. echo $mydate;
  225. }
  226. /*
  227. * function display_dateonly
  228. */
  229. function display_dateonly($mydate)
  230. {
  231. if (strlen($mydate) > 0 && $mydate != '0000-00-00'){
  232. echo date("m/d/Y", strtotime($mydate));
  233. }
  234. }
  235. /*
  236. * function res_display_dateformat
  237. */
  238. function res_display_dateformat($mydate){
  239. if (DB_TYPE == "mysql"){
  240. if (strlen($mydate)==14){
  241. // YYYY-MM-DD HH:MM:SS 20300331225242
  242. $res= substr($mydate,0,4).'-'.substr($mydate,4,2).'-'.substr($mydate,6,2);
  243. $res.= ' '.substr($mydate,8,2).':'.substr($mydate,10,2).':'.substr($mydate,12,2);
  244. return $res;
  245. }
  246. }
  247. return $mydate;
  248. }
  249. /*
  250. * function display_minute
  251. */
  252. function display_minute($sessiontime){
  253. global $resulttype;
  254. if ((!isset($resulttype)) || ($resulttype=="min")){
  255. $minutes = sprintf("%02d",intval($sessiontime/60)).":".sprintf("%02d",intval($sessiontime%60));
  256. }else{
  257. $minutes = $sessiontime;
  258. }
  259. echo $minutes;
  260. }
  261. function display_2dec($var){
  262. echo number_format($var,2);
  263. }
  264. function display_2dec_percentage($var){
  265. if (isset($var))
  266. {
  267. echo number_format($var,2)."%";
  268. }else
  269. {
  270. echo "n/a";
  271. }
  272. }
  273. function display_2bill($var, $currency = BASE_CURRENCY){
  274. global $currencies_list, $choose_currency;
  275. if (isset($choose_currency) && strlen($choose_currency)==3) $currency=$choose_currency;
  276. if ( (!isset($currencies_list)) || (!is_array($currencies_list)) ) $currencies_list = get_currencies();
  277. $var = $var / $currencies_list[strtoupper($currency)][2];
  278. echo number_format($var,3).' '.$currency;
  279. }
  280. function remove_prefix($phonenumber){
  281. if (substr($phonenumber,0,3) == "011"){
  282. echo substr($phonenumber,3);
  283. return 1;
  284. }
  285. echo $phonenumber;
  286. }
  287. /*
  288. * function linkonmonitorfile
  289. */
  290. function linkonmonitorfile($value){
  291. $myfile = $value.".".MONITOR_FORMATFILE;
  292. $myfile = base64_encode($myfile);
  293. echo "<a target=_blank href=\"call-log-customers.php?download=file&file=".$myfile."\">";
  294. echo '<img src="'.Images_Path.'/stock-mic.png" height="18" /></a>';
  295. }
  296. function linktocustomer($value){
  297. $handle = DbConnect();
  298. $inst_table = new Table("cc_card", "id");
  299. $FG_TABLE_CLAUSE = "username = '$value'";
  300. $list_customer = $inst_table -> Get_list ($handle, $FG_TABLE_CLAUSE, "", "", "", "", "", "", "", 10);
  301. $id = $list_customer[0][0];
  302. if($id > 0){
  303. echo "<a href=\"A2B_entity_card.php?form_action=ask-edit&id=$id\">$value</a>";
  304. }else{
  305. echo $value;
  306. }
  307. }
  308. /*
  309. * function MDP_STRING
  310. */
  311. function MDP_STRING($chrs = LEN_CARDNUMBER){
  312. $pwd = "" ;
  313. mt_srand ((double) microtime() * 1000000);
  314. while (strlen($pwd)<$chrs)
  315. {
  316. $chr = chr(mt_rand (0,255));
  317. if (preg_match("/^[0-9a-z]$/i", $chr))
  318. $pwd = $pwd.$chr;
  319. };
  320. return strtolower($pwd);
  321. }
  322. function MDP_NUMERIC($chrs = LEN_CARDNUMBER){
  323. $pwd = "" ;
  324. mt_srand ((double) microtime() * 1000000);
  325. while (strlen($pwd)<$chrs)
  326. {
  327. $chr = mt_rand (0,9);
  328. if (preg_match("/^[0-9]$/i", $chr))
  329. $pwd = $pwd.$chr;
  330. };
  331. return strtolower($pwd);
  332. }
  333. function MDP($chrs = LEN_CARDNUMBER){
  334. $pwd = "" ;
  335. mt_srand ((double) microtime() * 1000000);
  336. while (strlen($pwd)<$chrs)
  337. {
  338. $chr = chr(mt_rand (0,255));
  339. if (preg_match("/^[0-9]$/i", $chr))
  340. $pwd = $pwd.$chr;
  341. };
  342. return $pwd;
  343. }
  344. function gen_card($table = "cc_card", $len = LEN_CARDNUMBER, $field="username"){
  345. $DBHandle_max = DbConnect();
  346. for ($k=0;$k<=200;$k++){
  347. $card_gen = MDP($len);
  348. if ($k==200){ echo "ERROR : Impossible to generate a $field not yet used!<br>Perhaps check the LEN_CARDNUMBER (value:".LEN_CARDNUMBER.")";exit();}
  349. $query = "SELECT ".$field." FROM ".$table." where ".$field."='$card_gen'";
  350. $resmax = $DBHandle_max -> Execute($query);
  351. $numrow = 0;
  352. if ($resmax)
  353. $numrow = $resmax -> RecordCount( );
  354. if ($numrow!=0) continue;
  355. return $card_gen;
  356. }
  357. }
  358. function gen_card_with_alias($table = "cc_card", $api=0, $length_cardnumber=LEN_CARDNUMBER){
  359. $DBHandle_max = DbConnect();
  360. for ($k=0;$k<=200;$k++){
  361. $card_gen = MDP($length_cardnumber);
  362. $alias_gen = MDP(LEN_ALIASNUMBER);
  363. if ($k==200){
  364. if ($api){
  365. global $mail_content, $email_alarm, $logfile;
  366. mail($email_alarm, "ALARM : API (gen_card_with_alias - CODE_ERROR 8)", $mail_content);
  367. error_log ("[" . date("Y/m/d G:i:s", mktime()) . "] "."[gen_card_with_alias] - CODE_ERROR 8"."\n", 3, $logfile);
  368. echo("500 Internal server error");
  369. exit();
  370. }else{
  371. echo "ERROR : Impossible to generate a Cardnumber & Aliasnumber not yet used!<br>Perhaps check the LEN_CARDNUMBER (value:".LEN_CARDNUMBER.") & LEN_ALIASNUMBER (value:".LEN_ALIASNUMBER.")";
  372. exit();
  373. }
  374. }
  375. $query = "SELECT username FROM ".$table." where username='$card_gen' OR useralias='$alias_gen'";
  376. $numrow = 0;
  377. $resmax = $DBHandle_max -> Execute($query);
  378. if ($resmax)
  379. $numrow = $resmax -> RecordCount( );
  380. if ($numrow!=0) continue;
  381. $arr_val [0] = $card_gen;
  382. $arr_val [1] = $alias_gen;
  383. return $arr_val;
  384. }
  385. }
  386. //Get productID and all parameter and retrieve info for card creation into cc_ecommerce_product
  387. function get_productinfo($DBHandle, $instance_table, $productid, $email_alarm, $mail_content, $logfile){
  388. global $FG_DEBUG;
  389. $QUERY = 'SELECT
  390. product_name, creationdate, description, expirationdate, enableexpire, expiredays, credit, tariff, id_didgroup, activated, simultaccess, currency,
  391. typepaid, creditlimit, language, runservice, sip_friend, iax_friend, cc_ecommerce_product.mailtype, fromemail, fromname, subject, messagetext,
  392. messagehtml
  393. FROM cc_ecommerce_product, cc_templatemail
  394. WHERE cc_ecommerce_product.mailtype=cc_templatemail.mailtype AND id='.$productid;
  395. $result = $instance_table -> SQLExec ($DBHandle, $QUERY);
  396. if ($FG_DEBUG>0){ echo "<br><b>$QUERY</b><br>"; print_r ($result); echo "<hr><br>"; }
  397. if( !is_array($result)){
  398. if ($FG_DEBUG > 0) echo ("get_productinfo ERROR");
  399. mail($email_alarm, "ALARM : API (CODE_ERROR get_productinfo)", $mail_content);
  400. error_log ("[" . date("Y/m/d G:i:s", mktime()) . "] "."CODE_ERROR get_productinfo"."\n", 3, $logfile);
  401. echo("500 Internal server error");
  402. exit();
  403. }
  404. return $result[0];
  405. }
  406. // *********************************
  407. // ONLY USER BY THE OLD FRAME WORK
  408. // *********************************
  409. $lang['strfirst']='&lt;&lt; First';
  410. $lang['strprev']='&lt; Prev';
  411. $lang['strnext']='Next &gt;';
  412. $lang['strlast']='Last &gt;&gt;';
  413. /**
  414. * Do multi-page navigation. Displays the prev, next and page options.
  415. * @param $page the page currently viewed
  416. * @param $pages the maximum number of pages
  417. * @param $url the url to refer to with the page number inserted
  418. * @param $max_width the number of pages to make available at any one time (default = 20)
  419. */
  420. function printPages($page, $pages, $url, $max_width = 20) {
  421. global $lang;
  422. $window = 8;
  423. echo "Old !!" ;
  424. if ($page < 0 || $page > $pages) return;
  425. if ($pages < 0) return;
  426. if ($max_width <= 0) return;
  427. if ($pages > 1) {
  428. //echo "<center><p>\n";
  429. if ($page != 1) {
  430. $temp = str_replace('%s', 1-1, $url);
  431. echo "<a class=\"pagenav\" href=\"{$temp}\">{$lang['strfirst']}</a>\n";
  432. $temp = str_replace('%s', $page - 1-1, $url);
  433. echo "<a class=\"pagenav\" href=\"{$temp}\">{$lang['strprev']}</a>\n";
  434. }
  435. if ($page <= $window) {
  436. $min_page = 1;
  437. $max_page = min(2 * $window, $pages);
  438. }
  439. elseif ($page > $window && $pages >= $page + $window) {
  440. $min_page = ($page - $window) + 1;
  441. $max_page = $page + $window;
  442. }
  443. else {
  444. $min_page = ($page - (2 * $window - ($pages - $page))) + 1;
  445. $max_page = $pages;
  446. }
  447. // Make sure min_page is always at least 1
  448. // and max_page is never greater than $pages
  449. $min_page = max($min_page, 1);
  450. $max_page = min($max_page, $pages);
  451. for ($i = $min_page; $i <= $max_page; $i++) {
  452. $temp = str_replace('%s', $i-1, $url);
  453. if ($i != $page) echo "<a class=\"pagenav\" href=\"{$temp}\">$i</a>\n";
  454. else echo "$i\n";
  455. }
  456. if ($page != $pages) {
  457. $temp = str_replace('%s', $page + 1-1, $url);
  458. echo "<a class=\"pagenav\" href=\"{$temp}\">{$lang['strnext']}</a>\n";
  459. $temp = str_replace('%s', $pages-1, $url);
  460. echo "<a class=\"pagenav\" href=\"{$temp}\">{$lang['strlast']}</a>\n";
  461. }
  462. }
  463. }
  464. /**
  465. * Validate the Uploaded Files. Return the error string if any.
  466. * @param $the_file the file to validate
  467. * @param $the_file_type the file type
  468. */
  469. function validate_upload($the_file, $the_file_type) {
  470. $registered_types = array(
  471. "application/x-gzip-compressed" => ".tar.gz, .tgz",
  472. "application/x-zip-compressed" => ".zip",
  473. "application/x-tar" => ".tar",
  474. "text/plain" => ".html, .php, .txt, .inc (etc)",
  475. "image/bmp" => ".bmp, .ico",
  476. "image/gif" => ".gif",
  477. "image/pjpeg" => ".jpg, .jpeg",
  478. "image/jpeg" => ".jpg, .jpeg",
  479. "image/png" => ".png",
  480. "application/x-shockwave-flash" => ".swf",
  481. "application/msword" => ".doc",
  482. "application/vnd.ms-excel" => ".xls",
  483. "application/octet-stream" => ".exe, .fla (etc)",
  484. "text/x-comma-separated-values" => ".csv"
  485. ); # these are only a few examples, you can find many more!
  486. $allowed_types = array("text/plain", "text/x-comma-separated-values");
  487. $start_error = "\n<b>ERROR:</b>\n<ul>";
  488. $error = "";
  489. if ($the_file=="")
  490. {
  491. $error .= "\n<li>".gettext("File size is greater than allowed limit.")."\n<ul>";
  492. }else
  493. {
  494. if ($the_file == "none") {
  495. $error .= "\n<li>".gettext("You did not upload anything!")."</li>";
  496. }
  497. elseif ($_FILES['the_file']['size'] == 0)
  498. {
  499. $error .= "\n<li>".gettext("Failed to upload the file, The file you uploaded may not exist on disk.")."!</li>";
  500. }
  501. else
  502. {
  503. if (!in_array($the_file_type,$allowed_types))
  504. {
  505. $error .= "\n<li>".gettext("file type is not allowed")."\n<ul>";
  506. while ($type = current($allowed_types))
  507. {
  508. $error .= "\n<li>" . $registered_types[$type] . " (" . $type . ")</li>";
  509. next($allowed_types);
  510. }
  511. $error .= "\n</ul>";
  512. }
  513. }
  514. }
  515. if ($error)
  516. {
  517. $error = $start_error . $error . "\n</ul>";
  518. return $error;
  519. }
  520. else
  521. {
  522. return false;
  523. }
  524. } # END validate_upload
  525. /** Calculate arguments in a string of the form "Test %1 or %4 .."
  526. This function is carefully written, so that it could be used securely, for
  527. example, when 'eval(string_param(" echo %&0",array( $dangerous_str)))' is called.
  528. That is, we have some special prefixes:
  529. %#x means the x-th parameter as a number, 0 if nan
  530. %&x means the x-th parameter as a quoted string
  531. %% will become '%', as will %X where X not [1-9a-z]
  532. @param $str The input string
  533. @param $parm_arr An array with the parameters, so %1 will become $parm_arr[1]
  534. @param $noffset The offset of the param. noffset=1 means %1 = $parm_arr[0],
  535. noffset=-2 means %0 = $parm_arr[2]
  536. @note This fn won't work for more than 10 params!
  537. */
  538. function str_params($str, $parm_arr, $noffset = 0){
  539. $strlen=strlen($str);
  540. $strp=0;
  541. $stro=0;
  542. $resstr='';
  543. do{
  544. $strp=strpos($str,"%",$stro);
  545. if($strp===false){
  546. $resstr=$resstr . substr($str,$stro);
  547. break;
  548. }
  549. $resstr=$resstr . substr($str,$stro,$strp-$stro);
  550. $strp++;
  551. if ($strp>=$strlen)
  552. break;
  553. $sm=0;
  554. if ($str[$strp] == '#'){
  555. $sm=1;
  556. $strp++;
  557. }
  558. else if ($str[$strp] =='&'){
  559. $sm=2;
  560. $strp++;
  561. }
  562. if (( $str[$strp]>='0') && ( $str[$strp]<='9')){
  563. $pv=$str{$strp} - '0';
  564. // echo "Var %$pv\n";
  565. if (isset($parm_arr[$pv - $noffset]))
  566. $v = $parm_arr[$pv - $noffset];
  567. else $v = '';
  568. if ($sm==1)
  569. $v = (integer) $v;
  570. else if ($sm == 2)
  571. $v = addslashes($v);
  572. $resstr= $resstr . $v;
  573. }else
  574. $resstr= $resstr . $str[$strp];
  575. $stro=$strp+1;
  576. }while ($stro<$strlen);
  577. return $resstr;
  578. }
  579. /** Calculate arguments in a string of the form "Test %1 or %4 .."
  580. This function is intended for database usage:
  581. eg. str_dbparams(dbh,"SELECT %1 , %2 ; ", array("me", "'DROP DATABASE sql_inject;'"));
  582. will result in "SELECT 'me', '''DROP DATABASE sql_inject;''' ;" which is safe!
  583. %#x means the x-th parameter as a number, 0 if nan
  584. Additionaly, parms in the form %!3 will result in "NULL" when parm is empty.
  585. @param $str The input string, say, the sql command
  586. @param $parm_arr An array with the parameters, so %1 will become $parm_arr[0]
  587. @param $dbh the db handle
  588. @note This fn won't work for more than 10 params!
  589. */
  590. function str_dbparams($dbh, $str, $parm_arr){
  591. $strlen=strlen($str);
  592. $strp=0;
  593. $stro=0;
  594. $resstr='';
  595. do{
  596. $strp=strpos($str,"%",$stro);
  597. if($strp===false){
  598. $resstr=$resstr . substr($str,$stro);
  599. break;
  600. }
  601. $resstr=$resstr . substr($str,$stro,$strp-$stro);
  602. $strp++;
  603. if ($strp>=$strlen)
  604. break;
  605. $sm=0;
  606. if ($str[$strp] == '!'){
  607. $sm=1;
  608. $strp++;
  609. }else
  610. if ($str[$strp] == '#'){
  611. $sm=2;
  612. $strp++;
  613. }
  614. if (( $str[$strp]>='0') && ( $str[$strp]<='9')){
  615. $pv=$str{$strp} - '0';
  616. // echo "Var %$pv\n";
  617. $v= null;
  618. if (isset($parm_arr[$pv - 1]))
  619. $v = $parm_arr[$pv - 1];
  620. if ($sm==1) {
  621. if ($v == '') $v = null;
  622. if ($v == null)
  623. $resstr .= 'NULL';
  624. else
  625. $resstr .= $dbh->Quote($v);
  626. } else if ($sm ==2) {
  627. if ($v == '')
  628. $v = null;
  629. if ($v == null)
  630. $resstr .= '0';
  631. elseif (preg_match('/^\-?[0-9]+([,.][0-9]*)?$/',$v)>=1)
  632. $resstr .= $v;
  633. else
  634. $resstr .= '0';
  635. }
  636. else {
  637. if ($v == null) $v = '';
  638. $resstr .= $dbh->Quote($v);
  639. }
  640. }else
  641. $resstr .= $str[$strp];
  642. $stro=$strp+1;
  643. }while ($stro<$strlen);
  644. return $resstr;
  645. }
  646. /** Calculate arguments in a string of the form "Test %var or %id .."
  647. This function is carefully written, so that it could be used securely, for
  648. example, when 'eval(string_param(" echo %&str",array( $dangerous_str)))' is called.
  649. That is, we have some special prefixes:
  650. %#x means the x parameter as a number, 0 if nan
  651. %&x means the x parameter as a quoted string
  652. %@x means the x parameter must be html-escaped
  653. %% will become '%', as will %X where X not [1-9a-z]
  654. @param $str The input string
  655. @param $parm_arr An array with the parameters, so %id will become $parm_arr['id']
  656. @note The param name can contain alphanumeric, '_' . The name terminates at non-alpha.
  657. */
  658. function str_alparams($str, $parm_arr, $noffset = 0){
  659. $strlen=strlen($str);
  660. $strp=0;
  661. $stro=0;
  662. $resstr='';
  663. do{
  664. $strp=strpos($str,"%",$stro);
  665. if($strp===false){
  666. $resstr=$resstr . substr($str,$stro);
  667. break;
  668. }
  669. $resstr=$resstr . substr($str,$stro,$strp-$stro);
  670. $strp++;
  671. if ($strp>=$strlen)
  672. break;
  673. $sm=0;
  674. if ($str[$strp] == '#'){
  675. $sm=1;
  676. $strp++;
  677. }
  678. else if ($str[$strp] =='&'){
  679. $sm=2;
  680. $strp++;
  681. }
  682. else if ($str[$strp] =='@'){
  683. $sm=3;
  684. $strp++;
  685. }
  686. for ($stre=$strp ; ($stre<$strlen) && (($str[$stre] == '_' )|| ctype_alnum($str[$stre]));$stre++);
  687. if ($stre>$strp){
  688. $pv=substr($str,$strp,$stre-$strp);
  689. if (isset($parm_arr[$pv]))
  690. $v = $parm_arr[$pv];
  691. else $v = '';
  692. if ($sm==1)
  693. $v = (integer) $v;
  694. elseif ($sm == 2)
  695. $v = addslashes($v);
  696. elseif ($sm == 3)
  697. $v = nl2br(htmlspecialchars($v));
  698. $resstr= $resstr . $v;
  699. }else {
  700. $resstr= $resstr . $str[$strp];
  701. $stre++;
  702. }
  703. $stro=$stre;
  704. }while ($stro<$strlen);
  705. return $resstr;
  706. }
  707. function str_aldbparams(&$dbh,$str, $parm_arr){
  708. $strlen=strlen($str);
  709. $strp=0;
  710. $stro=0;
  711. $resstr='';
  712. do{
  713. $strp=strpos($str,"%",$stro);
  714. if($strp===false){
  715. $resstr=$resstr . substr($str,$stro);
  716. break;
  717. }
  718. $resstr=$resstr . substr($str,$stro,$strp-$stro);
  719. $strp++;
  720. if ($strp>=$strlen)
  721. break;
  722. $sm=0;
  723. if ($str[$strp] == '!'){
  724. $sm=1;
  725. $strp++;
  726. }
  727. else if ($str[$strp] =='#'){
  728. $sm=2;
  729. $strp++;
  730. }
  731. for ($stre=$strp ; ($stre<$strlen) && (($str[$stre] == '_' )|| ctype_alnum($str[$stre]));$stre++);
  732. if ($stre>$strp){
  733. $pv=substr($str,$strp,$stre-$strp);
  734. if (isset($parm_arr[$pv]))
  735. $v = $parm_arr[$pv];
  736. else $v = '';
  737. if ($sm==1) {
  738. if ($v == '') $v = null;
  739. if ($v == null)
  740. $resstr .= 'NULL';
  741. else
  742. $resstr .= $dbh->Quote($v);
  743. } else if ($sm ==2) {
  744. if ($v == '')
  745. $v = null;
  746. if ($v == null)
  747. $resstr .= '0';
  748. elseif (preg_match('/^\-?[0-9]+$/',$v)>=1)
  749. $resstr .= $v;
  750. else
  751. $resstr .= '0';
  752. }
  753. else {
  754. if ($v == null) $v = '';
  755. $resstr .= $dbh->Quote($v);
  756. }
  757. }else {
  758. $resstr= $resstr . $str[$strp];
  759. $stre++;
  760. }
  761. $stro=$stre;
  762. }while ($stro<$strlen);
  763. return $resstr;
  764. }
  765. /** For code clarity only: it will produce the string for an &lt;acronym&gt; element
  766. @param acr The acronym, the short one
  767. @param title the explanation (usually a hint)
  768. */
  769. function acronym($acr, $title){
  770. $res ="<acronym title=\"";
  771. $res .= $title;
  772. $res .= "\" >";
  773. $res .= $acr;
  774. $res .= "</acronym>";
  775. return $res;
  776. }
  777. /** Format a where clause, based on the date selection table.
  778. The selection parameters are automatically got from the _GET/_POST
  779. \param col The table column to check the dates against.
  780. \note Postgres only!
  781. */
  782. function fmt_dateclause($dbhandle, $col){
  783. global $Period, $frommonth, $fromstatsmonth, $tomonth, $tostatsmonth, $fromday, $fromstatsday_sday, $fromstatsmonth_sday, $today, $tostatsday_sday, $tostatsmonth_sday, $fromstatsmonth_sday, $fromstatsmonth_shour, $tostatsmonth_sday, $tostatsmonth_shour, $fromstatsmonth_smin, $tostatsmonth_smin;
  784. $date_clauses = array();
  785. if ($Period == "Month"){
  786. if ($frommonth && isset($fromstatsmonth))
  787. $date_clauses[] ="$col >= timestamptz " .
  788. $dbhandle->Quote($fromstatsmonth."-01");
  789. if ($tomonth && isset($tostatsmonth))
  790. $date_clauses[] ="date_trunc('month', $col) <= timestamptz " . $dbhandle->Quote( $tostatsmonth."-01");
  791. }elseif ($Period == "Day") {
  792. //echo "Day!" ;
  793. //echo "From: $fromday $fromstatsday_sday,$fromstatsmonth_sday, $fromstatsmonth_shour, $fromstatsmonth_smin <br>\n";
  794. if ($fromday && isset($fromstatsday_sday) && isset($fromstatsmonth_sday) && isset($fromstatsmonth_shour) && isset($fromstatsmonth_smin) )
  795. $date_clauses[]= "$col >= timestamptz " .
  796. $dbhandle->Quote( $fromstatsmonth_sday. "-".$fromstatsday_sday. " " . $fromstatsmonth_shour.":". $fromstatsmonth_smin);
  797. if ($today&& isset($tostatsday_sday) && isset($tostatsmonth_sday) && isset($tostatsmonth_shour) && isset($tostatsmonth_smin))
  798. $date_clauses[] =" $col <= timestamptz ". $dbhandle->Quote(sprintf("%12s-%02d %02d:%02d",
  799. $tostatsmonth_sday, intval($tostatsday_sday), intval($tostatsmonth_shour), intval($tostatsmonth_smin)));
  800. }
  801. // if other period, no date_clause!
  802. return implode(" AND ",$date_clauses);
  803. }
  804. /** A companion to fmt_dateclause: find the clause for items \b before the
  805. date clause. This is useful for the sums carried to our interval */
  806. function fmt_dateclause_c($dbhandle, $col){
  807. global $Period, $frommonth, $fromstatsmonth, $fromday, $fromstatsday_sday, $fromstatsmonth_sday,$fromstatsmonth_sday, $fromstatsmonth_shour, $fromstatsmonth_smin;
  808. $date_clause = "";
  809. if ($Period == "Month"){
  810. if ($frommonth && isset($fromstatsmonth))
  811. $date_clause ="$col < timestamptz " .
  812. $dbhandle->Quote($fromstatsmonth."-01");
  813. }elseif ($Period == "Day") {
  814. if ($fromday && isset($fromstatsday_sday) && isset($fromstatsmonth_sday) && isset($fromstatsmonth_shour) && isset($fromstatsmonth_smin) )
  815. $date_clause = "$col < timestamptz " .
  816. $dbhandle->Quote( $fromstatsmonth_sday. "-".$fromstatsday_sday. " " . $fromstatsmonth_shour.":". $fromstatsmonth_smin);
  817. }
  818. // if other period, no date_clause!
  819. return $date_clause;
  820. }
  821. function sql_encodeArray($DBHandle,$arr_data){
  822. $tmp_arr = array();
  823. foreach($arr_data as $data)
  824. if (is_numeric($data))
  825. $tmp_arr[] = (string) $data;
  826. else
  827. $tmp_arr[] = $DBHandle->Quote($data);
  828. if (!count($tmp_arr))
  829. return 'NULL';
  830. return 'ARRAY[' . implode(', ', $tmp_arr) . ']';
  831. }
  832. function sql_decodeArray($arr_str){
  833. if (!is_string($arr_str))
  834. return array();
  835. $len = strlen($arr_str)-1;
  836. if (($arr_str[0] != '{' ) || ($arr_str[$len] != '}'))
  837. return array();
  838. //$a=1;
  839. $b=1;
  840. $ret_array=array();
  841. while($b<=$len){
  842. $tmp_str='';
  843. for(;($b<$len) && ($arr_str[$b] == ' ');$b++);
  844. if ($arr_str[$b] =='"'){
  845. for($b=$b+1;($b<$len) && ($arr_str[$b]!='"');$b++)
  846. $tmp_str.=$arr_str[$b];
  847. $b++;
  848. }
  849. for(;($b<$len) &&($arr_str[$b]!=',');$b++)
  850. $tmp_str.=$arr_str[$b];
  851. $b++;
  852. $ret_array[]=$tmp_str;
  853. }
  854. return $ret_array;
  855. }
  856. function securitykey ($key, $data)
  857. {
  858. // RFC 2104 HMAC implementation for php.
  859. // Creates an md5 HMAC.
  860. // Eliminates the need to install mhash to compute a HMAC
  861. // Hacked by Lance Rushing
  862. $b = 64; // byte length for md5
  863. if (strlen($key) > $b) {
  864. $key = pack("H*",md5($key));
  865. }
  866. $key = str_pad($key, $b, chr(0x00));
  867. $ipad = str_pad('', $b, chr(0x36));
  868. $opad = str_pad('', $b, chr(0x5c));
  869. $k_ipad = $key ^ $ipad ;
  870. $k_opad = $key ^ $opad;
  871. return md5($k_opad . pack("H*",md5($k_ipad . $data)));
  872. }
  873. /*
  874. Function to show GMT DateTime.
  875. */
  876. function get_timezones($handle = null)
  877. {
  878. if (empty($handle)){
  879. $handle = DbConnect();
  880. }
  881. $instance_table = new Table();
  882. $QUERY = "SELECT id, gmttime, gmtzone from cc_timezone order by id";
  883. $result = $instance_table -> SQLExec ($handle, $QUERY);
  884. if (is_array($result)){
  885. $num_cur = count($result);
  886. for ($i=0;$i<$num_cur;$i++){
  887. $timezone_list[$result[$i][0]] = array (1 => $result[$i][1], 2 => $result[$i][2]);
  888. }
  889. }
  890. return $timezone_list;
  891. }
  892. function display_GMT($currDate, $number, $fulldate = 1)
  893. {
  894. $date_time_array = getdate(strtotime($currDate));
  895. $hours = $date_time_array['hours'];
  896. $minutes = $date_time_array['minutes'];
  897. $seconds = $date_time_array['seconds'];
  898. $month = $date_time_array['mon'];
  899. $day = $date_time_array['mday'];
  900. $year = $date_time_array['year'];
  901. $timestamp = mktime($hours, $minutes, $seconds, $month, $day, $year);
  902. if ($number < 0){ $timestamp = $timestamp -($number); }
  903. else { $timestamp = $timestamp +($number);}
  904. if($fulldate == 1)
  905. {
  906. $gmdate = gmdate("m/d/Y h:i:s A", $timestamp);
  907. }
  908. else
  909. {
  910. $gmdate = gmdate("m/d/Y", $timestamp);
  911. }
  912. return $gmdate;
  913. }
  914. /*
  915. * Following fuctions return the latest title to add as
  916. * agi-conf(title_number) for Global configurations and List of confiurations
  917. * Tables : cc_confi_group
  918. * Operations : SELECT
  919. *
  920. */
  921. function agi_confx_title($handle=null)
  922. {
  923. if (empty($handle)){
  924. $handle = DbConnect();
  925. }
  926. $instance_table = new Table();
  927. $QUERY = "SELECT id,group_title,group_description from cc_config_group where group_title like '%agi-conf%' order by group_title";
  928. $result = $instance_table -> SQLExec ($handle, $QUERY);
  929. if (is_array($result)) {
  930. $num_cur = count($result);
  931. for ($i=0;$i<$num_cur;$i++) {
  932. $config_group_id = $result[0][0];
  933. $group_title[] = $result[$i][1];
  934. $description = $result[0][2];
  935. }
  936. }
  937. foreach($group_title as $value) {
  938. $agi_number[] = (int)substr($value, -1);
  939. }
  940. $len_agi_array = sizeof($agi_number);
  941. $agi_conf_number = $len_agi_array + 1;
  942. for($i=1; $i <= $len_agi_array; $i++) {
  943. if ($i != $agi_number[$i - 1]) {
  944. $agi_conf_number = $i;
  945. break;
  946. }
  947. }
  948. $config_group = array();
  949. $config_group[0] = "agi-conf".$agi_conf_number;
  950. $config_group[1] = $config_group_id;
  951. $config_group[2] = $description;
  952. return $config_group;
  953. }
  954. /*
  955. * Following function will generate agi-confx,
  956. * Duplicate all the configurations of agi-conf1 and produce agi-confx
  957. * Subquery is also used in this function to improve functional response.
  958. * Operations : SELECT , INSERT
  959. * Tables : cc_config, cc_config_group
  960. */
  961. function add_agi_confx($handle = null)
  962. {
  963. if (empty($handle)){
  964. $handle = DbConnect();
  965. }
  966. $instance_table = new Table();
  967. $config_group = array();
  968. $config_group = agi_confx_title(); // calling function to generate agi-conf(title_number)
  969. $group_title = $config_group[0];
  970. $config_group_id = $config_group[1];
  971. $description = $config_group[2];
  972. $value = "'$group_title','$description'";
  973. $func_fields = "group_title,group_description";
  974. $func_table = 'cc_config_group';
  975. $id_name = "id";
  976. $inserted_id = $instance_table -> Add_table ($handle, $value, $func_fields, $func_table, $id_name);
  977. $value = "SELECT config_title,config_key,config_value,config_description,config_valuetype,$inserted_id,config_listvalues FROM cc_config WHERE config_group_id = $config_group_id";
  978. $func_fields = "config_title,config_key,config_value,config_description,config_valuetype,config_group_id,config_listvalues";
  979. $func_table = 'cc_config';
  980. $id_name = "";
  981. $subquery = true;
  982. $result = $instance_table -> Add_table ($handle, $value, $func_fields, $func_table, $id_name,$subquery);
  983. return $inserted_id;
  984. }
  985. /*
  986. * This function delete agi-confx, all its global configurations and list of configurations
  987. * Operations : DELETE
  988. * Tables : cc_config, cc_config_group
  989. */
  990. function delete_agi_confx($id_agi)
  991. {
  992. if (empty($handle)){
  993. $handle = DbConnect();
  994. }
  995. $instance_table = new Table();
  996. $clause = "id = $id_agi";
  997. $fun_table = "cc_config_group";
  998. $result = $instance_table -> Delete_table ($handle, $clause, $fun_table);
  999. $clause = "config_group_id = $id_agi";
  1000. $fun_table = "cc_config";
  1001. $result = $instance_table -> Delete_table ($handle, $clause, $fun_table);
  1002. return $result;
  1003. }
  1004. function check_translated($id, $languages)
  1005. {
  1006. if (empty($handle)){
  1007. $handle = DbConnect();
  1008. }
  1009. $instance_table = new Table();
  1010. $QUERY = "SELECT id from cc_templatemail where id = $id and id_language = '$languages'";
  1011. $result = $instance_table -> SQLExec ($handle, $QUERY);
  1012. if (is_array($result)){
  1013. if(count($result) > 0)
  1014. return true;
  1015. else
  1016. return false;
  1017. }else{
  1018. return false;
  1019. }
  1020. }
  1021. function update_translation($id, $languages, $subject, $mailtext)
  1022. {
  1023. if (empty($handle)){
  1024. $handle = DbConnect();
  1025. }
  1026. $instance_table = new Table();
  1027. $param_update = "subject = '$subject', messagetext = '$mailtext'";
  1028. $clause = "id = $id and id_language = '$languages'";
  1029. $func_table = 'cc_templatemail';
  1030. $update = $instance_table -> Update_table ($handle, $param_update, $clause, $func_table);
  1031. return $update;
  1032. }
  1033. function insert_translation($id, $languages, $subject, $mailtext)
  1034. {
  1035. if (empty($handle)){
  1036. $handle = DbConnect();
  1037. }
  1038. $instance_table = new Table();
  1039. $fromemail = '';
  1040. $fromname = '';
  1041. $mailtype = '';
  1042. $QUERY = "SELECT fromemail,fromname,mailtype from cc_templatemail where id = $id and id_language = 'en'";
  1043. $result = $instance_table -> SQLExec ($handle, $QUERY);
  1044. if (is_array($result)) {
  1045. if(count($result) > 0){
  1046. $fromemail = $result[0][0];
  1047. $fromname = $result[0][1];
  1048. $mailtype = $result[0][2];
  1049. }
  1050. }
  1051. $value = "$id, '$languages', '$subject', '$mailtext', '$mailtype','$fromemail','$fromname'";
  1052. $func_fields = "id,id_language,subject,messagetext,mailtype,fromemail,fromname";
  1053. $func_table = 'cc_templatemail';
  1054. $id_name = "";
  1055. $inserted = $instance_table -> Add_table ($handle, $value, $func_fields, $func_table, $id_name);
  1056. return $inserted;
  1057. }
  1058. function mailtemplate_latest_id()
  1059. {
  1060. if (empty($handle)){
  1061. $handle = DbConnect();
  1062. }
  1063. $instance_table = new Table();
  1064. $QUERY = "SELECT max(id) as latest_id from cc_templatemail where id_language = 'en'";
  1065. $result = $instance_table -> SQLExec ($handle, $QUERY);
  1066. $result[0][0] = $result[0][0] + 1;
  1067. return $result[0][0];
  1068. }
  1069. /*
  1070. * Function use to archive data and call records
  1071. * Insert in cc_call_archive and cc_card_archive on seletion criteria
  1072. * Delete from cc_call and cc_card
  1073. * Used in
  1074. * 1. A2Billing_UI/Public/A2B_data_archving.php
  1075. * 2. A2Billing_UI/Public/A2B_call_archiving.php
  1076. */
  1077. function archive_data($condition, $entity = ""){
  1078. if(empty($condition)){
  1079. return 0;
  1080. exit;
  1081. }
  1082. $handle = DbConnect();
  1083. $instance_table = new Table();
  1084. if(!empty($entity)) {
  1085. if($entity == "card") {
  1086. $value = "SELECT id, creationdate, firstusedate, expirationdate, enableexpire, expiredays, username, useralias, uipass, credit, tariff, id_didgroup, activated, status, lastname, firstname, address, city, state, country, zipcode, phone, email,fax, inuse, simultaccess, currency, lastuse,nbused, typepaid, creditlimit, voipcall, sip_buddy, iax_buddy, language, redial, runservice, nbservice, id_campaign, num_trials_done, callback, vat, servicelastrun, initialbalance, invoiceday,autorefill, loginkey, activatedbyuser, mac_addr, id_timezone, tag, template_invoice, template_outstanding FROM cc_card $condition";
  1087. $func_fields = "id, creationdate, firstusedate, expirationdate, enableexpire, expiredays, username, useralias, uipass, credit, tariff, id_didgroup, activated, status, lastname, firstname, address, city, state, country, zipcode, phone, email,fax, inuse, simultaccess, currency, lastuse,nbused, typepaid, creditlimit, voipcall, sip_buddy, iax_buddy, language, redial, runservice, nbservice, id_campaign, num_trials_done, callback, vat, servicelastrun, initialbalance, invoiceday,autorefill, loginkey, activatedbyuser, mac_addr, id_timezone, tag, template_invoice, template_outstanding";
  1088. $func_table = 'cc_card_archive';
  1089. $id_name = "";
  1090. $subquery = true;
  1091. $result = $instance_table -> Add_table ($handle, $value, $func_fields, $func_table, $id_name,$subquery);
  1092. $fun_table = "cc_card";
  1093. if (strpos($condition,'WHERE') > 0){
  1094. $condition = str_replace("WHERE", "", $condition);
  1095. }
  1096. $result = $instance_table -> Delete_table ($handle, $condition, $fun_table);
  1097. } else if($entity == "call") {
  1098. $value = "SELECT id, sessionid,uniqueid,username,nasipaddress,starttime,stoptime,sessiontime,calledstation,startdelay,stopdelay,terminatecause,usertariff,calledprovider,calledcountry,calledsub,calledrate,sessionbill,destination,id_tariffgroup,id_tariffplan,id_ratecard,id_trunk,sipiax,src,id_did,buyrate,buycost,id_card_package_offer,real_sessiontime FROM cc_call $condition";
  1099. $func_fields = "id, sessionid,uniqueid,username,nasipaddress,starttime,stoptime,sessiontime,calledstation,startdelay,stopdelay,terminatecause,usertariff,calledprovider,calledcountry,calledsub,calledrate,sessionbill,destination,id_tariffgroup,id_tariffplan,id_ratecard,id_trunk,sipiax,src,id_did,buyrate,buycost,id_card_package_offer,real_sessiontime";
  1100. $func_table = 'cc_call_archive';
  1101. $id_name = "";
  1102. $subquery = true;
  1103. $result = $instance_table -> Add_table ($handle, $value, $func_fields, $func_table, $id_name,$subquery);
  1104. if (strpos($condition,'WHERE') > 0){
  1105. $condition = str_replace("WHERE", "", $condition);
  1106. }
  1107. $fun_table = "cc_call";
  1108. $result = $instance_table -> Delete_table ($handle, $condition, $fun_table);
  1109. }
  1110. }
  1111. return 1;
  1112. }
  1113. /*
  1114. * Function use to define exact sql statement for
  1115. * different criteria selection
  1116. */
  1117. function do_field($sql,$fld,$dbfld){
  1118. $fldtype = $fld.'type';
  1119. global $$fld;
  1120. global $$fldtype;
  1121. if ($$fld){
  1122. if (strpos($sql,'WHERE') > 0){
  1123. $sql = "$sql AND ";
  1124. }else{
  1125. $sql = "$sql WHERE ";
  1126. }
  1127. $sql = "$sql $dbfld";
  1128. if (isset ($$fldtype)){
  1129. switch ($$fldtype) {
  1130. case 1: $sql = "$sql='".$$fld."'"; break;
  1131. case 2: $sql = "$sql LIKE '".$$fld."%'"; break;
  1132. case 3: $sql = "$sql LIKE '%".$$fld."%'"; break;
  1133. case 4: $sql = "$sql LIKE '%".$$fld."'";
  1134. }
  1135. }else{ $sql = "$sql LIKE '%".$$fld."%'"; }
  1136. }
  1137. return $sql;
  1138. }
  1139. function arguments($argv) {
  1140. $_ARG = array();
  1141. array_shift($argv); //skip argv[0] !
  1142. foreach ($argv as $arg) {
  1143. if (preg_match('/--([^=]+)=(.*)/',$arg,$reg)) {
  1144. $_ARG[$reg[1]] = $reg[2];
  1145. } elseif(preg_match('/--([^=]+)/',$arg,$reg)){
  1146. $_ARG[$reg[1]] = true;
  1147. } elseif(preg_match('/^-([a-zA-Z0-9])/',$arg,$reg)) {
  1148. $_ARG[$reg[1]] = true;
  1149. } else {
  1150. $_ARG['input'][]=$arg;
  1151. }
  1152. }
  1153. return $_ARG;
  1154. }
  1155. ?>