PageRenderTime 102ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 1ms

/phpfn6.php

https://github.com/fredd-for/emaus_tesoreria
PHP | 3668 lines | 3052 code | 282 blank | 334 comment | 622 complexity | 68c545dfd046f4f3af2cd28c10ce4523 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * PHPMaker Common classes and functions
  4. * (C) 2002-2008 e.World Technology Limited. All rights reserved.
  5. */
  6. /**
  7. * Functions to init arrays
  8. */
  9. function ew_InitArray($iLen, $vValue) {
  10. if (function_exists('array_fill')) { // PHP 4 >= 4.2.0,
  11. return array_fill(0, $iLen, $vValue);
  12. } else {
  13. $aResult = array();
  14. for ($iCount = 0; $iCount < $iLen; $iCount++)
  15. $aResult[] = $vValue;
  16. return $aResult;
  17. }
  18. }
  19. function ew_Init2DArray($iLen1, $iLen2, $vValue) {
  20. return ew_InitArray($iLen1, ew_InitArray($iLen2, $vValue));
  21. }
  22. /**
  23. * Functions for converting encoding
  24. */
  25. function ew_ConvertToUtf8($str) {
  26. return ew_Convert(EW_ENCODING, "UTF-8", $str);
  27. }
  28. function ew_ConvertFromUtf8($str) {
  29. return ew_Convert("UTF-8", EW_ENCODING, $str);
  30. }
  31. function ew_Convert($from, $to, $str)
  32. {
  33. if ($from != "" && $to != "" && $from != $to) {
  34. if (function_exists("iconv")) {
  35. return iconv($from, $to, $str);
  36. } elseif (function_exists("mb_convert_encoding")) {
  37. return mb_convert_encoding($str, $to, $from);
  38. } else {
  39. return $str;
  40. }
  41. } else {
  42. return $str;
  43. }
  44. }
  45. /**
  46. * XML document class
  47. */
  48. class cXMLDocument {
  49. var $Encoding = EW_XML_ENCODING;
  50. var $RootTagName;
  51. var $RowTagName;
  52. var $XmlDoc;
  53. var $XmlTbl;
  54. var $XmlRow;
  55. var $XML = '';
  56. var $NullValue = 'NULL';
  57. function cXMLDocument($roottagname = 'table') {
  58. $this->RootTagName = $roottagname;
  59. if (EW_IS_PHP5) {
  60. $this->XmlDoc = new DOMDocument("1.0", $this->Encoding);
  61. $this->XmlTbl = $this->XmlDoc->createElement($this->RootTagName);
  62. $this->XmlDoc->appendChild($this->XmlTbl);
  63. }
  64. }
  65. function BeginRow($rowtagname = 'row') {
  66. $this->RowTagName = $rowtagname;
  67. if (EW_IS_PHP5) {
  68. $this->XmlRow = $this->XmlDoc->createElement($this->RowTagName);
  69. $this->XmlTbl->appendChild($this->XmlRow);
  70. } else {
  71. $this->XML .= "<$this->RowTagName>";
  72. }
  73. }
  74. function EndRow() {
  75. if (!EW_IS_PHP5) {
  76. $this->XML .= "</$this->RowTagName>";
  77. }
  78. }
  79. function AddField($name, $value) {
  80. if (is_null($value)) $value = $this->NullValue;
  81. if (EW_IS_PHP5) {
  82. $value = ew_ConvertToUtf8($value); // Convert to UTF-8
  83. $xmlfld = $this->XmlDoc->createElement($name);
  84. $this->XmlRow->appendChild($xmlfld);
  85. $xmlfld->appendChild($this->XmlDoc->createTextNode($value));
  86. } else {
  87. $value = ew_Convert(EW_ENCODING, EW_XML_ENCODING, $value); // Convert to output encoding
  88. $this->XML .= "<$name>" . htmlspecialchars($value) . "</$name>";
  89. }
  90. }
  91. function XML() {
  92. if (EW_IS_PHP5) {
  93. return $this->XmlDoc->saveXML();
  94. } else {
  95. return "<?xml version=\"1.0\"". (($this->Encoding <> "") ? " encoding=\"$this->Encoding\"" : "") .
  96. " ?>\n<$this->RootTagName>$this->XML</$this->RootTagName>";
  97. }
  98. }
  99. }
  100. /**
  101. * QueryString class
  102. */
  103. class cQueryString {
  104. var $values = array();
  105. var $Count;
  106. function cQueryString() {
  107. $ar = explode("&", ew_ServerVar("QUERY_STRING"));
  108. foreach ($ar as $p) {
  109. $arp = explode("=", $p);
  110. if (count($arp) == 2) $this->values[urldecode($arp[0])] = $arp[1];
  111. }
  112. $this->Count = count($this->values);
  113. }
  114. function getValue($name) {
  115. return (array_key_exists($name, $this->values)) ? $this->values[$name] : "";
  116. }
  117. function getUrlDecodedValue($name) {
  118. return urldecode($this->getValue($name));
  119. }
  120. function getRawUrlDecodedValue($name) {
  121. return rawurldecode($this->getValue($name));
  122. }
  123. function getConvertedValue($name) {
  124. return ew_ConvertFromUtf8($this->getRawUrlDecodedValue($name));
  125. }
  126. }
  127. /**
  128. * Email class
  129. */
  130. class cEmail {
  131. // Class properties
  132. var $Sender; // Sender
  133. var $Recipient; // Recipient
  134. var $Cc; // Cc
  135. var $Bcc; // Bcc
  136. var $Subject; // Subject
  137. var $Format; // Format
  138. var $Content; // Content
  139. function cEmail() {
  140. $this->Sender = "";
  141. $this->Recipient = "";
  142. $this->Cc = "";
  143. $this->Bcc = "";
  144. $this->Subject = "";
  145. $this->Format = "";
  146. $this->Content = "";
  147. }
  148. // Method to load email from template
  149. function Load($fn) {
  150. $fn = ew_ScriptFolder() . EW_PATH_DELIMITER . $fn;
  151. $sWrk = ew_ReadFile($fn); // Load text file content
  152. if ($sWrk <> "") {
  153. // Locate Header & Mail Content
  154. if (EW_IS_WINDOWS) {
  155. $i = strpos($sWrk, "\r\n\r\n");
  156. } else {
  157. $i = strpos($sWrk, "\n\n");
  158. if ($i === FALSE) $i = strpos($sWrk, "\r\n\r\n");
  159. }
  160. if ($i > 0) {
  161. $sHeader = substr($sWrk, 0, $i);
  162. $this->Content = trim(substr($sWrk, $i, strlen($sWrk)));
  163. if (EW_IS_WINDOWS) {
  164. $arrHeader = explode("\r\n", $sHeader);
  165. } else {
  166. $arrHeader = explode("\n", $sHeader);
  167. }
  168. for ($j = 0; $j < count($arrHeader); $j++) {
  169. $i = strpos($arrHeader[$j], ":");
  170. if ($i > 0) {
  171. $sName = trim(substr($arrHeader[$j], 0, $i));
  172. $sValue = trim(substr($arrHeader[$j], $i+1, strlen($arrHeader[$j])));
  173. switch (strtolower($sName))
  174. {
  175. case "subject":
  176. $this->Subject = $sValue;
  177. break;
  178. case "from":
  179. $this->Sender = $sValue;
  180. break;
  181. case "to":
  182. $this->Recipient = $sValue;
  183. break;
  184. case "cc":
  185. $this->Cc = $sValue;
  186. break;
  187. case "bcc":
  188. $this->Bcc = $sValue;
  189. break;
  190. case "format":
  191. $this->Format = $sValue;
  192. break;
  193. }
  194. }
  195. }
  196. }
  197. }
  198. }
  199. // Method to replace sender
  200. function ReplaceSender($ASender) {
  201. $this->Sender = str_replace('<!--$From-->', $ASender, $this->Sender);
  202. }
  203. // Method to replace recipient
  204. function ReplaceRecipient($ARecipient) {
  205. $this->Recipient = str_replace('<!--$To-->', $ARecipient, $this->Recipient);
  206. }
  207. // Method to add Cc email
  208. function AddCc($ACc) {
  209. if ($ACc <> "") {
  210. if ($this->Cc <> "") $this->Cc .= ";";
  211. $this->Cc .= $ACc;
  212. }
  213. }
  214. // Method to add Bcc email
  215. function AddBcc($ABcc) {
  216. if ($ABcc <> "") {
  217. if ($this->Bcc <> "") $this->Bcc .= ";";
  218. $this->Bcc .= $ABcc;
  219. }
  220. }
  221. // Method to replace subject
  222. function ReplaceSubject($ASubject) {
  223. $this->Subject = str_replace('<!--$Subject-->', $ASubject, $this->Subject);
  224. }
  225. // Method to replace content
  226. function ReplaceContent($Find, $ReplaceWith) {
  227. $this->Content = str_replace($Find, $ReplaceWith, $this->Content);
  228. }
  229. // Method to send email
  230. function Send() {
  231. return ew_SendEmail($this->Sender, $this->Recipient, $this->Cc, $this->Bcc,
  232. $this->Subject, $this->Content, $this->Format);
  233. }
  234. }
  235. /**
  236. * Pager item class
  237. */
  238. class cPagerItem {
  239. var $Start;
  240. var $Text;
  241. var $Enabled;
  242. }
  243. /**
  244. * Numeric pager class
  245. */
  246. class cNumericPager {
  247. var $Items = array();
  248. var $Count, $FromIndex, $ToIndex, $RecordCount, $PageSize, $Range;
  249. var $FirstButton, $PrevButton, $NextButton, $LastButton;
  250. var $ButtonCount = 0;
  251. var $Visible = TRUE;
  252. function cNumericPager($StartRec, $DisplayRecs, $TotalRecs, $RecRange)
  253. {
  254. $this->FirstButton = new cPagerItem;
  255. $this->PrevButton = new cPagerItem;
  256. $this->NextButton = new cPagerItem;
  257. $this->LastButton = new cPagerItem;
  258. $this->FromIndex = intval($StartRec);
  259. $this->PageSize = intval($DisplayRecs);
  260. $this->RecordCount = intval($TotalRecs);
  261. $this->Range = intval($RecRange);
  262. if ($this->PageSize == 0) return;
  263. if ($this->FromIndex > $this->RecordCount)
  264. $this->FromIndex = $this->RecordCount;
  265. $this->ToIndex = $this->FromIndex + $this->PageSize - 1;
  266. if ($this->ToIndex > $this->RecordCount)
  267. $this->ToIndex = $this->RecordCount;
  268. // setup
  269. $this->SetupNumericPager();
  270. // update button count
  271. if ($this->FirstButton->Enabled) $this->ButtonCount++;
  272. if ($this->PrevButton->Enabled) $this->ButtonCount++;
  273. if ($this->NextButton->Enabled) $this->ButtonCount++;
  274. if ($this->LastButton->Enabled) $this->ButtonCount++;
  275. $this->ButtonCount += count($this->Items);
  276. }
  277. // Add pager item
  278. function AddPagerItem($StartIndex, $Text, $Enabled)
  279. {
  280. $Item = new cPagerItem;
  281. $Item->Start = $StartIndex;
  282. $Item->Text = $Text;
  283. $Item->Enabled = $Enabled;
  284. $this->Items[] = $Item;
  285. }
  286. // Setup pager items
  287. function SetupNumericPager()
  288. {
  289. if ($this->RecordCount > $this->PageSize) {
  290. $Eof = ($this->RecordCount < ($this->FromIndex + $this->PageSize));
  291. $HasPrev = ($this->FromIndex > 1);
  292. // First Button
  293. $TempIndex = 1;
  294. $this->FirstButton->Start = $TempIndex;
  295. $this->FirstButton->Enabled = ($this->FromIndex > $TempIndex);
  296. // Prev Button
  297. $TempIndex = $this->FromIndex - $this->PageSize;
  298. if ($TempIndex < 1) $TempIndex = 1;
  299. $this->PrevButton->Start = $TempIndex;
  300. $this->PrevButton->Enabled = $HasPrev;
  301. // Page links
  302. if ($HasPrev || !$Eof) {
  303. $x = 1;
  304. $y = 1;
  305. $dx1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->PageSize*$this->Range + 1;
  306. $dy1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->Range + 1;
  307. if (($dx1+$this->PageSize*$this->Range-1) > $this->RecordCount) {
  308. $dx2 = intval($this->RecordCount/$this->PageSize)*$this->PageSize + 1;
  309. $dy2 = intval($this->RecordCount/$this->PageSize) + 1;
  310. } else {
  311. $dx2 = $dx1 + $this->PageSize*$this->Range - 1;
  312. $dy2 = $dy1 + $this->Range - 1;
  313. }
  314. while ($x <= $this->RecordCount) {
  315. if ($x >= $dx1 && $x <= $dx2) {
  316. $this->AddPagerItem($x, $y, $this->FromIndex<>$x);
  317. $x += $this->PageSize;
  318. $y++;
  319. } elseif ($x >= ($dx1-$this->PageSize*$this->Range) && $x <= ($dx2+$this->PageSize*$this->Range)) {
  320. if ($x+$this->Range*$this->PageSize < $this->RecordCount) {
  321. $this->AddPagerItem($x, $y . "-" . ($y+$this->Range-1), TRUE);
  322. } else {
  323. $ny = intval(($this->RecordCount-1)/$this->PageSize) + 1;
  324. if ($ny == $y) {
  325. $this->AddPagerItem($x, $y, TRUE);
  326. } else {
  327. $this->AddPagerItem($x, $y . "-" . $ny, TRUE);
  328. }
  329. }
  330. $x += $this->Range*$this->PageSize;
  331. $y += $this->Range;
  332. } else {
  333. $x += $this->Range*$this->PageSize;
  334. $y += $this->Range;
  335. }
  336. }
  337. }
  338. // Next Button
  339. $TempIndex = $this->FromIndex + $this->PageSize;
  340. $this->NextButton->Start = $TempIndex;
  341. $this->NextButton->Enabled = !$Eof;
  342. // Last Button
  343. $TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
  344. $this->LastButton->Start = $TempIndex;
  345. $this->LastButton->Enabled = ($this->FromIndex < $TempIndex);
  346. }
  347. }
  348. }
  349. /**
  350. * PrevNext pager class
  351. */
  352. class cPrevNextPager {
  353. var $FirstButton, $PrevButton, $NextButton, $LastButton;
  354. var $CurrentPage, $PageCount, $FromIndex, $ToIndex, $RecordCount;
  355. var $Visible = TRUE;
  356. function cPrevNextPager($StartRec, $DisplayRecs, $TotalRecs)
  357. {
  358. $this->FirstButton = new cPagerItem;
  359. $this->PrevButton = new cPagerItem;
  360. $this->NextButton = new cPagerItem;
  361. $this->LastButton = new cPagerItem;
  362. $this->FromIndex = intval($StartRec);
  363. $this->PageSize = intval($DisplayRecs);
  364. $this->RecordCount = intval($TotalRecs);
  365. if ($this->PageSize == 0) return;
  366. $this->CurrentPage = intval(($this->FromIndex-1)/$this->PageSize) + 1;
  367. $this->PageCount = intval(($this->RecordCount-1)/$this->PageSize) + 1;
  368. if ($this->FromIndex > $this->RecordCount)
  369. $this->FromIndex = $this->RecordCount;
  370. $this->ToIndex = $this->FromIndex + $this->PageSize - 1;
  371. if ($this->ToIndex > $this->RecordCount)
  372. $this->ToIndex = $this->RecordCount;
  373. // First Button
  374. $TempIndex = 1;
  375. $this->FirstButton->Start = $TempIndex;
  376. $this->FirstButton->Enabled = ($TempIndex <> $this->FromIndex);
  377. // Prev Button
  378. $TempIndex = $this->FromIndex - $this->PageSize;
  379. if ($TempIndex < 1) $TempIndex = 1;
  380. $this->PrevButton->Start = $TempIndex;
  381. $this->PrevButton->Enabled = ($TempIndex <> $this->FromIndex);
  382. // Next Button
  383. $TempIndex = $this->FromIndex + $this->PageSize;
  384. if ($TempIndex > $this->RecordCount)
  385. $TempIndex = $this->FromIndex;
  386. $this->NextButton->Start = $TempIndex;
  387. $this->NextButton->Enabled = ($TempIndex <> $this->FromIndex);
  388. // Last Button
  389. $TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
  390. $this->LastButton->Start = $TempIndex;
  391. $this->LastButton->Enabled = ($TempIndex <> $this->FromIndex);
  392. }
  393. }
  394. /**
  395. * Field class
  396. */
  397. class cField {
  398. var $TblVar; // Table var
  399. var $FldName; // Field name
  400. var $FldVar; // Field var
  401. var $FldExpression; // Field expression (used in sql)
  402. var $FldType; // Field type
  403. var $FldDataType; // PHPMaker Field type
  404. var $AdvancedSearch; // AdvancedSearch Object
  405. var $Upload; // Upload Object
  406. var $FldDateTimeFormat; // Date time format
  407. var $CssStyle; // CSS style
  408. var $CssClass; // CSS class
  409. var $ImageAlt; // Image alt
  410. var $ImageWidth = 0; // Image width
  411. var $ImageHeight = 0; // Image height
  412. var $ViewCustomAttributes; // View custom attributes
  413. var $EditCustomAttributes; // Edit custom attributes
  414. var $Count; // Count
  415. var $Total; // Total
  416. var $TrueValue = '1';
  417. var $FalseValue = '0';
  418. var $Visible = TRUE;
  419. function cField($tblvar, $fldvar, $fldname, $fldexpression, $fldtype, $flddtfmt, $upload = FALSE) {
  420. $this->TblVar = $tblvar;
  421. $this->FldVar = $fldvar;
  422. $this->FldName = $fldname;
  423. $this->FldExpression = $fldexpression;
  424. $this->FldType = $fldtype;
  425. $this->FldDataType = ew_FieldDataType($fldtype);
  426. $this->FldDateTimeFormat = $flddtfmt;
  427. $this->AdvancedSearch = new cAdvancedSearch();
  428. if ($upload)
  429. $this->Upload = new cUpload($this->TblVar, $this->FldVar);
  430. }
  431. // View Attributes
  432. function ViewAttributes() {
  433. $sAtt = "";
  434. if (trim($this->CssStyle) <> "") {
  435. $sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
  436. }
  437. if (trim($this->CssClass) <> "") {
  438. $sAtt .= " class=\"" . trim($this->CssClass) . "\"";
  439. }
  440. if (trim($this->ImageAlt) <> "") {
  441. $sAtt .= " alt=\"" . trim($this->ImageAlt) . "\"";
  442. }
  443. if (intval($this->ImageWidth) > 0) {
  444. $sAtt .= " width=\"" . intval($this->ImageWidth) . "\"";
  445. }
  446. if (intval($this->ImageHeight) > 0) {
  447. $sAtt .= " height=\"" . intval($this->ImageHeight) . "\"";
  448. }
  449. if (trim($this->ViewCustomAttributes) <> "") {
  450. $sAtt .= " " . trim($this->ViewCustomAttributes);
  451. }
  452. return $sAtt;
  453. }
  454. // Edit Attributes
  455. function EditAttributes() {
  456. $sAtt = "";
  457. if (trim($this->CssStyle) <> "") {
  458. $sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
  459. }
  460. if (trim($this->CssClass) <> "") {
  461. $sAtt .= " class=\"" . trim($this->CssClass) . "\"";
  462. }
  463. if (trim($this->EditCustomAttributes) <> "") {
  464. $sAtt .= " " . trim($this->EditCustomAttributes);
  465. }
  466. return $sAtt;
  467. }
  468. var $CustomMsg = ""; // Custom message
  469. var $RowAttributes = ""; // Row attributes
  470. var $CellCssClass = ""; // Cell CSS class
  471. var $CellCssStyle = ""; // Cell CSS style
  472. var $CellCustomAttributes = ""; // Cell custom attributes
  473. // Cell Attributes
  474. function CellAttributes() {
  475. $sAtt = "";
  476. if (trim($this->CellCssStyle) <> "") {
  477. $sAtt .= " style=\"" . trim($this->CellCssStyle) . "\"";
  478. }
  479. if (trim($this->CellCssClass) <> "") {
  480. $sAtt .= " class=\"" . trim($this->CellCssClass) . "\"";
  481. }
  482. if (trim($this->CellCustomAttributes) <> "") {
  483. $sAtt .= " " . trim($this->CellCustomAttributes);
  484. }
  485. return $sAtt;
  486. }
  487. // Sort Attributes
  488. function getSort() {
  489. return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar];
  490. }
  491. function setSort($v) {
  492. if (@$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] <> $v) {
  493. $_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] = $v;
  494. }
  495. }
  496. function ReverseSort() {
  497. return ($this->getSort() == "ASC") ? "DESC" : "ASC";
  498. }
  499. var $MultiUpdate; // Multi update
  500. var $OldValue; // Old Value
  501. var $ConfirmValue; // Confirm Value
  502. var $CurrentValue; // Current value
  503. var $ViewValue; // View value
  504. var $EditValue; // Edit value
  505. var $EditValue2; // Edit value 2 (search)
  506. var $HrefValue; // Href value
  507. var $HrefValue2; // Href value 2 (confirm page UPLOAD control)
  508. // If ew_Empty(ViewValue) Then
  509. // Return " "
  510. // Else
  511. // Dim Result As String = Convert.ToString(ViewValue)
  512. // Dim Result2 As String = Regex.Replace(Result, "<[^>]*>", String.Empty) ' Remove HTML tags
  513. // Return IIf(Result2.Trim.Equals(String.Empty), " ", Result)
  514. // End If
  515. // List view value
  516. function ListViewValue() {
  517. $value = strval($this->ViewValue);
  518. if (trim($value) <> "") {
  519. $value2 = preg_replace('/<[^>]*>/', '', $value);
  520. return (trim($value2) <> "") ? $this->ViewValue : "&nbsp;";
  521. } else {
  522. return "&nbsp;";
  523. }
  524. }
  525. // Export Value
  526. function ExportValue($Export, $Original) {
  527. $ExportValue = ($Original) ? $this->CurrentValue : $this->ViewValue;
  528. if ($Export == "xml" && is_null($ExportValue))
  529. $ExportValue = "<Null>";
  530. return $ExportValue;
  531. }
  532. // Form value
  533. var $FormValue;
  534. function setFormValue($v) {
  535. $this->FormValue = ew_StripSlashes($v);
  536. if (is_array($this->FormValue))
  537. $this->FormValue = implode(",", $this->FormValue);
  538. $this->CurrentValue = $this->FormValue;
  539. }
  540. // QueryString value
  541. var $QueryStringValue;
  542. function setQueryStringValue($v) {
  543. $this->QueryStringValue = ew_StripSlashes($v);
  544. $this->CurrentValue = $this->QueryStringValue;
  545. }
  546. // Database Value
  547. var $DbValue;
  548. function setDbValue($v) {
  549. $this->DbValue = $v;
  550. $this->CurrentValue = $this->DbValue;
  551. }
  552. // Set database value with error default
  553. function SetDbValueDef($value, $default) {
  554. switch ($this->FldType) {
  555. case 2:
  556. case 3:
  557. case 16:
  558. case 17:
  559. case 18: // Int
  560. $value = trim($value);
  561. $DbValue = (is_numeric($value)) ? intval($value) : $default;
  562. break;
  563. case 19:
  564. case 20:
  565. case 21: // Big Int
  566. $value = trim($value);
  567. $DbValue = (is_numeric($value)) ? $value : $default;
  568. break;
  569. case 5:
  570. case 6:
  571. case 14:
  572. case 131: // Double
  573. case 4: // Single
  574. $value = trim($value);
  575. $value = ew_StrToFloat($value);
  576. $DbValue = (is_float($value)) ? $value : $default;
  577. break;
  578. case 7:
  579. case 133:
  580. case 134:
  581. case 135: //Date
  582. case 201:
  583. case 203:
  584. case 129:
  585. case 130:
  586. case 200:
  587. case 202: // String
  588. $value = trim($value);
  589. $DbValue = ($value == "") ? $default : $value;
  590. break;
  591. case 128:
  592. case 204:
  593. case 205: // Binary
  594. $DbValue = (is_null($value)) ? $default : $value;
  595. break;
  596. case 72: // GUID
  597. $value = trim($value);
  598. $DbValue = ($value <> "" && ew_CheckGUID($value)) ? $value : $default;
  599. break;
  600. default:
  601. $DbValue = $value;
  602. }
  603. $this->setDbValue($DbValue);
  604. }
  605. // Session Value
  606. function getSessionValue() {
  607. return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"];
  608. }
  609. function setSessionValue($v) {
  610. $_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"] = $v;
  611. }
  612. }
  613. /**
  614. * List option collection class
  615. */
  616. class cListOptions {
  617. var $Items = array();
  618. // Add and return a new option
  619. function Add() {
  620. $this->Items[] = new cListOption();
  621. return $this->Items[count($this->Items)-1];
  622. }
  623. }
  624. /**
  625. * List option class
  626. */
  627. class cListOption {
  628. var $Visible = TRUE;
  629. var $HeaderCellHtml = "";
  630. var $FooterCellHtml = "";
  631. var $BodyCellHtml = "";
  632. var $MultiColumnLinkHtml = "";
  633. }
  634. ?>
  635. <?php
  636. /**
  637. * Advanced Search class
  638. */
  639. class cAdvancedSearch {
  640. var $SearchValue; // Search value
  641. var $SearchOperator; // Search operator
  642. var $SearchCondition; // Search condition
  643. var $SearchValue2; // Search value 2
  644. var $SearchOperator2; // Search operator 2
  645. }
  646. ?>
  647. <?php
  648. /**
  649. * Upload class
  650. */
  651. class cUpload {
  652. var $Index = 0; // Index to handle multiple form elements
  653. var $TblVar; // Table variable
  654. var $FldVar; // Field variable
  655. var $Message; // Error message
  656. var $DbValue; // Value from database
  657. var $Value = NULL; // Upload value
  658. var $Action; // Upload action
  659. var $UploadPath; // Upload path
  660. var $FileName; // Upload file name
  661. var $FileSize; // Upload file size
  662. var $ContentType; // File content type
  663. var $ImageWidth; // Image width
  664. var $ImageHeight; // Image height
  665. // Class initialize
  666. function cUpload($TblVar, $FldVar, $Binary = FALSE) {
  667. $this->TblVar = $TblVar;
  668. $this->FldVar = $FldVar;
  669. }
  670. function getSessionID() {
  671. return EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_" . $this->Index;
  672. }
  673. // Save Db value to Session
  674. function SaveDbToSession() {
  675. $sSessionID = $this->getSessionID();
  676. $_SESSION[$sSessionID . "_DbValue"] = $this->DbValue;
  677. }
  678. // Restore Db value from Session
  679. function RestoreDbFromSession() {
  680. $sSessionID = $this->getSessionID();
  681. $this->DbValue = @$_SESSION[$sSessionID . "_DbValue"];
  682. }
  683. // Remove Db value from Session
  684. function RemoveDbFromSession() {
  685. $sSessionID = $this->getSessionID();
  686. unset($_SESSION[$sSessionID . "_DbValue"]);
  687. }
  688. // Save Upload values to Session
  689. function SaveToSession() {
  690. $sSessionID = $this->getSessionID();
  691. $_SESSION[$sSessionID . "_Action"] = $this->Action;
  692. $_SESSION[$sSessionID . "_FileSize"] = $this->FileSize;
  693. $_SESSION[$sSessionID . "_FileName"] = $this->FileName;
  694. $_SESSION[$sSessionID . "_ContentType"] = $this->ContentType;
  695. $_SESSION[$sSessionID . "_ImageWidth"] = $this->ImageWidth;
  696. $_SESSION[$sSessionID . "_ImageHeight"] = $this->ImageHeight;
  697. $_SESSION[$sSessionID . "_Value"] = $this->Value;
  698. }
  699. // Restore Upload values from Session
  700. function RestoreFromSession() {
  701. $sSessionID = $this->getSessionID();
  702. $this->Action = @$_SESSION[$sSessionID . "_Action"];
  703. $this->FileSize = @$_SESSION[$sSessionID . "_FileSize"];
  704. $this->FileName = @$_SESSION[$sSessionID . "_FileName"];
  705. $this->ContentType = @$_SESSION[$sSessionID . "_ContentType"];
  706. $this->ImageWidth = @$_SESSION[$sSessionID . "_ImageWidth"];
  707. $this->ImageHeight = @$_SESSION[$sSessionID . "_ImageHeight"];
  708. $this->Value = @$_SESSION[$sSessionID . "_Value"];
  709. }
  710. // Remove Upload values from Session
  711. function RemoveFromSession() {
  712. $sSessionID = $this->getSessionID();
  713. unset($_SESSION[$sSessionID . "_Action"]);
  714. unset($_SESSION[$sSessionID . "_FileSize"]);
  715. unset($_SESSION[$sSessionID . "_FileName"]);
  716. unset($_SESSION[$sSessionID . "_ContentType"]);
  717. unset($_SESSION[$sSessionID . "_ImageWidth"]);
  718. unset($_SESSION[$sSessionID . "_ImageHeight"]);
  719. unset($_SESSION[$sSessionID . "_Value"]);
  720. }
  721. // function to check the file type of the uploaded file
  722. function UploadAllowedFileExt($filename) {
  723. return ew_CheckFileType($filename);
  724. }
  725. // Get upload file
  726. function UploadFile() {
  727. global $objForm;
  728. $this->Value = NULL; // Reset first
  729. $gsFldVar = $this->FldVar;
  730. $gsFldVarAction = "a" . substr($gsFldVar, 1);
  731. $gsFldVarWidth = "wd" . substr($gsFldVar, 1);
  732. $gsFldVarHeight = "ht" . substr($gsFldVar, 1);
  733. // Get action
  734. $this->Action = $objForm->GetValue($gsFldVarAction);
  735. // Get and check the upload file size
  736. $this->FileSize = $objForm->GetUploadFileSize($gsFldVar);
  737. // Get and check the upload file type
  738. $this->FileName = $objForm->GetUploadFileName($gsFldVar);
  739. // Get upload file content type
  740. $this->ContentType = $objForm->GetUploadFileContentType($gsFldVar);
  741. // Get upload value
  742. $this->Value = $objForm->GetUploadFileData($gsFldVar);
  743. // Get image width and height
  744. $this->ImageWidth = $objForm->GetUploadImageWidth($gsFldVar);
  745. $this->ImageHeight = $objForm->GetUploadImageHeight($gsFldVar);
  746. if ($this->ImageWidth < 0 || $this->ImageHeight < 0) {
  747. $this->ImageWidth = $objForm->GetValue($gsFldVarWidth);
  748. $this->ImageHeight = $objForm->GetValue($gsFldVarHeight);
  749. }
  750. return TRUE; // Normal return
  751. }
  752. // Resize image
  753. function Resize($width, $height, $quality) {
  754. if (!is_null($this->Value)) {
  755. $wrkwidth = $width;
  756. $wrkheight = $height;
  757. if (ew_ResizeBinary($this->Value, $wrkwidth, $wrkheight, $quality)) { // P6
  758. $this->ImageWidth = $wrkwidth;
  759. $this->ImageHeight = $wrkheight;
  760. $this->FileSize = strlen($this->Value);
  761. }
  762. }
  763. }
  764. // Save uploaded data to file (Path relative to application root)
  765. function SaveToFile($Path, $NewFileName, $OverWrite) {
  766. if (!is_null($this->Value)) {
  767. $Path = ew_UploadPathEx(TRUE, $Path);
  768. if (trim(strval($NewFileName)) == "") $NewFileName = $this->FileName;
  769. if ($OverWrite) {
  770. return ew_SaveFile($Path, $NewFileName, $this->Value);
  771. } else {
  772. return ew_SaveFile($Path, ew_UploadFileNameEx($Path, $NewFileName), $this->Value);
  773. }
  774. }
  775. return FALSE;
  776. }
  777. // Resize and save uploaded data to file (Path relative to application root)
  778. function ResizeAndSaveToFile($Width, $Height, $Quality, $Path, $NewFileName, $OverWrite) {
  779. $bResult = FALSE;
  780. if (!is_null($this->Value)) {
  781. $OldValue = $this->Value;
  782. $this->Resize($Width, $Height, $Quality);
  783. $bResult = $this->SaveToFile($Path, $NewFileName, $OverWrite);
  784. $this->Value = $OldValue;
  785. }
  786. return $bResult;
  787. }
  788. }
  789. ?>
  790. <?php
  791. /**
  792. * Advanced Security class
  793. */
  794. class cAdvancedSecurity {
  795. var $UserLevel = array(); // All User Levels
  796. var $UserLevelPriv = array(); // All User Level permissions
  797. var $UserLevelID = array(); // User Level ID array
  798. var $UserID = array(); // User ID array
  799. var $CurrentUserLevelID;
  800. var $CurrentUserLevel; // Permissions
  801. var $CurrentUserID;
  802. var $CurrentParentUserID;
  803. // Class Initialize
  804. function cAdvancedSecurity() {
  805. // Init User Level
  806. $this->CurrentUserLevelID = $this->SessionUserLevelID();
  807. if (is_numeric($this->CurrentUserLevelID) && intval($this->CurrentUserLevelID) >= -1) {
  808. $this->UserLevelID[] = $this->CurrentUserLevelID;
  809. }
  810. // Init User ID
  811. $this->CurrentUserID = $this->SessionUserID();
  812. $this->CurrentParentUserID = $this->SessionParentUserID();
  813. // Load user level (for TablePermission_Loading event)
  814. $this->LoadUserLevel();
  815. }
  816. // Session user id
  817. function SessionUserID() {
  818. return strval(@$_SESSION[EW_SESSION_USER_ID]);
  819. }
  820. function setSessionUserID($v) {
  821. $_SESSION[EW_SESSION_USER_ID] = $v;
  822. $this->CurrentUserID = $v;
  823. }
  824. // Session parent user id
  825. function SessionParentUserID() {
  826. return strval(@$_SESSION[EW_SESSION_PARENT_USER_ID]);
  827. }
  828. function setSessionParentUserID($v) {
  829. $_SESSION[EW_SESSION_PARENT_USER_ID] = $v;
  830. $this->CurrentParentUserID = $v;
  831. }
  832. // Session user level id
  833. function SessionUserLevelID() {
  834. return @$_SESSION[EW_SESSION_USER_LEVEL_ID];
  835. }
  836. function setSessionUserLevelID($v) {
  837. $_SESSION[EW_SESSION_USER_LEVEL_ID] = $v;
  838. $this->CurrentUserLevelID = $v;
  839. }
  840. // Session user level value
  841. function SessionUserLevel() {
  842. return @$_SESSION[EW_SESSION_USER_LEVEL];
  843. }
  844. function setSessionUserLevel($v) {
  845. $_SESSION[EW_SESSION_USER_LEVEL] = $v;
  846. $this->CurrentUserLevel = $v;
  847. }
  848. // Current user name
  849. function getCurrentUserName() {
  850. return strval(@$_SESSION[EW_SESSION_USER_NAME]);
  851. }
  852. function setCurrentUserName($v) {
  853. $_SESSION[EW_SESSION_USER_NAME] = $v;
  854. }
  855. function CurrentUserName() {
  856. return $this->getCurrentUserName();
  857. }
  858. // Current User ID
  859. function CurrentUserID() {
  860. return $this->CurrentUserID;
  861. }
  862. // Current parent User ID
  863. function CurrentParentUserID() {
  864. return $this->CurrentParentUserID;
  865. }
  866. // Current User Level id
  867. function CurrentUserLevelID() {
  868. return $this->CurrentUserLevelID;
  869. }
  870. // Current User Level value
  871. function CurrentUserLevel() {
  872. return $this->CurrentUserLevel;
  873. }
  874. // Can add
  875. function CanAdd() {
  876. return (($this->CurrentUserLevel & EW_ALLOW_ADD) == EW_ALLOW_ADD);
  877. }
  878. function setCanAdd($b) {
  879. if ($b) {
  880. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_ADD);
  881. } else {
  882. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_ADD));
  883. }
  884. }
  885. // Can delete
  886. function CanDelete() {
  887. return (($this->CurrentUserLevel & EW_ALLOW_DELETE) == EW_ALLOW_DELETE);
  888. }
  889. function setCanDelete($b) {
  890. if ($b) {
  891. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_DELETE);
  892. } else {
  893. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_DELETE));
  894. }
  895. }
  896. // Can edit
  897. function CanEdit() {
  898. return (($this->CurrentUserLevel & EW_ALLOW_EDIT) == EW_ALLOW_EDIT);
  899. }
  900. function setCanEdit($b) {
  901. if ($b) {
  902. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_EDIT);
  903. } else {
  904. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_EDIT));
  905. }
  906. }
  907. // Can view
  908. function CanView() {
  909. return (($this->CurrentUserLevel & EW_ALLOW_VIEW) == EW_ALLOW_VIEW);
  910. }
  911. function setCanView($b) {
  912. if ($b) {
  913. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_VIEW);
  914. } else {
  915. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_VIEW));
  916. }
  917. }
  918. // Can list
  919. function CanList() {
  920. return (($this->CurrentUserLevel & EW_ALLOW_LIST) == EW_ALLOW_LIST);
  921. }
  922. function setCanList($b) {
  923. if ($b) {
  924. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_LIST);
  925. } else {
  926. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_LIST));
  927. }
  928. }
  929. // Can report
  930. function CanReport() {
  931. return (($this->CurrentUserLevel & EW_ALLOW_REPORT) == EW_ALLOW_REPORT);
  932. }
  933. function setCanReport($b) {
  934. if ($b) {
  935. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_REPORT);
  936. } else {
  937. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_REPORT));
  938. }
  939. }
  940. // Can search
  941. function CanSearch() {
  942. return (($this->CurrentUserLevel & EW_ALLOW_SEARCH) == EW_ALLOW_SEARCH);
  943. }
  944. function setCanSearch($b) {
  945. if ($b) {
  946. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_SEARCH);
  947. } else {
  948. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_SEARCH));
  949. }
  950. }
  951. // Can admin
  952. function CanAdmin() {
  953. return (($this->CurrentUserLevel & EW_ALLOW_ADMIN) == EW_ALLOW_ADMIN);
  954. }
  955. function setCanAdmin($b) {
  956. if ($b) {
  957. $this->CurrentUserLevel = ($this->CurrentUserLevel | EW_ALLOW_ADMIN);
  958. } else {
  959. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EW_ALLOW_ADMIN));
  960. }
  961. }
  962. // Last url
  963. function LastUrl() {
  964. return @$_COOKIE[EW_PROJECT_NAME]['LastUrl'];
  965. }
  966. // Save last url
  967. function SaveLastUrl() {
  968. $s = ew_ServerVar("SCRIPT_NAME");
  969. $q = ew_ServerVar("QUERY_STRING");
  970. if ($q <> "") $s .= "?" . $q;
  971. if ($this->LastUrl() == $s) $s = "";
  972. @setcookie(EW_PROJECT_NAME . '[LastUrl]', $s);
  973. }
  974. // Auto login
  975. function AutoLogin() {
  976. if (@$_COOKIE[EW_PROJECT_NAME]['AutoLogin'] == "autologin") {
  977. $usr = @$_COOKIE[EW_PROJECT_NAME]['UserName'];
  978. $pwd = @$_COOKIE[EW_PROJECT_NAME]['Password'];
  979. $pwd = TEAdecrypt($pwd, EW_RANDOM_KEY);
  980. $AutoLogin = $this->ValidateUser($usr, $pwd);
  981. } else {
  982. $AutoLogin = FALSE;
  983. }
  984. return $AutoLogin;
  985. }
  986. // Validate user
  987. function ValidateUser($usr, $pwd) {
  988. global $conn;
  989. global $usuario;
  990. $ValidateUser = FALSE;
  991. // Check hard coded admin first
  992. if (EW_CASE_SENSITIVE_PASSWORD) {
  993. $ValidateUser = (EW_ADMIN_USER_NAME == $usr && EW_ADMIN_PASSWORD == $pwd);
  994. } else {
  995. $ValidateUser = (strtolower(EW_ADMIN_USER_NAME) == strtolower($usr) &&
  996. strtolower(EW_ADMIN_PASSWORD) == strtolower($pwd));
  997. }
  998. if ($ValidateUser) {
  999. $_SESSION[EW_SESSION_STATUS] = "login";
  1000. $_SESSION[EW_SESSION_SYS_ADMIN] = 1; // System Administrator
  1001. $this->setCurrentUserName("Administrator"); // Load user name
  1002. $this->setSessionUserLevelID(-1); // System Administrator
  1003. $this->SetUpUserLevel();
  1004. }
  1005. // Check other users
  1006. if (!$ValidateUser) {
  1007. $sFilter = "(`login` = '" . ew_AdjustSql($usr) . "')";
  1008. // Set up filter (Sql Where Clause) and get Return SQL
  1009. // SQL constructor in <UseTable> class, <UserTable>info.php
  1010. $sSql = $usuario->GetSQL($sFilter, "");
  1011. if ($rs = $conn->Execute($sSql)) {
  1012. if (!$rs->EOF) {
  1013. if (EW_CASE_SENSITIVE_PASSWORD) {
  1014. if (EW_MD5_PASSWORD) {
  1015. $ValidateUser = ($rs->fields('password') == md5($pwd));
  1016. } else {
  1017. $ValidateUser = ($rs->fields('password') == $pwd);
  1018. }
  1019. } else {
  1020. if (EW_MD5_PASSWORD) {
  1021. $ValidateUser = ($rs->fields('password') == md5(strtolower($pwd)));
  1022. } else {
  1023. $ValidateUser = (strtolower($rs->fields('password')) == strtolower($pwd));
  1024. }
  1025. }
  1026. if ($ValidateUser) {
  1027. $_SESSION[EW_SESSION_STATUS] = "login";
  1028. $_SESSION[EW_SESSION_SYS_ADMIN] = 0; // Non System Administrator
  1029. $this->setCurrentUserName($rs->fields('login')); // Load user name
  1030. if (is_null($rs->fields('idRol'))) {
  1031. $this->setSessionUserLevelID(0);
  1032. } else {
  1033. $this->setSessionUserLevelID(intval($rs->fields('idRol'))); // Load User Level
  1034. }
  1035. $this->SetUpUserLevel();
  1036. // Call User Validated event
  1037. $this->User_Validated($rs);
  1038. }
  1039. }
  1040. $rs->Close();
  1041. }
  1042. }
  1043. return $ValidateUser;
  1044. }
  1045. // Dynamic User Level security
  1046. // Get User Level settings from database
  1047. function SetUpUserLevel() {
  1048. $this->SetUpUserLevelEx(); // Load all user levels
  1049. // User Level loaded event
  1050. $this->UserLevel_Loaded();
  1051. // Save the User Level to session variable
  1052. $this->SaveUserLevel();
  1053. }
  1054. // Get all User Level settings from database
  1055. function SetUpUserLevelEx() {
  1056. global $conn;
  1057. // Get the User Level definitions
  1058. $sSql = "SELECT " . EW_USER_LEVEL_ID_FIELD . ", " . EW_USER_LEVEL_NAME_FIELD . " FROM " . EW_USER_LEVEL_TABLE;
  1059. if ($rs = $conn->Execute($sSql)) {
  1060. $this->UserLevel = $rs->GetRows();
  1061. $rs->Close();
  1062. }
  1063. // Get the User Level privileges
  1064. $sSql = "SELECT " . EW_USER_LEVEL_PRIV_TABLE_NAME_FIELD . ", " . EW_USER_LEVEL_PRIV_USER_LEVEL_ID_FIELD . ", " . EW_USER_LEVEL_PRIV_PRIV_FIELD . " FROM " . EW_USER_LEVEL_PRIV_TABLE;
  1065. if ($rs = $conn->Execute($sSql)) {
  1066. $this->UserLevelPriv = $rs->GetRows();
  1067. $rs->Close();
  1068. }
  1069. }
  1070. // Add user permission
  1071. function AddUserPermission($UserLevelName, $TableName, $UserPermission) {
  1072. // Get user level id from user name
  1073. $UserLevelID = "";
  1074. if (is_array($this->UserLevel)) {
  1075. foreach ($this->UserLevel as $row) {
  1076. list($levelid, $name) = $row;
  1077. if (strval($UserLevelName) == strval($name)) {
  1078. $UserLevelID = $levelid;
  1079. break;
  1080. }
  1081. }
  1082. }
  1083. if (is_array($this->UserLevelPriv) && $UserLevelID <> "") {
  1084. $cnt = count($this->UserLevelPriv);
  1085. for ($i = 0; $i < $cnt; $i++) {
  1086. list($table, $levelid, $priv) = $this->UserLevelPriv[$i];
  1087. if (strtolower($table) == strtolower($TableName) && strval($levelid) == strval($UserLevelID)) {
  1088. $this->UserLevelPriv[$i][2] = $priv | $UserPermission; // Add permission
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. }
  1094. // Delete user permission
  1095. function DeleteUserPermission($UserLevelName, $TableName, $UserPermission) {
  1096. // Get user level id from user name
  1097. $UserLevelID = "";
  1098. if (is_array($this->UserLevel)) {
  1099. foreach ($this->UserLevel as $row) {
  1100. list($levelid, $name) = $row;
  1101. if (strval($UserLevelName) == strval($name)) {
  1102. $UserLevelID = $levelid;
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. if (is_array($this->UserLevelPriv) && $UserLevelID <> "") {
  1108. $cnt = count($this->UserLevelPriv);
  1109. for ($i = 0; $i < $cnt; $i++) {
  1110. list($table, $levelid, $priv) = $this->UserLevelPriv[$i];
  1111. if (strtolower($table) == strtolower($TableName) && strval($levelid) == strval($UserLevelID)) {
  1112. $this->UserLevelPriv[$i][2] = $priv & (127 - $UserPermission); // Remove permission
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. }
  1118. // Load current user level
  1119. function LoadCurrentUserLevel($Table) {
  1120. $this->LoadUserLevel();
  1121. $this->setSessionUserLevel($this->CurrentUserLevelPriv($Table));
  1122. }
  1123. // Get current user privilege
  1124. function CurrentUserLevelPriv($TableName) {
  1125. if ($this->IsLoggedIn()) {
  1126. $Priv= 0;
  1127. foreach ($this->UserLevelID as $UserLevelID)
  1128. $Priv |= $this->GetUserLevelPrivEx($TableName, $UserLevelID);
  1129. return $Priv;
  1130. } else {
  1131. return 0;
  1132. }
  1133. }
  1134. // Get user level ID by user level name
  1135. function GetUserLevelID($UserLevelName) {
  1136. if (strval($UserLevelName) == "Administrator") {
  1137. return -1;
  1138. } elseif ($UserLevelName <> "") {
  1139. if (is_array($this->UserLevel)) {
  1140. foreach ($this->UserLevel as $row) {
  1141. list($levelid, $name) = $row;
  1142. if (strval($name) == strval($UserLevelName))
  1143. return $levelid;
  1144. }
  1145. }
  1146. }
  1147. return -2;
  1148. }
  1149. // Add user level (for use with UserLevel_Loading event)
  1150. function AddUserLevel($UserLevelName) {
  1151. if (strval($UserLevelName) == "") return;
  1152. $UserLevelID = $this->GetUserLevelID($UserLevelName);
  1153. if (!is_numeric($UserLevelID)) return;
  1154. if ($UserLevelID < -1) return;
  1155. if (!in_array($UserLevelID, $this->UserLevelID))
  1156. $this->UserLevelID[] = $UserLevelID;
  1157. }
  1158. // Delete user level (for use with UserLevel_Loading event)
  1159. function DeleteUserLevel($UserLevelName) {
  1160. if (strval($UserLevelName) == "") return;
  1161. $UserLevelID = $this->GetUserLevelID($UserLevelName);
  1162. if (!is_numeric($UserLevelID)) return;
  1163. if ($UserLevelID < -1) return;
  1164. $cnt = count($this->UserLevelID);
  1165. for ($i = 0; $i < $cnt; $i++) {
  1166. if ($this->UserLevelID[$i] == $UserLevelID) {
  1167. unset($this->UserLevelID[$i]);
  1168. break;
  1169. }
  1170. }
  1171. }
  1172. // User level list
  1173. function UserLevelList() {
  1174. return implode(", ", $this->UserLevelID);
  1175. }
  1176. // User level name list
  1177. function UserLevelNameList() {
  1178. $list = "";
  1179. foreach ($this->UserLevelID as $UserLevelID) {
  1180. if ($list <> "") $lList .= ", ";
  1181. $list .= ew_QuotedValue($this->GetUserLevelName($UserLevelID), EW_DATATYPE_STRING);
  1182. }
  1183. return $list;
  1184. }
  1185. // Get user privilege based on table name and User Level
  1186. function GetUserLevelPrivEx($TableName, $UserLevelID) {
  1187. if (strval($UserLevelID) == "-1") { // System Administrator
  1188. if (defined("EW_USER_LEVEL_COMPAT")) {
  1189. return 31; // Use old User Level values
  1190. } else {
  1191. return 127; // Use new User Level values (separate View/Search)
  1192. }
  1193. } elseif ($UserLevelID >= 0) {
  1194. if (is_array($this->UserLevelPriv)) {
  1195. foreach ($this->UserLevelPriv as $row) {
  1196. list($table, $levelid, $priv) = $row;
  1197. if (strtolower($table) == strtolower($TableName) && strval($levelid) == strval($UserLevelID)) {
  1198. if (is_null($priv) || !is_numeric($priv)) return 0;
  1199. return intval($priv);
  1200. }
  1201. }
  1202. }
  1203. }
  1204. return 0;
  1205. }
  1206. // Get current User Level name
  1207. function CurrentUserLevelName() {
  1208. return $this->GetUserLevelName($this->CurrentUserLevelID());
  1209. }
  1210. // Get User Level name based on User Level
  1211. function GetUserLevelName($UserLevelID) {
  1212. if (strval($UserLevelID) == "-1") {
  1213. return "Administrator";
  1214. } elseif ($UserLevelID >= 0) {
  1215. if (is_array($this->UserLevel)) {
  1216. foreach ($this->UserLevel as $row) {
  1217. list($levelid, $name) = $row;
  1218. if (strval($levelid) == strval($UserLevelID))
  1219. return $name;
  1220. }
  1221. }
  1222. }
  1223. return "";
  1224. }
  1225. // function to display all the User Level settings (for debug only)
  1226. function ShowUserLevelInfo() {
  1227. echo "<pre class=\"phpmaker\">";
  1228. print_r($this->UserLevel);
  1229. print_r($this->UserLevelPriv);
  1230. echo "</pre>";
  1231. echo "<p>Current User Level ID = " . $this->CurrentUserLevelID() . "</p>";
  1232. echo "<p>Current User Level ID List = " . $this->UserLevelList() . "</p>";
  1233. }
  1234. // function to check privilege for List page (for menu items)
  1235. function AllowList($TableName) {
  1236. return ($this->CurrentUserLevelPriv($TableName) & EW_ALLOW_LIST);
  1237. }
  1238. // function to check privilege for Add page (for Allow-Add)
  1239. function AllowAdd($TableName) {
  1240. return ($this->CurrentUserLevelPriv($TableName) & EW_ALLOW_ADD);
  1241. }
  1242. // Check if user is logged in
  1243. function IsLoggedIn() {
  1244. return (@$_SESSION[EW_SESSION_STATUS] == "login");
  1245. }
  1246. // Check if user is system administrator
  1247. function IsSysAdmin() {
  1248. return (@$_SESSION[EW_SESSION_SYS_ADMIN] == 1);
  1249. }
  1250. // Check if user is administrator
  1251. function IsAdmin() {
  1252. return ($this->CurrentUserLevelID() == -1 || $this->IsSysAdmin());
  1253. }
  1254. // Save User Level to session
  1255. function SaveUserLevel() {
  1256. $_SESSION[EW_SESSION_AR_USER_LEVEL] = $this->UserLevel;
  1257. $_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV] = $this->UserLevelPriv;
  1258. }
  1259. // Load User Level from session
  1260. function LoadUserLevel() {
  1261. if (!is_array(@$_SESSION[EW_SESSION_AR_USER_LEVEL])) {
  1262. $this->SetupUserLevel();
  1263. $this->SaveUserLevel();
  1264. } else {
  1265. $this->UserLevel = $_SESSION[EW_SESSION_AR_USER_LEVEL];
  1266. $this->UserLevelPriv = $_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV];
  1267. }
  1268. }
  1269. // Get current user info
  1270. function CurrentUserInfo($fieldname) {
  1271. $info = NULL;
  1272. return $info;
  1273. }
  1274. // UserID Loading event
  1275. function UserID_Loading() {
  1276. //echo "UserID Loading: " . $this->CurrentUserID() . "<br>";
  1277. }
  1278. // UserID Loaded event
  1279. function UserID_Loaded() {
  1280. //echo "UserID Loaded: " . $this->UserIDList() . "<br>";
  1281. }
  1282. // User Level Loaded event
  1283. function UserLevel_Loaded() {
  1284. //$this->AddUserPermission(<UserLevelName>, <TableName>, <UserPermission>);
  1285. //$this->DeleteUserPermission(<UserLevelName>, <TableName>, <UserPermission>);
  1286. }
  1287. // Table Permission Loading event
  1288. function TablePermission_Loading() {
  1289. //echo "Table Permission Loading: " . $this->CurrentUserLevelID() . "<br>";
  1290. }
  1291. // Table Permission Loaded event
  1292. function TablePermission_Loaded() {
  1293. //echo "Table Permission Loaded: " . $this->CurrentUserLevel() . "<br>";
  1294. }
  1295. // User Validated event
  1296. function User_Validated(&$rs) {
  1297. //e.g. $_SESSION['UserEmail'] = $rs->fields('Email');
  1298. }
  1299. }
  1300. ?>
  1301. <?php
  1302. /**
  1303. * Common functions
  1304. */
  1305. // Connection/Query error handler
  1306. function ew_ErrorFn($DbType, $ErrorType, $ErrorNo, $ErrorMsg, $Param1, $Param2, $Object) {
  1307. if ($ErrorType == 'CONNECT') {
  1308. $msg = "Failed to connect to $Param2 at $Param1. Error: " . $ErrorMsg;
  1309. } elseif ($ErrorType == 'EXECUTE') {
  1310. if (defined("EW_DEBUG_ENABLED")) {
  1311. $msg = "Failed to execute SQL: $Param1. Error: " . $ErrorMsg;
  1312. } else {
  1313. $msg = "Failed to execute SQL. Error: " . $ErrorMsg;
  1314. }
  1315. }
  1316. $_SESSION[EW_SESSION_MESSAGE] = $msg;
  1317. }
  1318. // Connect to database
  1319. function &ew_Connect() {
  1320. $object =& new mysqlt_driver_ADOConnection();
  1321. if (defined("EW_DEBUG_ENABLED"))
  1322. $object->debug = TRUE;
  1323. $object->port = EW_CONN_PORT;
  1324. $object->raiseErrorFn = 'ew_ErrorFn';
  1325. $object->Connect(EW_CONN_HOST, EW_CONN_USER, EW_CONN_PASS, EW_CONN_DB);
  1326. if (EW_MYSQL_CHARSET <> "") $object->Execute("SET NAMES '" . EW_MYSQL_CHARSET . "'");
  1327. $object->raiseErrorFn = '';
  1328. return $object;
  1329. }
  1330. // Get server variable by name
  1331. function ew_ServerVar($Name) {
  1332. $str = @$_SERVER[$Name];
  1333. if (empty($str)) $str = @$_ENV[$Name];
  1334. return $str;
  1335. }
  1336. // Check if HTTP POST
  1337. function ew_IsHttpPost() {
  1338. $ct = ew_ServerVar("CONTENT_TYPE");
  1339. if (empty($ct)) $ct = ew_ServerVar("HTTP_CONTENT_TYPE");
  1340. return ($ct == "application/x-www-form-urlencoded");
  1341. }
  1342. // Get script name
  1343. function ew_ScriptName() {
  1344. $sn = ew_ServerVar("PHP_SELF");
  1345. if (empty($sn)) $sn = ew_ServerVar("SCRIPT_NAME");
  1346. if (empty($sn)) $sn = ew_ServerVar("ORIG_PATH_INFO");
  1347. if (empty($sn)) $sn = ew_ServerVar("ORIG_SCRIPT_NAME");
  1348. if (empty($sn)) $sn = ew_ServerVar("REQUEST_URI");
  1349. if (empty($sn)) $sn = ew_ServerVar("URL");
  1350. if (empty($sn)) $sn = "UNKNOWN";
  1351. return $sn;
  1352. }
  1353. // Return multi-value search SQL
  1354. function ew_GetMultiSearchSql(&$Fld, $FldVal) {
  1355. $sWrk = "";
  1356. $arVal = explode(",", $FldVal);
  1357. foreach ($arVal as $sVal) {
  1358. $sVal = trim($sVal);
  1359. if (EW_IS_MYSQL) {
  1360. $sSql = "FIND_IN_SET('" . ew_AdjustSql($sVal) . "', " . $Fld->FldExpression . ")";
  1361. } else {
  1362. if (count($arVal) == 1 || EW_SEARCH_MULTI_VALUE_OPTION == 3) {
  1363. $sSql = $Fld->FldExpression . " = '" . ew_AdjustSql($sVal) . "' OR " . ew_GetMultiSearchSqlPart($Fld, $sVal);
  1364. } else {
  1365. $sSql = ew_GetMultiSearchSqlPart($Fld, $sVal);
  1366. }
  1367. }
  1368. if ($sWrk <> "") {
  1369. if (EW_SEARCH_MULTI_VALUE_OPTION == 2) {
  1370. $sWrk .= " AND ";
  1371. } elseif (EW_SEARCH_MULTI_VALUE_OPTION == 3) {
  1372. $sWrk .= " OR ";
  1373. }
  1374. }
  1375. $sWrk .= "($sSql)";
  1376. }
  1377. return $sWrk;
  1378. }
  1379. // Get multi search SQL part
  1380. function ew_GetMultiSearchSqlPart(&$Fld, $FldVal) {
  1381. return $Fld->FldExpression . " LIKE '" . ew_AdjustSql($FldVal) . ",%' OR " .
  1382. $Fld->FldExpression . " LIKE '%," . $FldVal . ",%' OR " .
  1383. $Fld->FldExpression . " LIKE '%," . $FldVal . "'";
  1384. }
  1385. // Get search sql
  1386. function ew_GetSearchSql(&$Fld, $FldVal, $FldOpr, $FldCond, $FldVal2, $FldOpr2) {
  1387. $sSql = "";
  1388. if ($FldOpr == "BETWEEN") {
  1389. $IsValidValue = ($Fld->FldDataType <> EW_DATATYPE_NUMBER) ||
  1390. ($Fld->FldDataType == EW_DATATYPE_NUMBER && is_numeric($FldVal) && is_numeric($FldVal2));
  1391. if ($FldVal <> "" && $FldVal2 <> "" && $IsValidValue)
  1392. $sSql = $Fld->FldExpression . " BETWEEN " . ew_QuotedValue($FldVal, $Fld->FldDataType) .
  1393. " AND " . ew_QuotedValue($FldVal2, $Fld->FldDataType);
  1394. } elseif ($FldOpr == "IS NULL" || $FldOpr == "IS NOT NULL") {
  1395. $sSql = $Fld->FldExpression . " " . $FldOpr;
  1396. } else {
  1397. $IsValidValue = ($Fld->FldDataType <> EW_DATATYPE_NUMBER) ||
  1398. ($Fld->FldDataType == EW_DATATYPE_NUMBER && is_numeric($FldVal));
  1399. if ($FldVal <> "" && $IsValidValue && ew_IsValidOpr($FldOpr, $Fld->FldDataType))
  1400. $sSql = $Fld->FldExpression . ew_SearchString($FldOpr, $FldVal, $Fld->FldDataType);
  1401. $IsValidValue = ($Fld->FldDataType <> EW_DATATYPE_NUMBER) ||
  1402. ($Fld->FldDataType == EW_DATATYPE_NUMBER && is_numeric($FldVal2));
  1403. if ($FldVal2 <> "" && $IsValidValue && ew_IsValidOpr($FldOpr2, $Fld->FldDataType)) {
  1404. if ($sSql <> "")
  1405. $sSql .= " " . (($FldCond == "OR") ? "OR" : "AND") . " ";
  1406. $sSql = "(" . $sSql . $Fld->FldExpression . ew_SearchString($FldOpr2, $FldVal2, $Fld->FldDataType) . ")";
  1407. }
  1408. }
  1409. return $sSql;
  1410. }
  1411. // Return search string
  1412. function ew_SearchString($FldOpr, $FldVal, $FldType) {
  1413. if ($FldOpr == "LIKE" || $FldOpr == "NOT LIKE") {
  1414. return " $FldOpr " . ew_QuotedValue("%$FldVal%", $FldType);
  1415. } elseif ($FldOpr == "STARTS WITH") {
  1416. return " LIKE " . ew_QuotedValue("$FldVal%", $FldType);
  1417. } else {
  1418. return " $FldOpr " . ew_QuotedValue($FldVal, $FldType);
  1419. }
  1420. }
  1421. // Check if valid operator
  1422. function ew_IsValidOpr($Opr, $FldType) {
  1423. $Valid = ($Opr == "=" || $Opr == "<" || $Opr == "<=" ||
  1424. $Opr == ">" || $Opr == ">=" || $Opr == "<>");
  1425. if ($FldType == EW_DATATYPE_STRING || $FldType == EW_DATATYPE_MEMO)
  1426. $Valid = ($Valid || $Opr == "LIKE" || $Opr == "NOT LIKE" || $Opr == "STARTS WITH");
  1427. return $Valid;
  1428. }
  1429. // quote field values
  1430. function ew_QuotedValue($Value, $FldType) {
  1431. if (is_null($Value)) return "NULL";
  1432. switch ($FldType) {
  1433. case EW_DATATYPE_STRING:
  1434. case EW_DATATYPE_MEMO:
  1435. case EW_DATATYPE_TIME:
  1436. if (EW_REMOVE_XSS) {
  1437. return "'" . ew_AdjustSql(ew_RemoveXSS($Value)) . "'";
  1438. } else {
  1439. return "'" . ew_AdjustSql($Value) . "'";
  1440. }
  1441. case EW_DATATYPE_BLOB:
  1442. return "'" . ew_AdjustSql($Value) . "'";
  1443. case EW_DATATYPE_DATE:
  1444. return (EW_IS_MSACCESS) ? "#" . ew_AdjustSql($Value) . "#" :
  1445. "'" . ew_AdjustSql($Value) . "'";
  1446. case EW_DATATYPE_GUID:
  1447. if (EW_IS_MSACCESS) {
  1448. if (strlen($Value) == 38) {
  1449. return "{guid " . $Value . "}";
  1450. } elseif (strlen($Value) == 36) {
  1451. return "{guid {" . $Value . "}}";
  1452. }
  1453. } else {
  1454. return "'" . $Value . "'";
  1455. }
  1456. case EW_DATATYPE_BOOLEAN: // enum('Y'/'N') or enum('1'/'0')
  1457. return "'" . $Value . "'";
  1458. default:
  1459. return $Value;
  1460. }
  1461. }
  1462. // Convert different data type value
  1463. function ew_Conv($v, $t) {
  1464. switch ($t) {
  1465. case 2:
  1466. case 3:
  1467. case 16:
  1468. case 17:
  1469. case 18:
  1470. case 19: // adSmallInt/adInteger/adTinyInt/adUnsignedTinyInt/adUnsignedSmallInt
  1471. return (is_null($v)) ? NULL : intval($v);
  1472. case 4:
  1473. Case 5:
  1474. case 6:
  1475. case 131: // adSingle/adDouble/adCurrency/adNumeric
  1476. return (is_null($v)) ? NULL : (float)$v;
  1477. default:
  1478. return (is_null($v)) ? NULL : $v;
  1479. }
  1480. }
  1481. // Convert string to float
  1482. function ew_StrToFloat($v) {
  1483. $v = str_replace(" ", "", $v);
  1484. // Enter your code here, e.g.
  1485. //$v = str_replace(",", ".", $v);
  1486. if ($v <> "") $v = (float)$v;
  1487. return $v;
  1488. }
  1489. // function for debug
  1490. function ew_Trace($msg) {
  1491. $filename = "debug.txt";
  1492. if (!$handle = fopen($filename, 'a')) exit;
  1493. if (is_writable($filename)) fwrite($handle, $msg . "\n");
  1494. fclose($handle);
  1495. }
  1496. // function to compare values with special handling for null values
  1497. function ew_CompareValue($v1, $v2) {
  1498. if (is_null($v1) && is_null($v2)) {
  1499. return TRUE;
  1500. } elseif (is_null($v1) || is_null($v2)) {
  1501. return FALSE;
  1502. } else {
  1503. return ($v1 == $v2);
  1504. }
  1505. }
  1506. // Strip slashes
  1507. function ew_StripSlashes($value) {
  1508. if (!get_magic_quotes_gpc()) return $value;
  1509. if (is_array($value)) {
  1510. return array_map('ew_StripSlashes', $value);
  1511. } else {
  1512. return stripslashes($value);
  1513. }
  1514. }
  1515. // Add slashes for SQL
  1516. function ew_AdjustSql($val) {
  1517. $val = addslashes(trim($val));
  1518. return $val;
  1519. }
  1520. // Build SELECT SQL based on different sql part
  1521. function ew_BuildSelectSql($sSelect, $sWhere, $sGroupBy, $sHaving, $sOrderBy, $sFilter, $sSort) {
  1522. $sDbWhere = $sWhere;
  1523. if ($sDbWhere <> "") {
  1524. if ($sFilter <> "") $sDbWhere = "($sDbWhere) AND ($sFilter)";
  1525. } else {
  1526. $sDbWhere = $sFilter;
  1527. }
  1528. $sDbOrderBy = $sOrderBy;
  1529. if ($sSort <> "") $sDbOrderBy = $sSort;
  1530. $sSql = $sSelect;
  1531. if ($sDbWhere <> "") $sSql .= " WHERE " . $sDbWhere;
  1532. if ($sGroupBy <> "") $sSql .= " GROUP BY " . $sGroupBy;
  1533. if ($sHaving <> "") $sSql .= " HAVING " . $sHaving;
  1534. if ($sDbOrderBy <> "") $sSql .= " ORDER BY " . $sDbOrderBy;
  1535. return $sSql;
  1536. }
  1537. // Executes the query, and returns the first column of the first row
  1538. function ew_ExecuteScalar($SQL) {
  1539. global $conn;
  1540. if ($conn && $rs = $conn->Execute($SQL)) {
  1541. if (!$rs->EOF && $rs->FieldCount() > 0)
  1542. return $rs->fields[0];
  1543. }
  1544. return NULL;
  1545. }
  1546. // Write Audit Trail (login/logout)
  1547. function ew_WriteAuditTrailOnLogInOut($logtype) {
  1548. $table = $logtype;
  1549. $sKey = "";
  1550. // Write Audit Trail
  1551. $filePfx = "log";
  1552. $curDate = date("Y/m/d");
  1553. $curTime = date("H:i:s");
  1554. $id = ew_ScriptName();
  1555. $curUser = CurrentUserName();
  1556. $action = $logtype;
  1557. ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $curUser, $action, $table, "", "", "", "");
  1558. }
  1559. // Function for writing audit trail
  1560. function ew_WriteAuditTrail($pfx, $curDate, $curTime, $id, $user, $action, $table, $field, $keyvalue, $oldvalue, $newvalue) {
  1561. global $conn;
  1562. $sTab = "\t";
  1563. $userwrk = $user;
  1564. if ($userwrk == "") $userwrk = "-1"; // assume Administrator if no user
  1565. $sHeader = "date" . $sTab . "time" . $sTab . "id" .
  1566. $sTab . "user" . $sTab . "action" . $sTab . "table" .
  1567. $sTab . "field" . $sTab . "key value" . $sTab . "old value" .
  1568. $sTab . "new value";
  1569. $sMsg = $curDate . $sTab . $curTime . $sTab .
  1570. $id . $sTab . $userwrk . $sTab .
  1571. $action . $sTab . $table . $sTab .
  1572. $field . $sTab . $keyvalue . $sTab .
  1573. $oldvalue . $sTab . $newvalue;
  1574. $sFolder = EW_AUDIT_TRAIL_PATH;
  1575. $sFn = $pfx . "_" . date("Ymd") . ".txt";
  1576. $filename = ew_UploadPathEx(TRUE, $sFolder) . $sFn;
  1577. if (file_exists($filename)) {
  1578. $fileHandler = fopen($filename, "a+b");
  1579. } else {
  1580. $fileHandler = fopen($filename, "a+b");
  1581. fwrite($fileHandler,$sHeader."\r\n");
  1582. }
  1583. fwrite($fileHandler, $sMsg."\r\n");
  1584. fclose($fileHandler);
  1585. // Sample code to write audit trail to database
  1586. // (change the table and names according to your table schema)
  1587. // $sAuditSql = "INSERT INTO AuditTrailTable (`date`, `time`, `id`, `user`, " .
  1588. // "`action`, `table`, `field`, `keyvalue`, `oldvalue`, `newvalue`) VALUES (" .
  1589. // "'" . ew_AdjustSql($curDate) . "', " .
  1590. // "'" . ew_AdjustSql($curTime) . "', " .
  1591. // "'" . ew_AdjustSql($id) . "', " .
  1592. // "'" . ew_AdjustSql($userwrk) . "', " .
  1593. // "'" . ew_AdjustSql($action) . "', " .
  1594. // "'" . ew_AdjustSql($table) . "', " .
  1595. // "'" . ew_AdjustSql($field) . "', " .
  1596. // "'" . ew_AdjustSql($keyvalue) . "', " .
  1597. // "'" . ew_AdjustSql($oldvalue) . "', " .
  1598. // "'" . ew_AdjustSql($newvalue) . "')";
  1599. // // echo sAuditSql; // uncomment to debug
  1600. // $conn->Execute($sAuditSql);
  1601. }
  1602. // Unformat date time based on format type
  1603. function ew_UnFormatDateTime($dt, $namedformat) {
  1604. $dt = trim($dt);
  1605. while (strpos($dt, " ") !== FALSE) $dt = str_replace(" ", " ", $dt);
  1606. $arDateTime = explode(" ", $dt);
  1607. if (count($arDateTime) == 0) return $dt;
  1608. if ($namedformat == 0 || $namedformat == 1 || $namedformat == 2 || $namedformat == 8) {
  1609. $arDefFmt = explode(EW_DATE_SEPARATOR, EW_DEFAULT_DATE_FORMAT);
  1610. if ($arDefFmt[0] == "yyyy") {
  1611. $namedformat = 9;
  1612. } elseif ($arDefFmt[0] == "mm") {
  1613. $namedformat = 10;
  1614. } elseif ($arDefFmt[0] == "dd") {
  1615. $namedformat = 11;
  1616. }
  1617. }
  1618. $arDatePt = explode(EW_DATE_SEPARATOR, $arDateTime[0]);
  1619. if (count($arDatePt) == 3) {
  1620. switch ($namedformat) {
  1621. case 5:
  1622. case 9: //yyyymmdd
  1623. if (ew_CheckDate($arDateTime[0])) {
  1624. list($year, $month, $day) = $arDatePt;
  1625. break;
  1626. } else {
  1627. return $dt;
  1628. }
  1629. case 6:
  1630. case 10: //mmddyyyy
  1631. if (ew_CheckUSDate($arDateTime[0])) {
  1632. list($month, $day, $year) = $arDatePt;
  1633. break;
  1634. } else {
  1635. return $dt;
  1636. }
  1637. case 7:
  1638. case 11: //ddmmyyyy
  1639. if (ew_CheckEuroDate($arDateTime[0])) {
  1640. list($day, $month, $year) = $arDatePt;
  1641. break;
  1642. } else {
  1643. return $dt;
  1644. }
  1645. default:
  1646. return $dt;
  1647. }
  1648. return $year . "-" . str_pad($month, 2, "0", STR_PAD_LEFT) . "-" .
  1649. str_pad($day, 2, "0", STR_PAD_LEFT) .
  1650. ((count($arDateTime) > 1) ? " " . $arDateTime[1] : "");
  1651. } else {
  1652. return $dt;
  1653. }
  1654. }
  1655. //-------------------------------------------------------------------------------
  1656. // Functions for default date format
  1657. // FormatDateTime
  1658. //Format a timestamp, datetime, date or time field from MySQL
  1659. //$namedformat:
  1660. //0 - General Date,
  1661. //1 - Long Date,
  1662. //2 - Short Date (Default),
  1663. //3 - Long Time,
  1664. //4 - Short Time (hh:mm:ss),
  1665. //5 - Short Date (yyyy/mm/dd),
  1666. //6 - Short Date (mm/dd/yyyy),
  1667. //7 - Short Date (dd/mm/yyyy),
  1668. //8 - Short Date (Default) + Short Time (if not 00:00:00)
  1669. //9 - Short Date (yyyy/mm/dd) + Short Time (hh:mm:ss),
  1670. //10 - Short Date (mm/dd/yyyy) + Short Time (hh:mm:ss),
  1671. //11 - Short Date (dd/mm/yyyy) + Short Time (hh:mm:ss)
  1672. function ew_FormatDateTime($ts, $namedformat) {
  1673. $DefDateFormat = str_replace("yyyy", "%Y", EW_DEFAULT_DATE_FORMAT);
  1674. $DefDateFormat = str_replace("mm", "%m", $DefDateFormat);
  1675. $DefDateFormat = str_replace("dd", "%d", $DefDateFormat);
  1676. if (is_numeric($ts)) // timestamp
  1677. {
  1678. switch (strlen($ts)) {
  1679. case 14:
  1680. $patt = '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  1681. break;
  1682. case 12:
  1683. $patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  1684. break;
  1685. case 10:
  1686. $patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  1687. break;
  1688. case 8:
  1689. $patt = '/(\d{4})(\d{2})(\d{2})/';
  1690. break;
  1691. case 6:
  1692. $patt = '/(\d{2})(\d{2})(\d{2})/';
  1693. break;
  1694. case 4:
  1695. $patt = '/(\d{2})(\d{2})/';
  1696. break;
  1697. case 2:
  1698. $patt = '/(\d{2})/';
  1699. break;
  1700. default:
  1701. return $ts;
  1702. }
  1703. if ((isset($patt))&&(preg_match($patt, $ts, $matches)))
  1704. {
  1705. $year = $matches[1];
  1706. $month = @$matches[2];
  1707. $day = @$matches[3];
  1708. $hour = @$matches[4];
  1709. $min = @$matches[5];
  1710. $sec = @$matches[6];
  1711. }
  1712. if (($namedformat==0)&&(strlen($ts)<10)) $namedformat = 2;
  1713. }
  1714. elseif (is_string($ts))
  1715. {
  1716. if (preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // datetime
  1717. {
  1718. $year = $matches[1];
  1719. $month = $matches[2];
  1720. $day = $matches[3];
  1721. $hour = $matches[4];
  1722. $min = $matches[5];
  1723. $sec = $matches[6];
  1724. }
  1725. elseif (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $ts, $matches)) // date
  1726. {
  1727. $year = $matches[1];
  1728. $month = $matches[2];
  1729. $day = $matches[3];
  1730. if ($namedformat==0) $namedformat = 2;
  1731. }
  1732. elseif (preg_match('/(^|\s)(\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // time
  1733. {
  1734. $hour = $matches[2];
  1735. $min = $matches[3];
  1736. $sec = $matches[4];
  1737. if (($namedformat==0)||($namedformat==1)) $namedformat = 3;
  1738. if ($namedformat==2) $namedformat = 4;
  1739. }
  1740. else
  1741. {
  1742. return $ts;
  1743. }
  1744. }
  1745. else
  1746. {
  1747. return $ts;
  1748. }
  1749. if (!isset($year)) $year = 0; // dummy value for times
  1750. if (!isset($month)) $month = 1;
  1751. if (!isset($day)) $day = 1;
  1752. if (!isset($hour)) $hour = 0;
  1753. if (!isset($min)) $min = 0;
  1754. if (!isset($sec)) $sec = 0;
  1755. $uts = @mktime($hour, $min, $sec, $month, $day, $year);
  1756. if ($uts < 0 || $uts == FALSE || // failed to convert
  1757. (intval($year) == 0 && intval($month) == 0 && intval($day) == 0)) {
  1758. $year = substr_replace("0000", $year, -1 * strlen($year));
  1759. $month = substr_replace("00", $month, -1 * strlen($month));
  1760. $day = substr_replace("00", $day, -1 * strlen($day));
  1761. $hour = substr_replace("00", $hour, -1 * strlen($hour));
  1762. $min = substr_replace("00", $min, -1 * strlen($min));
  1763. $sec = substr_replace("00", $sec, -1 * strlen($sec));
  1764. $DefDateFormat = str_replace("yyyy", $year, EW_DEFAULT_DATE_FORMAT);
  1765. $DefDateFormat = str_replace("mm", $month, $DefDateFormat);
  1766. $DefDateFormat = str_replace("dd", $day, $DefDateFormat);
  1767. switch ($namedformat) {
  1768. case 0:
  1769. return $DefDateFormat." $hour:$min:$sec";
  1770. break;
  1771. case 1://unsupported, return general date
  1772. return $DefDateFormat." $hour:$min:$sec";
  1773. break;
  1774. case 2:
  1775. return $DefDateFormat;
  1776. break;
  1777. case 3:
  1778. if (intval($hour)==0)
  1779. return "12:$min:$sec AM";
  1780. elseif (intval($hour)>0 && intval($hour)<12)
  1781. return "$hour:$min:$sec AM";
  1782. elseif (intval($hour)==12)
  1783. return "$hour:$min:$sec PM";
  1784. elseif (intval($hour)>12 && intval($hour)<=23)
  1785. return (intval($hour)-12).":$min:$sec PM";
  1786. else
  1787. return "$hour:$min:$sec";
  1788. break;
  1789. case 4:
  1790. return "$hour:$min:$sec";
  1791. break;
  1792. case 5:
  1793. return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day";
  1794. break;
  1795. case 6:
  1796. return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year";
  1797. break;
  1798. case 7:
  1799. return "$day" . EW_DATE_SEPARATOR ."$month" . EW_DATE_SEPARATOR . "$year";
  1800. break;
  1801. case 8:
  1802. return $DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " $hour:$min:$sec");
  1803. break;
  1804. case 9:
  1805. return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day $hour:$min:$sec";
  1806. break;
  1807. case 10:
  1808. return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year $hour:$min:$sec";
  1809. break;
  1810. case 11:
  1811. return "$day" . EW_DATE_SEPARATOR ."$month" . EW_DATE_SEPARATOR . "$year $hour:$min:$sec";
  1812. break;
  1813. }
  1814. } else {
  1815. switch ($namedformat) {
  1816. case 0:
  1817. return strftime($DefDateFormat." %H:%M:%S", $uts);
  1818. break;
  1819. case 1:
  1820. return strftime("%A, %B %d, %Y", $uts);
  1821. break;
  1822. case 2:
  1823. return strftime($DefDateFormat, $uts);
  1824. break;
  1825. case 3:
  1826. return strftime("%I:%M:%S %p", $uts);
  1827. break;
  1828. case 4:
  1829. return strftime("%H:%M:%S", $uts);
  1830. break;
  1831. case 5:
  1832. return strftime("%Y" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%d", $uts);
  1833. break;
  1834. case 6:
  1835. return strftime("%m" . EW_DATE_SEPARATOR . "%d" . EW_DATE_SEPARATOR . "%Y", $uts);
  1836. break;
  1837. case 7:
  1838. return strftime("%d" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%Y", $uts);
  1839. break;
  1840. case 8:
  1841. return strftime($DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " %H:%M:%S"), $uts);
  1842. break;
  1843. case 9:
  1844. return strftime("%Y" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%d %H:%M:%S", $uts);
  1845. break;
  1846. case 10:
  1847. return strftime("%m" . EW_DATE_SEPARATOR . "%d" . EW_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
  1848. break;
  1849. case 11:
  1850. return strftime("%d" . EW_DATE_SEPARATOR . "%m" . EW_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
  1851. break;
  1852. }
  1853. }
  1854. }
  1855. // FormatCurrency
  1856. //ew_FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  1857. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  1858. //NumDigitsAfterDecimal is the numeric value indicating how many places to the
  1859. //right of the decimal are displayed
  1860. //-1 Use Default
  1861. //The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  1862. //arguments have the following settings:
  1863. //-1 True
  1864. //0 False
  1865. //-2 Use Default
  1866. function ew_FormatCurrency($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  1867. // export the values returned by localeconv into the local scope
  1868. if (!EW_USE_DEFAULT_LOCALE) extract(localeconv()); // PHP 4 >= 4.0.5
  1869. // set defaults if locale is not set
  1870. if (empty($decimal_point)) $decimal_point = DEFAULT_DECIMAL_POINT;
  1871. if (empty($thousands_sep)) $thousands_sep = DEFAULT_THOUSANDS_SEP;
  1872. if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
  1873. if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
  1874. if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
  1875. if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
  1876. if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
  1877. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
  1878. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
  1879. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
  1880. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
  1881. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
  1882. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
  1883. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
  1884. // check $NumDigitsAfterDecimal
  1885. if ($NumDigitsAfterDecimal > -1)
  1886. $frac_digits = $NumDigitsAfterDecimal;
  1887. // check $UseParensForNegativeNumbers
  1888. if ($UseParensForNegativeNumbers == -1) {
  1889. $n_sign_posn = 0;
  1890. if ($p_sign_posn == 0) {
  1891. if (DEFAULT_P_SIGN_POSN != 0)
  1892. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  1893. else
  1894. $p_sign_posn = 3;
  1895. }
  1896. } elseif ($UseParensForNegativeNumbers == 0) {
  1897. if ($n_sign_posn == 0)
  1898. if (DEFAULT_P_SIGN_POSN != 0)
  1899. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  1900. else
  1901. $n_sign_posn = 3;
  1902. }
  1903. // check $GroupDigits
  1904. if ($GroupDigits == -1) {
  1905. $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
  1906. } elseif ($GroupDigits == 0) {
  1907. $mon_thousands_sep = "";
  1908. }
  1909. // start by formatting the unsigned number
  1910. $number = number_format(abs($amount),
  1911. $frac_digits,
  1912. $mon_decimal_point,
  1913. $mon_thousands_sep);
  1914. // check $IncludeLeadingDigit
  1915. if ($IncludeLeadingDigit == 0) {
  1916. if (substr($number, 0, 2) == "0.")
  1917. $number = substr($number, 1, strlen($number)-1);
  1918. }
  1919. if ($amount < 0) {
  1920. $sign = $negative_sign;
  1921. // "extracts" the boolean value as an integer
  1922. $n_cs_precedes = intval($n_cs_precedes == true);
  1923. $n_sep_by_space = intval($n_sep_by_space == true);
  1924. $key = $n_cs_precedes . $n_sep_by_space . $n_sign_posn;
  1925. } else {
  1926. $sign = $positive_sign;
  1927. $p_cs_precedes = intval($p_cs_precedes == true);
  1928. $p_sep_by_space = intval($p_sep_by_space == true);
  1929. $key = $p_cs_precedes . $p_sep_by_space . $p_sign_posn;
  1930. }
  1931. $formats = array(
  1932. // currency symbol is after amount
  1933. // no space between amount and sign
  1934. '000' => '(%s' . $currency_symbol . ')',
  1935. '001' => $sign . '%s ' . $currency_symbol,
  1936. '002' => '%s' . $currency_symbol . $sign,
  1937. '003' => '%s' . $sign . $currency_symbol,
  1938. '004' => '%s' . $sign . $currency_symbol,
  1939. // one space between amount and sign
  1940. '010' => '(%s ' . $currency_symbol . ')',
  1941. '011' => $sign . '%s ' . $currency_symbol,
  1942. '012' => '%s ' . $currency_symbol . $sign,
  1943. '013' => '%s ' . $sign . $currency_symbol,
  1944. '014' => '%s ' . $sign . $currency_symbol,
  1945. // currency symbol is before amount
  1946. // no space between amount and sign
  1947. '100' => '(' . $currency_symbol . '%s)',
  1948. '101' => $sign . $currency_symbol . '%s',
  1949. '102' => $currency_symbol . '%s' . $sign,
  1950. '103' => $sign . $currency_symbol . '%s',
  1951. '104' => $currency_symbol . $sign . '%s',
  1952. // one space between amount and sign
  1953. '110' => '(' . $currency_symbol . ' %s)',
  1954. '111' => $sign . $currency_symbol . ' %s',
  1955. '112' => $currency_symbol . ' %s' . $sign,
  1956. '113' => $sign . $currency_symbol . ' %s',
  1957. '114' => $currency_symbol . ' ' . $sign . '%s');
  1958. // lookup the key in the above array
  1959. return sprintf($formats[$key], $number);
  1960. }
  1961. // FormatNumber
  1962. //ew_FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  1963. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  1964. //NumDigitsAfterDecimal is the numeric value indicating how many places to the
  1965. //right of the decimal are displayed
  1966. //-1 Use Default
  1967. //The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  1968. //arguments have the following settings:
  1969. //-1 True
  1970. //0 False
  1971. //-2 Use Default
  1972. function ew_FormatNumber($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  1973. // export the values returned by localeconv into the local scope
  1974. if (!EW_USE_DEFAULT_LOCALE) extract(localeconv()); // PHP 4 >= 4.0.5
  1975. // set defaults if locale is not set
  1976. if (empty($decimal_point)) $decimal_point = DEFAULT_DECIMAL_POINT;
  1977. if (empty($thousands_sep)) $thousands_sep = DEFAULT_THOUSANDS_SEP;
  1978. if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
  1979. if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
  1980. if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
  1981. if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
  1982. if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
  1983. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
  1984. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
  1985. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
  1986. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
  1987. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
  1988. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
  1989. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
  1990. // check $NumDigitsAfterDecimal
  1991. if ($NumDigitsAfterDecimal > -1)
  1992. $frac_digits = $NumDigitsAfterDecimal;
  1993. // check $UseParensForNegativeNumbers
  1994. if ($UseParensForNegativeNumbers == -1) {
  1995. $n_sign_posn = 0;
  1996. if ($p_sign_posn == 0) {
  1997. if (DEFAULT_P_SIGN_POSN != 0)
  1998. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  1999. else
  2000. $p_sign_posn = 3;
  2001. }
  2002. } elseif ($UseParensForNegativeNumbers == 0) {
  2003. if ($n_sign_posn == 0)
  2004. if (DEFAULT_P_SIGN_POSN != 0)
  2005. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  2006. else
  2007. $n_sign_posn = 3;
  2008. }
  2009. // check $GroupDigits
  2010. if ($GroupDigits == -1) {
  2011. $thousands_sep = DEFAULT_THOUSANDS_SEP;
  2012. } elseif ($GroupDigits == 0) {
  2013. $thousands_sep = "";
  2014. }
  2015. // start by formatting the unsigned number
  2016. $number = number_format(abs($amount),
  2017. $frac_digits,
  2018. $decimal_point,
  2019. $thousands_sep);
  2020. // check $IncludeLeadingDigit
  2021. if ($IncludeLeadingDigit == 0) {
  2022. if (substr($number, 0, 2) == "0.")
  2023. $number = substr($number, 1, strlen($number)-1);
  2024. }
  2025. if ($amount < 0) {
  2026. $sign = $negative_sign;
  2027. $key = $n_sign_posn;
  2028. } else {
  2029. $sign = $positive_sign;
  2030. $key = $p_sign_posn;
  2031. }
  2032. $formats = array(
  2033. '0' => '(%s)',
  2034. '1' => $sign . '%s',
  2035. '2' => $sign . '%s',
  2036. '3' => $sign . '%s',
  2037. '4' => $sign . '%s');
  2038. // lookup the key in the above array
  2039. return sprintf($formats[$key], $number);
  2040. }
  2041. // FormatPercent
  2042. //ew_FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  2043. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  2044. //NumDigitsAfterDecimal is the numeric value indicating how many places to the
  2045. //right of the decimal are displayed
  2046. //-1 Use Default
  2047. //The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  2048. //arguments have the following settings:
  2049. //-1 True
  2050. //0 False
  2051. //-2 Use Default
  2052. function ew_FormatPercent($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  2053. // export the values returned by localeconv into the local scope
  2054. if (!EW_USE_DEFAULT_LOCALE) extract(localeconv()); // PHP 4 >= 4.0.5
  2055. // set defaults if locale is not set
  2056. if (empty($decimal_point)) $decimal_point = DEFAULT_DECIMAL_POINT;
  2057. if (empty($thousands_sep)) $thousands_sep = DEFAULT_THOUSANDS_SEP;
  2058. if (empty($currency_symbol)) $currency_symbol = DEFAULT_CURRENCY_SYMBOL;
  2059. if (empty($mon_decimal_point)) $mon_decimal_point = DEFAULT_MON_DECIMAL_POINT;
  2060. if (empty($mon_thousands_sep)) $mon_thousands_sep = DEFAULT_MON_THOUSANDS_SEP;
  2061. if (empty($positive_sign)) $positive_sign = DEFAULT_POSITIVE_SIGN;
  2062. if (empty($negative_sign)) $negative_sign = DEFAULT_NEGATIVE_SIGN;
  2063. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = DEFAULT_FRAC_DIGITS;
  2064. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = DEFAULT_P_CS_PRECEDES;
  2065. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = DEFAULT_P_SEP_BY_SPACE;
  2066. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = DEFAULT_N_CS_PRECEDES;
  2067. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = DEFAULT_N_SEP_BY_SPACE;
  2068. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = DEFAULT_P_SIGN_POSN;
  2069. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = DEFAULT_N_SIGN_POSN;
  2070. // check $NumDigitsAfterDecimal
  2071. if ($NumDigitsAfterDecimal > -1)
  2072. $frac_digits = $NumDigitsAfterDecimal;
  2073. // check $UseParensForNegativeNumbers
  2074. if ($UseParensForNegativeNumbers == -1) {
  2075. $n_sign_posn = 0;
  2076. if ($p_sign_posn == 0) {
  2077. if (DEFAULT_P_SIGN_POSN != 0)
  2078. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  2079. else
  2080. $p_sign_posn = 3;
  2081. }
  2082. } elseif ($UseParensForNegativeNumbers == 0) {
  2083. if ($n_sign_posn == 0)
  2084. if (DEFAULT_P_SIGN_POSN != 0)
  2085. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  2086. else
  2087. $n_sign_posn = 3;
  2088. }
  2089. // check $GroupDigits
  2090. if ($GroupDigits == -1) {
  2091. $thousands_sep = DEFAULT_THOUSANDS_SEP;
  2092. } elseif ($GroupDigits == 0) {
  2093. $thousands_sep = "";
  2094. }
  2095. // start by formatting the unsigned number
  2096. $number = number_format(abs($amount)*100,
  2097. $frac_digits,
  2098. $decimal_point,
  2099. $thousands_sep);
  2100. // check $IncludeLeadingDigit
  2101. if ($IncludeLeadingDigit == 0) {
  2102. if (substr($number, 0, 2) == "0.")
  2103. $number = substr($number, 1, strlen($number)-1);
  2104. }
  2105. if ($amount < 0) {
  2106. $sign = $negative_sign;
  2107. $key = $n_sign_posn;
  2108. } else {
  2109. $sign = $positive_sign;
  2110. $key = $p_sign_posn;
  2111. }
  2112. $formats = array(
  2113. '0' => '(%s%%)',
  2114. '1' => $sign . '%s%%',
  2115. '2' => $sign . '%s%%',
  2116. '3' => $sign . '%s%%',
  2117. '4' => $sign . '%s%%');
  2118. // lookup the key in the above array
  2119. return sprintf($formats[$key], $number);
  2120. }
  2121. // Encode html
  2122. function ew_HtmlEncode($exp) {
  2123. return htmlspecialchars(strval($exp));
  2124. }
  2125. // Encode value for single-quoted JavaScript string
  2126. function ew_JsEncode($val) {
  2127. return str_replace("'", "\\'", strval($val));
  2128. }
  2129. // Generate Value Separator based on current row count
  2130. // rowcnt - zero based row count
  2131. function ew_ValueSeparator($rowcnt) {
  2132. return ", ";
  2133. }
  2134. // Generate View Option Separator based on current row count (Multi-Select / CheckBox)
  2135. // rowcnt - zero based row count
  2136. function ew_ViewOptionSeparator($rowcnt) {
  2137. $sep = ", ";
  2138. // Sample code to adjust 2 options per row
  2139. //if (($rowcnt + 1) % 2 == 0) { // 2 options per row
  2140. //return $sep += "<br>";
  2141. //}
  2142. return $sep;
  2143. }
  2144. // Move uploaded file
  2145. function ew_MoveUploadFile($srcfile, $destfile) {
  2146. $res = move_uploaded_file($srcfile, $destfile);
  2147. if ($res) chmod($destfile, EW_UPLOADED_FILE_MODE);
  2148. return $res;
  2149. }
  2150. // Render repeat column table
  2151. // rowcnt - zero based row count
  2152. function ew_RepeatColumnTable($totcnt, $rowcnt, $repeatcnt, $rendertype) {
  2153. $sWrk = "";
  2154. if ($rendertype == 1) { // Render control start
  2155. if ($rowcnt == 0) $sWrk .= "<table class=\"" . EW_ITEM_TABLE_CLASSNAME . "\">";
  2156. if ($rowcnt % $repeatcnt == 0) $sWrk .= "<tr>";
  2157. $sWrk .= "<td>";
  2158. } elseif ($rendertype == 2) { // Render control end
  2159. $sWrk .= "</td>";
  2160. if ($rowcnt % $repeatcnt == $repeatcnt - 1) {
  2161. $sWrk .= "</tr>";
  2162. } elseif ($rowcnt == $totcnt - 1) {
  2163. for ($i = ($rowcnt % $repeatcnt) + 1; $i < $repeatcnt; $i++) {
  2164. $sWrk .= "<td>&nbsp;</td>";
  2165. }
  2166. $sWrk .= "</tr>";
  2167. }
  2168. if ($rowcnt == $totcnt - 1) $sWrk .= "</table>";
  2169. }
  2170. return $sWrk;
  2171. }
  2172. // Truncate Memo Field based on specified length, string truncated to nearest space or CrLf
  2173. function ew_TruncateMemo($str, $ln) {
  2174. if (strlen($str) > 0 && strlen($str) > $ln) {
  2175. $k = 0;
  2176. while ($k >= 0 && $k < strlen($str)) {
  2177. $i = strpos($str, " ", $k);
  2178. $j = strpos($str, chr(10), $k);
  2179. if ($i === FALSE && $j === FALSE) { // Not able to truncate
  2180. return $str;
  2181. } else {
  2182. // Get nearest space or CrLf
  2183. if ($i > 0 && $j > 0) {
  2184. if ($i < $j) {
  2185. $k = $i;
  2186. } else {
  2187. $k = $j;
  2188. }
  2189. } elseif ($i > 0) {
  2190. $k = $i;
  2191. } elseif ($j > 0) {
  2192. $k = $j;
  2193. }
  2194. // Get truncated text
  2195. if ($k >= $ln) {
  2196. return substr($str, 0, $k) . "...";
  2197. } else {
  2198. $k++;
  2199. }
  2200. }
  2201. }
  2202. } else {
  2203. return $str;
  2204. }
  2205. }
  2206. // Send notify email
  2207. function ew_SendNotifyEmail($sFn, $sSubject, $sTable, $sKey, $sAction) {
  2208. // Send Email
  2209. if (EW_SENDER_EMAIL <> "" && EW_RECIPIENT_EMAIL <> "") {
  2210. return ew_SendTemplateEmail($sFn, EW_SENDER_EMAIL, EW_RECIPIENT_EMAIL, "", "",
  2211. $sSubject, array("<!--table-->" => $sTable, "<!--key-->" => $sKey, "<!--action-->" => $sAction));
  2212. }
  2213. }
  2214. // Send email by template
  2215. Function ew_SendTemplateEmail($sTemplate, $sSender, $sRecipient, $sCcEmail, $sBccEmail, $sSubject, $arContent) {
  2216. if ($sSender <> "" && $sRecipient <> "") {
  2217. $Email = new cEmail;
  2218. $Email->Load($sTemplate);
  2219. $Email->ReplaceSender($sSender); // Replace Sender
  2220. $Email->ReplaceRecipient($sRecipient); // Replace Recipient
  2221. if ($sCcEmail <> "") $Email->AddCc($sCcEmail); // Add Cc
  2222. if ($sBccEmail <> "") $Email->AddBcc($sBccEmail); // Add Bcc
  2223. if ($sSubject <> "") $Email->ReplaceSubject($sSubject); // Replace subject
  2224. if (is_array($arContent)) {
  2225. foreach ($arContent as $key => $value)
  2226. $Email->ReplaceContent($key, $value);
  2227. }
  2228. return $Email->Send();
  2229. }
  2230. return FALSE;
  2231. }
  2232. // Include PHPMailer class is selected
  2233. if (EW_EMAIL_COMPONENT == "PHPMAILER") {
  2234. include("phpmailer" . EW_PATH_DELIMITER . "class.phpmailer.php");
  2235. }
  2236. // Function to send email
  2237. function ew_SendEmail($sFrEmail, $sToEmail, $sCcEmail, $sBccEmail, $sSubject, $sMail, $sFormat) {
  2238. /* for debug only
  2239. echo "sSubject: " . $sSubject . "<br>";
  2240. echo "sFrEmail: " . $sFrEmail . "<br>";
  2241. echo "sToEmail: " . $sToEmail . "<br>";
  2242. echo "sCcEmail: " . $sCcEmail . "<br>";
  2243. echo "sSubject: " . $sSubject . "<br>";
  2244. echo "sMail: " . $sMail . "<br>";
  2245. echo "sFormat: " . $sFormat . "<br>";
  2246. exit();
  2247. */
  2248. if (EW_EMAIL_COMPONENT == "PHPMAILER") {
  2249. $mail = new PHPMailer();
  2250. $mail->IsSMTP();
  2251. $mail->Host = EW_SMTP_SERVER;
  2252. $mail->SMTPAuth = (EW_SMTP_SERVER_USERNAME <> "" && EW_SMTP_SERVER_PASSWORD <> "");
  2253. $mail->Username = EW_SMTP_SERVER_USERNAME;
  2254. $mail->Password = EW_SMTP_SERVER_PASSWORD;
  2255. $mail->Port = EW_SMTP_SERVER_PORT;
  2256. $mail->From = $sFrEmail;
  2257. $mail->FromName = $sFrEmail;
  2258. $mail->Subject = $sSubject;
  2259. $mail->Body = $sMail;
  2260. $sToEmail = str_replace(";", ",", $sToEmail);
  2261. $arrTo = explode(",", $sToEmail);
  2262. foreach ($arrTo as $sTo) {
  2263. $mail->AddAddress(trim($sTo));
  2264. }
  2265. if ($sCcEmail <> "") {
  2266. $sCcEmail = str_replace(";", ",", $sCcEmail);
  2267. $arrCc = explode(",", $sCcEmail);
  2268. foreach ($arrCc as $sCc) {
  2269. $mail->AddCC(trim($sCc));
  2270. }
  2271. }
  2272. if ($sBccEmail <> "") {
  2273. $sBccEmail = str_replace(";", ",", $sBccEmail);
  2274. $arrBcc = explode(",", $sBccEmail);
  2275. foreach ($arrBcc as $sBcc) {
  2276. $mail->AddBCC(trim($sBcc));
  2277. }
  2278. }
  2279. if (strtolower($sFormat) == "html") {
  2280. $mail->ContentType = "text/html";
  2281. } else {
  2282. $mail->ContentType = "text/plain";
  2283. }
  2284. $res = $mail->Send();
  2285. $mail->ClearAddresses();
  2286. $mail->ClearAttachments();
  2287. return $res;
  2288. } else {
  2289. $to = $sToEmail;
  2290. $subject = $sSubject;
  2291. $headers = "";
  2292. if (strtolower($sFormat) == "html") {
  2293. $content_type = "text/html";
  2294. } else {
  2295. $content_type = "text/plain";
  2296. }
  2297. $headers = "Content-type: " . $content_type . "\r\n";
  2298. $message = $sMail;
  2299. $headers .= "From: " . str_replace(";", ",", $sFrEmail) . "\r\n";
  2300. if ($sCcEmail <> "") {
  2301. $headers .= "Cc: " . str_replace(";", ",", $sCcEmail) . "\r\n";
  2302. }
  2303. if ($sBccEmail <>"") {
  2304. $headers .= "Bcc: " . str_replace(";", ",", $sBccEmail) . "\r\n";
  2305. }
  2306. if (EW_IS_WINDOWS) {
  2307. if (EW_SMTP_SERVER <> "")
  2308. ini_set("SMTP", EW_SMTP_SERVER);
  2309. if (is_int(EW_SMTP_SERVER_PORT))
  2310. ini_set("smtp_port", EW_SMTP_SERVER_PORT);
  2311. }
  2312. ini_set("sendmail_from", $sFrEmail);
  2313. return mail($to, $subject, $message, $headers);
  2314. }
  2315. }
  2316. // Field data type
  2317. function ew_FieldDataType($fldtype) {
  2318. switch ($fldtype) {
  2319. case 20:
  2320. case 3:
  2321. case 2:
  2322. case 16:
  2323. case 4:
  2324. case 5:
  2325. case 131:
  2326. case 6:
  2327. case 17:
  2328. case 18:
  2329. case 19:
  2330. case 21: // Numeric
  2331. return EW_DATATYPE_NUMBER;
  2332. case 7:
  2333. case 133:
  2334. case 135: // Date
  2335. return EW_DATATYPE_DATE;
  2336. case 134: // Time
  2337. return EW_DATATYPE_TIME;
  2338. case 201:
  2339. case 203: // Memo
  2340. return EW_DATATYPE_MEMO;
  2341. case 129:
  2342. case 130:
  2343. case 200:
  2344. case 202: // String
  2345. return EW_DATATYPE_STRING;
  2346. case 11: // Boolean
  2347. return EW_DATATYPE_BOOLEAN;
  2348. case 72: // GUID
  2349. return EW_DATATYPE_GUID;
  2350. case 128:
  2351. case 204:
  2352. case 205: // Binary
  2353. return EW_DATATYPE_BLOB;
  2354. default:
  2355. return EW_DATATYPE_OTHER;
  2356. }
  2357. }
  2358. // function to get application root
  2359. function ew_AppRoot() {
  2360. // 1. use root relative path
  2361. if (EW_ROOT_RELATIVE_PATH <> "") {
  2362. $Path = realpath(EW_ROOT_RELATIVE_PATH);
  2363. $Path = str_replace("\\\\", EW_PATH_DELIMITER, $Path);
  2364. }
  2365. // 2. if empty, use the document root if available
  2366. if (empty($Path)) $Path = ew_ServerVar("DOCUMENT_ROOT");
  2367. // 3. if empty, use current folder
  2368. if (empty($Path)) $Path = realpath(".");
  2369. // 4. use custom path, uncomment the following line and enter your path
  2370. // e.g. $Path = 'C:\Inetpub\wwwroot\MyWebRoot'; // Windows
  2371. //$Path = 'enter your path here';
  2372. if (empty($Path)) die("Path of website root unknown.");
  2373. return ew_IncludeTrailingDelimiter($Path, TRUE);
  2374. }
  2375. // Get path relative to application root
  2376. function ew_ServerMapPath($Path) {
  2377. return ew_PathCombine(ew_AppRoot(), $Path, TRUE);
  2378. }
  2379. // Get path relative to a base path
  2380. function ew_PathCombine($BasePath, $RelPath, $PhyPath) {
  2381. $BasePath = ew_RemoveTrailingDelimiter($BasePath, TRUE);
  2382. if ($PhyPath) {
  2383. $Delimiter = EW_PATH_DELIMITER;
  2384. $RelPath = str_replace('/', EW_PATH_DELIMITER, $RelPath);
  2385. $RelPath = str_replace('\\', EW_PATH_DELIMITER, $RelPath);
  2386. } else {
  2387. $Delimiter = '/';
  2388. $RelPath = str_replace('\\', '/', $RelPath);
  2389. }
  2390. if ($RelPath == '.' || $RelPath == '..') $RelPath .= $Delimiter;
  2391. $p1 = strpos($RelPath, $Delimiter);
  2392. $Path2 = "";
  2393. while ($p1 !== FALSE) {
  2394. $Path = substr($RelPath, 0, $p1 + 1);
  2395. if ($Path == $Delimiter || $Path == ".$Delimiter") {
  2396. // Skip
  2397. } elseif ($Path == "..$Delimiter") {
  2398. $p2 = strrpos($BasePath, $Delimiter);
  2399. if ($p2 !== FALSE) $BasePath = substr($BasePath, 0, $p2-1);
  2400. } else {
  2401. $Path2 .= $Path;
  2402. }
  2403. $RelPath = substr($RelPath, p1+1);
  2404. $p1 = strpos($RelPath, $Delimiter);
  2405. }
  2406. return ew_IncludeTrailingDelimiter($BasePath, TRUE) . $Path2 . $RelPath;
  2407. }
  2408. // Remove the last delimiter for a path
  2409. function ew_RemoveTrailingDelimiter($Path, $PhyPath) {
  2410. $Delimiter = ($PhyPath) ? EW_PATH_DELIMITER : '/';
  2411. while (substr($Path, -1) == $Delimiter)
  2412. $Path = substr($Path, 0, strlen($Path)-1);
  2413. return $Path;
  2414. }
  2415. // Include the last delimiter for a path
  2416. function ew_IncludeTrailingDelimiter($Path, $PhyPath) {
  2417. $Path = ew_RemoveTrailingDelimiter($Path, $PhyPath);
  2418. $Delimiter = ($PhyPath) ? EW_PATH_DELIMITER : '/';
  2419. return $Path . $Delimiter;
  2420. }
  2421. // function to include the last delimiter for a path
  2422. //function ew_IncludeTrailingDelimiter($Path, $PhyPath) {
  2423. // if ($PhyPath) {
  2424. // if (substr($Path, -1) <> EW_PATH_DELIMITER) $Path .= EW_PATH_DELIMITER;
  2425. // } else {
  2426. // if (substr($Path, -1) <> "/") $Path .= "/";
  2427. // }
  2428. // return $Path;
  2429. //}
  2430. // function to write the paths for config/debug only
  2431. function ew_WritePaths() {
  2432. echo 'DOCUMENT_ROOT=' . ew_ServerVar("DOCUMENT_ROOT") . "<br>";
  2433. echo 'EW_ROOT_RELATIVE_PATH=' . EW_ROOT_RELATIVE_PATH . "<br>";
  2434. echo 'ew_AppRoot()=' . ew_AppRoot() . "<br>";
  2435. echo 'realpath(".")=' . realpath(".") . "<br>";
  2436. echo '__FILE__=' . __FILE__ . "<br>";
  2437. }
  2438. // function to return path of the uploaded file
  2439. // Parameter: If PhyPath is true(1), return physical path on the server;
  2440. // If PhyPath is false(0), return relative URL
  2441. function ew_UploadPathEx($PhyPath, $DestPath) {
  2442. if ($PhyPath) {
  2443. $Path = ew_AppRoot();
  2444. $Path .= str_replace("/", EW_PATH_DELIMITER, $DestPath);
  2445. } else {
  2446. $Path = EW_ROOT_RELATIVE_PATH;
  2447. $Path = str_replace("\\\\", "/", $Path);
  2448. $Path = str_replace("\\", "/", $Path);
  2449. $Path = ew_IncludeTrailingDelimiter($Path, FALSE) . $DestPath;
  2450. }
  2451. return ew_IncludeTrailingDelimiter($Path, $PhyPath);
  2452. }
  2453. // Return path of the uploaded file
  2454. // returns global upload folder, for backward compatibility only
  2455. function ew_UploadPath($PhyPath) {
  2456. return ew_UploadPathEx($PhyPath, EW_UPLOAD_DEST_PATH);
  2457. }
  2458. function ew_UploadFileNameEx($folder, $sFileName) {
  2459. // By default, ew_UniqueFileName() is used to get an unique file name,
  2460. // you can change the logic here
  2461. $sOutFileName = ew_UniqueFilename($folder, $sFileName);
  2462. // Return computed output file name
  2463. return $sOutFileName;
  2464. }
  2465. // function to generate an unique file name (filename(n).ext)
  2466. function ew_UniqueFilename($folder, $oriFilename) {
  2467. if ($oriFilename == "") $oriFilename = ew_DefaultFileName();
  2468. $oriFilename = str_replace(" ", "_", $oriFilename);
  2469. $oriFilename = strtolower(basename($oriFilename));
  2470. $destFullPath = $folder . $oriFilename;
  2471. $newFilename = $oriFilename;
  2472. $i = 1;
  2473. if (!file_exists($folder)) {
  2474. if (!ew_CreateFolder($folder)) {
  2475. die("Folder does not exist: " . $folder);
  2476. }
  2477. }
  2478. while (file_exists($destFullPath)) {
  2479. $file_extension = strtolower(strrchr($oriFilename, "."));
  2480. $file_name = basename($oriFilename, $file_extension);
  2481. $newFilename = $file_name . "($i)" . $file_extension;
  2482. $destFullPath = $folder . $newFilename;
  2483. $i++;
  2484. }
  2485. return $newFilename;
  2486. }
  2487. // function to create a default file name(yyyymmddhhmmss.bin)
  2488. function ew_DefaultFileName() {
  2489. return date("YmdHis") . ".bin";
  2490. }
  2491. // Get current page name
  2492. function ew_CurrentPage() {
  2493. return ew_GetPageName(ew_ScriptName());
  2494. }
  2495. // Get refer page name
  2496. function ew_ReferPage() {
  2497. return ew_GetPageName(ew_ServerVar("HTTP_REFERER"));
  2498. }
  2499. // Get page name
  2500. function ew_GetPageName($url) {
  2501. $PageName = "";
  2502. if ($url <> "") {
  2503. $PageName = $url;
  2504. $p = strpos($PageName, "?");
  2505. if ($p !== FALSE)
  2506. $PageName = substr($PageName, 0, $p); // Remove querystring
  2507. $p = strrpos($PageName, "/");
  2508. if ($p !== FALSE)
  2509. $PageName = substr($PageName, $p+1); // Remove path
  2510. }
  2511. return $PageName;
  2512. }
  2513. // Get script physical folder
  2514. function ew_ScriptFolder() {
  2515. $folder = "";
  2516. $path = ew_ServerVar("SCRIPT_FILENAME");
  2517. $p = strrpos($path, EW_PATH_DELIMITER);
  2518. if ($p !== FALSE)
  2519. $folder = substr($path, 0, $p);
  2520. return ($folder <> "") ? $folder : realpath(".");
  2521. }
  2522. // Get full url
  2523. function ew_FullUrl() {
  2524. $sUrl = "http";
  2525. $bSSL = (ew_ServerVar("HTTPS") <> "" && ew_ServerVar("HTTPS") <> "off");
  2526. $sPort = strval(ew_ServerVar("SERVER_PORT"));
  2527. $defPort = ($bSSL) ? "443" : "80";
  2528. $sPort = ($sPort == $defPort) ? "" : ":$sPort";
  2529. $sUrl .= ($bSSL) ? "s" : "";
  2530. $sUrl .= "://";
  2531. $sUrl .= ew_ServerVar("SERVER_NAME") . $sPort . ew_ScriptName();
  2532. return $sUrl;
  2533. }
  2534. // Convert to full url
  2535. function ew_ConvertFullUrl($url) {
  2536. if ($url == "") return "";
  2537. $sUrl = ew_FullUrl();
  2538. return substr($sUrl, 0, strrpos($sUrl, "/")+1) . $url;
  2539. }
  2540. // Get a temp folder for temp file
  2541. function ew_TmpFolder() {
  2542. $tmpfolder = NULL;
  2543. $folders = array();
  2544. if (EW_IS_WINDOWS) {
  2545. $folders[] = ew_ServerVar("TEMP");
  2546. $folders[] = ew_ServerVar("TMP");
  2547. } else {
  2548. if (EW_UPLOAD_TMP_PATH <> "") $folders[] = ew_AppRoot() . str_replace("/", EW_PATH_DELIMITER, EW_UPLOAD_TMP_PATH);
  2549. $folders[] = '/tmp';
  2550. }
  2551. if (ini_get('upload_tmp_dir')) {
  2552. $folders[] = ini_get('upload_tmp_dir');
  2553. }
  2554. foreach ($folders as $folder) {
  2555. if (!$tmpfolder && is_dir($folder)) {
  2556. $tmpfolder = $folder;
  2557. }
  2558. }
  2559. //if ($tmpfolder) $tmpfolder = ew_IncludeTrailingDelimiter($tmpfolder, TRUE);
  2560. return $tmpfolder;
  2561. }
  2562. // Create folder
  2563. function ew_CreateFolder($dir, $mode = 0777) {
  2564. if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
  2565. if (!ew_CreateFolder(dirname($dir), $mode)) return FALSE;
  2566. return @mkdir($dir, $mode);
  2567. }
  2568. // Load file data
  2569. function ew_ReadFile($file) {
  2570. $content = '';
  2571. if ($handle = @fopen($file, 'r')) {
  2572. $content = fread($handle, filesize($file));
  2573. fclose($handle);
  2574. }
  2575. return $content;
  2576. }
  2577. // Save file
  2578. function ew_SaveFile($folder, $fn, $filedata) {
  2579. $res = FALSE;
  2580. if (ew_CreateFolder($folder)) {
  2581. if ($handle = fopen($folder . $fn, 'w')) { // P6
  2582. $res = fwrite($handle, $filedata);
  2583. fclose($handle);
  2584. }
  2585. if ($res)
  2586. chmod($folder . $fn, EW_UPLOADED_FILE_MODE);
  2587. }
  2588. return $res;
  2589. }
  2590. // function to generate random number
  2591. function ew_Random() {
  2592. if (phpversion() < "4.2.0") {
  2593. list($usec, $sec) = explode(' ', microtime());
  2594. $seed = (float) $sec + ((float) $usec * 100000);
  2595. mt_srand($seed);
  2596. }
  2597. return mt_rand();
  2598. }
  2599. // function to remove CR and LF
  2600. function ew_RemoveCrLf($s) {
  2601. if (strlen($s) > 0) {
  2602. $s = str_replace("\n", " ", $s);
  2603. $s = str_replace("\r", " ", $s);
  2604. $s = str_replace("\l", " ", $s);
  2605. }
  2606. return $s;
  2607. }
  2608. // Functions for Export
  2609. function ew_ExportHeader($ExpType) {
  2610. switch ($ExpType) {
  2611. case "html":
  2612. return "<link rel=\"stylesheet\" type=\"text/css\" href=\"project1.css\">\n" .
  2613. "<table class=\"ewExportTable\">";
  2614. case "word":
  2615. case "excel":
  2616. return "<table>";
  2617. case "csv":
  2618. return "";
  2619. }
  2620. }
  2621. function ew_ExportFooter($ExpType) {
  2622. switch ($ExpType) {
  2623. case "html":
  2624. case "word":
  2625. case "excel":
  2626. return "</table>";
  2627. case "csv":
  2628. return "";
  2629. }
  2630. }
  2631. function ew_ExportAddValue(&$str, $val, $ExpType) {
  2632. switch ($ExpType) {
  2633. case "html":
  2634. case "word":
  2635. case "excel":
  2636. $str .= "<td>$val</td>";
  2637. break;
  2638. case "csv":
  2639. if ($str <> "")
  2640. $str .= ",";
  2641. $str .= "\"" . str_replace("\"", "\"\"", strval($val)) . "\"";
  2642. }
  2643. }
  2644. function ew_ExportLine($str, $ExpType) {
  2645. switch ($ExpType) {
  2646. case "html":
  2647. case "word":
  2648. case "excel":
  2649. return "<tr>$str</tr>";
  2650. case "csv":
  2651. return "$str\r\n";
  2652. }
  2653. }
  2654. function ew_ExportField($cap, $val, $ExpType) {
  2655. return "<tr><td>$cap</td><td>$val</td></tr>";
  2656. }
  2657. ?>
  2658. <?php
  2659. /**
  2660. * Form class
  2661. */
  2662. class cFormObj {
  2663. var $Index;
  2664. // Class Inialize
  2665. function cFormObj() {
  2666. $this->Index = 0;
  2667. }
  2668. // Get form element name based on index
  2669. function GetIndexedName($name) {
  2670. if ($this->Index <= 0) {
  2671. return $name;
  2672. } else {
  2673. return substr($name, 0, 1) . $this->Index . substr($name, 1);
  2674. }
  2675. }
  2676. // Get value for form element
  2677. function GetValue($name) {
  2678. $wrkname = $this->GetIndexedName($name);
  2679. return @$_POST[$wrkname];
  2680. }
  2681. // Get upload file size
  2682. function GetUploadFileSize($name) {
  2683. $wrkname = $this->GetIndexedName($name);
  2684. return @$_FILES[$wrkname]['size'];
  2685. }
  2686. // Get upload file name
  2687. function GetUploadFileName($name) {
  2688. $wrkname = $this->GetIndexedName($name);
  2689. return @$_FILES[$wrkname]['name'];
  2690. }
  2691. // Get file content type
  2692. function GetUploadFileContentType($name) {
  2693. $wrkname = $this->GetIndexedName($name);
  2694. return @$_FILES[$wrkname]['type'];
  2695. }
  2696. // Get file error
  2697. function GetUploadFileError($name) {
  2698. $wrkname = $this->GetIndexedName($name);
  2699. return @$_FILES[$wrkname]['error'];
  2700. }
  2701. // Get file temp name
  2702. function GetUploadFileTmpName($name) {
  2703. $wrkname = $this->GetIndexedName($name);
  2704. return @$_FILES[$wrkname]['tmp_name'];
  2705. }
  2706. // Check if is uplaod file
  2707. function IsUploadedFile($name) {
  2708. $wrkname = $this->GetIndexedName($name);
  2709. return is_uploaded_file(@$_FILES[$wrkname]["tmp_name"]);
  2710. }
  2711. // Get upload file data
  2712. function GetUploadFileData($name) {
  2713. if ($this->IsUploadedFile($name)) {
  2714. $wrkname = $this->GetIndexedName($name);
  2715. return ew_ReadFile($_FILES[$wrkname]["tmp_name"]);
  2716. } else {
  2717. return NULL;
  2718. }
  2719. }
  2720. // Get image sizes
  2721. var $size;
  2722. function GetImageDimension($name) {
  2723. if (!isset($this->size)) {
  2724. $wrkname = $this->GetIndexedName($name);
  2725. $this->size = @getimagesize($_FILES[$wrkname]['tmp_name']);
  2726. }
  2727. }
  2728. // Get file image width
  2729. function GetUploadImageWidth($name) {
  2730. $this->GetImageDimension($name);
  2731. return $this->size[0];
  2732. }
  2733. // Get file image height
  2734. function GetUploadImageHeight($name) {
  2735. $this->GetImageDimension($name);
  2736. return $this->size[1];
  2737. }
  2738. }
  2739. ?>
  2740. <?php
  2741. /**
  2742. * Functions for image resize
  2743. */
  2744. // Resize binary to thumbnail
  2745. function ew_ResizeBinary($filedata, &$width, &$height, $quality) {
  2746. return TRUE; // No resize
  2747. }
  2748. // Resize file to thumbnail file
  2749. function ew_ResizeFile($fn, $tn, &$width, &$height, $quality) {
  2750. if (file_exists($fn)) { // Copy only
  2751. return ($fn <> $tn) ? copy($fn, $tn) : TRUE;
  2752. } else {
  2753. return FALSE;
  2754. }
  2755. }
  2756. // Resize file to binary
  2757. function ew_ResizeFileToBinary($fn, &$width, &$height, $quality) {
  2758. return ew_ReadFile($fn); // Return original file content only
  2759. }
  2760. ?>
  2761. <?php
  2762. /**
  2763. * Functions for search
  2764. */
  2765. // Highlight value based on basic search / advanced search keywords
  2766. function ew_Highlight($name, $src, $bkw, $bkwtype, $akw) {
  2767. $outstr = "";
  2768. if (strlen($src) > 0 && (strlen($bkw) > 0 || strlen($akw) > 0)) {
  2769. $xx = 0;
  2770. $yy = strpos($src, "<", $xx);
  2771. if ($yy === FALSE) $yy = strlen($src);
  2772. while ($yy > 0) {
  2773. if ($yy > $xx) {
  2774. $wrksrc = substr($src, $xx, $yy - $xx);
  2775. $kwstr = trim($bkw);
  2776. if (strlen($bkw) > 0 && strlen($bkwtype) == 0) { // check for exact phase
  2777. $kwlist = array($kwstr); // use single array element
  2778. } else {
  2779. $kwlist = explode(" ", $kwstr);
  2780. }
  2781. if (strlen($akw) > 0)
  2782. $kwlist[] = $akw;
  2783. $x = 0;
  2784. ew_GetKeyword($wrksrc, $kwlist, $x, $y, $kw);
  2785. while ($y >= 0) {
  2786. $outstr .= substr($wrksrc, $x, $y-$x) .
  2787. "<span name=\"$name\" id=\"$name\" class=\"ewHighlightSearch\">" .
  2788. substr($src, $y, strlen($kw)) . "</span>";
  2789. $x = $y + strlen($kw);
  2790. ew_GetKeyword($wrksrc, $kwlist, $x, $y, $kw);
  2791. }
  2792. $outstr .= substr($wrksrc, $x);
  2793. $xx += strlen($wrksrc);
  2794. }
  2795. if ($xx < strlen($src)) {
  2796. $yy = strpos($src, ">", $xx);
  2797. if ($yy !== FALSE) {
  2798. $outstr .= substr($src, $xx, $yy - $xx + 1);
  2799. $xx = $yy + 1;
  2800. $yy = strpos($src, "<", $xx);
  2801. if ($yy === FALSE) $yy = strlen($src);
  2802. } else {
  2803. $outstr .= substr($src, $xx);
  2804. $yy = -1;
  2805. }
  2806. } else {
  2807. $yy = -1;
  2808. }
  2809. }
  2810. } else {
  2811. $outstr = $src;
  2812. }
  2813. return $outstr;
  2814. }
  2815. // Get keyword
  2816. function ew_GetKeyword(&$src, &$kwlist, &$x, &$y, &$kw) {
  2817. $thisy = -1;
  2818. $thiskw = "";
  2819. foreach ($kwlist as $wrkkw) {
  2820. $wrkkw = trim($wrkkw);
  2821. if ($wrkkw <> "") {
  2822. if (EW_HIGHLIGHT_COMPARE) { // Case-insensitive
  2823. if (function_exists('stripos')) { // PHP 5
  2824. $wrky = stripos($src, $wrkkw, $x);
  2825. } else {
  2826. $wrky = strpos(strtoupper($src), strtoupper($wrkkw), $x);
  2827. }
  2828. } else {
  2829. $wrky = strpos($src, $wrkkw, $x);
  2830. }
  2831. if ($wrky !== FALSE) {
  2832. if ($thisy == -1) {
  2833. $thisy = $wrky;
  2834. $thiskw = $wrkkw;
  2835. } elseif ($wrky < $thisy) {
  2836. $thisy = $wrky;
  2837. $thiskw = $wrkkw;
  2838. }
  2839. }
  2840. }
  2841. }
  2842. $y = $thisy;
  2843. $kw = $thiskw;
  2844. }
  2845. ?>
  2846. <?php
  2847. /**
  2848. * Functions for Auto-Update fields
  2849. */
  2850. // Get user IP
  2851. function ew_CurrentUserIP() {
  2852. return ew_ServerVar("REMOTE_ADDR");
  2853. }
  2854. // Get current host name, e.g. "www.mycompany.com"
  2855. function ew_CurrentHost() {
  2856. return ew_ServerVar("HTTP_HOST");
  2857. }
  2858. // Get current date in default date format
  2859. // $namedformat = -1|5|6|7 (see comment for ew_FormatDateTime)
  2860. function ew_CurrentDate($namedformat = -1) {
  2861. if ($namedformat > -1) {
  2862. if ($namedformat == 6 || $namedformat == 7) {
  2863. return ew_FormatDateTime(date('Y-m-d'), $namedformat);
  2864. } else {
  2865. return ew_FormatDateTime(date('Y-m-d'), 5);
  2866. }
  2867. } else {
  2868. return date('Y-m-d');
  2869. }
  2870. }
  2871. // Get current time in hh:mm:ss format
  2872. function ew_CurrentTime() {
  2873. return date("H:i:s");
  2874. }
  2875. // Get current date in default date format with time in hh:mm:ss format
  2876. // $namedformat = -1|9|10|11 (see comment for ew_FormatDateTime)
  2877. function ew_CurrentDateTime($namedformat = -1) {
  2878. if ($namedformat > -1) {
  2879. if ($namedformat == 10 || $namedformat == 11) {
  2880. return ew_FormatDateTime(date('Y-m-d H:i:s'), $namedformat);
  2881. } else {
  2882. return ew_FormatDateTime(date('Y-m-d H:i:s'), 9);
  2883. }
  2884. } else {
  2885. return date('Y-m-d H:i:s');
  2886. }
  2887. }
  2888. /**
  2889. * Functions for backward compatibilty
  2890. */
  2891. // Get current user name
  2892. function CurrentUserName() {
  2893. global $Security;
  2894. return (isset($Security)) ? $Security->CurrentUserName() : strval(@$_SESSION[EW_SESSION_USER_NAME]);
  2895. }
  2896. // Get current user ID
  2897. function CurrentUserID() {
  2898. global $Security;
  2899. return (isset($Security)) ? $Security->CurrentUserID() : strval(@$_SESSION[EW_SESSION_USER_ID]);
  2900. }
  2901. // Get current parent user ID
  2902. function CurrentParentUserID() {
  2903. global $Security;
  2904. return (isset($Security)) ? $Security->CurrentParentUserID() : strval(@$_SESSION[EW_SESSION_PARENT_USER_ID]);
  2905. }
  2906. // Get current User Level
  2907. function CurrentUserLevel() {
  2908. global $Security;
  2909. return (isset($Security)) ? $Security->CurrentUserLevelID() : @$_SESSION[EW_SESSION_USER_LEVEL_ID];
  2910. }
  2911. // Get current user level list
  2912. function CurrentUserLevelList() {
  2913. global $Security;
  2914. return (isset($Security)) ? $Security->UserLevelList() : strval(@$_SESSION[EW_SESSION_USER_LEVEL_ID]);
  2915. }
  2916. // Allow list
  2917. function AllowList($TableName) {
  2918. global $Security;
  2919. return $Security->AllowList($TableName);
  2920. }
  2921. // Allow add
  2922. function AllowAdd($TableName) {
  2923. global $Security;
  2924. return $Security->AllowAdd($TableName);
  2925. }
  2926. // Is Logged In
  2927. function IsLoggedIn() {
  2928. global $Security;
  2929. return (isset($Security)) ? $Security->IsLoggedIn() : ($_SESSION[EW_SESSION_STATUS] == "login");
  2930. }
  2931. // Is System Admin
  2932. function IsSysAdmin() {
  2933. global $Security;
  2934. return (isset($Security)) ? $Security->IsSysAdmin() : ($_SESSION[EW_SESSION_SYS_ADMIN] == 1);
  2935. }
  2936. /**
  2937. * Functions for TEA encryption/decryption
  2938. */
  2939. function long2str($v, $w) {
  2940. $len = count($v);
  2941. $s = array();
  2942. for ($i = 0; $i < $len; $i++)
  2943. {
  2944. $s[$i] = pack("V", $v[$i]);
  2945. }
  2946. if ($w) {
  2947. return substr(join('', $s), 0, $v[$len - 1]);
  2948. } else {
  2949. return join('', $s);
  2950. }
  2951. }
  2952. function str2long($s, $w) {
  2953. $v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
  2954. $v = array_values($v);
  2955. if ($w) {
  2956. $v[count($v)] = strlen($s);
  2957. }
  2958. return $v;
  2959. }
  2960. // encrypt
  2961. function TEAencrypt($str, $key) {
  2962. if ($str == "") {
  2963. return "";
  2964. }
  2965. $v = str2long($str, true);
  2966. $k = str2long($key, false);
  2967. if (count($k) < 4) {
  2968. for ($i = count($k); $i < 4; $i++) {
  2969. $k[$i] = 0;
  2970. }
  2971. }
  2972. $n = count($v) - 1;
  2973. $z = $v[$n];
  2974. $y = $v[0];
  2975. $delta = 0x9E3779B9;
  2976. $q = floor(6 + 52 / ($n + 1));
  2977. $sum = 0;
  2978. while (0 < $q--) {
  2979. $sum = int32($sum + $delta);
  2980. $e = $sum >> 2 & 3;
  2981. for ($p = 0; $p < $n; $p++) {
  2982. $y = $v[$p + 1];
  2983. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  2984. $z = $v[$p] = int32($v[$p] + $mx);
  2985. }
  2986. $y = $v[0];
  2987. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  2988. $z = $v[$n] = int32($v[$n] + $mx);
  2989. }
  2990. return ew_UrlEncode(long2str($v, false));
  2991. }
  2992. // decrypt
  2993. function TEAdecrypt($str, $key) {
  2994. $str = ew_UrlDecode($str);
  2995. if ($str == "") {
  2996. return "";
  2997. }
  2998. $v = str2long($str, false);
  2999. $k = str2long($key, false);
  3000. if (count($k) < 4) {
  3001. for ($i = count($k); $i < 4; $i++) {
  3002. $k[$i] = 0;
  3003. }
  3004. }
  3005. $n = count($v) - 1;
  3006. $z = $v[$n];
  3007. $y = $v[0];
  3008. $delta = 0x9E3779B9;
  3009. $q = floor(6 + 52 / ($n + 1));
  3010. $sum = int32($q * $delta);
  3011. while ($sum != 0) {
  3012. $e = $sum >> 2 & 3;
  3013. for ($p = $n; $p > 0; $p--) {
  3014. $z = $v[$p - 1];
  3015. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  3016. $y = $v[$p] = int32($v[$p] - $mx);
  3017. }
  3018. $z = $v[$n];
  3019. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  3020. $y = $v[0] = int32($v[0] - $mx);
  3021. $sum = int32($sum - $delta);
  3022. }
  3023. return long2str($v, true);
  3024. }
  3025. function int32($n) {
  3026. while ($n >= 2147483648) $n -= 4294967296;
  3027. while ($n <= -2147483649) $n += 4294967296;
  3028. return (int)$n;
  3029. }
  3030. function ew_UrlEncode($string) {
  3031. $data = base64_encode($string);
  3032. return str_replace(array('+','/','='), array('-','_','.'), $data);
  3033. }
  3034. function ew_UrlDecode($string) {
  3035. $data = str_replace(array('-','_','.'), array('+','/','='), $string);
  3036. return base64_decode($data);
  3037. }
  3038. /**
  3039. * Remove XSS
  3040. * Note: If you decide to allow some keywords (at your own risk), remove them
  3041. * from the array $ra1 or $ra2
  3042. */
  3043. function ew_RemoveXSS($val) {
  3044. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  3045. // this prevents some character re-spacing such as <java\0script>
  3046. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  3047. $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
  3048. // straight replacements, the user should never need these since they're normal characters
  3049. // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
  3050. $search = 'abcdefghijklmnopqrstuvwxyz';
  3051. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3052. $search .= '1234567890!@#$%^&*()';
  3053. $search .= '~`";:?+/={}[]-_|\'\\';
  3054. for ($i = 0; $i < strlen($search); $i++) {
  3055. // ;? matches the ;, which is optional
  3056. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  3057. // &#x0040 @ search for the hex values
  3058. $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
  3059. // &#00064 @ 0{0,7} matches '0' zero to seven times
  3060. $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
  3061. }
  3062. // now the only remaining whitespace attacks are \t, \n, and \r
  3063. $ra1 = Array('javascript', 'vbscript', 'expression', '<applet', '<meta', '<xml', '<blink', '<link', '<style', '<script', '<embed', '<object', '<iframe', '<frame', '<frameset', '<ilayer', '<layer', '<bgsound', '<title', '<base'); // less strict
  3064. $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
  3065. $ra = array_merge($ra1, $ra2);
  3066. $found = true; // keep replacing as long as the previous round replaced something
  3067. while ($found == true) {
  3068. $val_before = $val;
  3069. for ($i = 0; $i < sizeof($ra); $i++) {
  3070. $pattern = '/';
  3071. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  3072. if ($j > 0) {
  3073. $pattern .= '(';
  3074. $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
  3075. $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
  3076. $pattern .= ')?';
  3077. }
  3078. $pattern .= $ra[$i][$j];
  3079. }
  3080. $pattern .= '/i';
  3081. $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
  3082. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  3083. if ($val_before == $val) {
  3084. // no replacements were made, so exit the loop
  3085. $found = false;
  3086. }
  3087. }
  3088. }
  3089. return $val;
  3090. }
  3091. /**
  3092. * Validation functions
  3093. */
  3094. // Check date format
  3095. // format: std/us/euro
  3096. function ew_CheckDateEx($value, $format, $sep) {
  3097. if (strval($value) == "") return TRUE;
  3098. while (strpos($value, " ") !== FALSE)
  3099. $value = str_replace(" ", " ", $value);
  3100. $value = trim($value);
  3101. $arDT = explode(" ", $value);
  3102. if (count($arDT) > 0) {
  3103. $sep = "\\$sep";
  3104. switch ($format) {
  3105. case "std":
  3106. $pattern = '/^([0-9]{4})' . $sep . '([0]?[1-9]|[1][0-2])' . $sep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])$/';
  3107. break;
  3108. case "us":
  3109. $pattern = '/^([0]?[1-9]|[1][0-2])' . $sep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $sep . '([0-9]{4})$/';
  3110. break;
  3111. case "euro":
  3112. $pattern = '/^([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $sep . '([0]?[1-9]|[1][0-2])' . $sep . '([0-9]{4})$/';
  3113. break;
  3114. }
  3115. if (!preg_match($pattern, $arDT[0])) return FALSE;
  3116. $arD = explode(EW_DATE_SEPARATOR, $arDT[0]);
  3117. switch ($format) {
  3118. case "std":
  3119. $sYear = $arD[0];
  3120. $sMonth = $arD[1];
  3121. $sDay = $arD[2];
  3122. break;
  3123. case "us":
  3124. $sYear = $arD[2];
  3125. $sMonth = $arD[0];
  3126. $sDay = $arD[1];
  3127. break;
  3128. case "euro":
  3129. $sYear = $arD[2];
  3130. $sMonth = $arD[1];
  3131. $sDay = $arD[0];
  3132. break;
  3133. }
  3134. if (!ew_CheckDay($sYear, $sMonth, $sDay)) return FALSE;
  3135. }
  3136. if (count($arDT) > 1 && !ew_CheckTime($arDT[1])) return FALSE;
  3137. return TRUE;
  3138. }
  3139. // Check Date format (yyyy/mm/dd)
  3140. function ew_CheckDate($value) {
  3141. return ew_CheckDateEx($value, "std", EW_DATE_SEPARATOR);
  3142. }
  3143. // Check US Date format (mm/dd/yyyy)
  3144. function ew_CheckUSDate($value) {
  3145. return ew_CheckDateEx($value, "us", EW_DATE_SEPARATOR);
  3146. }
  3147. // Check Euro Date format (dd/mm/yyyy)
  3148. function ew_CheckEuroDate($value) {
  3149. return ew_CheckDateEx($value, "euro", EW_DATE_SEPARATOR);
  3150. }
  3151. // Check day
  3152. function ew_CheckDay($checkYear, $checkMonth, $checkDay) {
  3153. $maxDay = 31;
  3154. if ($checkMonth == 4 || $checkMonth == 6 || $checkMonth == 9 || $checkMonth == 11) {
  3155. $maxDay = 30;
  3156. } elseif ($checkMonth == 2) {
  3157. if ($checkYear % 4 > 0) {
  3158. $maxDay = 28;
  3159. } elseif ($checkYear % 100 == 0 && $checkYear % 400 > 0) {
  3160. $maxDay = 28;
  3161. } else {
  3162. $maxDay = 29;
  3163. }
  3164. }
  3165. return ew_CheckRange($checkDay, 1, $maxDay);
  3166. }
  3167. // Check integer
  3168. function ew_CheckInteger($value) {
  3169. if (strval($value) == "") return TRUE;
  3170. return preg_match('/^\-?\+?[0-9]+$/', $value);
  3171. }
  3172. // Check number range
  3173. function ew_NumberRange($value, $min, $max) {
  3174. if ((!is_null($min) && $value < $min) ||
  3175. (!is_null($max) && $value > $max))
  3176. return FALSE;
  3177. return TRUE;
  3178. }
  3179. // Check number
  3180. function ew_CheckNumber($value) {
  3181. if (strval($value) == "") return TRUE;
  3182. return is_numeric(trim($value));
  3183. }
  3184. // Check range
  3185. function ew_CheckRange($value, $min, $max) {
  3186. if (strval($value) == "") return TRUE;
  3187. if (!ew_CheckNumber($value)) return FALSE;
  3188. return ew_NumberRange($value, $min, $max);
  3189. }
  3190. // Check time
  3191. function ew_CheckTime($value) {
  3192. if (strval($value) == "") return TRUE;
  3193. return preg_match('/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $value);
  3194. }
  3195. // Check US phone number
  3196. function ew_CheckPhone($value) {
  3197. if (strval($value) == "") return TRUE;
  3198. return preg_match('/^\(\d{3}\) ?\d{3}( |-)?\d{4}|^\d{3}( |-)?\d{3}( |-)?\d{4}$/', $value);
  3199. }
  3200. // Check US zip code
  3201. function ew_CheckZip($value) {
  3202. if (strval($value) == "") return TRUE;
  3203. return preg_match('/^\d{5}$|^\d{5}-\d{4}$/', $value);
  3204. }
  3205. // Check credit card
  3206. function ew_CheckCreditCard($value, $type="") {
  3207. if (strval($value) == "") return TRUE;
  3208. $creditcard = array("visa" => "/^4\d{3}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  3209. "mastercard" => "/^5[1-5]\d{2}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  3210. "discover" => "/^6011[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  3211. "amex" => "/^3[4,7]\d{13}$/",
  3212. "diners" => "/^3[0,6,8]\d{12}$/",
  3213. "bankcard" => "/^5610[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  3214. "jcb" => "/^[3088|3096|3112|3158|3337|3528]\d{12}$/",
  3215. "enroute" => "/^[2014|2149]\d{11}$/",
  3216. "switch" => "/^[4903|4911|4936|5641|6333|6759|6334|6767]\d{12}$/");
  3217. if (empty($type)) {
  3218. $match = FALSE;
  3219. foreach ($creditcard as $type => $pattern) {
  3220. if (@preg_match($pattern, $value) == 1) {
  3221. $match = TRUE;
  3222. break;
  3223. }
  3224. }
  3225. return ($match) ? ew_CheckSum($value) : FALSE;
  3226. } else {
  3227. if (!preg_match($creditcard[strtolower(trim($type))], $value)) return FALSE;
  3228. return ew_CheckSum($value);
  3229. }
  3230. }
  3231. // Check sum
  3232. function ew_CheckSum($value) {
  3233. $value = str_replace(array('-',' '), array('',''), $value);
  3234. $checksum = 0;
  3235. for ($i=(2-(strlen($value) % 2)); $i<=strlen($value); $i+=2)
  3236. $checksum += (int)($value[$i-1]);
  3237. for ($i=(strlen($value)%2)+1; $i <strlen($value); $i+=2) {
  3238. $digit = (int)($value[$i-1]) * 2;
  3239. $checksum += ($digit < 10) ? $digit : ($digit-9);
  3240. }
  3241. return ($checksum % 10 == 0);
  3242. }
  3243. // Check US social security number
  3244. function ew_CheckSSC($value) {
  3245. if (strval($value) == "") return TRUE;
  3246. return preg_match('/^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}$/', $value);
  3247. }
  3248. // Check email
  3249. function ew_CheckEmail($value) {
  3250. if (strval($value) == "") return TRUE;
  3251. return preg_match('/^[A-Za-z0-9\._\-+]+@[A-Za-z0-9_\-+]+(\.[A-Za-z0-9_\-+]+)+$/', $value);
  3252. }
  3253. // Check GUID
  3254. function ew_CheckGUID($value) {
  3255. if (strval($value) == "") return TRUE;
  3256. $p1 = '/^{{1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}}{1}$/';
  3257. $p2 = '/^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$/';
  3258. return preg_match($p1, $value) || preg_match($p2, $value);
  3259. }
  3260. // Check file extension
  3261. function ew_CheckFileType($value) {
  3262. if (strval($value) == "") return TRUE;
  3263. $extension = substr(strtolower(strrchr($value, ".")), 1);
  3264. $allowExt = explode(",", strtolower(EW_UPLOAD_ALLOWED_FILE_EXT));
  3265. return (in_array($extension, $allowExt) || trim(EW_UPLOAD_ALLOWED_FILE_EXT) == "");
  3266. }
  3267. // Check empty string
  3268. function ew_EmptyStr($value) {
  3269. $str = strval($value);
  3270. $str = str_replace("&nbsp;", "", $str);
  3271. return (trim($str) == "");
  3272. }
  3273. // Check by preg
  3274. function ew_CheckByRegEx($value, $pattern) {
  3275. if (strval($value) == "") return TRUE;
  3276. return preg_match($pattern, $value);
  3277. }
  3278. ?>