PageRenderTime 44ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/phprptinc/ewrfn5.php

https://bitbucket.org/joemarmatulac/ebutton
PHP | 5950 lines | 4888 code | 483 blank | 579 comment | 1169 complexity | a3ee7402a967cdb6c8efb8195c9a516b MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. // Functions for PHP Report Maker 5
  3. // (C) 2007-2011 e.World Technology Limited
  4. if (!function_exists("G")) {
  5. function &G($name) {
  6. return $GLOBALS[$name];
  7. }
  8. }
  9. // Get current page object
  10. function &CurrentPage() {
  11. return $GLOBALS["Page"];
  12. }
  13. // Get current main table object
  14. function &CurrentTable() {
  15. return $GLOBALS["Table"];
  16. }
  17. /**
  18. * Langauge class for reports
  19. */
  20. class crLanguage {
  21. var $LanguageId;
  22. var $Phrases = NULL;
  23. // Constructor
  24. function crLanguage() {
  25. global $gsLanguage;
  26. $this->LoadFileList(); // Set up file list
  27. if (@$_GET["language"] <> "") { // Set up language id
  28. $this->LanguageId = $_GET["language"];
  29. $_SESSION[EWRPT_SESSION_LANGUAGE_ID] = $this->LanguageId;
  30. } elseif (@$_SESSION[EWRPT_SESSION_LANGUAGE_ID] <> "") {
  31. $this->LanguageId = $_SESSION[EWRPT_SESSION_LANGUAGE_ID];
  32. } else {
  33. $this->LanguageId = EWRPT_LANGUAGE_DEFAULT_ID;
  34. }
  35. $gsLanguage = $this->LanguageId;
  36. $this->Load($this->LanguageId);
  37. }
  38. // Load language file list
  39. function LoadFileList() {
  40. global $EWRPT_LANGUAGE_FILE;
  41. if (is_array($EWRPT_LANGUAGE_FILE)) {
  42. $cnt = count($EWRPT_LANGUAGE_FILE);
  43. for ($i = 0; $i < $cnt; $i++)
  44. $EWRPT_LANGUAGE_FILE[$i][1] = $this->LoadFileDesc(EWRPT_LANGUAGE_FOLDER . $EWRPT_LANGUAGE_FILE[$i][2]);
  45. }
  46. }
  47. // Load language file description
  48. function LoadFileDesc($File) {
  49. if (EWRPT_USE_DOM_XML) {
  50. $this->Phrases = new crXMLDocument();
  51. if ($this->Phrases->Load($File))
  52. return $this->GetNodeAtt($this->Phrases->DocumentElement(), "desc");
  53. } else {
  54. $ar = ewrpt_Xml2Array(substr(file_get_contents($File), 0, 512)); // Just read the first part
  55. return (is_array($ar)) ? @$ar['ew-language']['attr']['desc'] : "";
  56. }
  57. }
  58. // Load language file
  59. function Load($id) {
  60. $sFileName = $this->GetFileName($id);
  61. if ($sFileName == "")
  62. $sFileName = $this->GetFileName(EWRPT_LANGUAGE_DEFAULT_ID);
  63. if ($sFileName == "")
  64. return;
  65. if (EWRPT_USE_DOM_XML) {
  66. $this->Phrases = new crXMLDocument();
  67. $this->Phrases->Load($sFileName);
  68. } else {
  69. if (is_array(@$_SESSION[EWRPT_PROJECT_VAR . "_" . $sFileName])) {
  70. $this->Phrases = $_SESSION[EWRPT_PROJECT_VAR . "_" . $sFileName];
  71. } else {
  72. $this->Phrases = ewrpt_Xml2Array(file_get_contents($sFileName));
  73. }
  74. }
  75. }
  76. // Get language file name
  77. function GetFileName($Id) {
  78. global $EWRPT_LANGUAGE_FILE;
  79. if (is_array($EWRPT_LANGUAGE_FILE)) {
  80. $cnt = count($EWRPT_LANGUAGE_FILE);
  81. for ($i = 0; $i < $cnt; $i++)
  82. if ($EWRPT_LANGUAGE_FILE[$i][0] == $Id) {
  83. return EWRPT_LANGUAGE_FOLDER . $EWRPT_LANGUAGE_FILE[$i][2];
  84. }
  85. }
  86. return "";
  87. }
  88. // Get node attribute
  89. function GetNodeAtt($Nodes, $Att) {
  90. $value = ($Nodes) ? $this->Phrases->GetAttribute($Nodes, $Att) : "";
  91. //return ewrpt_ConvertFromUtf8($value);
  92. return $value;
  93. }
  94. // Get phrase
  95. function Phrase($Name) {
  96. if (is_object($this->Phrases)) {
  97. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//global/phrase[@id='" . strtolower($Name) . "']"), "value");
  98. } elseif (is_array($this->Phrases)) {
  99. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['global']['phrase'][strtolower($Name)]['attr']['value']);
  100. }
  101. }
  102. // Get project phrase
  103. function ProjectPhrase($Id) {
  104. if (is_object($this->Phrases)) {
  105. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//project/phrase[@id='" . strtolower($Id) . "']"), "value");
  106. } elseif (is_array($this->Phrases)) {
  107. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['project']['phrase'][strtolower($Id)]['attr']['value']);
  108. }
  109. }
  110. // Set project phrase
  111. function setProjectPhrase($Id, $Value) {
  112. if (is_array($this->Phrases)) {
  113. $this->Phrases['ew-language']['project']['phrase'][strtolower($Id)]['attr']['value'] = $Value;
  114. }
  115. }
  116. // Get menu phrase
  117. function MenuPhrase($MenuId, $Id) {
  118. if (is_object($this->Phrases)) {
  119. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//project/menu[@id='" . $MenuId . "']/phrase[@id='" . strtolower($Id) . "']"), "value");
  120. } elseif (is_array($this->Phrases)) {
  121. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['project']['menu'][$MenuId]['phrase'][strtolower($Id)]['attr']['value']);
  122. }
  123. }
  124. // Set menu phrase
  125. function setMenuPhrase($MenuId, $Id, $Value) {
  126. if (is_array($this->Phrases)) {
  127. $this->Phrases['ew-language']['project']['menu'][$MenuId]['phrase'][strtolower($Id)]['attr']['value'] = $Value;
  128. }
  129. }
  130. // Get table phrase
  131. function TablePhrase($TblVar, $Id) {
  132. if (is_object($this->Phrases)) {
  133. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//project/table[@id='" . strtolower($TblVar) . "']/phrase[@id='" . strtolower($Id) . "']"), "value");
  134. } elseif (is_array($this->Phrases)) {
  135. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['phrase'][strtolower($Id)]['attr']['value']);
  136. }
  137. }
  138. // Set table phrase
  139. function setTablePhrase($TblVar, $Id, $Value) {
  140. if (is_array($this->Phrases)) {
  141. $this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['phrase'][strtolower($Id)]['attr']['value'] = $Value;
  142. }
  143. }
  144. // Get chart phrase
  145. function ChartPhrase($TblVar, $ChtVar, $Id) {
  146. if (is_object($this->Phrases)) {
  147. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//project/table[@id='" . strtolower($TblVar) . "']/chart[@id='" . strtolower($ChtVar) . "']/phrase[@id='" . strtolower($Id) . "']"), "value");
  148. } elseif (is_array($this->Phrases)) {
  149. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['chart'][strtolower($ChtVar)]['phrase'][strtolower($Id)]['attr']['value']);
  150. }
  151. }
  152. // Set chart phrase
  153. function setChartPhrase($TblVar, $FldVar, $Id, $Value) {
  154. if (is_array($this->Phrases)) {
  155. $this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['chart'][strtolower($FldVar)]['phrase'][strtolower($Id)]['attr']['value'] = $Value;
  156. }
  157. }
  158. // Get field phrase
  159. function FieldPhrase($TblVar, $FldVar, $Id) {
  160. if (is_object($this->Phrases)) {
  161. return $this->GetNodeAtt($this->Phrases->SelectSingleNode("//project/table[@id='" . strtolower($TblVar) . "']/field[@id='" . strtolower($FldVar) . "']/phrase[@id='" . strtolower($Id) . "']"), "value");
  162. } elseif (is_array($this->Phrases)) {
  163. return ewrpt_ConvertFromUtf8(@$this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['field'][strtolower($FldVar)]['phrase'][strtolower($Id)]['attr']['value']);
  164. }
  165. }
  166. // Set field phrase
  167. function setFieldPhrase($TblVar, $FldVar, $Id, $Value) {
  168. if (is_array($this->Phrases)) {
  169. $this->Phrases['ew-language']['project']['table'][strtolower($TblVar)]['field'][strtolower($FldVar)]['phrase'][strtolower($Id)]['attr']['value'] = $Value;
  170. }
  171. }
  172. // Output XML as JSON
  173. function XmlToJSON($XPath) {
  174. $NodeList = $this->Phrases->SelectNodes($XPath);
  175. $Str = "{";
  176. foreach ($NodeList as $Node) {
  177. $Id = $this->GetNodeAtt($Node, "id");
  178. $Value = $this->GetNodeAtt($Node, "value");
  179. $Str .= "\"" . ewrpt_JsEncode2($Id) . "\":\"" . ewrpt_JsEncode2($Value) . "\",";
  180. }
  181. if (substr($Str, -1) == ",") $Str = substr($Str, 0, strlen($Str)-1);
  182. $Str .= "}";
  183. return $Str;
  184. }
  185. // Output array as JSON
  186. function ArrayToJSON($client) {
  187. $ar = @$this->Phrases['ew-language']['global']['phrase'];
  188. $Str = "{";
  189. if (is_array($ar)) {
  190. foreach ($ar as $id => $node) {
  191. $is_client = @$node['attr']['client'] == '1';
  192. $value = ewrpt_ConvertFromUtf8(@$node['attr']['value']);
  193. if (!$client || ($client && $is_client))
  194. $Str .= "\"" . ewrpt_JsEncode2($id) . "\":\"" . ewrpt_JsEncode2($value) . "\",";
  195. }
  196. }
  197. if (substr($Str, -1) == ",") $Str = substr($Str, 0, strlen($Str)-1);
  198. $Str .= "}";
  199. return $Str;
  200. }
  201. // Output all phrases as JSON
  202. function AllToJSON() {
  203. if (is_object($this->Phrases)) {
  204. return "var ewLanguage = new ewrpt_Language(" . $this->XmlToJSON("//global/phrase") . ");";
  205. } elseif (is_array($this->Phrases)) {
  206. return "var ewLanguage = new ewrpt_Language(" . $this->ArrayToJSON(FALSE) . ");";
  207. }
  208. }
  209. // Output client phrases as JSON
  210. function ToJSON() {
  211. if (is_object($this->Phrases)) {
  212. return "var ewLanguage = new ewrpt_Language(" . $this->XmlToJSON("//global/phrase[@client='1']") . ");";
  213. } elseif (is_array($this->Phrases)) {
  214. return "var ewLanguage = new ewrpt_Language(" . $this->ArrayToJSON(TRUE) . ");";
  215. }
  216. }
  217. }
  218. // Convert XML to array
  219. function ewrpt_Xml2Array($contents) {
  220. if (!$contents) return array();
  221. if (!function_exists('xml_parser_create')) return FALSE;
  222. $get_attributes = 1; // Always get attributes. DO NOT CHANGE!
  223. // Get the XML Parser of PHP
  224. $parser = xml_parser_create();
  225. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); // Always return in utf-8
  226. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  227. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  228. xml_parse_into_struct($parser, trim($contents), $xml_values);
  229. xml_parser_free($parser);
  230. if (!$xml_values) return;
  231. $xml_array = array();
  232. $parents = array();
  233. $opened_tags = array();
  234. $arr = array();
  235. $current = &$xml_array;
  236. $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
  237. foreach ($xml_values as $data) {
  238. unset($attributes, $value); // Remove existing values
  239. // Extract these variables into the foreach scope
  240. // tag(string), type(string), level(int), attributes(array)
  241. extract($data);
  242. $result = array();
  243. if (isset($value))
  244. $result['value'] = $value; // Put the value in a assoc array
  245. // Set the attributes
  246. if (isset($attributes) and $get_attributes) {
  247. foreach ($attributes as $attr => $val)
  248. $result['attr'][$attr] = $val; // Set all the attributes in a array called 'attr'
  249. }
  250. // See tag status and do the needed
  251. if ($type == "open") { // The starting of the tag '<tag>'
  252. $parent[$level-1] = &$current;
  253. if (!is_array($current) || !in_array($tag, array_keys($current))) { // Insert New tag
  254. if ($tag <> 'ew-language' && @$result['attr']['id'] <> '') { //
  255. $last_item_index = $result['attr']['id'];
  256. $current[$tag][$last_item_index] = $result;
  257. $repeated_tag_index[$tag.'_'.$level] = 1;
  258. $current = &$current[$tag][$last_item_index];
  259. } else {
  260. $current[$tag] = $result;
  261. $repeated_tag_index[$tag.'_'.$level] = 0;
  262. $current = &$current[$tag];
  263. }
  264. } else { // Another element with the same tag name
  265. if ($repeated_tag_index[$tag.'_'.$level] > 0) { // If there is a 0th element it is already an array
  266. if (@$result['attr']['id'] <> '') {
  267. $last_item_index = $result['attr']['id'];
  268. } else {
  269. $last_item_index = $repeated_tag_index[$tag.'_'.$level];
  270. }
  271. $current[$tag][$last_item_index] = $result;
  272. $repeated_tag_index[$tag.'_'.$level]++;
  273. } else { // Make the value an array if multiple tags with the same name appear together
  274. $temp = $current[$tag];
  275. $current[$tag] = array();
  276. if (@$temp['attr']['id'] <> '') {
  277. $current[$tag][$temp['attr']['id']] = $temp;
  278. } else {
  279. $current[$tag][] = $temp;
  280. }
  281. if (@$result['attr']['id'] <> '') {
  282. $last_item_index = $result['attr']['id'];
  283. } else {
  284. $last_item_index = 1;
  285. }
  286. $current[$tag][$last_item_index] = $result;
  287. $repeated_tag_index[$tag.'_'.$level] = 2;
  288. }
  289. $current = &$current[$tag][$last_item_index];
  290. }
  291. } elseif ($type == "complete") { // Tags that ends in one line '<tag>'
  292. if (!isset($current[$tag])) { // New key
  293. $current[$tag] = array(); // Always use array for "complete" type
  294. if (@$result['attr']['id'] <> '') {
  295. $current[$tag][$result['attr']['id']] = $result;
  296. } else {
  297. $current[$tag][] = $result;
  298. }
  299. $repeated_tag_index[$tag.'_'.$level] = 1;
  300. } else { // Existing key
  301. if (@$result['attr']['id'] <> '') {
  302. $current[$tag][$result['attr']['id']] = $result;
  303. } else {
  304. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  305. }
  306. $repeated_tag_index[$tag.'_'.$level]++;
  307. }
  308. } elseif ($type == 'close') { // End of tag '</tag>'
  309. $current = &$parent[$level-1];
  310. }
  311. }
  312. return($xml_array);
  313. }
  314. /**
  315. * XML document class
  316. */
  317. class crXMLDocument {
  318. var $Encoding = "utf-8";
  319. var $RootTagName;
  320. var $RowTagName;
  321. var $XmlDoc = FALSE;
  322. var $XmlTbl;
  323. var $XmlRow;
  324. var $NullValue = 'NULL';
  325. function crXMLDocument($encoding = "") {
  326. if ($encoding <> "")
  327. $this->Encoding = $encoding;
  328. if ($this->Encoding <> "") {
  329. $this->XmlDoc = new DOMDocument("1.0", strval($this->Encoding));
  330. } else {
  331. $this->XmlDoc = new DOMDocument("1.0");
  332. }
  333. }
  334. function Load($filename) {
  335. $filepath = realpath($filename);
  336. return $this->XmlDoc->load($filepath);
  337. }
  338. function &DocumentElement() {
  339. $de = $this->XmlDoc->documentElement;
  340. return $de;
  341. }
  342. function GetAttribute($element, $name) {
  343. return ($element) ? ewrpt_ConvertFromUtf8($element->getAttribute($name)) : "";
  344. }
  345. function SelectSingleNode($query) {
  346. $elements = $this->SelectNodes($query);
  347. return ($elements->length > 0) ? $elements->item(0) : NULL;
  348. }
  349. function SelectNodes($query) {
  350. $xpath = new DOMXPath($this->XmlDoc);
  351. return $xpath->query($query);
  352. }
  353. function AddRoot($roottagname = 'table') {
  354. $this->RootTagName = $roottagname;
  355. $this->XmlTbl = $this->XmlDoc->createElement($this->RootTagName);
  356. $this->XmlDoc->appendChild($this->XmlTbl);
  357. }
  358. function AddRow($rowtagname = 'row') {
  359. $this->RowTagName = $rowtagname;
  360. $this->XmlRow = $this->XmlDoc->createElement($this->RowTagName);
  361. if ($this->XmlTbl)
  362. $this->XmlTbl->appendChild($this->XmlRow);
  363. }
  364. function AddField($name, $value) {
  365. if (is_null($value)) $value = $this->NullValue;
  366. $value = ewrpt_ConvertToUtf8($value); // Convert to UTF-8
  367. $xmlfld = $this->XmlDoc->createElement($name);
  368. $this->XmlRow->appendChild($xmlfld);
  369. $xmlfld->appendChild($this->XmlDoc->createTextNode($value));
  370. }
  371. function XML() {
  372. return $this->XmlDoc->saveXML();
  373. }
  374. }
  375. // Select nodes from XML document
  376. function &ewrpt_SelectNodes(&$xmldoc, $query) {
  377. if ($xmldoc) {
  378. $xpath = new DOMXPath($xmldoc);
  379. return $xpath->query($query);
  380. }
  381. return NULL;
  382. }
  383. // Select single node from XML document
  384. function &ewrpt_SelectSingleNode(&$xmldoc, $query) {
  385. $elements = ewrpt_SelectNodes($xmldoc, $query);
  386. return ($elements && $elements->length > 0) ? $elements->item(0) : NULL;
  387. }
  388. // Debug timer
  389. class crTimer {
  390. var $StartTime;
  391. var $EndTime;
  392. function crTimer($start = TRUE) {
  393. if ($start)
  394. $this->Start();
  395. }
  396. function GetTime() {
  397. list($usec, $sec) = explode(" ", microtime());
  398. return ((float)$usec + (float)$sec);
  399. }
  400. // Get script start time
  401. function Start() {
  402. if (EWRPT_DEBUG_ENABLED)
  403. $this->StartTime = $this->GetTime();
  404. }
  405. // display elapsed time (in seconds)
  406. function Stop() {
  407. if (EWRPT_DEBUG_ENABLED)
  408. $this->EndTime = $this->GetTime();
  409. if (isset($this->EndTime) && isset($this->StartTime) &&
  410. $this->EndTime > $this->StartTime)
  411. echo '<p>Page processing time: ' . ($this->EndTime - $this->StartTime) . ' seconds</p>';
  412. }
  413. }
  414. /**
  415. * Field class
  416. */
  417. class crField {
  418. var $TblName; // Table name
  419. var $TblVar; // Table variable name
  420. var $FldName; // Field name
  421. var $FldVar; // Field variable name
  422. var $FldExpression; // Field expression (used in SQL)
  423. var $FldDefaultErrMsg; // Default error message
  424. var $FldType; // Field type
  425. var $FldDataType; // PHPMaker Field type
  426. var $FldDateTimeFormat; // Date time format
  427. var $Count; // Count
  428. var $SumValue; // Sum
  429. var $AvgValue; // Average
  430. var $MinValue; // Minimum
  431. var $MaxValue; // MaxValue
  432. var $SumViewValue; // Sum
  433. var $AvgViewValue; // Average
  434. var $MinViewValue; // Minimum
  435. var $MaxViewValue; // MaxValue
  436. var $OldValue; // Old Value
  437. var $CurrentValue; // Current value
  438. var $ViewValue; // View value
  439. var $HrefValue; // Href value
  440. var $FormValue; // Form value
  441. var $QueryStringValue; // QueryString value
  442. var $DbValue; // Database value
  443. var $ImageWidth = 0; // Image width
  444. var $ImageHeight = 0; // Image height
  445. var $ImageResize = FALSE; // Image resize
  446. var $Sortable = TRUE; // Sortable
  447. var $GroupingFieldId = 0; // Grouping field id
  448. var $UploadPath = EWRPT_UPLOAD_DEST_PATH; // Upload path
  449. var $TruncateMemoRemoveHtml = FALSE; // Remove HTML from memo field
  450. var $CellAttrs = array(); // Cell custom attributes
  451. var $ViewAttrs = array(); // View custom attributes
  452. var $LinkAttrs = array(); // Href custom attributes
  453. var $FldGroupByType; // Group By Type
  454. var $FldGroupInt; // Group Interval
  455. var $FldGroupSql; // Group SQL
  456. var $GroupDbValues; // Group DB Values
  457. var $GroupViewValue; // Group View Value
  458. var $GroupSummaryOldValue; // Group Summary Old Value
  459. var $GroupSummaryValue; // Group Summary Value
  460. var $GroupSummaryViewValue; // Group Summary View Value
  461. var $SqlSelect; // Field SELECT
  462. var $SqlGroupBy; // Field GROUP BY
  463. var $SqlOrderBy; // Field ORDER BY
  464. var $ValueList; // Value List
  465. var $SelectionList; // Selection List
  466. var $DefaultSelectionList; // Default Selection List
  467. var $AdvancedFilters; // Advanced Filters
  468. var $RangeFrom; // Range From
  469. var $RangeTo; // Range To
  470. var $DropDownList; // Dropdown List
  471. var $DropDownValue; // Dropdown Value
  472. var $DefaultDropDownValue; // Default Dropdown Value
  473. var $DateFilter; // Date Filter
  474. var $SearchValue; // Search Value 1
  475. var $SearchValue2; // Search Value 2
  476. var $SearchOperator; // Search Operator 1
  477. var $SearchOperator2; // Search Operator 2
  478. var $SearchCondition; // Search Condition
  479. var $DefaultSearchValue; // Default Search Value 1
  480. var $DefaultSearchValue2; // Default Search Value 2
  481. var $DefaultSearchOperator; // Default Search Operator 1
  482. var $DefaultSearchOperator2; // Default Search Operator 2
  483. var $DefaultSearchCondition; // Default Search Condition
  484. // Constructor
  485. function crField($tblvar, $tblname, $fldvar, $fldname, $fldexpression, $fldtype, $flddatatype, $flddtfmt) {
  486. $this->TblVar = $tblvar;
  487. $this->TblName = $tblname;
  488. $this->FldVar = $fldvar;
  489. $this->FldName = $fldname;
  490. $this->FldExpression = $fldexpression;
  491. $this->FldType = $fldtype;
  492. $this->FldDataType = $flddatatype;
  493. $this->FldDateTimeFormat = $flddtfmt;
  494. }
  495. // Field caption
  496. function FldCaption() {
  497. global $ReportLanguage;
  498. return $ReportLanguage->FieldPhrase($this->TblVar, substr($this->FldVar, 2), "FldCaption");
  499. }
  500. // Field title
  501. function FldTitle() {
  502. global $ReportLanguage;
  503. return $ReportLanguage->FieldPhrase($this->TblVar, substr($this->FldVar, 2), "FldTitle");
  504. }
  505. // Field image alt
  506. function FldAlt() {
  507. global $ReportLanguage;
  508. return $ReportLanguage->FieldPhrase($this->TblVar, substr($this->FldVar, 2), "FldAlt");
  509. }
  510. // Field error message
  511. function FldErrMsg() {
  512. global $ReportLanguage;
  513. $err = $ReportLanguage->FieldPhrase($this->TblVar, substr($this->FldVar, 2), "FldErrMsg");
  514. if ($err == "") $err = $this->FldDefaultErrMsg . " - " . $this->FldCaption();
  515. return $err;
  516. }
  517. // Reset CSS styles for field object
  518. function ResetCSS() {
  519. $this->CellAttrs["style"] = "";
  520. $this->CellAttrs["class"] = "";
  521. $this->ViewAttrs["style"] = "";
  522. $this->ViewAttrs["class"] = "";
  523. }
  524. // View Attributes
  525. function ViewAttributes() {
  526. $sAtt = "";
  527. if (intval($this->ImageWidth) > 0 && (!$this->ImageResize || ($this->ImageResize && intval($this->ImageHeight) <= 0)))
  528. $sAtt .= " width=\"" . intval($this->ImageWidth) . "\"";
  529. if (intval($this->ImageHeight) > 0 && (!$this->ImageResize || ($this->ImageResize && intval($this->ImageWidth) <= 0)))
  530. $sAtt .= " height=\"" . intval($this->ImageHeight) . "\"";
  531. foreach ($this->ViewAttrs as $k => $v) {
  532. if (trim($v) <> "")
  533. $sAtt .= " " . $k . "=\"" . trim($v) . "\"";
  534. }
  535. return $sAtt;
  536. }
  537. // Link Attributes
  538. function LinkAttributes() {
  539. $sAtt = "";
  540. $sHref = trim($this->HrefValue);
  541. foreach ($this->LinkAttrs as $k => $v) {
  542. if (trim($v) <> "") {
  543. if ($k == "href")
  544. $sHref .= " " . $v;
  545. else
  546. $sAtt .= " " . $k . "=\"" . trim($v) . "\"";
  547. }
  548. }
  549. if ($sHref <> "")
  550. $sAtt .= " href=\"" . trim($sHref) . "\"";
  551. // if (trim($this->LinkCustomAttributes) <> "")
  552. // $sAtt .= " " . trim($this->LinkCustomAttributes);
  553. return $sAtt;
  554. }
  555. // Cell attributes
  556. function CellAttributes() {
  557. $sAtt = "";
  558. foreach ($this->CellAttrs as $k => $v) {
  559. if (trim($v) <> "")
  560. $sAtt .= " " . $k . "=\"" . trim($v) . "\"";
  561. }
  562. return $sAtt;
  563. }
  564. // Sort
  565. function getSort() {
  566. return @$_SESSION[EWRPT_PROJECT_VAR . "_" . $this->TblVar . "_" . EWRPT_TABLE_SORT . "_" . $this->FldVar];
  567. }
  568. function setSort($v) {
  569. if (@$_SESSION[EWRPT_PROJECT_VAR . "_" . $this->TblVar . "_" . EWRPT_TABLE_SORT . "_" . $this->FldVar] <> $v) {
  570. $_SESSION[EWRPT_PROJECT_VAR . "_" . $this->TblVar . "_" . EWRPT_TABLE_SORT . "_" . $this->FldVar] = $v;
  571. }
  572. }
  573. function ReverseSort() {
  574. return ($this->getSort() == "ASC") ? "DESC" : "ASC";
  575. }
  576. // List view value
  577. function ListViewValue() {
  578. $value = trim(strval($this->ViewValue));
  579. if ($value <> "") {
  580. $value2 = trim(preg_replace('/<[^img][^>]*>/i', '', strval($value)));
  581. return ($value2 <> "") ? $this->ViewValue : "&nbsp;";
  582. } else {
  583. return "&nbsp;";
  584. }
  585. }
  586. // Form value
  587. function setFormValue($v) {
  588. $this->FormValue = ewrpt_StripSlashes($v);
  589. if (is_array($this->FormValue))
  590. $this->FormValue = implode(",", $this->FormValue);
  591. $this->CurrentValue = $this->FormValue;
  592. }
  593. // QueryString value
  594. function setQueryStringValue($v) {
  595. $this->QueryStringValue = ewrpt_StripSlashes($v);
  596. $this->CurrentValue = $this->QueryStringValue;
  597. }
  598. // Database value
  599. function setDbValue($v) {
  600. $this->OldValue = $this->DbValue;
  601. if (EWRPT_IS_MSSQL && ($this->FldType == 131 || $this->FldType == 139)) // MS SQL adNumeric/adVarNumeric field
  602. $this->DbValue = floatval($v);
  603. else
  604. $this->DbValue = $v;
  605. $this->CurrentValue = $this->DbValue;
  606. }
  607. // Group value
  608. function GroupValue() {
  609. return $this->getGroupValue($this->CurrentValue);
  610. }
  611. // Group old value
  612. function GroupOldValue() {
  613. return $this->getGroupValue($this->OldValue);
  614. }
  615. // Get group value
  616. function getGroupValue($v) {
  617. if ($this->GroupingFieldId == 1) {
  618. return $v;
  619. } elseif (is_array($this->GroupDbValues)) {
  620. return @$this->GroupDbValues[$v];
  621. } elseif ($this->FldGroupByType <> "" && $this->FldGroupByType <> "n") {
  622. return ewrpt_GroupValue($this, $v);
  623. } else {
  624. return $v;
  625. }
  626. }
  627. }
  628. /**
  629. * Chart class
  630. */
  631. class crChart {
  632. var $TblName; // Table name
  633. var $TblVar; // Table variable name
  634. var $ChartName; // Chart name
  635. var $ChartVar; // Chart variable name
  636. var $ChartXFldName; // Chart X Field name
  637. var $ChartYFldName; // Chart Y Field name
  638. var $ChartSFldName; // Chart Series Field name
  639. var $ChartType; // Chart Type
  640. var $ChartSummaryType; // Chart Type
  641. var $ChartWidth; // Chart Width
  642. var $ChartHeight; // Chart Height
  643. var $ChartAlign; // Chart Align
  644. var $SqlSelect;
  645. var $SqlGroupBy;
  646. var $SqlOrderBy;
  647. var $XAxisDateFormat;
  648. var $NameDateFormat;
  649. var $SeriesDateType;
  650. var $SqlSelectSeries;
  651. var $SqlGroupBySeries;
  652. var $SqlOrderBySeries;
  653. var $ID;
  654. var $Parms = array();
  655. var $Trends;
  656. var $Data;
  657. var $Series;
  658. var $XmlDoc;
  659. var $XmlRoot;
  660. // Constructor
  661. function crChart($tblvar, $tblname, $chartvar, $chartname, $xfld, $yfld, $sfld, $type, $smrytype, $width, $height, $align="") {
  662. $this->TblVar = $tblvar;
  663. $this->TblName = $tblname;
  664. $this->ChartVar = $chartvar;
  665. $this->ChartName = $chartname;
  666. $this->ChartXFldName = $xfld;
  667. $this->ChartYFldName = $yfld;
  668. $this->ChartSFldName = $sfld;
  669. $this->ChartType = $type;
  670. $this->ChartSummaryType = $smrytype;
  671. $this->ChartWidth = $width;
  672. $this->ChartHeight = $height;
  673. $this->ChartAlign = $align;
  674. $this->ID = NULL;
  675. $this->Parms = NULL;
  676. $this->Trends = NULL;
  677. $this->Data = NULL;
  678. $this->Series = NULL;
  679. $this->XmlDoc = new DOMDocument("1.0", "utf-8");
  680. }
  681. // Chart caption
  682. function ChartCaption() {
  683. global $ReportLanguage;
  684. return $ReportLanguage->ChartPhrase($this->TblVar, $this->ChartVar, "ChartCaption");
  685. }
  686. // function xaxisname
  687. function ChartXAxisName() {
  688. global $ReportLanguage;
  689. return $ReportLanguage->ChartPhrase($this->TblVar, $this->ChartVar, "ChartXAxisName");
  690. }
  691. // function yaxisname
  692. function ChartYAxisName() {
  693. global $ReportLanguage;
  694. return $ReportLanguage->ChartPhrase($this->TblVar, $this->ChartVar, "ChartYAxisName");
  695. }
  696. // function PYAxisName
  697. function ChartPYAxisName() {
  698. global $ReportLanguage;
  699. return $ReportLanguage->ChartPhrase($this->TblVar, $this->ChartVar, "ChartPYAxisName");
  700. }
  701. // function SYAxisName
  702. function ChartSYAxisName() {
  703. global $ReportLanguage;
  704. return $ReportLanguage->ChartPhrase($this->TblVar, $this->ChartVar, "ChartSYAxisName");
  705. }
  706. // Set chart parameters
  707. function SetChartParam($Name, $Value, $Output) {
  708. $this->Parms[$Name] = array($Name, $Value, $Output);
  709. }
  710. // Set up default chart parm
  711. function SetupDefaultChartParm($key, $value) {
  712. if (is_array($this->Parms)) {
  713. $parm = $this->LoadParm($key);
  714. if (is_null($parm)) {
  715. $this->Parms[$key] = array($key, $value, TRUE);
  716. } elseif ($parm == "") {
  717. $this->SaveParm($key, $value);
  718. }
  719. }
  720. }
  721. // Load chart parm
  722. function LoadParm($key) {
  723. if (is_array($this->Parms) && array_key_exists($key, $this->Parms))
  724. return $this->Parms[$key][1];
  725. return NULL;
  726. }
  727. // Save chart parm
  728. function SaveParm($key, $value) {
  729. if (is_array($this->Parms) && array_key_exists($key, $this->Parms))
  730. $this->Parms[$key][1] = $value;
  731. }
  732. // Chart Xml
  733. function ChartXml() {
  734. // Initialize default values
  735. $this->SetupDefaultChartParm("caption", "Chart");
  736. // Show names/values/hover
  737. $this->SetupDefaultChartParm("shownames", "1"); // Default show names
  738. $this->SetupDefaultChartParm("showvalues", "1"); // Default show values
  739. $this->SetupDefaultChartParm("showhover", "1"); // Default show hover
  740. // Get showvalues/showhovercap
  741. $cht_showValues = $this->LoadParm("showvalues");
  742. $cht_showHoverCap = $this->LoadParm("showhovercap");
  743. // Format percent for Pie charts
  744. $cht_showPercentageValues = $this->LoadParm("showPercentageValues");
  745. $cht_showPercentageInLabel = $this->LoadParm("showPercentageInLabel");
  746. $cht_type = $this->LoadParm("type");
  747. if ($cht_type == 2 || $cht_type == 6 || $cht_type == 8 || $cht_type == 101) {
  748. if (($cht_showHoverCap == "1" && $cht_showPercentageValues == "1") ||
  749. ($cht_showValues == "1" && $cht_showPercentageInLabel == "1")) {
  750. $this->SetupDefaultChartParm("formatNumber", "1");
  751. $this->SaveParm("formatNumber", "1");
  752. }
  753. } elseif ($cht_type == 20) {
  754. $this->SetupDefaultChartParm("bearBorderColor", "E33C3C");
  755. $this->SetupDefaultChartParm("bearFillColor", "E33C3C");
  756. }
  757. // Process chart parms
  758. $this->ProcessChartParms($cht_type, $this->Parms);
  759. $chartseries =& $this->Series;
  760. $chartdata =& $this->Data;
  761. $cht_series = ((intval($cht_type) >= 9 && intval($cht_type) <= 19) || (intval($cht_type) >= 102 && intval($cht_type) <= 103)) ? 1 : 0; // $cht_series = 1 (Multi series charts)
  762. $cht_series_type = $this->LoadParm("seriestype");
  763. $cht_alpha = $this->LoadParm("alpha");
  764. // Hide legend for single series (Bar 3D / Column 2D / Line 2D / Area 2D)
  765. $scrollchart = (intval($this->LoadParm("numVisiblePlot")) > 0 && ($cht_type == 1 || $cht_type == 4 || $cht_type == 7)) ? 1 : 0;
  766. $cht_single_series = ($cht_type == 104 || $scrollchart == 1) ? 1 : 0;
  767. if ($cht_single_series == 1) {
  768. $this->SetupDefaultChartParm("showLegend", "0");
  769. $this->SaveParm("showLegend", "0");
  770. }
  771. if (is_array($chartdata)) {
  772. $this->WriteChartHeader(); // Write chart header
  773. // Candlestick
  774. if ($cht_type == 20) {
  775. // Write candlestick cat
  776. if (count($chartdata[0]) >= 7) {
  777. $cats = $this->XmlDoc->createElement('categories');
  778. $this->XmlRoot->appendChild($cats);
  779. $cntcat = count($chartdata);
  780. for ($i = 0; $i < $cntcat; $i++) {
  781. $xindex = $i+1;
  782. $name = $chartdata[$i][6];
  783. if ($name <> "")
  784. $this->WriteChartCandlestickCatContent($cats, $xindex, $name);
  785. }
  786. }
  787. // Write candlestick data
  788. $data = $this->XmlDoc->createElement('data');
  789. $this->XmlRoot->appendChild($data);
  790. $cntdata = count($chartdata);
  791. for ($i = 0; $i < $cntdata; $i++) {
  792. $open = is_null($chartdata[$i][2]) ? 0 : (float)$chartdata[$i][2];
  793. $high = is_null($chartdata[$i][3]) ? 0 : (float)$chartdata[$i][3];
  794. $low = is_null($chartdata[$i][4]) ? 0 : (float)$chartdata[$i][4];
  795. $close = is_null($chartdata[$i][5]) ? 0 : (float)$chartdata[$i][5];
  796. $xindex = $i+1;
  797. $this->WriteChartCandlestickContent($data, $open, $high, $low, $close, $xindex);
  798. }
  799. // Multi series
  800. } else if ($cht_series == 1) {
  801. // Multi-Y values
  802. if ($cht_series_type == "1") {
  803. // Write cat
  804. $cats = $this->XmlDoc->createElement('categories');
  805. $this->XmlRoot->appendChild($cats);
  806. $cntcat = count($chartdata);
  807. for ($i = 0; $i < $cntcat; $i++) {
  808. $name = $this->ChartFormatName($chartdata[$i][0]);
  809. $this->WriteChartCatContent($cats, $name);
  810. }
  811. // Write series
  812. $cntdata = count($chartdata);
  813. $cntseries = count($chartseries);
  814. if ($cntseries > count($chartdata[0])-2) $cntseries = count($chartdata[0])-2;
  815. for ($i = 0; $i < $cntseries; $i++) {
  816. $color = $this->GetPaletteColor($i);
  817. $bShowSeries = EWRPT_CHART_SHOW_BLANK_SERIES;
  818. $dataset = $this->XmlDoc->createElement('dataset');
  819. $this->WriteChartSeriesHeader($dataset, $chartseries[$i], $color, $cht_alpha);
  820. $bWriteSeriesHeader = TRUE;
  821. for ($j = 0; $j < $cntdata; $j++) {
  822. $val = $chartdata[$j][$i+2];
  823. $val = (is_null($val)) ? 0 : (float)$val;
  824. if ($val <> 0) $bShowSeries = TRUE;
  825. $this->WriteChartSeriesContent($dataset, $val);
  826. }
  827. if ($bShowSeries)
  828. $this->XmlRoot->appendChild($dataset);
  829. }
  830. // Series field
  831. } else {
  832. // Get series names
  833. if (is_array($chartseries)) {
  834. $nSeries = count($chartseries);
  835. } else {
  836. $nSeries = 0;
  837. }
  838. // Write cat
  839. $cats = $this->XmlDoc->createElement('categories');
  840. $this->XmlRoot->appendChild($cats);
  841. $chartcats = array();
  842. $cntdata = count($chartdata);
  843. for ($i = 0; $i < $cntdata; $i++) {
  844. $name = $chartdata[$i][0];
  845. if (!in_array($name, $chartcats)) {
  846. $this->WriteChartCatContent($cats, $name);
  847. $chartcats[] = $name;
  848. }
  849. }
  850. // Write series
  851. for ($i = 0; $i < $nSeries; $i++) {
  852. $seriesname = (is_array($chartseries[$i])) ? $chartseries[$i][0] : $chartseries[$i];
  853. $color = $this->GetPaletteColor($i);
  854. $bShowSeries = EWRPT_CHART_SHOW_BLANK_SERIES;
  855. $dataset = $this->XmlDoc->createElement('dataset');
  856. $this->WriteChartSeriesHeader($dataset, $chartseries[$i], $color, $cht_alpha);
  857. $cntcats = count($chartcats);
  858. $cntdata = count($chartdata);
  859. for ($j = 0; $j < $cntcats; $j++) {
  860. $val = 0;
  861. for ($k = 0; $k < $cntdata; $k++) {
  862. if ($chartdata[$k][0] == $chartcats[$j] && $chartdata[$k][1] == $seriesname) {
  863. $val = $chartdata[$k][2];
  864. $val = (is_null($val)) ? 0 : (float)$val;
  865. if ($val <> 0) $bShowSeries = TRUE;
  866. break;
  867. }
  868. }
  869. $this->WriteChartSeriesContent($dataset, $val);
  870. }
  871. if ($bShowSeries)
  872. $this->XmlRoot->appendChild($dataset);
  873. }
  874. }
  875. // Show single series
  876. } elseif ($cht_single_series == 1) {
  877. // Write multiple cats
  878. $cats = $this->XmlDoc->createElement('categories');
  879. $this->XmlRoot->appendChild($cats);
  880. $cntcat = count($chartdata);
  881. for ($i = 0; $i < $cntcat; $i++) {
  882. $name = $this->ChartFormatName($chartdata[$i][0]);
  883. if ($chartdata[$i][1] <> "")
  884. $name .= ", " . $chartdata[$i][1];
  885. $this->WriteChartCatContent($cats, $name);
  886. }
  887. // Write series
  888. $toolTipSep = $this->LoadParm("toolTipSepChar");
  889. if ($toolTipSep == "") $toolTipSep = ":";
  890. $cntdata = count($chartdata);
  891. $dataset = $this->XmlDoc->createElement('dataset');
  892. $this->WriteChartSeriesHeader($dataset, '', '', $cht_alpha);
  893. for ($i = 0; $i < $cntdata; $i++) {
  894. $name = $this->ChartFormatName($chartdata[$i][0]);
  895. if ($chartdata[$i][1] <> "")
  896. $name .= ", " . $chartdata[$i][1];
  897. $val = $chartdata[$i][2];
  898. $val = (is_null($val)) ? 0 : (float)$val;
  899. $color = $this->GetPaletteColor($i);
  900. $toolText = $name . $toolTipSep . $val;
  901. $this->WriteChartSeriesContent($dataset, $val, $color, $cht_alpha, '', $toolText);
  902. $this->XmlRoot->appendChild($dataset);
  903. }
  904. // Single series
  905. } else {
  906. $cntdata = count($chartdata);
  907. for ($i = 0; $i < $cntdata; $i++) {
  908. $name = $this->ChartFormatName($chartdata[$i][0]);
  909. $color = $this->GetPaletteColor($i);
  910. if ($chartdata[$i][1] <> "")
  911. $name .= ", " . $chartdata[$i][1];
  912. $val = $chartdata[$i][2];
  913. $val = (is_null($val)) ? 0 : (float)$val;
  914. $this->WriteChartContent($this->XmlRoot, $name, $val, $color, $cht_alpha, @$link); // Get chart content
  915. }
  916. }
  917. // Get trend lines
  918. $this->WriteChartTrendLines();
  919. }
  920. $wrk = $this->XmlDoc->saveXML();
  921. return $wrk;
  922. // ewrpt_Trace($wrk);
  923. }
  924. // Show chart (FusionCharts Free)
  925. // typ: chart type (1/2/3/4/...)
  926. // id: chart id
  927. // parms: "bgcolor=FFFFFF|..."
  928. // trends: trend lines
  929. function ShowChartFCF($xml) {
  930. $typ = $this->ChartType;
  931. $id = $this->ID;
  932. $parms = $this->Parms;
  933. $trends = $this->Trends;
  934. $data = $this->Data;
  935. $series = $this->Series;
  936. $width = $this->ChartWidth;
  937. $height = $this->ChartHeight;
  938. $align = $this->ChartAlign;
  939. if (empty($typ))
  940. $typ = 1;
  941. // Get chart swf
  942. switch ($typ) {
  943. // Single Series
  944. case 1: $chartswf = "FCF_Column2D.swf"; break; // Column 2D
  945. case 2: $chartswf = "FCF_Pie2D.swf"; break; // Pie 2D
  946. case 3: $chartswf = "FCF_Bar2D.swf"; break; // Bar 2D
  947. case 4: $chartswf = "FCF_Line.swf"; break; // Line 2D
  948. case 5: $chartswf = "FCF_Column3D.swf"; break; // Column 3D
  949. case 6: $chartswf = "FCF_Pie3D.swf"; break; // Pie 3D
  950. case 7: $chartswf = "FCF_Area2D.swf"; break; // Area 2D
  951. case 8: $chartswf = "FCF_Doughnut2D.swf"; break; // Doughnut 2D
  952. // Multi Series
  953. case 9: $chartswf = "FCF_MSColumn2D.swf"; break; // Multi-series Column 2D
  954. case 10: $chartswf = "FCF_MSColumn3D.swf"; break; // Multi-series Column 3D
  955. case 11: $chartswf = "FCF_MSLine.swf"; break; // Multi-series Line 2D
  956. case 12: $chartswf = "FCF_MSArea2D.swf"; break; // Multi-series Area 2D
  957. case 13: $chartswf = "FCF_MSBar2D.swf"; break; // Multi-series Bar 2D
  958. // Stacked
  959. case 14: $chartswf = "FCF_StackedColumn2D.swf"; break; // Stacked Column 2D
  960. case 15: $chartswf = "FCF_StackedColumn3D.swf"; break; // Stacked Column 3D
  961. case 16: $chartswf = "FCF_StackedArea2D.swf"; break; // Stacked Area 2D
  962. case 17: $chartswf = "FCF_StackedBar2D.swf"; break; // Stacked Bar 2D
  963. // Combination
  964. case 18: $chartswf = "FCF_MSColumn2DLineDY.swf"; break; // Multi-series Column 2D Line Dual Y Chart
  965. case 19: $chartswf = "FCF_MSColumn3DLineDY.swf"; break; // Multi-series Column 3D Line Dual Y Chart
  966. // Financial
  967. case 20: $chartswf = "FCF_Candlestick.swf"; break; // Candlestick
  968. // Other
  969. case 21: $chartswf = "FCF_Gantt.swf"; break; // Gantt
  970. case 22: $chartswf = "FCF_Funnel.swf"; break; // Funnel
  971. // Additional FusionCharts
  972. case 101: $chartswf = "FCF_Doughnut2D.swf"; break; // Doughnut 3D, switch back to 2D
  973. case 102: $chartswf = "FCF_MSBar2D.swf"; break; // Multi-series Bar 3D, switch back to 2D
  974. case 103: $chartswf = "FCF_StackedBar2D.swf"; break; // Stacked Bar 3D, switch back to 2D
  975. case 104: $chartswf = "FCF_Bar2D.swf"; break; // Bar 3D, switch back to 2D
  976. // Default
  977. default: $chartswf = "FCF_Column2D.swf"; // Default = Column 2D
  978. }
  979. // Set width, height and align
  980. if (is_numeric($width) && is_numeric($height)) {
  981. $wrkwidth = $width;
  982. $wrkheight = $height;
  983. } else { // default
  984. $wrkwidth = EWRPT_CHART_WIDTH;
  985. $wrkheight = EWRPT_CHART_HEIGHT;
  986. }
  987. if (strtolower($align) == "left" || strtolower($align) == "right") {
  988. $wrkalign = strtolower($align);
  989. } else {
  990. $wrkalign = EWRPT_CHART_ALIGN; // default
  991. }
  992. // Output JavaScript for FCF
  993. $chartxml = $xml;
  994. $wrk = "<script type=\"text/javascript\">\n";
  995. $wrk .= "var chartwidth = \"$wrkwidth\";\n";
  996. $wrk .= "var chartheight = \"$wrkheight\";\n";
  997. //$wrk .= "var chartalign = \"$wrkalign\";\n";
  998. $wrk .= "var chartxml = \"" . ewrpt_EscapeJs($chartxml) . "\";\n";
  999. $wrk .= "var chartid = \"div_$id\";\n";
  1000. $wrk .= "var chartswf = \"" . EWRPT_FUSIONCHARTS_FREE_CHART_PATH . $chartswf . "\";\n";
  1001. $wrk .= "var cht_$id = new FusionChartsFree(chartswf, \"chart_$id\", chartwidth, chartheight);\n";
  1002. $wrk .= "cht_$id.addParam(\"wmode\", \"transparent\");\n";
  1003. $wrk .= "cht_$id.setDataXML(chartxml);\n";
  1004. $wrk .= "var f = " . CurrentPage()->PageObjName . ".Chart_Rendering;\n";
  1005. $wrk .= "if (typeof f == \"function\") f(cht_$id, 'chart_$id');\n";
  1006. $wrk .= "cht_$id.render(chartid);\n";
  1007. $wrk .= "f = " . CurrentPage()->PageObjName . ".Chart_Rendered;\n";
  1008. $wrk .= "if (typeof f == \"function\") f(cht_$id, 'chart_$id');\n";
  1009. $wrk .= "</script>\n";
  1010. // Add debug xml
  1011. if (EWRPT_DEBUG_ENABLED)
  1012. $wrk .= "<p>(Chart XML): " . ewrpt_HtmlEncode($chartxml) . "</p>";
  1013. return $wrk;
  1014. }
  1015. // Show Chart Xml
  1016. function ShowChartXml() {
  1017. // Build chart content
  1018. $sChartContent = $this->ChartXml();
  1019. header("Content-Type: text/xml; charset=UTF-8");
  1020. // Write utf-8 BOM
  1021. echo "\xEF\xBB\xBF";
  1022. // Write utf-8 encoding
  1023. echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
  1024. // Write content
  1025. echo $sChartContent;
  1026. }
  1027. // Show Chart Text
  1028. function ShowChartText() {
  1029. // Build chart content
  1030. $sChartContent = $this->ChartXml();
  1031. header("Content-Type: text/plain; charset=UTF-8");
  1032. // Write content
  1033. echo $sChartContent;
  1034. }
  1035. // Get color
  1036. function GetPaletteColor($i) {
  1037. $colorpalette = $this->LoadParm("colorpalette");
  1038. $ar_cht_colorpalette = explode("|", $colorpalette);
  1039. if (is_array($ar_cht_colorpalette))
  1040. $cntar = count($ar_cht_colorpalette);
  1041. return $ar_cht_colorpalette[$i % $cntar];
  1042. }
  1043. // Convert to HTML color
  1044. function ColorCode($c) {
  1045. if ($c <> "") {
  1046. // remove #
  1047. $color = str_replace("#", "", $c);
  1048. // fill to 6 digits
  1049. return str_pad($color, 6, "0", STR_PAD_LEFT);
  1050. } else {
  1051. return "";
  1052. }
  1053. }
  1054. // Output chart header
  1055. function WriteChartHeader() {
  1056. $cht_parms = $this->Parms;
  1057. $chartElement = ($this->ChartType == 20 || (EWRPT_FUSIONCHARTS_FREE && $this->ChartType <> 21 && $this->ChartType <> 22)) ? 'graph' : 'chart';
  1058. $chart = $this->XmlDoc->createElement($chartElement);
  1059. $this->XmlRoot =& $chart;
  1060. $this->XmlDoc->appendChild($chart);
  1061. if (is_array($cht_parms)) {
  1062. foreach ($cht_parms as $parm) {
  1063. if ($parm[2])
  1064. $this->WriteAtt($chart, $parm[0], $parm[1]);
  1065. }
  1066. }
  1067. }
  1068. // Get TrendLine XML
  1069. // <trendlines>
  1070. // <line startvalue='0.8' displayValue='Good' color='FF0000' thickness='1' isTrendZone='0'/>
  1071. // <line startvalue='-0.4' displayValue='Bad' color='009999' thickness='1' isTrendZone='0'/>
  1072. // </trendlines>
  1073. function WriteChartTrendLines() {
  1074. $cht_trends = $this->Trends;
  1075. if (is_array($cht_trends)) {
  1076. foreach ($cht_trends as $trend) {
  1077. $trends = $this->XmlDoc->createElement('trendlines');
  1078. $this->XmlRoot->appendChild($trends);
  1079. // Get all trend lines
  1080. $this->WriteChartTrendLine($trends, $trend[0], $trend[1], $trend[2], $trend[3], $trend[4], $trend[5], $trend[6], $trend[7]);
  1081. }
  1082. }
  1083. }
  1084. // Output trend line
  1085. function WriteChartTrendLine(&$node, $startval, $endval, $color, $dispval, $thickness, $trendzone, $showontop, $alpha) {
  1086. $line = $this->XmlDoc->createElement('line');
  1087. $this->WriteAtt($line, "startValue", $startval); // Starting y value
  1088. if ($endval <> 0)
  1089. $this->WriteAtt($line, "endValue", $endval); // Ending y value
  1090. $this->WriteAtt($line, "color", $this->CheckColorCode($color)); // Color
  1091. if ($dispval <> "")
  1092. $this->WriteAtt($line, "displayValue", $dispval); // Display value
  1093. if ($thickness > 0)
  1094. $this->WriteAtt($line, "thickness", $thickness); // Thickness
  1095. $this->WriteAtt($line, "isTrendZone", $trendzone); // Display trend as zone or line
  1096. $this->WriteAtt($line, "showOnTop", $showontop); // Show on top
  1097. if ($alpha > 0)
  1098. $this->WriteAtt($line, "alpha", $alpha); // Alpha
  1099. $node->appendChild($line);
  1100. }
  1101. // Series header/footer XML (multi series)
  1102. function WriteChartSeriesHeader(&$node, $series, $color, $alpha) {
  1103. global $ReportLanguage;
  1104. $seriesname = is_array($series) ? $series[0] : $series;
  1105. if (is_null($seriesname)) {
  1106. $seriesname = $ReportLanguage->Phrase("NullLabel");
  1107. } elseif ($seriesname == "") {
  1108. $seriesname = $ReportLanguage->Phrase("EmptyLabel");
  1109. }
  1110. $this->WriteAtt($node, "seriesname", $seriesname);
  1111. $this->WriteAtt($node, "color", $this->ColorCode($color));
  1112. $this->WriteAtt($node, "alpha", $alpha);
  1113. if (is_array($series))
  1114. $this->WriteAtt($node, "parentYAxis", $series[1]);
  1115. }
  1116. // Series content XML (multi series)
  1117. function WriteChartSeriesContent(&$node, $val, $color = "", $alpha = "", $lnk = "", $toolText = "") {
  1118. $set = $this->XmlDoc->createElement('set');
  1119. $this->WriteAtt($set, "value", $this->ChartFormatNumber($val));
  1120. if ($color <> "")
  1121. $this->WriteAtt($set, "color", $this->ColorCode($color));
  1122. if ($alpha <> "")
  1123. $this->WriteAtt($set, "alpha", $alpha);
  1124. if ($lnk <> "")
  1125. $this->WriteAtt($set, "link", $lnk);
  1126. if ($toolText <> "")
  1127. $this->WriteAtt($set, "toolText", $toolText);
  1128. $node->appendChild($set);
  1129. }
  1130. // Category content XML (Candlestick category)
  1131. function WriteChartCandlestickCatContent(&$node, $xindex, $name) {
  1132. $cat = $this->XmlDoc->createElement('category');
  1133. $this->WriteAtt($cat, "name", $name);
  1134. $this->WriteAtt($cat, "xindex", $xindex);
  1135. $this->WriteAtt($cat, "showline", "1");
  1136. $node->appendChild($cat);
  1137. }
  1138. // Chart content XML (Candlestick)
  1139. function WriteChartCandlestickContent(&$node, $open, $high, $low, $close, $xindex) {
  1140. $set = $this->XmlDoc->createElement('set');
  1141. $this->WriteAtt($set, "open", $this->ChartFormatNumber($open));
  1142. $this->WriteAtt($set, "high", $this->ChartFormatNumber($high));
  1143. $this->WriteAtt($set, "low", $this->ChartFormatNumber($low));
  1144. $this->WriteAtt($set, "close", $this->ChartFormatNumber($close));
  1145. if ($xindex <> "")
  1146. $this->WriteAtt($set, "xindex", $xindex);
  1147. $node->appendChild($set);
  1148. }
  1149. // Format name for chart
  1150. function ChartFormatName($name) {
  1151. global $ReportLanguage;
  1152. if (is_null($name)) {
  1153. return $ReportLanguage->Phrase("NullLabel");
  1154. } elseif ($name == "") {
  1155. return $ReportLanguage->Phrase("EmptyLabel");
  1156. } else {
  1157. return $name;
  1158. }
  1159. }
  1160. // Format number for chart
  1161. function ChartFormatNumber($v) {
  1162. $cht_decimalprecision = $this->LoadParm("decimalPrecision");
  1163. if (is_null($cht_decimalprecision)) {
  1164. return $v;
  1165. } else {
  1166. return number_format($v, $cht_decimalprecision, '.', '');
  1167. }
  1168. }
  1169. // Write attribute
  1170. function WriteAtt(&$node, $name, $val) {
  1171. $val = $this->CheckColorCode(strval($val));
  1172. $val = $this->ChartEncode($val);
  1173. if ($node->hasAttribute($name)) {
  1174. $node->getAttributeNode($name)->value = ewrpt_XmlEncode(ewrpt_ConvertToUtf8($val));
  1175. } else {
  1176. $att = $this->XmlDoc->createAttribute($name);
  1177. $att->value = ewrpt_XmlEncode(ewrpt_ConvertToUtf8($val));
  1178. $node->appendChild($att);
  1179. }
  1180. }
  1181. // Check color code
  1182. function CheckColorCode($val) {
  1183. if (substr($val, 0, 1) == "#" && strlen($val) == 7) {
  1184. return substr($val, 1);
  1185. } else {
  1186. return $val;
  1187. }
  1188. }
  1189. // Process chart parms
  1190. function ProcessChartParms(&$ChartType, &$Parms) {
  1191. if ($ChartType == 104) $ChartType = 3; // Bar 3D, Switch back to Bar 2D
  1192. // Remove numVisiblePlot (scroll charts)
  1193. if (array_key_exists("numVisiblePlot", $Parms))
  1194. unset($Parms["numVisiblePlot"]);
  1195. }
  1196. // Encode special characters for FusionChartsFree
  1197. // + => %2B
  1198. function ChartEncode($val) {
  1199. $v = str_replace("+", "%2B", $val);
  1200. return $v;
  1201. }
  1202. // Category content XML (multi series)
  1203. function WriteChartCatContent(&$node, $name) {
  1204. $cat = $this->XmlDoc->createElement('category');
  1205. $this->WriteAtt($cat, "name", $name);
  1206. $node->appendChild($cat);
  1207. }
  1208. // Chart content XML
  1209. function WriteChartContent(&$node, $name, $val, $color, $alpha, $lnk) {
  1210. $cht_shownames = $this->LoadParm("shownames");
  1211. $set = $this->XmlDoc->createElement('set');
  1212. $this->WriteAtt($set, "name", $name);
  1213. $this->WriteAtt($set, "value", $this->ChartFormatNumber($val));
  1214. $this->WriteAtt($set, "color", $this->ColorCode($color));
  1215. $this->WriteAtt($set, "alpha", $alpha);
  1216. $this->WriteAtt($set, "link", $lnk);
  1217. if ($cht_shownames == "1")
  1218. $this->WriteAtt($set, "showName", "1");
  1219. $node->appendChild($set);
  1220. }
  1221. }
  1222. //
  1223. // Column class
  1224. //
  1225. class crCrosstabColumn {
  1226. var $Caption;
  1227. var $Value;
  1228. var $Visible;
  1229. function crCrosstabColumn($value, $caption, $visible = TRUE) {
  1230. $this->Caption = $caption;
  1231. $this->Value = $value;
  1232. $this->Visible = $visible;
  1233. }
  1234. }
  1235. //
  1236. // Advanced filter class
  1237. //
  1238. class crAdvancedFilter {
  1239. var $ID;
  1240. var $Name;
  1241. var $FunctionName;
  1242. var $Enabled = TRUE;
  1243. function crAdvancedFilter($filterid, $filtername, $filterfunc) {
  1244. $this->ID = $filterid;
  1245. $this->Name = $filtername;
  1246. $this->FunctionName = $filterfunc;
  1247. }
  1248. }
  1249. /**
  1250. * List option collection class
  1251. */
  1252. class crListOptions {
  1253. var $Items = array();
  1254. var $CustomItem = "";
  1255. var $Tag = "td";
  1256. var $Separator = "";
  1257. // Add and return a new option (return-by-reference is for PHP 5 only)
  1258. function &Add($Name) {
  1259. $item = new crListOption($Name, $this->Tag, $this->Separator);
  1260. $item->Parent =& $this;
  1261. $this->Items[$Name] = $item;
  1262. return $item;
  1263. }
  1264. // Load default settings
  1265. function LoadDefault() {
  1266. $this->CustomItem = "";
  1267. foreach ($this->Items as $key => $item)
  1268. $this->Items[$key]->Body = "";
  1269. }
  1270. // Hide all options
  1271. function HideAllOptions() {
  1272. foreach ($this->Items as $key => $item)
  1273. $this->Items[$key]->Visible = FALSE;
  1274. }
  1275. // Show all options
  1276. function ShowAllOptions() {
  1277. foreach ($this->Items as $key => $item)
  1278. $this->Items[$key]->Visible = TRUE;
  1279. }
  1280. // Get item by name (return-by-reference is for PHP 5 only)
  1281. // predefined names: view/edit/copy/delete/detail_<DetailTable>/userpermission/checkbox
  1282. function &GetItem($Name) {
  1283. $item = array_key_exists($Name, $this->Items) ? $this->Items[$Name] : NULL;
  1284. return $item;
  1285. }
  1286. // Move item to position
  1287. function MoveItem($Name, $Pos) {
  1288. $cnt = count($this->Items);
  1289. if ($Pos < 0 || $Pos >= $cnt)
  1290. return;
  1291. $item = $this->GetItem($Name);
  1292. if ($item) {
  1293. unset($this->Items[$Name]);
  1294. $this->Items = array_merge(array_slice($this->Items, 0, $Pos),
  1295. array($Name => $item), array_slice($this->Items, $Pos));
  1296. }
  1297. }
  1298. // Render list options
  1299. function Render($Part, $Pos="") {
  1300. if ($this->CustomItem <> "") {
  1301. $cnt = 0;
  1302. foreach ($this->Items as &$item) {
  1303. if ($item->Visible && $this->ShowPos($item->OnLeft, $Pos))
  1304. $cnt++;
  1305. if ($item->Name == $this->CustomItem)
  1306. $opt = $item;
  1307. }
  1308. if (is_object($opt) && $cnt > 0) {
  1309. if ($this->ShowPos($opt->OnLeft, $Pos)) {
  1310. echo $opt->Render($Part, $cnt);
  1311. } else {
  1312. echo $opt->Render("", $cnt);
  1313. }
  1314. }
  1315. } else {
  1316. foreach ($this->Items as &$item) {
  1317. if ($item->Visible && $this->ShowPos($item->OnLeft, $Pos))
  1318. echo $item->Render($Part);
  1319. }
  1320. }
  1321. }
  1322. function ShowPos($OnLeft, $Pos) {
  1323. return ($OnLeft && $Pos == "left") || (!$OnLeft && $Pos == "right") || ($Pos == "");
  1324. }
  1325. }
  1326. /**
  1327. * List option class
  1328. */
  1329. class crListOption {
  1330. var $Name;
  1331. var $OnLeft;
  1332. var $CssStyle;
  1333. var $Visible = TRUE;
  1334. var $Header;
  1335. var $Body;
  1336. var $Footer;
  1337. var $Tag = "td";
  1338. var $Separator = "";
  1339. var $Parent;
  1340. function crListOption($Name, $Tag, $Separator) {
  1341. $this->Name = $Name;
  1342. $this->Tag = $Tag;
  1343. $this->Separator = $Separator;
  1344. }
  1345. function MoveTo($Pos) {
  1346. $this->Parent->MoveItem($this->Name, $Pos);
  1347. }
  1348. function Render($Part, $ColSpan = 1) {
  1349. if ($Part == "header") {
  1350. $value = $this->Header;
  1351. } elseif ($Part == "body") {
  1352. $value = $this->Body;
  1353. } elseif ($Part == "footer") {
  1354. $value = $this->Footer;
  1355. } else {
  1356. $value = $Part;
  1357. }
  1358. if (strval($value) == "" && strtolower($this->Tag) <> "td")
  1359. return "";
  1360. $res = ($value <> "") ? $value : "&nbsp;";
  1361. $tage = "</" . $this->Tag . ">";
  1362. $tags = "<" . $this->Tag;
  1363. if ($this->CssStyle <> "")
  1364. $tags .= " style=\"" . $this->CssStyle . "\"";
  1365. if (strtolower($this->Tag) == "td" && $ColSpan > 1)
  1366. $tags .= " colspan=\"" . $ColSpan . "\"";
  1367. $tags .= " class=\"phpmaker\"";
  1368. $tags .= ">";
  1369. $res = $tags . $res . $tage . $this->Separator;
  1370. return $res;
  1371. }
  1372. }
  1373. /**
  1374. * Advanced Security class
  1375. */
  1376. class crAdvancedSecurity {
  1377. var $UserLevel = array(); // All User Levels
  1378. var $UserLevelPriv = array(); // All User Level permissions
  1379. var $UserLevelID = array(); // User Level ID array
  1380. var $UserID = array(); // User ID array
  1381. var $CurrentUserLevelID;
  1382. var $CurrentUserLevel; // Permissions
  1383. var $CurrentUserID;
  1384. var $CurrentParentUserID;
  1385. // Constructor
  1386. function crAdvancedSecurity() {
  1387. // Init User Level
  1388. $this->CurrentUserLevelID = $this->SessionUserLevelID();
  1389. if (is_numeric($this->CurrentUserLevelID) && intval($this->CurrentUserLevelID) >= -1) {
  1390. $this->UserLevelID[] = $this->CurrentUserLevelID;
  1391. }
  1392. // Init User ID
  1393. $this->CurrentUserID = $this->SessionUserID();
  1394. $this->CurrentParentUserID = $this->SessionParentUserID();
  1395. // Load user level
  1396. $this->LoadUserLevel();
  1397. }
  1398. // Session User ID
  1399. function SessionUserID() {
  1400. return strval(@$_SESSION[EWRPT_SESSION_USER_ID]);
  1401. }
  1402. function setSessionUserID($v) {
  1403. $_SESSION[EWRPT_SESSION_USER_ID] = trim(strval($v));
  1404. $this->CurrentUserID = trim(strval($v));
  1405. }
  1406. // Session Parent User ID
  1407. function SessionParentUserID() {
  1408. return strval(@$_SESSION[EWRPT_SESSION_PARENT_USER_ID]);
  1409. }
  1410. function setSessionParentUserID($v) {
  1411. $_SESSION[EWRPT_SESSION_PARENT_USER_ID] = trim(strval($v));
  1412. $this->CurrentParentUserID = trim(strval($v));
  1413. }
  1414. // Session User Level ID
  1415. function SessionUserLevelID() {
  1416. return @$_SESSION[EWRPT_SESSION_USER_LEVEL_ID];
  1417. }
  1418. function setSessionUserLevelID($v) {
  1419. $_SESSION[EWRPT_SESSION_USER_LEVEL_ID] = $v;
  1420. $this->CurrentUserLevelID = $v;
  1421. if (is_numeric($v) && $v >= -1)
  1422. $this->UserLevelID = array($v);
  1423. }
  1424. // Session User Level value
  1425. function SessionUserLevel() {
  1426. return @$_SESSION[EWRPT_SESSION_USER_LEVEL];
  1427. }
  1428. function setSessionUserLevel($v) {
  1429. $_SESSION[EWRPT_SESSION_USER_LEVEL] = $v;
  1430. $this->CurrentUserLevel = $v;
  1431. }
  1432. // Current user name
  1433. function getCurrentUserName() {
  1434. return strval(@$_SESSION[EWRPT_SESSION_USER_NAME]);
  1435. }
  1436. function setCurrentUserName($v) {
  1437. $_SESSION[EWRPT_SESSION_USER_NAME] = $v;
  1438. }
  1439. function CurrentUserName() {
  1440. return $this->getCurrentUserName();
  1441. }
  1442. // Current User ID
  1443. function CurrentUserID() {
  1444. return $this->CurrentUserID;
  1445. }
  1446. // Current Parent User ID
  1447. function CurrentParentUserID() {
  1448. return $this->CurrentParentUserID;
  1449. }
  1450. // Current User Level ID
  1451. function CurrentUserLevelID() {
  1452. return $this->CurrentUserLevelID;
  1453. }
  1454. // Current User Level value
  1455. function CurrentUserLevel() {
  1456. return $this->CurrentUserLevel;
  1457. }
  1458. // Can list
  1459. function CanList() {
  1460. return (($this->CurrentUserLevel & EWRPT_ALLOW_LIST) == EWRPT_ALLOW_LIST);
  1461. }
  1462. function setCanList($b) {
  1463. if ($b) {
  1464. $this->CurrentUserLevel = ($this->CurrentUserLevel | EWRPT_ALLOW_LIST);
  1465. } else {
  1466. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EWRPT_ALLOW_LIST));
  1467. }
  1468. }
  1469. // Can report
  1470. function CanReport() {
  1471. return (($this->CurrentUserLevel & EWRPT_ALLOW_REPORT) == EWRPT_ALLOW_REPORT);
  1472. }
  1473. function setCanReport($b) {
  1474. if ($b) {
  1475. $this->CurrentUserLevel = ($this->CurrentUserLevel | EWRPT_ALLOW_REPORT);
  1476. } else {
  1477. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EWRPT_ALLOW_REPORT));
  1478. }
  1479. }
  1480. // Can admin
  1481. function CanAdmin() {
  1482. return (($this->CurrentUserLevel & EWRPT_ALLOW_ADMIN) == EWRPT_ALLOW_ADMIN);
  1483. }
  1484. function setCanAdmin($b) {
  1485. if ($b) {
  1486. $this->CurrentUserLevel = ($this->CurrentUserLevel | EWRPT_ALLOW_ADMIN);
  1487. } else {
  1488. $this->CurrentUserLevel = ($this->CurrentUserLevel & (~ EWRPT_ALLOW_ADMIN));
  1489. }
  1490. }
  1491. // Last URL
  1492. function LastUrl() {
  1493. return @$_COOKIE[EWRPT_PROJECT_VAR]['LastUrl'];
  1494. }
  1495. // Save last URL
  1496. function SaveLastUrl() {
  1497. $s = ewrpt_ServerVar("SCRIPT_NAME");
  1498. $q = ewrpt_ServerVar("QUERY_STRING");
  1499. if ($q <> "") $s .= "?" . $q;
  1500. if ($this->LastUrl() == $s) $s = "";
  1501. @setcookie(EWRPT_PROJECT_VAR . '[LastUrl]', $s);
  1502. }
  1503. // Auto login
  1504. function AutoLogin() {
  1505. if (@$_COOKIE[EWRPT_PROJECT_VAR]['AutoLogin'] == "autologin") {
  1506. $usr = TEAdecrypt(@$_COOKIE[EWRPT_PROJECT_VAR]['Username'], EWRPT_RANDOM_KEY);
  1507. $pwd = TEAdecrypt(@$_COOKIE[EWRPT_PROJECT_VAR]['Password'], EWRPT_RANDOM_KEY);
  1508. $AutoLogin = $this->ValidateUser($usr, $pwd, TRUE);
  1509. } else {
  1510. $AutoLogin = FALSE;
  1511. }
  1512. return $AutoLogin;
  1513. }
  1514. // Validate user
  1515. function ValidateUser($usr, $pwd, $autologin) {
  1516. global $conn, $ReportLanguage;
  1517. $ValidateUser = FALSE;
  1518. // Call User Custom Validate event
  1519. if (EWRPT_USE_CUSTOM_LOGIN) {
  1520. $ValidateUser = $this->User_CustomValidate($usr, $pwd);
  1521. if ($ValidateUser) {
  1522. $_SESSION[EWRPT_SESSION_STATUS] = "login";
  1523. }
  1524. }
  1525. if (!$ValidateUser)
  1526. $_SESSION[EWRPT_SESSION_STATUS] = ""; // Clear login status
  1527. return $ValidateUser;
  1528. }
  1529. // No User Level security
  1530. function SetUpUserLevel() {}
  1531. // Add user permission
  1532. function AddUserPermission($UserLevelName, $TableName, $UserPermission) {
  1533. // Get User Level ID from user name
  1534. $UserLevelID = "";
  1535. if (is_array($this->UserLevel)) {
  1536. foreach ($this->UserLevel as $row) {
  1537. list($levelid, $name) = $row;
  1538. if (strval($UserLevelName) == strval($name)) {
  1539. $UserLevelID = $levelid;
  1540. break;
  1541. }
  1542. }
  1543. }
  1544. if (is_array($this->UserLevelPriv) && $UserLevelID <> "") {
  1545. $cnt = count($this->UserLevelPriv);
  1546. for ($i = 0; $i < $cnt; $i++) {
  1547. list($table, $levelid, $priv) = $this->UserLevelPriv[$i];
  1548. if (strtolower($table) == strtolower(EWRPT_TABLE_PREFIX . $TableName) && strval($levelid) == strval($UserLevelID)) {
  1549. $this->UserLevelPriv[$i][2] = $priv | $UserPermission; // Add permission
  1550. break;
  1551. }
  1552. }
  1553. }
  1554. }
  1555. // Delete user permission
  1556. function DeleteUserPermission($UserLevelName, $TableName, $UserPermission) {
  1557. // Get User Level ID from user name
  1558. $UserLevelID = "";
  1559. if (is_array($this->UserLevel)) {
  1560. foreach ($this->UserLevel as $row) {
  1561. list($levelid, $name) = $row;
  1562. if (strval($UserLevelName) == strval($name)) {
  1563. $UserLevelID = $levelid;
  1564. break;
  1565. }
  1566. }
  1567. }
  1568. if (is_array($this->UserLevelPriv) && $UserLevelID <> "") {
  1569. $cnt = count($this->UserLevelPriv);
  1570. for ($i = 0; $i < $cnt; $i++) {
  1571. list($table, $levelid, $priv) = $this->UserLevelPriv[$i];
  1572. if (strtolower($table) == strtolower(EWRPT_TABLE_PREFIX . $TableName) && strval($levelid) == strval($UserLevelID)) {
  1573. $this->UserLevelPriv[$i][2] = $priv & (127 - $UserPermission); // Remove permission
  1574. break;
  1575. }
  1576. }
  1577. }
  1578. }
  1579. // Load current User Level
  1580. function LoadCurrentUserLevel($Table) {
  1581. $this->LoadUserLevel();
  1582. $this->setSessionUserLevel($this->CurrentUserLevelPriv($Table));
  1583. }
  1584. // Get current user privilege
  1585. function CurrentUserLevelPriv($TableName) {
  1586. if ($this->IsLoggedIn()) {
  1587. $Priv= 0;
  1588. foreach ($this->UserLevelID as $UserLevelID)
  1589. $Priv |= $this->GetUserLevelPrivEx($TableName, $UserLevelID);
  1590. return $Priv;
  1591. } else {
  1592. return 0;
  1593. }
  1594. }
  1595. // Get User Level ID by User Level name
  1596. function GetUserLevelID($UserLevelName) {
  1597. if (strval($UserLevelName) == "Administrator") {
  1598. return -1;
  1599. } elseif ($UserLevelName <> "") {
  1600. if (is_array($this->UserLevel)) {
  1601. foreach ($this->UserLevel as $row) {
  1602. list($levelid, $name) = $row;
  1603. if (strval($name) == strval($UserLevelName))
  1604. return $levelid;
  1605. }
  1606. }
  1607. }
  1608. return -2;
  1609. }
  1610. // Add User Level (for use with UserLevel_Loading event)
  1611. function AddUserLevel($UserLevelName) {
  1612. if (strval($UserLevelName) == "") return;
  1613. $UserLevelID = $this->GetUserLevelID($UserLevelName);
  1614. if (!is_numeric($UserLevelID)) return;
  1615. if ($UserLevelID < -1) return;
  1616. if (!in_array($UserLevelID, $this->UserLevelID))
  1617. $this->UserLevelID[] = $UserLevelID;
  1618. }
  1619. // Delete User Level (for use with UserLevel_Loading event)
  1620. function DeleteUserLevel($UserLevelName) {
  1621. if (strval($UserLevelName) == "") return;
  1622. $UserLevelID = $this->GetUserLevelID($UserLevelName);
  1623. if (!is_numeric($UserLevelID)) return;
  1624. if ($UserLevelID < -1) return;
  1625. $cnt = count($this->UserLevelID);
  1626. for ($i = 0; $i < $cnt; $i++) {
  1627. if ($this->UserLevelID[$i] == $UserLevelID) {
  1628. unset($this->UserLevelID[$i]);
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. // User Level list
  1634. function UserLevelList() {
  1635. return implode(", ", $this->UserLevelID);
  1636. }
  1637. // User Level name list
  1638. function UserLevelNameList() {
  1639. $list = "";
  1640. foreach ($this->UserLevelID as $UserLevelID) {
  1641. if ($list <> "") $lList .= ", ";
  1642. $list .= ewrpt_QuotedValue($this->GetUserLevelName($UserLevelID), EWRPT_DATATYPE_STRING);
  1643. }
  1644. return $list;
  1645. }
  1646. // Get user privilege based on table name and User Level
  1647. function GetUserLevelPrivEx($TableName, $UserLevelID) {
  1648. if (strval($UserLevelID) == "-1") { // System Administrator
  1649. return 31; // Use old User Level values
  1650. } elseif ($UserLevelID >= 0) {
  1651. if (is_array($this->UserLevelPriv)) {
  1652. foreach ($this->UserLevelPriv as $row) {
  1653. list($table, $levelid, $priv) = $row;
  1654. if (strtolower($table) == strtolower(EWRPT_TABLE_PREFIX . $TableName) && strval($levelid) == strval($UserLevelID)) {
  1655. if (is_null($priv) || !is_numeric($priv)) return 0;
  1656. return intval($priv);
  1657. }
  1658. }
  1659. }
  1660. }
  1661. return 0;
  1662. }
  1663. // Get current User Level name
  1664. function CurrentUserLevelName() {
  1665. return $this->GetUserLevelName($this->CurrentUserLevelID());
  1666. }
  1667. // Get User Level name based on User Level
  1668. function GetUserLevelName($UserLevelID) {
  1669. if (strval($UserLevelID) == "-1") {
  1670. return "Administrator";
  1671. } elseif ($UserLevelID >= 0) {
  1672. if (is_array($this->UserLevel)) {
  1673. foreach ($this->UserLevel as $row) {
  1674. list($levelid, $name) = $row;
  1675. if (strval($levelid) == strval($UserLevelID))
  1676. return $name;
  1677. }
  1678. }
  1679. }
  1680. return "";
  1681. }
  1682. // Display all the User Level settings (for debug only)
  1683. function ShowUserLevelInfo() {
  1684. echo "<pre class=\"phpmaker\">";
  1685. print_r($this->UserLevel);
  1686. print_r($this->UserLevelPriv);
  1687. echo "</pre>";
  1688. echo "<p>Current User Level ID = " . $this->CurrentUserLevelID() . "</p>";
  1689. echo "<p>Current User Level ID List = " . $this->UserLevelList() . "</p>";
  1690. }
  1691. // Check privilege for List page (for menu items)
  1692. function AllowList($TableName) {
  1693. return ($this->CurrentUserLevelPriv($TableName) & EWRPT_ALLOW_LIST);
  1694. }
  1695. // Check if user is logged in
  1696. function IsLoggedIn() {
  1697. return (@$_SESSION[EWRPT_SESSION_STATUS] == "login");
  1698. }
  1699. // Check if user is system administrator
  1700. function IsSysAdmin() {
  1701. return (@$_SESSION[EWRPT_SESSION_SYSTEM_ADMIN] == 1);
  1702. }
  1703. // Check if user is administrator
  1704. function IsAdmin() {
  1705. $IsAdmin = $this->IsSysAdmin();
  1706. return $IsAdmin;
  1707. }
  1708. // Save User Level to Session
  1709. function SaveUserLevel() {
  1710. $_SESSION[EWRPT_SESSION_AR_USER_LEVEL] = $this->UserLevel;
  1711. $_SESSION[EWRPT_SESSION_AR_USER_LEVEL_PRIV] = $this->UserLevelPriv;
  1712. }
  1713. // Load User Level from Session
  1714. function LoadUserLevel() {
  1715. if (!is_array(@$_SESSION[EWRPT_SESSION_AR_USER_LEVEL]) || !is_array(@$_SESSION[EWRPT_SESSION_AR_USER_LEVEL_PRIV])) {
  1716. $this->SetupUserLevel();
  1717. $this->SaveUserLevel();
  1718. } else {
  1719. $this->UserLevel = $_SESSION[EWRPT_SESSION_AR_USER_LEVEL];
  1720. $this->UserLevelPriv = $_SESSION[EWRPT_SESSION_AR_USER_LEVEL_PRIV];
  1721. }
  1722. }
  1723. // Get current user info
  1724. function CurrentUserInfo($fieldname) {
  1725. $info = NULL;
  1726. return $info;
  1727. }
  1728. // UserID Loading event
  1729. function UserID_Loading() {
  1730. //echo "UserID Loading: " . $this->CurrentUserID() . "<br>";
  1731. }
  1732. // UserID Loaded event
  1733. function UserID_Loaded() {
  1734. //echo "UserID Loaded: " . $this->UserIDList() . "<br>";
  1735. }
  1736. // User Level Loaded event
  1737. function UserLevel_Loaded() {
  1738. //$this->AddUserPermission(<UserLevelName>, <TableName>, <UserPermission>);
  1739. //$this->DeleteUserPermission(<UserLevelName>, <TableName>, <UserPermission>);
  1740. }
  1741. // User Custom Validate event
  1742. function User_CustomValidate(&$usr, &$pwd) {
  1743. // Return FALSE to continue with default validation after event exits, or return TRUE to skip default validation
  1744. return FALSE;
  1745. }
  1746. // User Validated event
  1747. function User_Validated(&$rs) {
  1748. // Example:
  1749. //$_SESSION['UserEmail'] = $rs['Email'];
  1750. }
  1751. }
  1752. /**
  1753. * Functions for backward compatibilty
  1754. */
  1755. // Get current user name
  1756. function CurrentUserName() {
  1757. global $Security;
  1758. return (isset($Security)) ? $Security->CurrentUserName() : strval(@$_SESSION[EWRPT_SESSION_USER_NAME]);
  1759. }
  1760. // Get current user ID
  1761. function CurrentUserID() {
  1762. global $Security;
  1763. return (isset($Security)) ? $Security->CurrentUserID() : strval(@$_SESSION[EWRPT_SESSION_USER_ID]);
  1764. }
  1765. // Get current parent user ID
  1766. function CurrentParentUserID() {
  1767. global $Security;
  1768. return (isset($Security)) ? $Security->CurrentParentUserID() : strval(@$_SESSION[EWRPT_SESSION_PARENT_USER_ID]);
  1769. }
  1770. // Get current user level
  1771. function CurrentUserLevel() {
  1772. global $Security;
  1773. return (isset($Security)) ? $Security->CurrentUserLevelID() : @$_SESSION[EWRPT_SESSION_USER_LEVEL_ID];
  1774. }
  1775. // Get current user level list
  1776. function CurrentUserLevelList() {
  1777. global $Security;
  1778. return (isset($Security)) ? $Security->UserLevelList() : strval(@$_SESSION[EWRPT_SESSION_USER_LEVEL_ID]);
  1779. }
  1780. // Get Current user info
  1781. function CurrentUserInfo($fldname) {
  1782. global $Security;
  1783. if (isset($Security)) {
  1784. return $Security->CurrentUserInfo($fldname);
  1785. } elseif (defined("EWRPT_USER_TABLE") && !IsSysAdmin()) {
  1786. $user = CurrentUserName();
  1787. if (strval($user) <> "")
  1788. return ew_ExecuteScalar("SELECT " . ew_QuotedName($fldname) . " FROM " . EW_USER_TABLE . " WHERE " .
  1789. str_replace("%u", ew_AdjustSql($user), EWRPT_USER_NAME_FILTER));
  1790. }
  1791. return NULL;
  1792. }
  1793. // Is logged in
  1794. function IsLoggedIn() {
  1795. global $Security;
  1796. return (isset($Security)) ? $Security->IsLoggedIn() : (@$_SESSION[EWRPT_SESSION_STATUS] == "login");
  1797. }
  1798. // Check if user is system administrator
  1799. function IsSysAdmin() {
  1800. return (@$_SESSION[EWRPT_SESSION_SYSTEM_ADMIN] == 1);
  1801. }
  1802. // Get current page ID
  1803. function CurrentPageID() {
  1804. if (isset($GLOBALS["Page"])) {
  1805. return $GLOBALS["Page"]->PageID;
  1806. } elseif (defined("EWRPT_PAGE_ID")) {
  1807. return EWRPT_PAGE_ID;
  1808. }
  1809. return "";
  1810. }
  1811. // Allow list
  1812. function AllowList($TableName) {
  1813. global $Security;
  1814. return $Security->AllowList($TableName);
  1815. }
  1816. // Load recordset
  1817. function &ew_LoadRecordset($SQL) {
  1818. global $conn;
  1819. $conn->raiseErrorFn = 'ewrpt_ErrorFn'; //*** changed to "ewrpt_"
  1820. $rs = $conn->Execute($SQL);
  1821. $conn->raiseErrorFn = '';
  1822. return $rs;
  1823. }
  1824. // Executes the query, and returns the first column of the first row
  1825. function ew_ExecuteScalar($SQL) {
  1826. $res = FALSE;
  1827. $rs = ew_LoadRecordset($SQL);
  1828. if ($rs && !$rs->EOF && $rs->FieldCount() > 0) {
  1829. $res = $rs->fields[0];
  1830. $rs->Close();
  1831. }
  1832. return $res;
  1833. }
  1834. // Executes the query, and returns the first row
  1835. function ew_ExecuteRow($SQL) {
  1836. $res = FALSE;
  1837. $rs = ew_LoadRecordset($SQL);
  1838. if ($rs && !$rs->EOF) {
  1839. $res = $rs->fields;
  1840. $rs->Close();
  1841. }
  1842. return $res;
  1843. }
  1844. // Check if valid operator
  1845. function ewrpt_IsValidOpr($Opr, $FldType) {
  1846. $valid = ($Opr == "=" || $Opr == "<" || $Opr == "<=" ||
  1847. $Opr == ">" || $Opr == ">=" || $Opr == "<>");
  1848. if ($FldType == EWRPT_DATATYPE_STRING || $FldType == EWRPT_DATATYPE_MEMO)
  1849. $valid = ($valid || $Opr == "LIKE" || $Opr == "NOT LIKE" || $Opr == "STARTS WITH");
  1850. return $valid;
  1851. }
  1852. // Quote table/field name
  1853. function ewrpt_QuotedName($Name) {
  1854. $Name = str_replace(EWRPT_DB_QUOTE_END, EWRPT_DB_QUOTE_END . EWRPT_DB_QUOTE_END, $Name);
  1855. return EWRPT_DB_QUOTE_START . $Name . EWRPT_DB_QUOTE_END;
  1856. }
  1857. // quote field values
  1858. function ewrpt_QuotedValue($Value, $FldType) {
  1859. if (is_null($Value))
  1860. return "NULL";
  1861. switch ($FldType) {
  1862. case EWRPT_DATATYPE_STRING:
  1863. case EWRPT_DATATYPE_BLOB:
  1864. case EWRPT_DATATYPE_MEMO:
  1865. case EWRPT_DATATYPE_TIME:
  1866. return "'" . ewrpt_AdjustSql($Value) . "'";
  1867. case EWRPT_DATATYPE_DATE:
  1868. return (EWRPT_IS_MSACCESS) ? "#" . ewrpt_AdjustSql($Value) . "#" :
  1869. "'" . ewrpt_AdjustSql($Value) . "'";
  1870. // case EWRPT_DATATYPE_GUID:
  1871. // if (EWRPT_IS_MSACCESS) {
  1872. // if (strlen($Value) == 38) {
  1873. // return "{guid " . $Value . "}";
  1874. // } elseif (strlen($Value) == 36) {
  1875. // return "{guid {" . $Value . "}}";
  1876. // }
  1877. // } else {
  1878. // return "'" . $Value . "'";
  1879. // }
  1880. case EWRPT_DATATYPE_BOOLEAN: // enum('Y'/'N') or enum('1'/'0')
  1881. //return "'" . $Value . "'";
  1882. return (EWRPT_IS_MSACCESS) ? $Value : "'" . ewrpt_AdjustSql($Value) . "'";
  1883. default:
  1884. return $Value;
  1885. }
  1886. }
  1887. // Get distinct values
  1888. function ewrpt_GetDistinctValues($FldOpr, $sql) {
  1889. global $conn;
  1890. $ar = array();
  1891. if (strval($sql) == "")
  1892. return;
  1893. $wrkrs = $conn->Execute($sql);
  1894. if ($wrkrs && !$wrkrs->EOF) {
  1895. $ar[] = ewrpt_ConvertValue($FldOpr, $wrkrs->fields[0]);
  1896. $wrkrs->MoveNext();
  1897. while (!$wrkrs->EOF) {
  1898. $wrkval = ewrpt_ConvertValue($FldOpr, $wrkrs->fields[0]);
  1899. $cntar = count($ar);
  1900. if ($wrkval <> $ar[$cntar-1])
  1901. $ar[] = $wrkval;
  1902. $wrkrs->MoveNext();
  1903. }
  1904. }
  1905. if ($wrkrs) $wrkrs->Close();
  1906. return $ar;
  1907. }
  1908. // Convert value
  1909. function ewrpt_ConvertValue($FldOpr, $val) {
  1910. if (is_null($val)) {
  1911. return EWRPT_NULL_VALUE;
  1912. } elseif ($val == "") {
  1913. return EWRPT_EMPTY_VALUE;
  1914. }
  1915. if (is_float($val))
  1916. $val = (float)$val;
  1917. if ($FldOpr == "")
  1918. return $val;
  1919. if ($ar = explode(" ", $val)) {
  1920. $ar = explode("-", $ar[0]);
  1921. } else {
  1922. return $val;
  1923. }
  1924. if (!$ar || count($ar) <> 3)
  1925. return $val;
  1926. list($year, $month, $day) = $ar;
  1927. switch (strtolower($FldOpr)) {
  1928. case "year":
  1929. return $year;
  1930. case "quarter":
  1931. return "$year|" . ceil(intval($month)/3);
  1932. case "month":
  1933. return "$year|$month";
  1934. case "day":
  1935. return "$year|$month|$day";
  1936. case "date":
  1937. return "$year-$month-$day";
  1938. }
  1939. }
  1940. // Dropdown display values
  1941. function ewrpt_DropDownDisplayValue($v, $t, $fmt) {
  1942. global $ReportLanguage;
  1943. if ($v == EWRPT_NULL_VALUE) {
  1944. return $ReportLanguage->Phrase("NullLabel");
  1945. } elseif ($v == EWRPT_EMPTY_VALUE) {
  1946. return $ReportLanguage->Phrase("EmptyLabel");
  1947. } elseif (strtolower($t) == "boolean") {
  1948. return ewrpt_BooleanName($v);
  1949. }
  1950. if ($t == "")
  1951. return $v;
  1952. $ar = explode("|", strval($v));
  1953. switch (strtolower($t)) {
  1954. case "year":
  1955. return $v;
  1956. case "quarter":
  1957. if (count($ar) >= 2)
  1958. return ewrpt_QuarterName($ar[1]) . " " . $ar[0];
  1959. case "month":
  1960. if (count($ar) >= 2)
  1961. return ewrpt_MonthName($ar[1]) . " " . $ar[0];
  1962. case "day":
  1963. if (count($ar) >= 3)
  1964. return ewrpt_FormatDateTime($ar[0] . "-" . $ar[1] . "-" . $ar[2], $fmt);
  1965. case "date":
  1966. return ewrpt_FormatDateTime($v, $fmt);
  1967. }
  1968. }
  1969. // Get Boolean Name
  1970. // - Treat "T" / "True" / "Y" / "Yes" / "1" As True
  1971. function ewrpt_BooleanName($v) {
  1972. global $ReportLanguage;
  1973. if (is_null($v))
  1974. return $ReportLanguage->Phrase("NullLabel");
  1975. elseif (strtoupper($v) == "T" || strtoupper($v) == "TRUE" || strtoupper($v) == "Y" || strtoupper($v) == "YES" Or strval($v) == "1")
  1976. return $ReportLanguage->Phrase("BooleanYes");
  1977. else
  1978. return $ReportLanguage->Phrase("BooleanNo");
  1979. }
  1980. // Quarter name
  1981. function ewrpt_QuarterName($q) {
  1982. global $ReportLanguage;
  1983. switch ($q) {
  1984. case 1:
  1985. return $ReportLanguage->Phrase("Qtr1");
  1986. case 2:
  1987. return $ReportLanguage->Phrase("Qtr2");
  1988. case 3:
  1989. return $ReportLanguage->Phrase("Qtr3");
  1990. case 4:
  1991. return $ReportLanguage->Phrase("Qtr4");
  1992. default:
  1993. return $q;
  1994. }
  1995. }
  1996. // Month name
  1997. function ewrpt_MonthName($m) {
  1998. global $ReportLanguage;
  1999. switch ($m) {
  2000. case 1:
  2001. return $ReportLanguage->Phrase("MonthJan");
  2002. case 2:
  2003. return $ReportLanguage->Phrase("MonthFeb");
  2004. case 3:
  2005. return $ReportLanguage->Phrase("MonthMar");
  2006. case 4:
  2007. return $ReportLanguage->Phrase("MonthApr");
  2008. case 5:
  2009. return $ReportLanguage->Phrase("MonthMay");
  2010. case 6:
  2011. return $ReportLanguage->Phrase("MonthJun");
  2012. case 7:
  2013. return $ReportLanguage->Phrase("MonthJul");
  2014. case 8:
  2015. return $ReportLanguage->Phrase("MonthAug");
  2016. case 9:
  2017. return $ReportLanguage->Phrase("MonthSep");
  2018. case 10:
  2019. return $ReportLanguage->Phrase("MonthOct");
  2020. case 11:
  2021. return $ReportLanguage->Phrase("MonthNov");
  2022. case 12:
  2023. return $ReportLanguage->Phrase("MonthDec");
  2024. default:
  2025. return $m;
  2026. }
  2027. }
  2028. // Join array
  2029. function ewrpt_JoinArray($ar, $sep, $ft, $pos=0) {
  2030. if (!is_array($ar))
  2031. return "";
  2032. $arwrk = array_slice($ar, $pos); // return array from position pos
  2033. $cntar = count($arwrk);
  2034. for ($i = 0; $i < $cntar; $i++)
  2035. $arwrk[$i] = ewrpt_QuotedValue($arwrk[$i], $ft);
  2036. return implode($sep, $arwrk);
  2037. }
  2038. // Unformat date time based on format type
  2039. function ewrpt_UnFormatDateTime($dt, $namedformat) {
  2040. $dt = trim($dt);
  2041. while (strpos($dt, " ") !== FALSE) $dt = str_replace(" ", " ", $dt);
  2042. $arDateTime = explode(" ", $dt);
  2043. if (count($arDateTime) == 0) return $dt;
  2044. $arDatePt = explode(EWRPT_DATE_SEPARATOR, $arDateTime[0]);
  2045. if ($namedformat == 0 || $namedformat == 1 || $namedformat == 2 || $namedformat == 8) {
  2046. $arDefFmt = explode(EWRPT_DATE_SEPARATOR, EWRPT_DEFAULT_DATE_FORMAT);
  2047. if ($arDefFmt[0] == "yyyy") {
  2048. $namedformat = 9;
  2049. } elseif ($arDefFmt[0] == "mm") {
  2050. $namedformat = 10;
  2051. } elseif ($arDefFmt[0] == "dd") {
  2052. $namedformat = 11;
  2053. }
  2054. }
  2055. if (count($arDatePt) == 3) {
  2056. switch ($namedformat) {
  2057. case 5:
  2058. case 9: //yyyymmdd
  2059. if (ewrpt_CheckDate($arDateTime[0])) {
  2060. list($year, $month, $day) = $arDatePt;
  2061. break;
  2062. } else {
  2063. return $dt;
  2064. }
  2065. case 6:
  2066. case 10: //mmddyyyy
  2067. if (ewrpt_CheckUSDate($arDateTime[0])) {
  2068. list($month, $day, $year) = $arDatePt;
  2069. break;
  2070. } else {
  2071. return $dt;
  2072. }
  2073. case 7:
  2074. case 11: //ddmmyyyy
  2075. if (ewrpt_CheckEuroDate($arDateTime[0])) {
  2076. list($day, $month, $year) = $arDatePt;
  2077. break;
  2078. } else {
  2079. return $dt;
  2080. }
  2081. case 12:
  2082. case 15: //yymmdd
  2083. if (ewrpt_CheckShortDate($arDateTime[0])) {
  2084. list($year, $month, $day) = $arDatePt;
  2085. $year = ewrpt_UnformatYear($year);
  2086. break;
  2087. } else {
  2088. return $dt;
  2089. }
  2090. case 13:
  2091. case 16: //mmddyy
  2092. if (ewrpt_CheckShortUSDate($arDateTime[0])) {
  2093. list($month, $day, $year) = $arDatePt;
  2094. $year = ewrpt_UnformatYear($year);
  2095. break;
  2096. } else {
  2097. return $dt;
  2098. }
  2099. case 14:
  2100. case 17: //ddmmyy
  2101. if (ewrpt_CheckShortEuroDate($arDateTime[0])) {
  2102. list($day, $month, $year) = $arDatePt;
  2103. $year = ewrpt_UnformatYear($year);
  2104. break;
  2105. } else {
  2106. return $dt;
  2107. }
  2108. default:
  2109. return $dt;
  2110. }
  2111. if (strlen($year) <= 4 && strlen($month) <= 2 && strlen($day) <= 2) {
  2112. return $year . "-" . str_pad($month, 2, "0", STR_PAD_LEFT) . "-" .
  2113. str_pad($day, 2, "0", STR_PAD_LEFT) .
  2114. ((count($arDateTime) > 1) ? " " . $arDateTime[1] : "");
  2115. } else {
  2116. return $dt;
  2117. }
  2118. } else {
  2119. return $dt;
  2120. }
  2121. }
  2122. // ViewValue
  2123. // - return &nbsp; if empty
  2124. function ewrpt_ViewValue($value) {
  2125. if ($value <> "")
  2126. return $value;
  2127. else
  2128. return "&nbsp;";
  2129. }
  2130. // Get current year
  2131. function ewrpt_CurrentYear() {
  2132. return intval(date('Y'));
  2133. }
  2134. // Get current quarter
  2135. function ewrpt_CurrentQuarter() {
  2136. return ceil(intval(date('n'))/3);
  2137. }
  2138. // Get current month
  2139. function ewrpt_CurrentMonth() {
  2140. return intval(date('n'));
  2141. }
  2142. // Get current day
  2143. function ewrpt_CurrentDay() {
  2144. return intval(date('j'));
  2145. }
  2146. // FormatDateTime
  2147. // Format a timestamp, datetime, date or time field from MySQL
  2148. // $namedformat:
  2149. // 0 - General Date
  2150. // 1 - Long Date
  2151. // 2 - Short Date (Default)
  2152. // 3 - Long Time
  2153. // 4 - Short Time (hh:mm:ss)
  2154. // 5 - Short Date (yyyy/mm/dd)
  2155. // 6 - Short Date (mm/dd/yyyy)
  2156. // 7 - Short Date (dd/mm/yyyy)
  2157. // 8 - Short Date (Default) + Short Time (if not 00:00:00)
  2158. // 9 - Short Date (yyyy/mm/dd) + Short Time (hh:mm:ss)
  2159. // 10 - Short Date (mm/dd/yyyy) + Short Time (hh:mm:ss)
  2160. // 11 - Short Date (dd/mm/yyyy) + Short Time (hh:mm:ss)
  2161. // 12 - Short Date - 2 digit year (yy/mm/dd)
  2162. // 13 - Short Date - 2 digit year (mm/dd/yy)
  2163. // 14 - Short Date - 2 digit year (dd/mm/yy)
  2164. // 15 - Short Date - 2 digit year (yy/mm/dd) + Short Time (hh:mm:ss)
  2165. // 16 - Short Date (mm/dd/yyyy) + Short Time (hh:mm:ss)
  2166. // 17 - Short Date (dd/mm/yyyy) + Short Time (hh:mm:ss)
  2167. function ewrpt_FormatDateTime($ts, $namedformat) {
  2168. $DefDateFormat = str_replace("yyyy", "%Y", EWRPT_DEFAULT_DATE_FORMAT);
  2169. $DefDateFormat = str_replace("mm", "%m", $DefDateFormat);
  2170. $DefDateFormat = str_replace("dd", "%d", $DefDateFormat);
  2171. if (is_numeric($ts)) // timestamp
  2172. {
  2173. switch (strlen($ts)) {
  2174. case 14:
  2175. $patt = '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  2176. break;
  2177. case 12:
  2178. $patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  2179. break;
  2180. case 10:
  2181. $patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
  2182. break;
  2183. case 8:
  2184. $patt = '/(\d{4})(\d{2})(\d{2})/';
  2185. break;
  2186. case 6:
  2187. $patt = '/(\d{2})(\d{2})(\d{2})/';
  2188. break;
  2189. case 4:
  2190. $patt = '/(\d{2})(\d{2})/';
  2191. break;
  2192. case 2:
  2193. $patt = '/(\d{2})/';
  2194. break;
  2195. default:
  2196. return $ts;
  2197. }
  2198. if ((isset($patt))&&(preg_match($patt, $ts, $matches)))
  2199. {
  2200. $year = $matches[1];
  2201. $month = @$matches[2];
  2202. $day = @$matches[3];
  2203. $hour = @$matches[4];
  2204. $min = @$matches[5];
  2205. $sec = @$matches[6];
  2206. }
  2207. if (($namedformat==0)&&(strlen($ts)<10)) $namedformat = 2;
  2208. }
  2209. elseif (is_string($ts))
  2210. {
  2211. if (preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // datetime
  2212. {
  2213. $year = $matches[1];
  2214. $month = $matches[2];
  2215. $day = $matches[3];
  2216. $hour = $matches[4];
  2217. $min = $matches[5];
  2218. $sec = $matches[6];
  2219. }
  2220. elseif (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $ts, $matches)) // date
  2221. {
  2222. $year = $matches[1];
  2223. $month = $matches[2];
  2224. $day = $matches[3];
  2225. if ($namedformat==0) $namedformat = 2;
  2226. }
  2227. elseif (preg_match('/(^|\s)(\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // time
  2228. {
  2229. $hour = $matches[2];
  2230. $min = $matches[3];
  2231. $sec = $matches[4];
  2232. if (($namedformat==0)||($namedformat==1)) $namedformat = 3;
  2233. if ($namedformat==2) $namedformat = 4;
  2234. }
  2235. else
  2236. {
  2237. return $ts;
  2238. }
  2239. }
  2240. else
  2241. {
  2242. return $ts;
  2243. }
  2244. if (!isset($year)) $year = 0; // dummy value for times
  2245. if (!isset($month)) $month = 1;
  2246. if (!isset($day)) $day = 1;
  2247. if (!isset($hour)) $hour = 0;
  2248. if (!isset($min)) $min = 0;
  2249. if (!isset($sec)) $sec = 0;
  2250. $uts = @mktime($hour, $min, $sec, $month, $day, $year);
  2251. if ($uts < 0 || $uts == FALSE || // failed to convert
  2252. (intval($year) == 0 && intval($month) == 0 && intval($day) == 0)) {
  2253. $year = substr_replace("0000", $year, -1 * strlen($year));
  2254. $month = substr_replace("00", $month, -1 * strlen($month));
  2255. $day = substr_replace("00", $day, -1 * strlen($day));
  2256. $hour = substr_replace("00", $hour, -1 * strlen($hour));
  2257. $min = substr_replace("00", $min, -1 * strlen($min));
  2258. $sec = substr_replace("00", $sec, -1 * strlen($sec));
  2259. $DefDateFormat = str_replace("yyyy", $year, EWRPT_DEFAULT_DATE_FORMAT);
  2260. $DefDateFormat = str_replace("mm", $month, $DefDateFormat);
  2261. $DefDateFormat = str_replace("dd", $day, $DefDateFormat);
  2262. switch ($namedformat) {
  2263. case 0:
  2264. return $DefDateFormat." $hour:$min:$sec";
  2265. break;
  2266. case 1://unsupported, return general date
  2267. return $DefDateFormat." $hour:$min:$sec";
  2268. break;
  2269. case 2:
  2270. return $DefDateFormat;
  2271. break;
  2272. case 3:
  2273. if (intval($hour)==0)
  2274. return "12:$min:$sec AM";
  2275. elseif (intval($hour)>0 && intval($hour)<12)
  2276. return "$hour:$min:$sec AM";
  2277. elseif (intval($hour)==12)
  2278. return "$hour:$min:$sec PM";
  2279. elseif (intval($hour)>12 && intval($hour)<=23)
  2280. return (intval($hour)-12).":$min:$sec PM";
  2281. else
  2282. return "$hour:$min:$sec";
  2283. break;
  2284. case 4:
  2285. return "$hour:$min:$sec";
  2286. break;
  2287. case 5:
  2288. return "$year". EWRPT_DATE_SEPARATOR . "$month" . EWRPT_DATE_SEPARATOR . "$day";
  2289. break;
  2290. case 6:
  2291. return "$month". EWRPT_DATE_SEPARATOR ."$day" . EWRPT_DATE_SEPARATOR . "$year";
  2292. break;
  2293. case 7:
  2294. return "$day" . EWRPT_DATE_SEPARATOR ."$month" . EWRPT_DATE_SEPARATOR . "$year";
  2295. break;
  2296. case 8:
  2297. return $DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " $hour:$min:$sec");
  2298. break;
  2299. case 9:
  2300. return "$year". EWRPT_DATE_SEPARATOR . "$month" . EWRPT_DATE_SEPARATOR . "$day $hour:$min:$sec";
  2301. break;
  2302. case 10:
  2303. return "$month". EWRPT_DATE_SEPARATOR ."$day" . EWRPT_DATE_SEPARATOR . "$year $hour:$min:$sec";
  2304. break;
  2305. case 11:
  2306. return "$day" . EWRPT_DATE_SEPARATOR ."$month" . EWRPT_DATE_SEPARATOR . "$year $hour:$min:$sec";
  2307. break;
  2308. case 12:
  2309. return substr($year,-2) . EWRPT_DATE_SEPARATOR . $month . EWRPT_DATE_SEPARATOR . $day;
  2310. break;
  2311. case 13:
  2312. return substr($year,-2) . EWRPT_DATE_SEPARATOR . $month . EWRPT_DATE_SEPARATOR . $day;
  2313. break;
  2314. case 14:
  2315. return substr($year,-2) . EWRPT_DATE_SEPARATOR . $month . EWRPT_DATE_SEPARATOR . $day;
  2316. break;
  2317. default:
  2318. return $ts;
  2319. }
  2320. } else {
  2321. switch ($namedformat) {
  2322. case 0:
  2323. return strftime($DefDateFormat." %H:%M:%S", $uts);
  2324. break;
  2325. case 1:
  2326. return strftime("%A, %B %d, %Y", $uts);
  2327. break;
  2328. case 2:
  2329. return strftime($DefDateFormat, $uts);
  2330. break;
  2331. case 3:
  2332. return strftime("%I:%M:%S %p", $uts);
  2333. break;
  2334. case 4:
  2335. return strftime("%H:%M:%S", $uts);
  2336. break;
  2337. case 5:
  2338. return strftime("%Y" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%d", $uts);
  2339. break;
  2340. case 6:
  2341. return strftime("%m" . EWRPT_DATE_SEPARATOR . "%d" . EWRPT_DATE_SEPARATOR . "%Y", $uts);
  2342. break;
  2343. case 7:
  2344. return strftime("%d" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%Y", $uts);
  2345. break;
  2346. case 8:
  2347. return strftime($DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " %H:%M:%S"), $uts);
  2348. break;
  2349. case 9:
  2350. return strftime("%Y" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%d %H:%M:%S", $uts);
  2351. break;
  2352. case 10:
  2353. return strftime("%m" . EWRPT_DATE_SEPARATOR . "%d" . EWRPT_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
  2354. break;
  2355. case 11:
  2356. return strftime("%d" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%Y %H:%M:%S", $uts);
  2357. break;
  2358. case 12:
  2359. return strftime("%y" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%d", $uts);
  2360. break;
  2361. case 13:
  2362. return strftime("%m" . EWRPT_DATE_SEPARATOR . "%d" . EWRPT_DATE_SEPARATOR . "%y", $uts);
  2363. break;
  2364. case 14:
  2365. return strftime("%d" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%y", $uts);
  2366. break;
  2367. case 15:
  2368. return strftime("%y" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%d %H:%M:%S", $uts);
  2369. break;
  2370. case 16:
  2371. return strftime("%m" . EWRPT_DATE_SEPARATOR . "%d" . EWRPT_DATE_SEPARATOR . "%y %H:%M:%S", $uts);
  2372. break;
  2373. case 17:
  2374. return strftime("%d" . EWRPT_DATE_SEPARATOR . "%m" . EWRPT_DATE_SEPARATOR . "%y %H:%M:%S", $uts);
  2375. break;
  2376. default:
  2377. return $ts;
  2378. }
  2379. }
  2380. }
  2381. // FormatCurrency
  2382. // FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  2383. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  2384. // NumDigitsAfterDecimal is the numeric value indicating how many places to the
  2385. // right of the decimal are displayed
  2386. // -1 Use Default
  2387. // The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  2388. // arguments have the following settings:
  2389. // -1 True
  2390. // 0 False
  2391. // -2 Use Default
  2392. function ewrpt_FormatCurrency($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  2393. if (!is_numeric($amount))
  2394. return $amount;
  2395. // export the values returned by localeconv into the local scope
  2396. extract(localeconv());
  2397. // set defaults if locale is not set
  2398. if (empty($currency_symbol)) $currency_symbol = EWRPT_DEFAULT_CURRENCY_SYMBOL;
  2399. if (empty($mon_decimal_point)) $mon_decimal_point = EWRPT_DEFAULT_MON_DECIMAL_POINT;
  2400. if (empty($mon_thousands_sep)) $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2401. if (empty($positive_sign)) $positive_sign = EWRPT_DEFAULT_POSITIVE_SIGN;
  2402. if (empty($negative_sign)) $negative_sign = EWRPT_DEFAULT_NEGATIVE_SIGN;
  2403. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = EWRPT_DEFAULT_FRAC_DIGITS;
  2404. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = EWRPT_DEFAULT_P_CS_PRECEDES;
  2405. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = EWRPT_DEFAULT_P_SEP_BY_SPACE;
  2406. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = EWRPT_DEFAULT_N_CS_PRECEDES;
  2407. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = EWRPT_DEFAULT_N_SEP_BY_SPACE;
  2408. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = EWRPT_DEFAULT_P_SIGN_POSN;
  2409. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = EWRPT_DEFAULT_N_SIGN_POSN;
  2410. // check $NumDigitsAfterDecimal
  2411. if ($NumDigitsAfterDecimal > -1)
  2412. $frac_digits = $NumDigitsAfterDecimal;
  2413. // check $UseParensForNegativeNumbers
  2414. if ($UseParensForNegativeNumbers == -1) {
  2415. $n_sign_posn = 0;
  2416. if ($p_sign_posn == 0) {
  2417. if (DEFAULT_P_SIGN_POSN != 0)
  2418. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  2419. else
  2420. $p_sign_posn = 3;
  2421. }
  2422. } elseif ($UseParensForNegativeNumbers == 0) {
  2423. if ($n_sign_posn == 0)
  2424. if (DEFAULT_P_SIGN_POSN != 0)
  2425. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  2426. else
  2427. $n_sign_posn = 3;
  2428. }
  2429. // check $GroupDigits
  2430. if ($GroupDigits == -1) {
  2431. $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2432. } elseif ($GroupDigits == 0) {
  2433. $mon_thousands_sep = "";
  2434. }
  2435. // start by formatting the unsigned number
  2436. $number = number_format(abs($amount),
  2437. $frac_digits,
  2438. $mon_decimal_point,
  2439. $mon_thousands_sep);
  2440. // check $IncludeLeadingDigit
  2441. if ($IncludeLeadingDigit == 0) {
  2442. if (substr($number, 0, 2) == "0.")
  2443. $number = substr($number, 1, strlen($number)-1);
  2444. }
  2445. if ($amount < 0) {
  2446. $sign = $negative_sign;
  2447. // "extracts" the boolean value as an integer
  2448. $n_cs_precedes = intval($n_cs_precedes == true);
  2449. $n_sep_by_space = intval($n_sep_by_space == true);
  2450. $key = $n_cs_precedes . $n_sep_by_space . $n_sign_posn;
  2451. } else {
  2452. $sign = $positive_sign;
  2453. $p_cs_precedes = intval($p_cs_precedes == true);
  2454. $p_sep_by_space = intval($p_sep_by_space == true);
  2455. $key = $p_cs_precedes . $p_sep_by_space . $p_sign_posn;
  2456. }
  2457. $formats = array(
  2458. // currency symbol is after amount
  2459. // no space between amount and sign
  2460. '000' => '(%s' . $currency_symbol . ')',
  2461. '001' => $sign . '%s ' . $currency_symbol,
  2462. '002' => '%s' . $currency_symbol . $sign,
  2463. '003' => '%s' . $sign . $currency_symbol,
  2464. '004' => '%s' . $sign . $currency_symbol,
  2465. // one space between amount and sign
  2466. '010' => '(%s ' . $currency_symbol . ')',
  2467. '011' => $sign . '%s ' . $currency_symbol,
  2468. '012' => '%s ' . $currency_symbol . $sign,
  2469. '013' => '%s ' . $sign . $currency_symbol,
  2470. '014' => '%s ' . $sign . $currency_symbol,
  2471. // currency symbol is before amount
  2472. // no space between amount and sign
  2473. '100' => '(' . $currency_symbol . '%s)',
  2474. '101' => $sign . $currency_symbol . '%s',
  2475. '102' => $currency_symbol . '%s' . $sign,
  2476. '103' => $sign . $currency_symbol . '%s',
  2477. '104' => $currency_symbol . $sign . '%s',
  2478. // one space between amount and sign
  2479. '110' => '(' . $currency_symbol . ' %s)',
  2480. '111' => $sign . $currency_symbol . ' %s',
  2481. '112' => $currency_symbol . ' %s' . $sign,
  2482. '113' => $sign . $currency_symbol . ' %s',
  2483. '114' => $currency_symbol . ' ' . $sign . '%s');
  2484. // lookup the key in the above array
  2485. return sprintf($formats[$key], $number);
  2486. }
  2487. // FormatNumber
  2488. // FormatNumber(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  2489. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  2490. // NumDigitsAfterDecimal is the numeric value indicating how many places to the
  2491. // right of the decimal are displayed
  2492. // -1 Use Default
  2493. // The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  2494. // arguments have the following settings:
  2495. // -1 True
  2496. // 0 False
  2497. // -2 Use Default
  2498. function ewrpt_FormatNumber($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  2499. if (!is_numeric($amount))
  2500. return $amount;
  2501. // export the values returned by localeconv into the local scope
  2502. extract(localeconv());
  2503. // set defaults if locale is not set
  2504. if (empty($currency_symbol)) $currency_symbol = EWRPT_DEFAULT_CURRENCY_SYMBOL;
  2505. if (empty($mon_decimal_point)) $mon_decimal_point = EWRPT_DEFAULT_MON_DECIMAL_POINT;
  2506. if (empty($mon_thousands_sep)) $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2507. if (empty($positive_sign)) $positive_sign = EWRPT_DEFAULT_POSITIVE_SIGN;
  2508. if (empty($negative_sign)) $negative_sign = EWRPT_DEFAULT_NEGATIVE_SIGN;
  2509. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = EWRPT_DEFAULT_FRAC_DIGITS;
  2510. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = EWRPT_DEFAULT_P_CS_PRECEDES;
  2511. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = EWRPT_DEFAULT_P_SEP_BY_SPACE;
  2512. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = EWRPT_DEFAULT_N_CS_PRECEDES;
  2513. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = EWRPT_DEFAULT_N_SEP_BY_SPACE;
  2514. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = EWRPT_DEFAULT_P_SIGN_POSN;
  2515. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = EWRPT_DEFAULT_N_SIGN_POSN;
  2516. // check $NumDigitsAfterDecimal
  2517. if ($NumDigitsAfterDecimal > -1)
  2518. $frac_digits = $NumDigitsAfterDecimal;
  2519. // check $UseParensForNegativeNumbers
  2520. if ($UseParensForNegativeNumbers == -1) {
  2521. $n_sign_posn = 0;
  2522. if ($p_sign_posn == 0) {
  2523. if (DEFAULT_P_SIGN_POSN != 0)
  2524. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  2525. else
  2526. $p_sign_posn = 3;
  2527. }
  2528. } elseif ($UseParensForNegativeNumbers == 0) {
  2529. if ($n_sign_posn == 0)
  2530. if (DEFAULT_P_SIGN_POSN != 0)
  2531. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  2532. else
  2533. $n_sign_posn = 3;
  2534. }
  2535. // check $GroupDigits
  2536. if ($GroupDigits == -1) {
  2537. $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2538. } elseif ($GroupDigits == 0) {
  2539. $mon_thousands_sep = "";
  2540. }
  2541. // start by formatting the unsigned number
  2542. $number = number_format(abs($amount),
  2543. $frac_digits,
  2544. $mon_decimal_point,
  2545. $mon_thousands_sep);
  2546. // check $IncludeLeadingDigit
  2547. if ($IncludeLeadingDigit == 0) {
  2548. if (substr($number, 0, 2) == "0.")
  2549. $number = substr($number, 1, strlen($number)-1);
  2550. }
  2551. if ($amount < 0) {
  2552. $sign = $negative_sign;
  2553. $key = $n_sign_posn;
  2554. } else {
  2555. $sign = $positive_sign;
  2556. $key = $p_sign_posn;
  2557. }
  2558. $formats = array(
  2559. '0' => '(%s)',
  2560. '1' => $sign . '%s',
  2561. '2' => $sign . '%s',
  2562. '3' => $sign . '%s',
  2563. '4' => $sign . '%s');
  2564. // lookup the key in the above array
  2565. return sprintf($formats[$key], $number);
  2566. }
  2567. // FormatPercent
  2568. // FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit
  2569. // [,UseParensForNegativeNumbers [,GroupDigits]]]])
  2570. // NumDigitsAfterDecimal is the numeric value indicating how many places to the
  2571. // right of the decimal are displayed
  2572. // -1 Use Default
  2573. // The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits
  2574. // arguments have the following settings:
  2575. // -1 True
  2576. // 0 False
  2577. // -2 Use Default
  2578. function ewrpt_FormatPercent($amount, $NumDigitsAfterDecimal, $IncludeLeadingDigit = -2, $UseParensForNegativeNumbers = -2, $GroupDigits = -2) {
  2579. if (!is_numeric($amount))
  2580. return $amount;
  2581. // export the values returned by localeconv into the local scope
  2582. extract(localeconv());
  2583. // set defaults if locale is not set
  2584. if (empty($currency_symbol)) $currency_symbol = EWRPT_DEFAULT_CURRENCY_SYMBOL;
  2585. if (empty($mon_decimal_point)) $mon_decimal_point = EWRPT_DEFAULT_MON_DECIMAL_POINT;
  2586. if (empty($mon_thousands_sep)) $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2587. if (empty($positive_sign)) $positive_sign = EWRPT_DEFAULT_POSITIVE_SIGN;
  2588. if (empty($negative_sign)) $negative_sign = EWRPT_DEFAULT_NEGATIVE_SIGN;
  2589. if (empty($frac_digits) || $frac_digits == CHAR_MAX) $frac_digits = EWRPT_DEFAULT_FRAC_DIGITS;
  2590. if (empty($p_cs_precedes) || $p_cs_precedes == CHAR_MAX) $p_cs_precedes = EWRPT_DEFAULT_P_CS_PRECEDES;
  2591. if (empty($p_sep_by_space) || $p_sep_by_space == CHAR_MAX) $p_sep_by_space = EWRPT_DEFAULT_P_SEP_BY_SPACE;
  2592. if (empty($n_cs_precedes) || $n_cs_precedes == CHAR_MAX) $n_cs_precedes = EWRPT_DEFAULT_N_CS_PRECEDES;
  2593. if (empty($n_sep_by_space) || $n_sep_by_space == CHAR_MAX) $n_sep_by_space = EWRPT_DEFAULT_N_SEP_BY_SPACE;
  2594. if (empty($p_sign_posn) || $p_sign_posn == CHAR_MAX) $p_sign_posn = EWRPT_DEFAULT_P_SIGN_POSN;
  2595. if (empty($n_sign_posn) || $n_sign_posn == CHAR_MAX) $n_sign_posn = EWRPT_DEFAULT_N_SIGN_POSN;
  2596. // check $NumDigitsAfterDecimal
  2597. if ($NumDigitsAfterDecimal > -1)
  2598. $frac_digits = $NumDigitsAfterDecimal;
  2599. // check $UseParensForNegativeNumbers
  2600. if ($UseParensForNegativeNumbers == -1) {
  2601. $n_sign_posn = 0;
  2602. if ($p_sign_posn == 0) {
  2603. if (DEFAULT_P_SIGN_POSN != 0)
  2604. $p_sign_posn = DEFAULT_P_SIGN_POSN;
  2605. else
  2606. $p_sign_posn = 3;
  2607. }
  2608. } elseif ($UseParensForNegativeNumbers == 0) {
  2609. if ($n_sign_posn == 0)
  2610. if (DEFAULT_P_SIGN_POSN != 0)
  2611. $n_sign_posn = DEFAULT_P_SIGN_POSN;
  2612. else
  2613. $n_sign_posn = 3;
  2614. }
  2615. // check $GroupDigits
  2616. if ($GroupDigits == -1) {
  2617. $mon_thousands_sep = EWRPT_DEFAULT_MON_THOUSANDS_SEP;
  2618. } elseif ($GroupDigits == 0) {
  2619. $mon_thousands_sep = "";
  2620. }
  2621. // start by formatting the unsigned number
  2622. $number = number_format(abs($amount)*100,
  2623. $frac_digits,
  2624. $mon_decimal_point,
  2625. $mon_thousands_sep);
  2626. // check $IncludeLeadingDigit
  2627. if ($IncludeLeadingDigit == 0) {
  2628. if (substr($number, 0, 2) == "0.")
  2629. $number = substr($number, 1, strlen($number)-1);
  2630. }
  2631. if ($amount < 0) {
  2632. $sign = $negative_sign;
  2633. $key = $n_sign_posn;
  2634. } else {
  2635. $sign = $positive_sign;
  2636. $key = $p_sign_posn;
  2637. }
  2638. $formats = array(
  2639. '0' => '(%s%%)',
  2640. '1' => $sign . '%s%%',
  2641. '2' => $sign . '%s%%',
  2642. '3' => $sign . '%s%%',
  2643. '4' => $sign . '%s%%');
  2644. // lookup the key in the above array
  2645. return sprintf($formats[$key], $number);
  2646. }
  2647. // Add slashes for SQL
  2648. function ewrpt_AdjustSql($val) {
  2649. $val = addslashes(trim($val));
  2650. return $val;
  2651. }
  2652. // Build Report SQL
  2653. function ewrpt_BuildReportSql($sSelect, $sWhere, $sGroupBy, $sHaving, $sOrderBy, $sFilter, $sSort) {
  2654. $sDbWhere = $sWhere;
  2655. if ($sDbWhere <> "") $sDbWhere = "(" . $sDbWhere . ")";
  2656. if ($sFilter <> "") {
  2657. if ($sDbWhere <> "") $sDbWhere .= " AND ";
  2658. $sDbWhere .= "(" . $sFilter . ")";
  2659. }
  2660. $sDbOrderBy = ewrpt_UpdateSortFields($sOrderBy, $sSort, 1);
  2661. $sSql = $sSelect;
  2662. if ($sDbWhere <> "") $sSql .= " WHERE " . $sDbWhere;
  2663. if ($sGroupBy <> "") $sSql .= " GROUP BY " . $sGroupBy;
  2664. if ($sHaving <> "") $sSql .= " HAVING " . $sHaving;
  2665. if ($sDbOrderBy <> "") $sSql .= " ORDER BY " . $sDbOrderBy;
  2666. return $sSql;
  2667. }
  2668. // Update sort fields
  2669. // opt = 1, merge all sort fields
  2670. // opt = 2, merge sOrderBy fields only
  2671. function ewrpt_UpdateSortFields($sOrderBy, $sSort, $opt) {
  2672. if ($sOrderBy == "") {
  2673. if ($opt == 1)
  2674. return $sSort;
  2675. else
  2676. return "";
  2677. } elseif ($sSort == "") {
  2678. return $sOrderBy;
  2679. } else {
  2680. // Merge sort field list
  2681. $arorderby = ewrpt_GetSortFlds($sOrderBy);
  2682. $cntorderby = count($arorderby);
  2683. $arsort = ewrpt_GetSortFlds($sSort);
  2684. $cntsort = count($arsort);
  2685. for ($i = 0; $i < $cntsort; $i++) {
  2686. // Get sort field
  2687. $sortfld = trim($arsort[$i]);
  2688. if (strtoupper(substr($sortfld,-4)) == " ASC") {
  2689. $sortfld = trim(substr($sortfld,0,-4));
  2690. } elseif (strtoupper(substr($sortfld,-5)) == " DESC") {
  2691. $sortfld = trim(substr($sortfld,0,-4));
  2692. }
  2693. for ($j = 0; $j < $cntorderby; $j++) {
  2694. // Get orderby field
  2695. $orderfld = trim($arorderby[$j]);
  2696. if (strtoupper(substr($orderfld,-4)) == " ASC") {
  2697. $orderfld = trim(substr($orderfld,0,-4));
  2698. } elseif (strtoupper(substr($orderfld,-5)) == " DESC") {
  2699. $orderfld = trim(substr($orderfld,0,-4));
  2700. }
  2701. // Replace field
  2702. if ($orderfld == $sortfld) {
  2703. $arorderby[$j] = $arsort[$i];
  2704. break;
  2705. }
  2706. }
  2707. // Append field
  2708. if ($opt == 1) {
  2709. if ($orderfld <> $sortfld)
  2710. $arorderby[] = $arsort[$i];
  2711. }
  2712. }
  2713. return implode(", ", $arorderby);
  2714. }
  2715. }
  2716. // Get sort fields
  2717. function ewrpt_GetSortFlds($flds) {
  2718. $offset = -1;
  2719. $fldpos = 0;
  2720. $ar = array();
  2721. while ($offset = strpos($flds, ",", $offset + 1)) {
  2722. $orderfld = substr($flds,$fldpos,$offset-$fldpos);
  2723. if ((strtoupper(substr($orderfld,-4)) == " ASC") || (strtoupper(substr($orderfld,-5)) == " DESC")) {
  2724. $fldpos = $offset+1;
  2725. $ar[] = $orderfld;
  2726. }
  2727. }
  2728. $ar[] = substr($flds,$fldpos);
  2729. return $ar;
  2730. }
  2731. // Get reverse sort
  2732. function ewrpt_ReverseSort($sorttype) {
  2733. return ($sorttype == "ASC") ? "DESC" : "ASC";
  2734. }
  2735. // Construct a crosstab field name
  2736. function ewrpt_CrossTabField($smrytype, $smryfld, $colfld, $datetype, $val, $qc, $alias="") {
  2737. if ($val == EWRPT_NULL_VALUE) {
  2738. $wrkval = "NULL";
  2739. $wrkqc = "";
  2740. } elseif ($val == EWRPT_EMPTY_VALUE) {
  2741. $wrkval = "";
  2742. $wrkqc = $qc;
  2743. } else {
  2744. $wrkval = $val;
  2745. $wrkqc = $qc;
  2746. }
  2747. switch ($smrytype) {
  2748. case "SUM":
  2749. $fld = $smrytype . "(" . $smryfld . "*" . ewrpt_SQLDistinctFactor($colfld, $datetype, $val, $qc) . ")";
  2750. break;
  2751. case "COUNT":
  2752. $fld = "SUM(" . ewrpt_SQLDistinctFactor($colfld, $datetype, $wrkval, $wrkqc) . ")";
  2753. break;
  2754. case "MIN":
  2755. case "MAX":
  2756. $aggwrk = ewrpt_SQLDistinctFactor($colfld, $datetype, $wrkval, $wrkqc);
  2757. $fld = $smrytype . "(IF(" . $aggwrk . "=0,NULL," . $smryfld . "))";
  2758. if (EWRPT_IS_MSACCESS)
  2759. $fld = $smrytype . "(IIf(" . $aggwrk . "=0,NULL," . $smryfld . "))";
  2760. elseif (EWRPT_IS_MSSQL || EWRPT_IS_ORACLE)
  2761. $fld = $smrytype . "(CASE " . $aggwrk . " WHEN 0 THEN NULL ELSE " . $smryfld . " END)";
  2762. elseif (EWRPT_IS_MYSQL || EWRPT_IS_POSTGRESQL)
  2763. $fld = $smrytype . "(IF(" . $aggwrk . "=0,NULL," . $smryfld . "))";
  2764. break;
  2765. case "AVG":
  2766. $sumwrk = "SUM(" . $smryfld . "*" . ewrpt_SQLDistinctFactor($colfld, $datetype, $wrkval, $wrkqc) . ")";
  2767. if ($alias != "")
  2768. // $sumwrk .= " AS SUM_" . $alias;
  2769. $sumwrk .= " AS sum_" . $alias;
  2770. $cntwrk = "SUM(" . ewrpt_SQLDistinctFactor($colfld, $datetype, $wrkval, $wrkqc) . ")";
  2771. if ($alias != "")
  2772. // $cntwrk .= " AS CNT_" . $alias;
  2773. $cntwrk .= " AS cnt_" . $alias;
  2774. return $sumwrk . ", " . $cntwrk;
  2775. }
  2776. if ($alias != "")
  2777. $fld .= " AS " . $alias;
  2778. return $fld;
  2779. }
  2780. // Construct SQL Distinct factor (MySQL)
  2781. // - ACCESS
  2782. // y: IIf(Year(FieldName)=1996,1,0)
  2783. // q: IIf(DatePart(""q"",FieldName,1,0)=1,1,0))
  2784. // m: (IIf(DatePart(""m"",FieldName,1,0)=1,1,0)))
  2785. // others: (IIf(FieldName=val,1,0)))
  2786. // - MS SQL
  2787. // y: (1-ABS(SIGN(Year(FieldName)-1996)))
  2788. // q: (1-ABS(SIGN(DatePart(q,FieldName)-1)))
  2789. // m: (1-ABS(SIGN(DatePart(m,FieldName)-1)))
  2790. // d: (CASE Convert(VarChar(10),FieldName,120) WHEN '1996-1-1' THEN 1 ELSE 0 END)
  2791. // - MySQL
  2792. // y: IF(YEAR(FieldName)=1996,1,0))
  2793. // q: IF(QUARTER(FieldName)=1,1,0))
  2794. // m: IF(MONTH(FieldName)=1,1,0))
  2795. // - PostgreSql
  2796. // y: IF(EXTRACT(YEAR FROM FieldName)=1996,1,0))
  2797. // q: IF(EXTRACT(QUARTER FROM FieldName)=1,1,0))
  2798. // m: IF(EXTRACT(MONTH FROM FieldName)=1,1,0))
  2799. function ewrpt_SQLDistinctFactor($sFld, $dateType, $val, $qc) {
  2800. // ACCESS
  2801. if (EWRPT_IS_MSACCESS) {
  2802. if ($dateType == "y" && is_numeric($val)) {
  2803. return "IIf(Year(" . $sFld . ")=" . $val . ",1,0)";
  2804. } elseif (($dateType == "q" || $dateType == "m") && is_numeric($val)) {
  2805. return "IIf(DatePart(\"" . $dateType . "\"," . $sFld . ")=" . $val . ",1,0)";
  2806. } else {
  2807. if ($val == "NULL")
  2808. return "IIf(" . $sFld . " IS NULL,1,0)";
  2809. else
  2810. return "IIf(" . $sFld . "=" . $qc . ewrpt_AdjustSql($val) . $qc . ",1,0)";
  2811. }
  2812. // MS SQL
  2813. } elseif (EWRPT_IS_MSSQL) {
  2814. if ($dateType == "y" && is_numeric($val)) {
  2815. return "(1-ABS(SIGN(Year(" . $sFld . ")-" . $val . ")))";
  2816. } elseif (($dateType == "q" || $dateType == "m") && is_numeric($val)) {
  2817. return "(1-ABS(SIGN(DatePart(" . $dateType . "," . $sFld . ")-" . $val . ")))";
  2818. } elseif ($dateType == "d") {
  2819. return "(CASE CONVERT(VARCHAR(10)," . $sFld . ",120) WHEN " . $qc . ewrpt_AdjustSql($val) . $qc . " THEN 1 ELSE 0 END)";
  2820. } elseif ($dateType == "dt") {
  2821. return "(CASE CONVERT(VARCHAR," . $sFld . ",120) WHEN " . $qc . ewrpt_AdjustSql($val) . $qc . " THEN 1 ELSE 0 END)";
  2822. } else {
  2823. if ($val == "NULL")
  2824. return "(CASE WHEN " . $sFld . " IS NULL THEN 1 ELSE 0 END)";
  2825. else
  2826. return "(CASE " . $sFld . " WHEN " . $qc . ewrpt_AdjustSql($val) . $qc . " THEN 1 ELSE 0 END)";
  2827. }
  2828. // MySQL
  2829. } elseif (EWRPT_IS_MYSQL) {
  2830. if ($dateType == "y" && is_numeric($val)) {
  2831. return "IF(YEAR(" . $sFld . ")=" . $val . ",1,0)";
  2832. } elseif ($dateType == "q" && is_numeric($val)) {
  2833. return "IF(QUARTER(" . $sFld . ")=" . $val . ",1,0)";
  2834. } elseif ($dateType == "m" && is_numeric($val)) {
  2835. return "IF(MONTH(" . $sFld . ")=" . $val . ",1,0)";
  2836. } else {
  2837. if ($val == "NULL") {
  2838. return "IF(" . $sFld . " IS NULL,1,0)";
  2839. } else {
  2840. return "IF(" . $sFld . "=" . $qc . ewrpt_AdjustSql($val) . $qc . ",1,0)";
  2841. }
  2842. }
  2843. // PostgreSql
  2844. } elseif (EWRPT_IS_POSTGRESQL) {
  2845. if ($dateType == "y" && is_numeric($val)) {
  2846. return "CASE WHEN TO_CHAR(" . $sFld . ",'YYYY')='" . $val . "' THEN 1 ELSE 0 END";
  2847. } elseif ($dateType == "q" && is_numeric($val)) {
  2848. return "CASE WHEN TO_CHAR(" . $sFld . ",'Q')='" . $val . "' THEN 1 ELSE 0 END";
  2849. } elseif ($dateType == "m" && is_numeric($val)) {
  2850. return "CASE WHEN TO_CHAR(" . $sFld . ",'MM')=LPAD('" . $val . "',2,'0') THEN 1 ELSE 0 END";
  2851. } else {
  2852. if ($val == "NULL") {
  2853. return "CASE WHEN " . $sFld . " IS NULL THEN 1 ELSE 0 END";
  2854. } else {
  2855. return "CASE WHEN " . $sFld . "=" . $qc . ewrpt_AdjustSql($val) . $qc . " THEN 1 ELSE 0 END";
  2856. }
  2857. }
  2858. // Oracle
  2859. } elseif (EWRPT_IS_ORACLE || EWRPT_IS_POSTGRESQL) {
  2860. if ($dateType == "y" && is_numeric($val)) {
  2861. return "DECODE(TO_CHAR(" . $sFld . ",'YYYY'),'" . $val . "',1,0)";
  2862. } elseif ($dateType == "q" && is_numeric($val)) {
  2863. return "DECODE(TO_CHAR(" . $sFld . ",'Q'),'" . $val . "',1,0)";
  2864. } elseif ($dateType == "m" && is_numeric($val)) {
  2865. return "DECODE(TO_CHAR(" . $sFld . ",'MM'),LPAD('" . $val . "',2,'0'),1,0)";
  2866. } elseif ($dateType == "d") {
  2867. return "DECODE(" . $sFld . ",TO_DATE(" . $qc . ewrpt_AdjustSql($val) . $qc . ",'YYYY/MM/DD'),1,0)";
  2868. } elseif ($dateType == "dt") {
  2869. return "DECODE(" . $sFld . ",TO_DATE(" . $qc . ewrpt_AdjustSql($val) . $qc . ",'YYYY/MM/DD HH24:MI:SS'),1,0)";
  2870. } else {
  2871. if ($val == "NULL") {
  2872. return "(CASE WHEN " . $sFld . " IS NULL THEN 1 ELSE 0 END)";
  2873. } else {
  2874. return "DECODE(" . $sFld . "," . $qc . ewrpt_AdjustSql($val) . $qc . ",1,0)";
  2875. }
  2876. }
  2877. }
  2878. }
  2879. // Evaluate summary value
  2880. function ewrpt_SummaryValue($val1, $val2, $ityp) {
  2881. switch ($ityp) {
  2882. case "SUM":
  2883. case "COUNT":
  2884. case "AVG":
  2885. if (is_null($val2) || !is_numeric($val2)) {
  2886. return $val1;
  2887. } else {
  2888. return ($val1 + $val2);
  2889. }
  2890. case "MIN":
  2891. if (is_null($val2) || !is_numeric($val2)) {
  2892. return $val1; // Skip null and non-numeric
  2893. } elseif (is_null($val1)) {
  2894. return $val2; // Initialize for first valid value
  2895. } elseif ($val1 < $val2) {
  2896. return $val1;
  2897. } else {
  2898. return $val2;
  2899. }
  2900. case "MAX":
  2901. if (is_null($val2) || !is_numeric($val2)) {
  2902. return $val1; // Skip null and non-numeric
  2903. } elseif (is_null($val1)) {
  2904. return $val2; // Initialize for first valid value
  2905. } elseif ($val1 > $val2) {
  2906. return $val1;
  2907. } else {
  2908. return $val2;
  2909. }
  2910. }
  2911. }
  2912. // Match filter value
  2913. function ewrpt_MatchedFilterValue($ar, $value) {
  2914. if (!is_array($ar)) {
  2915. return (strval($ar) == strval($value));
  2916. } else {
  2917. foreach ($ar as $val) {
  2918. if (strval($val) == strval($value))
  2919. return TRUE;
  2920. }
  2921. return FALSE;
  2922. }
  2923. }
  2924. // Render repeat column table
  2925. // rowcnt - zero based row count
  2926. function ewrpt_RepeatColumnTable($totcnt, $rowcnt, $repeatcnt, $rendertype) {
  2927. $sWrk = "";
  2928. if ($rendertype == 1) { // Render control start
  2929. if ($rowcnt == 0) $sWrk .= "<table class=\"" . EWRPT_ITEM_TABLE_CLASSNAME . "\">";
  2930. if ($rowcnt % $repeatcnt == 0) $sWrk .= "<tr>";
  2931. $sWrk .= "<td>";
  2932. } elseif ($rendertype == 2) { // Render control end
  2933. $sWrk .= "</td>";
  2934. if ($rowcnt % $repeatcnt == $repeatcnt - 1) {
  2935. $sWrk .= "</tr>";
  2936. } elseif ($rowcnt == $totcnt - 1) {
  2937. for ($i = ($rowcnt % $repeatcnt) + 1; $i < $repeatcnt; $i++) {
  2938. $sWrk .= "<td>&nbsp;</td>";
  2939. }
  2940. $sWrk .= "</tr>";
  2941. }
  2942. if ($rowcnt == $totcnt - 1) $sWrk .= "</table>";
  2943. }
  2944. return $sWrk;
  2945. }
  2946. // Check if the value is selected
  2947. function ewrpt_IsSelectedValue(&$ar, $value, $ft) {
  2948. if (!is_array($ar))
  2949. return TRUE;
  2950. $af = (substr($value, 0, 2) == "@@");
  2951. foreach ($ar as $val) {
  2952. if ($af || substr($val, 0, 2) == "@@") { // Advanced filters
  2953. if ($val == $value)
  2954. return TRUE;
  2955. } else {
  2956. if (ewrpt_CompareValue($val, $value, $ft))
  2957. return TRUE;
  2958. }
  2959. }
  2960. return FALSE;
  2961. }
  2962. // Set up distinct values
  2963. // ar: array for distinct values
  2964. // val: value
  2965. // label: display value
  2966. // dup: check duplicate
  2967. function ewrpt_SetupDistinctValues(&$ar, $val, $label, $dup) {
  2968. $isarray = is_array($ar);
  2969. if ($dup && $isarray && in_array($val, array_keys($ar)))
  2970. return;
  2971. if (!$isarray) {
  2972. $ar = array($val => $label);
  2973. } elseif ($val == EWRPT_EMPTY_VALUE || $val == EWRPT_NULL_VALUE) { // Null/Empty
  2974. $ar = array_reverse($ar, TRUE);
  2975. $ar[$val] = $label; // Insert at top
  2976. $ar = array_reverse($ar, TRUE);
  2977. } else {
  2978. $ar[$val] = $label; // Default insert at end
  2979. }
  2980. }
  2981. // Compare values based on field type
  2982. function ewrpt_CompareValue($v1, $v2, $ft) {
  2983. switch ($ft) {
  2984. // Case adBigInt, adInteger, adSmallInt, adTinyInt, adUnsignedTinyInt, adUnsignedSmallInt, adUnsignedInt, adUnsignedBigInt
  2985. case 20:
  2986. case 3:
  2987. case 2:
  2988. case 16:
  2989. case 17:
  2990. case 18:
  2991. case 19:
  2992. case 21:
  2993. if (is_numeric($v1) && is_numeric($v2)) {
  2994. return (intval($v1) == intval($v2));
  2995. }
  2996. break;
  2997. // Case adSingle, adDouble, adNumeric, adCurrency
  2998. case 4:
  2999. case 5:
  3000. case 131:
  3001. case 6:
  3002. if (is_numeric($v1) && is_numeric($v2)) {
  3003. return ((float)$v1 == (float)$v2);
  3004. }
  3005. break;
  3006. // Case adDate, adDBDate, adDBTime, adDBTimeStamp
  3007. case 7:
  3008. case 133:
  3009. case 134:
  3010. case 135:
  3011. if (is_numeric(strtotime($v1)) && is_numeric(strtotime($v2))) {
  3012. return (strtotime($v1) == strtotime($v2));
  3013. }
  3014. break;
  3015. default:
  3016. return (strcmp($v1, $v2) == 0); // treat as string
  3017. }
  3018. }
  3019. // Register custom filter (retained for backward compatibility)
  3020. function ewrpt_RegisterCustomFilter(&$fld, $ID, $Name, $FunctionName) {
  3021. ewrpt_RegisterFilter($fld, $ID, $Name, $FunctionName);
  3022. }
  3023. // Register filter
  3024. function ewrpt_RegisterFilter(&$fld, $ID, $Name, $FunctionName) {
  3025. if (!is_array($fld->AdvancedFilters))
  3026. $fld->AdvancedFilters = array();
  3027. $wrkid = (substr($ID,0,2) == "@@") ? $ID : "@@" . $ID;
  3028. $key = substr($wrkid,2);
  3029. $fld->AdvancedFilters[$key] = new crAdvancedFilter($wrkid, $Name, $FunctionName);
  3030. }
  3031. function ewrpt_UnregisterFilter(&$fld, $ID) {
  3032. if (is_array($fld->AdvancedFilters)) {
  3033. $wrkid = (substr($ID,0,2) == "@@") ? $ID : "@@" . $ID;
  3034. $key = substr($wrkid,2);
  3035. foreach ($fld->AdvancedFilters as $filter) {
  3036. if ($filter->ID == $wrkid) {
  3037. unset($fld->AdvancedFilters[$key]);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. }
  3043. // Get custom filter
  3044. function ewrpt_GetCustomFilter(&$fld, $FldVal) {
  3045. $sWrk = "";
  3046. if (is_array($fld->AdvancedFilters)) {
  3047. foreach ($fld->AdvancedFilters as $filter) {
  3048. if ($filter->ID == $FldVal && $filter->Enabled) {
  3049. $sFld = $fld->FldExpression;
  3050. $sFn = $filter->FunctionName;
  3051. $sWrk = $sFn($sFld);
  3052. break;
  3053. }
  3054. }
  3055. }
  3056. return $sWrk;
  3057. }
  3058. // Return date value
  3059. function ewrpt_DateVal($FldOpr, $FldVal, $ValType) {
  3060. // Compose date string
  3061. switch (strtolower($FldOpr)) {
  3062. case "year":
  3063. if ($ValType == 1) {
  3064. $wrkVal = "$FldVal-01-01";
  3065. } elseif ($ValType == 2) {
  3066. $wrkVal = "$FldVal-12-31";
  3067. }
  3068. break;
  3069. case "quarter":
  3070. list($y, $q) = explode("|", $FldVal);
  3071. if (intval($y) == 0 || intval($q) == 0) {
  3072. $wrkVal = "0000-00-00";
  3073. } else {
  3074. if ($ValType == 1) {
  3075. $m = ($q - 1) * 3 + 1;
  3076. $m = str_pad($m, 2, "0", STR_PAD_LEFT);
  3077. $wrkVal = "$y-$m-01";
  3078. } elseif ($ValType == 2) {
  3079. $m = ($q - 1) * 3 + 3;
  3080. $m = str_pad($m, 2, "0", STR_PAD_LEFT);
  3081. $wrkVal = "$y-$m-" . ewrpt_DaysInMonth($y, $m);
  3082. }
  3083. }
  3084. break;
  3085. case "month":
  3086. list($y, $m) = explode("|", $FldVal);
  3087. if (intval($y) == 0 || intval($m) == 0) {
  3088. $wrkVal = "0000-00-00";
  3089. } else {
  3090. if ($ValType == 1) {
  3091. $m = str_pad($m, 2, "0", STR_PAD_LEFT);
  3092. $wrkVal = "$y-$m-01";
  3093. } elseif ($ValType == 2) {
  3094. $m = str_pad($m, 2, "0", STR_PAD_LEFT);
  3095. $wrkVal = "$y-$m-" . ewrpt_DaysInMonth($y, $m);
  3096. }
  3097. }
  3098. break;
  3099. case "day":
  3100. $wrkVal = str_replace("|", "-", $FldVal);
  3101. }
  3102. // Add time if necessary
  3103. if (preg_match('/(\d{4}|\d{2})-(\d{1,2})-(\d{1,2})/', $wrkVal)) { // date without time
  3104. if ($ValType == 1) {
  3105. $wrkVal .= " 00:00:00";
  3106. } elseif ($ValType == 2) {
  3107. $wrkVal .= " 23:59:59";
  3108. }
  3109. }
  3110. // Check if datetime
  3111. if (preg_match('/(\d{4}|\d{2})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/', $wrkVal)) { // datetime
  3112. $DateVal = $wrkVal;
  3113. } else {
  3114. $DateVal = "";
  3115. }
  3116. return $DateVal;
  3117. }
  3118. // "Past"
  3119. function ewrpt_IsPast($FldExpression) {
  3120. return ("($FldExpression < '" . date("Y-m-d H:i:s") . "')");
  3121. }
  3122. // "Future";
  3123. function ewrpt_IsFuture($FldExpression) {
  3124. return ("($FldExpression > '" . date("Y-m-d H:i:s") . "')");
  3125. }
  3126. // "Last 30 days"
  3127. function ewrpt_IsLast30Days($FldExpression) {
  3128. $dt1 = date("Y-m-d", strtotime("-29 days"));
  3129. $dt2 = date("Y-m-d", strtotime("+1 days"));
  3130. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3131. }
  3132. // "Last 14 days"
  3133. function ewrpt_IsLast14Days($FldExpression) {
  3134. $dt1 = date("Y-m-d", strtotime("-13 days"));
  3135. $dt2 = date("Y-m-d", strtotime("+1 days"));
  3136. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3137. }
  3138. // "Last 7 days"
  3139. function ewrpt_IsLast7Days($FldExpression) {
  3140. $dt1 = date("Y-m-d", strtotime("-6 days"));
  3141. $dt2 = date("Y-m-d", strtotime("+1 days"));
  3142. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3143. }
  3144. // "Next 30 days"
  3145. function ewrpt_IsNext30Days($FldExpression) {
  3146. $dt1 = date("Y-m-d");
  3147. $dt2 = date("Y-m-d", strtotime("+30 days"));
  3148. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3149. }
  3150. // "Next 14 days"
  3151. function ewrpt_IsNext14Days($FldExpression) {
  3152. $dt1 = date("Y-m-d");
  3153. $dt2 = date("Y-m-d", strtotime("+14 days"));
  3154. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3155. }
  3156. // "Next 7 days"
  3157. function ewrpt_IsNext7Days($FldExpression) {
  3158. $dt1 = date("Y-m-d");
  3159. $dt2 = date("Y-m-d", strtotime("+7 days"));
  3160. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3161. }
  3162. // "Yesterday"
  3163. function ewrpt_IsYesterday($FldExpression) {
  3164. $dt1 = date("Y-m-d", strtotime("-1 days"));
  3165. $dt2 = date("Y-m-d");
  3166. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3167. }
  3168. // "Today"
  3169. function ewrpt_IsToday($FldExpression) {
  3170. $dt1 = date("Y-m-d");
  3171. $dt2 = date("Y-m-d", strtotime("+1 days"));
  3172. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3173. }
  3174. // "Tomorrow"
  3175. function ewrpt_IsTomorrow($FldExpression) {
  3176. $dt1 = date("Y-m-d", strtotime("+1 days"));
  3177. $dt2 = date("Y-m-d", strtotime("+2 days"));
  3178. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3179. }
  3180. // "Last month"
  3181. function ewrpt_IsLastMonth($FldExpression) {
  3182. $dt1 = date("Y-m", strtotime("-1 months")) . "-01";
  3183. $dt2 = date("Y-m") . "-01";
  3184. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3185. }
  3186. // "This month"
  3187. function ewrpt_IsThisMonth($FldExpression) {
  3188. $dt1 = date("Y-m") . "-01";
  3189. $dt2 = date("Y-m", strtotime("+1 months")) . "-01";
  3190. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3191. }
  3192. // "Next month"
  3193. function ewrpt_IsNextMonth($FldExpression) {
  3194. $dt1 = date("Y-m", strtotime("+1 months")) . "-01";
  3195. $dt2 = date("Y-m", strtotime("+2 months")) . "-01";
  3196. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3197. }
  3198. // "Last two weeks"
  3199. function ewrpt_IsLast2Weeks($FldExpression) {
  3200. if (strtotime("this Sunday") == strtotime("today")) {
  3201. $dt1 = date("Y-m-d", strtotime("-14 days this Sunday"));
  3202. $dt2 = date("Y-m-d", strtotime("this Sunday"));
  3203. } else {
  3204. $dt1 = date("Y-m-d", strtotime("-14 days last Sunday"));
  3205. $dt2 = date("Y-m-d", strtotime("last Sunday"));
  3206. }
  3207. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3208. }
  3209. // "Last week"
  3210. function ewrpt_IsLastWeek($FldExpression) {
  3211. if (strtotime("this Sunday") == strtotime("today")) {
  3212. $dt1 = date("Y-m-d", strtotime("-7 days this Sunday"));
  3213. $dt2 = date("Y-m-d", strtotime("this Sunday"));
  3214. } else {
  3215. $dt1 = date("Y-m-d", strtotime("-7 days last Sunday"));
  3216. $dt2 = date("Y-m-d", strtotime("last Sunday"));
  3217. }
  3218. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3219. }
  3220. // "This week"
  3221. function ewrpt_IsThisWeek($FldExpression) {
  3222. if (strtotime("this Sunday") == strtotime("today")) {
  3223. $dt1 = date("Y-m-d", strtotime("this Sunday"));
  3224. $dt2 = date("Y-m-d", strtotime("+7 days this Sunday"));
  3225. } else {
  3226. $dt1 = date("Y-m-d", strtotime("last Sunday"));
  3227. $dt2 = date("Y-m-d", strtotime("+7 days last Sunday"));
  3228. }
  3229. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3230. }
  3231. // "Next week"
  3232. function ewrpt_IsNextWeek($FldExpression) {
  3233. if (strtotime("this Sunday") == strtotime("today")) {
  3234. $dt1 = date("Y-m-d", strtotime("+7 days this Sunday"));
  3235. $dt2 = date("Y-m-d", strtotime("+14 days this Sunday"));
  3236. } else {
  3237. $dt1 = date("Y-m-d", strtotime("+7 days last Sunday"));
  3238. $dt2 = date("Y-m-d", strtotime("+14 days last Sunday"));
  3239. }
  3240. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3241. }
  3242. // "Next two week"
  3243. function ewrpt_IsNext2Weeks($FldExpression) {
  3244. if (strtotime("this Sunday") == strtotime("today")) {
  3245. $dt1 = date("Y-m-d", strtotime("+7 days this Sunday"));
  3246. $dt2 = date("Y-m-d", strtotime("+21 days this Sunday"));
  3247. } else {
  3248. $dt1 = date("Y-m-d", strtotime("+7 days last Sunday"));
  3249. $dt2 = date("Y-m-d", strtotime("+21 days last Sunday"));
  3250. }
  3251. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3252. }
  3253. // "Last year"
  3254. function ewrpt_IsLastYear($FldExpression) {
  3255. $dt1 = date("Y", strtotime("-1 years")) . "-01-01";
  3256. $dt2 = date("Y") . "-01-01";
  3257. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3258. }
  3259. // "This year"
  3260. function ewrpt_IsThisYear($FldExpression) {
  3261. $dt1 = date("Y") . "-01-01";
  3262. $dt2 = date("Y", strtotime("+1 years")) . "-01-01";
  3263. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3264. }
  3265. // "Next year"
  3266. function ewrpt_IsNextYear($FldExpression) {
  3267. $dt1 = date("Y", strtotime("+1 years")) . "-01-01";
  3268. $dt2 = date("Y", strtotime("+2 years")) . "-01-01";
  3269. return ("($FldExpression >= '$dt1' AND $FldExpression < '$dt2')");
  3270. }
  3271. // "Next year"
  3272. function ewrpt_DaysInMonth($y, $m) {
  3273. if (in_array($m, array(1, 3, 5, 7, 8, 10, 12))) {
  3274. return 31;
  3275. } elseif (in_array($m, array(4, 6, 9, 11))) {
  3276. return 30;
  3277. } elseif ($m == 2) {
  3278. return ($y % 4 == 0) ? 29 : 28;
  3279. }
  3280. return 0;
  3281. }
  3282. // Function to calculate date difference
  3283. function ewrpt_DateDiff($dateTimeBegin, $dateTimeEnd, $interval = "d") {
  3284. $dateTimeBegin = strtotime($dateTimeBegin);
  3285. if ($dateTimeBegin === -1 || $dateTimeBegin === FALSE)
  3286. return FALSE;
  3287. $dateTimeEnd = strtotime($dateTimeEnd);
  3288. if($dateTimeEnd === -1 || $dateTimeEnd === FALSE)
  3289. return FALSE;
  3290. $dif = $dateTimeEnd - $dateTimeBegin;
  3291. $arBegin = getdate($dateTimeBegin);
  3292. $dateBegin = mktime(0, 0, 0, $arBegin["mon"], $arBegin["mday"], $arBegin["year"]);
  3293. $arEnd = getdate($dateTimeEnd);
  3294. $dateEnd = mktime(0, 0, 0, $arEnd["mon"], $arEnd["mday"], $arEnd["year"]);
  3295. $difDate = $dateEnd - $dateBegin;
  3296. switch ($interval) {
  3297. case "s": // seconds
  3298. return $dif;
  3299. case "n": // minutes
  3300. return ($dif > 0) ? floor($dif/60) : ceil($dif/60);
  3301. case "h": // hours
  3302. return ($dif > 0) ? floor($dif/3600) : ceil($dif/3600);
  3303. case "d": // days
  3304. return ($difDate > 0) ? floor($difDate/86400) : ceil($difDate/86400);
  3305. case "w": // weeks
  3306. return ($difDate > 0) ? floor($difDate/604800) : ceil($difDate/604800);
  3307. case "ww": // calendar weeks
  3308. $difWeek = (($dateEnd - $arEnd["wday"]*86400) - ($dateBegin - $arBegin["wday"]*86400))/604800;
  3309. return ($difWeek > 0) ? floor($difWeek) : ceil($difWeek);
  3310. case "m": // months
  3311. return (($arEnd["year"]*12 + $arEnd["mon"]) - ($arBegin["year"]*12 + $arBegin["mon"]));
  3312. case "yyyy": // years
  3313. return ($arEnd["year"] - $arBegin["year"]);
  3314. }
  3315. }
  3316. // Set up distinct values from ext. filter
  3317. function ewrpt_SetupDistinctValuesFromFilter(&$ar, $af) {
  3318. if (is_array($af)) {
  3319. foreach ($af as $filter) {
  3320. if ($filter->Enabled)
  3321. ewrpt_SetupDistinctValues($ar, $filter->ID, $filter->Name, FALSE);
  3322. }
  3323. }
  3324. }
  3325. // Get group value
  3326. // - Get the group value based on field type, group type and interval
  3327. // - ft: field type
  3328. // * 1: numeric, 2: date, 3: string
  3329. // - gt: group type
  3330. // * numeric: i = interval, n = normal
  3331. // * date: d = Day, w = Week, m = Month, q = Quarter, y = Year
  3332. // * string: f = first nth character, n = normal
  3333. // - intv: interval
  3334. function ewrpt_GroupValue(&$fld, $val) {
  3335. $ft = $fld->FldType;
  3336. $grp = $fld->FldGroupByType;
  3337. $intv = $fld->FldGroupInt;
  3338. switch ($ft) {
  3339. // Case adBigInt, adInteger, adSmallInt, adTinyInt, adSingle, adDouble, adNumeric, adCurrency, adUnsignedTinyInt, adUnsignedSmallInt, adUnsignedInt, adUnsignedBigInt (numeric)
  3340. case 20:
  3341. case 3:
  3342. case 2:
  3343. case 16:
  3344. case 4:
  3345. case 5:
  3346. case 131:
  3347. case 6:
  3348. case 17:
  3349. case 18:
  3350. case 19:
  3351. case 21:
  3352. if (!is_numeric($val)) return $val;
  3353. $wrkIntv = intval($intv);
  3354. if ($wrkIntv <= 0) $wrkIntv = 10;
  3355. switch ($grp) {
  3356. case "i":
  3357. return intval($val/$wrkIntv);
  3358. default:
  3359. return $val;
  3360. }
  3361. // Case adDate, adDBDate, adDBTime, adDBTimeStamp (date)
  3362. // case 7:
  3363. // case 133:
  3364. // case 134:
  3365. // case 135:
  3366. // Case adLongVarChar, adLongVarWChar, adChar, adWChar, adVarChar, adVarWChar (string)
  3367. case 201: // string
  3368. case 203:
  3369. case 129:
  3370. case 130:
  3371. case 200:
  3372. case 202:
  3373. $wrkIntv = intval($intv);
  3374. if ($wrkIntv <= 0) $wrkIntv = 1;
  3375. switch ($grp) {
  3376. case "f":
  3377. return substr($val, 0, $wrkIntv);
  3378. default:
  3379. return $val;
  3380. }
  3381. default:
  3382. return $val; // ignore
  3383. }
  3384. }
  3385. // Display group value
  3386. function ewrpt_DisplayGroupValue(&$fld, $val) {
  3387. global $ReportLanguage;
  3388. $ft = $fld->FldType;
  3389. $grp = $fld->FldGroupByType;
  3390. $intv = $fld->FldGroupInt;
  3391. if (is_null($val)) return $ReportLanguage->Phrase("NullLabel");
  3392. if ($val == "") return $ReportLanguage->Phrase("EmptyLabel");
  3393. switch ($ft) {
  3394. // Case adBigInt, adInteger, adSmallInt, adTinyInt, adSingle, adDouble, adNumeric, adCurrency, adUnsignedTinyInt, adUnsignedSmallInt, adUnsignedInt, adUnsignedBigInt (numeric)
  3395. case 20:
  3396. case 3:
  3397. case 2:
  3398. case 16:
  3399. case 4:
  3400. case 5:
  3401. case 131:
  3402. case 6:
  3403. case 17:
  3404. case 18:
  3405. case 19:
  3406. case 21:
  3407. $wrkIntv = intval($intv);
  3408. if ($wrkIntv <= 0) $wrkIntv = 10;
  3409. switch ($grp) {
  3410. case "i":
  3411. return strval($val*$wrkIntv) . " - " . strval(($val+1)*$wrkIntv-1);
  3412. default:
  3413. return $val;
  3414. }
  3415. break;
  3416. // Case adDate, adDBDate, adDBTime, adDBTimeStamp (date)
  3417. case 7:
  3418. case 133:
  3419. case 134:
  3420. case 135:
  3421. $ar = explode("|", $val);
  3422. switch ($grp) {
  3423. Case "y":
  3424. return $ar[0];
  3425. Case "q":
  3426. if (count($ar) < 2) return $val;
  3427. return ewrpt_FormatQuarter($ar[0], $ar[1]);
  3428. Case "m":
  3429. if (count($ar) < 2) return $val;
  3430. return ewrpt_FormatMonth($ar[0], $ar[1]);
  3431. Case "w":
  3432. if (count($ar) < 2) return $val;
  3433. return ewrpt_FormatWeek($ar[0], $ar[1]);
  3434. Case "d":
  3435. if (count($ar) < 3) return $val;
  3436. return ewrpt_FormatDay($ar[0], $ar[1], $ar[2]);
  3437. Case "h":
  3438. return ewrpt_FormatHour($ar[0]);
  3439. Case "min":
  3440. return ewrpt_FormatMinute($ar[0]);
  3441. default:
  3442. return $val;
  3443. }
  3444. break;
  3445. default: // string and others
  3446. return $val; // ignore
  3447. }
  3448. }
  3449. function ewrpt_FormatQuarter($y, $q) {
  3450. return "Q" . $q . "/" . $y;
  3451. }
  3452. function ewrpt_FormatMonth($y, $m) {
  3453. return $m . "/" . $y;
  3454. }
  3455. function ewrpt_FormatWeek($y, $w) {
  3456. return "WK" . $w . "/" . $y;
  3457. }
  3458. function ewrpt_FormatDay($y, $m, $d) {
  3459. return $y . "-" . $m . "-" . $d;
  3460. }
  3461. function ewrpt_FormatHour($h) {
  3462. if (intval($h) == 0) {
  3463. return "12 AM";
  3464. } elseif (intval($h) < 12) {
  3465. return $h . " AM";
  3466. } elseif (intval($h) == 12) {
  3467. return "12 PM";
  3468. } else {
  3469. return ($h-12) . " PM";
  3470. }
  3471. }
  3472. function ewrpt_FormatMinute($n) {
  3473. return $n . " MIN";
  3474. }
  3475. // Get JavaScript data in the form of:
  3476. // [value1, text1, selected], [value2, text2, selected], ...
  3477. // where value1: "value 1", text1: "text 1": selected: true|false
  3478. function ewrpt_GetJsData(&$fld, $ft) {
  3479. $jsdata = "";
  3480. $arv = $fld->ValueList;
  3481. $ars = $fld->SelectionList;
  3482. if (is_array($arv)) {
  3483. foreach ($arv as $key => $value) {
  3484. $jsselect = (ewrpt_IsSelectedValue($ars, $key, $ft)) ? "true" : "false";
  3485. if ($jsdata <> "") $jsdata .= ",";
  3486. $jsdata .= "[\"" . ewrpt_EscapeJs($key) . "\",\"" . ewrpt_EscapeJs($value) . "\",$jsselect]";
  3487. }
  3488. }
  3489. return $jsdata;
  3490. }
  3491. // Return detail filter SQL
  3492. function ewrpt_DetailFilterSQL(&$fld, $fn, $val) {
  3493. $ft = $fld->FldDataType;
  3494. if ($fld->FldGroupSql <> "") $ft = EWRPT_DATATYPE_STRING;
  3495. $sqlwrk = $fn;
  3496. if (is_null($val)) {
  3497. $sqlwrk .= " IS NULL";
  3498. } else {
  3499. $sqlwrk .= " = " . ewrpt_QuotedValue($val, $ft);
  3500. }
  3501. return $sqlwrk;
  3502. }
  3503. // Return popup filter SQL
  3504. function ewrpt_FilterSQL(&$fld, $fn, $ft) {
  3505. $ar = $fld->SelectionList;
  3506. $af = $fld->AdvancedFilters;
  3507. $gt = $fld->FldGroupByType;
  3508. $gi = $fld->FldGroupInt;
  3509. $sql = $fld->FldGroupSql;
  3510. if (!is_array($ar)) {
  3511. return TRUE;
  3512. } else {
  3513. $sqlwrk = "";
  3514. $i = 0;
  3515. foreach ($ar as $value) {
  3516. if ($value == EWRPT_EMPTY_VALUE) { // Empty string
  3517. $sqlwrk .= "$fn = '' OR ";
  3518. } elseif ($value == EWRPT_NULL_VALUE) { // Null value
  3519. $sqlwrk .= "$fn IS NULL OR ";
  3520. } elseif (substr($value, 0, 2) == "@@") { // Advanced filter
  3521. if (is_array($af)) {
  3522. $afsql = ewrpt_AdvancedFilterSQL($af, $fn, $value); // Process popup filter
  3523. if (!is_null($afsql))
  3524. $sqlwrk .= $afsql . " OR ";
  3525. }
  3526. } elseif ($sql <> "") {
  3527. $sqlwrk .= str_replace("%s", $fn, $sql) . " = '" . $value . "' OR ";
  3528. } else {
  3529. $sqlwrk .= "$fn IN (" . ewrpt_JoinArray($ar, ", ", $ft, $i) . ") OR ";
  3530. break;
  3531. }
  3532. $i++;
  3533. }
  3534. }
  3535. if ($sqlwrk != "")
  3536. $sqlwrk = "(" . substr($sqlwrk, 0, -4) . ")";
  3537. return $sqlwrk;
  3538. }
  3539. // Return Advanced Filter SQL
  3540. function ewrpt_AdvancedFilterSQL(&$af, $fn, $val) {
  3541. if (!is_array($af)) {
  3542. return NULL;
  3543. } elseif (is_null($val)) {
  3544. return NULL;
  3545. } else {
  3546. foreach ($af as $filter) {
  3547. if (strval($val) == strval($filter->ID) && $filter->Enabled) {
  3548. $func = $filter->FunctionName;
  3549. return $func($fn);
  3550. }
  3551. }
  3552. return NULL;
  3553. }
  3554. }
  3555. // Truncate Memo Field based on specified length, string truncated to nearest space or CrLf
  3556. function ewrpt_TruncateMemo($memostr, $ln, $removehtml) {
  3557. $str = ($removehtml) ? ewrpt_RemoveHtml($memostr) : $memostr;
  3558. if (strlen($str) > 0 && strlen($str) > $ln) {
  3559. $k = 0;
  3560. while ($k >= 0 && $k < strlen($str)) {
  3561. $i = strpos($str, " ", $k);
  3562. $j = strpos($str, chr(10), $k);
  3563. if ($i === FALSE && $j === FALSE) { // Not able to truncate
  3564. return $str;
  3565. } else {
  3566. // Get nearest space or CrLf
  3567. if ($i > 0 && $j > 0) {
  3568. if ($i < $j) {
  3569. $k = $i;
  3570. } else {
  3571. $k = $j;
  3572. }
  3573. } elseif ($i > 0) {
  3574. $k = $i;
  3575. } elseif ($j > 0) {
  3576. $k = $j;
  3577. }
  3578. // Get truncated text
  3579. if ($k >= $ln) {
  3580. return substr($str, 0, $k) . "...";
  3581. } else {
  3582. $k++;
  3583. }
  3584. }
  3585. }
  3586. } else {
  3587. return $str;
  3588. }
  3589. }
  3590. // Remove HTML tags from text
  3591. function ewrpt_RemoveHtml($str) {
  3592. return preg_replace('/<[^>]*>/', '', strval($str));
  3593. }
  3594. // Escape string for JavaScript
  3595. function ewrpt_EscapeJs($str) {
  3596. $str = strval($str);
  3597. $str = str_replace("\"", "\\\"", $str);
  3598. $str = str_replace("\r", "\\r", $str);
  3599. $str = str_replace("\n", "\\n", $str);
  3600. return $str;
  3601. }
  3602. // Load Chart Series
  3603. function ewrpt_LoadChartSeries($sSql, &$cht) {
  3604. global $conn;
  3605. $rscht = $conn->Execute($sSql);
  3606. $sdt = $cht->SeriesDateType;
  3607. while ($rscht && !$rscht->EOF) {
  3608. $cht->Series[] = ewrpt_ChartSeriesValue($rscht->fields[0], $sdt); // Series value
  3609. $rscht->MoveNext();
  3610. }
  3611. if ($rscht) $rscht->Close();
  3612. }
  3613. // Load Chart Data
  3614. function ewrpt_LoadChartData($sSql, &$cht) {
  3615. global $conn;
  3616. $rscht = $conn->Execute($sSql);
  3617. $sdt = $cht->SeriesDateType;
  3618. $xdt = $cht->XAxisDateFormat;
  3619. $ndt = ($cht->ChartType == 20) ? $cht->NameDateFormat : "";
  3620. if ($sdt <> "") $xdt = $sdt;
  3621. while ($rscht && !$rscht->EOF) {
  3622. $temp = array();
  3623. $temp[0] = ewrpt_ChartXValue($rscht->fields[0], $xdt); // X value
  3624. //echo "0: " . $rscht->fields[0] . "<br>";
  3625. $temp[1] = ewrpt_ChartSeriesValue($rscht->fields[1], $sdt); // Series value
  3626. for ($i=2; $i < $rscht->FieldCount(); $i++) {
  3627. if ($ndt <> "" && $i == $rscht->FieldCount()-1)
  3628. $temp[$i] = ewrpt_ChartXValue($rscht->fields[$i], $ndt); // Name value
  3629. else
  3630. $temp[$i] = $rscht->fields[$i]; // Y values
  3631. }
  3632. //echo "1: " . $rscht->fields[1] . "<br>";
  3633. $cht->Data[] = $temp;
  3634. $rscht->MoveNext();
  3635. }
  3636. if ($rscht) $rscht->Close();
  3637. }
  3638. // Get Chart X value
  3639. function ewrpt_ChartXValue($val, $dt) {
  3640. if (is_numeric($dt)) {
  3641. return ewrpt_FormatDateTime($val, $dt);
  3642. } elseif ($dt == "xyq") {
  3643. $ar = explode("|", $val);
  3644. if (count($ar) >= 2)
  3645. return $ar[0] . " " . ewrpt_QuarterName($ar[1]);
  3646. else
  3647. return $val;
  3648. }
  3649. elseif ($dt == "xym") {
  3650. $ar = explode("|", $val);
  3651. if (count($ar) >= 2)
  3652. return $ar[0] . " " . ewrpt_MonthName($ar[1]);
  3653. else
  3654. return $val;
  3655. }
  3656. elseif ($dt == "xq") {
  3657. return ewrpt_QuarterName($val);
  3658. }
  3659. elseif ($dt == "xm") {
  3660. return ewrpt_MonthName($val);
  3661. }
  3662. else {
  3663. if (is_string($val))
  3664. return trim($val);
  3665. else
  3666. return $val;
  3667. }
  3668. }
  3669. // Get Chart Series value
  3670. function ewrpt_ChartSeriesValue($val, $dt) {
  3671. if ($dt == "syq") {
  3672. $ar = explode("|", $val);
  3673. if (count($ar) >= 2)
  3674. return $ar[0] . " " . ewrpt_QuarterName($ar[1]);
  3675. else
  3676. return $val;
  3677. }
  3678. elseif ($dt == "sym") {
  3679. $ar = explode("|", $val);
  3680. if (count($ar) >= 2)
  3681. return $ar[0] . " " . ewrpt_MonthName($ar[1]);
  3682. else
  3683. return $val;
  3684. }
  3685. elseif ($dt == "sq") {
  3686. return ewrpt_QuarterName($val);
  3687. }
  3688. elseif ($dt == "sm") {
  3689. return ewrpt_MonthName($val);
  3690. }
  3691. else {
  3692. if (is_string($val))
  3693. return trim($val);
  3694. else
  3695. return $val;
  3696. }
  3697. }
  3698. // Sort chart data
  3699. function ewrpt_SortChartData(&$ar, $opt, $seq="") {
  3700. if ((($opt < 3 || $opt > 4) && $seq == "") || (($opt < 1 || $opt > 4) && $seq <> ""))
  3701. return;
  3702. if (is_array($ar)) {
  3703. $cntar = count($ar);
  3704. for ($i = 0; $i < $cntar; $i++) {
  3705. for ($j = $i+1; $j < $cntar; $j++) {
  3706. switch ($opt) {
  3707. case 1: // X values ascending
  3708. $bSwap = ewrpt_CompareValueCustom($ar[$i][0], $ar[$j][0], $seq);
  3709. break;
  3710. case 2: // X values descending
  3711. $bSwap = ewrpt_CompareValueCustom($ar[$j][0], $ar[$i][0], $seq);
  3712. break;
  3713. case 3: // Y values ascending
  3714. $bSwap = ewrpt_CompareValueCustom($ar[$i][2], $ar[$j][2], $seq);
  3715. break;
  3716. case 4: // Y values descending
  3717. $bSwap = ewrpt_CompareValueCustom($ar[$j][2], $ar[$i][2], $seq);
  3718. }
  3719. if ($bSwap) {
  3720. $tmpar = $ar[$i];
  3721. $ar[$i] = $ar[$j];
  3722. $ar[$j] = $tmpar;
  3723. }
  3724. }
  3725. }
  3726. }
  3727. }
  3728. // Sort chart multi series data
  3729. function ewrpt_SortMultiChartData(&$ar, $opt, $seq="") {
  3730. if (!is_array($ar) || (($opt < 3 || $opt > 4) && $seq == "") || (($opt < 1 || $opt > 4) && $seq <> ""))
  3731. return;
  3732. // Obtain a list of columns
  3733. foreach ($ar as $key => $row) {
  3734. $xvalues[$key] = $row[0];
  3735. $series[$key] = $row[1];
  3736. $yvalues[$key] = $row[2];
  3737. $ysums[$key] = $row[0]; // store the x-value for the time being
  3738. if (isset($xsums[$row[0]])) {
  3739. $xsums[$row[0]] += $row[2];
  3740. } else {
  3741. $xsums[$row[0]] = $row[2];
  3742. }
  3743. }
  3744. // Set up Y sum
  3745. if ($opt == 3 || $opt == 4) {
  3746. $cnt = count($ysums);
  3747. for ($i=0; $i<$cnt; $i++)
  3748. $ysums[$i] = $xsums[$ysums[$i]];
  3749. }
  3750. // No specific sequence, use array_multisort
  3751. if ($seq == "") {
  3752. switch ($opt) {
  3753. case 1: // X values ascending
  3754. array_multisort($xvalues, SORT_ASC, $ar);
  3755. break;
  3756. case 2: // X values descending
  3757. array_multisort($xvalues, SORT_DESC, $ar);
  3758. break;
  3759. case 3:
  3760. case 4: // Y values
  3761. if ($opt == 3) { // ascending
  3762. array_multisort($ysums, SORT_ASC, $ar);
  3763. } elseif ($opt == 4) { // descending
  3764. array_multisort($ysums, SORT_DESC, $ar);
  3765. }
  3766. }
  3767. // Handle specific sequence
  3768. } else {
  3769. // Build key list
  3770. if ($opt == 1 || $opt == 2)
  3771. $vals = array_unique($xvalues);
  3772. else
  3773. $vals = array_unique($ysums);
  3774. foreach ($vals as $key => $val) {
  3775. $keys[] = array($key, $val);
  3776. }
  3777. // Sort key list based on specific sequence
  3778. $cntkey = count($keys);
  3779. for ($i = 0; $i < $cntkey; $i++) {
  3780. for ($j = $i+1; $j < $cntkey; $j++) {
  3781. switch ($opt) {
  3782. // Ascending
  3783. case 1:
  3784. case 3:
  3785. $bSwap = ewrpt_CompareValueCustom($keys[$i][1], $keys[$j][1], $seq);
  3786. break;
  3787. // Descending
  3788. case 2:
  3789. case 4:
  3790. $bSwap = ewrpt_CompareValueCustom($keys[$j][1], $keys[$i][1], $seq);
  3791. break;
  3792. }
  3793. if ($bSwap) {
  3794. $tmpkey = $keys[$i];
  3795. $keys[$i] = $keys[$j];
  3796. $keys[$j] = $tmpkey;
  3797. }
  3798. }
  3799. }
  3800. for ($i = 0; $i < $cntkey; $i++) {
  3801. $xsorted[] = $xvalues[$keys[$i][0]];
  3802. }
  3803. // Sort array based on x sequence
  3804. $arwrk = $ar;
  3805. $rowcnt = 0;
  3806. $cntx = intval(count($xsorted));
  3807. for ($i = 0; $i < $cntx; $i++) {
  3808. foreach ($arwrk as $key => $row) {
  3809. if ($row[0] == $xsorted[$i]) {
  3810. $ar[$rowcnt] = $row;
  3811. $rowcnt++;
  3812. }
  3813. }
  3814. }
  3815. }
  3816. }
  3817. // Compare values by custom sequence
  3818. function ewrpt_CompareValueCustom($v1, $v2, $seq) {
  3819. if ($seq == "_number") { // Number
  3820. if (is_numeric($v1) && is_numeric($v2)) {
  3821. return ((float)$v1 > (float)$v2);
  3822. }
  3823. } else if ($seq == "_date") { // Date
  3824. if (is_numeric(strtotime($v1)) && is_numeric(strtotime($v2))) {
  3825. return (strtotime($v1) > strtotime($v2));
  3826. }
  3827. } else if ($seq <> "") { // Custom sequence
  3828. $ar = explode("|", $seq);
  3829. if (in_array($v1, $ar) && in_array($v2, $ar))
  3830. return (array_search($v1, $ar) > array_search($v2, $ar));
  3831. else
  3832. return in_array($v2, $ar);
  3833. }
  3834. return ($v1 > $v2);
  3835. }
  3836. // Load array from sql
  3837. function ewrpt_LoadArrayFromSql($sql, &$ar) {
  3838. global $conn;
  3839. if (strval($sql) == "")
  3840. return;
  3841. $rswrk = $conn->Execute($sql);
  3842. if ($rswrk) {
  3843. while (!$rswrk->EOF) {
  3844. $v = $rswrk->fields[0];
  3845. if (is_null($v)) {
  3846. $v = EWRPT_NULL_VALUE;
  3847. } elseif ($v == "") {
  3848. $v = EWRPT_EMPTY_VALUE;
  3849. }
  3850. if (!is_array($ar))
  3851. $ar = array();
  3852. $ar[] = $v;
  3853. $rswrk->MoveNext();
  3854. }
  3855. $rswrk->Close();
  3856. }
  3857. }
  3858. // Function to Match array
  3859. function ewrpt_MatchedArray(&$ar1, &$ar2) {
  3860. if (!is_array($ar1) && !is_array($ar2)) {
  3861. return TRUE;
  3862. } elseif (is_array($ar1) && is_array($ar2)) {
  3863. return (count(array_diff($ar1, $ar2)) == 0);
  3864. }
  3865. return FALSE;
  3866. }
  3867. // Write a value to file for debug
  3868. function ewrpt_Trace($msg) {
  3869. $filename = "debug.txt";
  3870. if (!$handle = fopen($filename, 'a')) exit;
  3871. if (is_writable($filename)) fwrite($handle, $msg . "\n");
  3872. fclose($handle);
  3873. }
  3874. // Connection/Query error handler
  3875. function ewrpt_ErrorFn($DbType, $ErrorType, $ErrorNo, $ErrorMsg, $Param1, $Param2, $Object) {
  3876. if ($ErrorType == 'CONNECT') {
  3877. $msg = "Failed to connect to $Param2 at $Param1. Error: " . $ErrorMsg;
  3878. } elseif ($ErrorType == 'EXECUTE') {
  3879. $msg = "Failed to execute SQL: $Param1. Error: " . $ErrorMsg;
  3880. }
  3881. $_SESSION[EWRPT_SESSION_MESSAGE] = $msg;
  3882. }
  3883. // Write HTTP header
  3884. function ewrpt_Header($cache, $charset = EWRPT_CHARSET) {
  3885. header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
  3886. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // Always modified
  3887. $export = @$_GET["export"];
  3888. if ($cache || !$cache && ewrpt_IsHttps() && $export <> "" && $export <> "print") { // Allow cache
  3889. header("Cache-Control: private, must-revalidate"); // HTTP/1.1
  3890. } else { // No cache
  3891. header("Cache-Control: private, no-store, no-cache, must-revalidate"); // HTTP/1.1
  3892. header("Cache-Control: post-check=0, pre-check=0", false);
  3893. header("Pragma: no-cache"); // HTTP/1.0
  3894. }
  3895. if ($charset <> "")
  3896. header("Content-Type: text/html; charset=" . $charset); // Charset
  3897. }
  3898. // Connect to database
  3899. function &ewrpt_Connect() {
  3900. $GLOBALS["ADODB_FETCH_MODE"] = ADODB_FETCH_BOTH;
  3901. $conn = new mysqlt_driver_ADOConnection();
  3902. $conn->debug = EWRPT_DEBUG_ENABLED;
  3903. // $conn->debug_echo = FALSE;
  3904. $conn->debug_echo = EWRPT_DEBUG_ENABLED;
  3905. $info = array("host" => EWRPT_CONN_HOST, "port" => EWRPT_CONN_PORT,
  3906. "user" => EWRPT_CONN_USER, "pass" => EWRPT_CONN_PASS, "db" => EWRPT_CONN_DB);
  3907. // Database connecting event
  3908. Database_Connecting($info);
  3909. $conn->port = intval($info["port"]);
  3910. $conn->raiseErrorFn = 'ewrpt_ErrorFn';
  3911. $conn->Connect($info["host"], $info["user"], $info["pass"], $info["db"]);
  3912. if (EWRPT_MYSQL_CHARSET <> "")
  3913. $conn->Execute("SET NAMES '" . EWRPT_MYSQL_CHARSET . "'");
  3914. $conn->raiseErrorFn = '';
  3915. // Database connected event
  3916. Database_Connected($conn);
  3917. return $conn;
  3918. }
  3919. // Database Connecting event
  3920. function Database_Connecting(&$info) {
  3921. // Example:
  3922. //var_dump($info);
  3923. //if (ew_ServerVar("REMOTE_ADDR") == "127.0.0.1") { // testing on local PC
  3924. // $info["host"] = "locahost";
  3925. // $info["user"] = "root";
  3926. // $info["pass"] = "";
  3927. //}
  3928. }
  3929. // Database Connected event
  3930. function Database_Connected(&$conn) {
  3931. // Example:
  3932. //$conn->Execute("Your SQL");
  3933. }
  3934. // Check if boolean value is TRUE
  3935. function ewrpt_ConvertToBool($value) {
  3936. return ($value === TRUE || strval($value) == "1" ||
  3937. strtolower(strval($value)) == "y" || strtolower(strval($value)) == "t");
  3938. }
  3939. // Check if HTTP POST
  3940. function ewrpt_IsHttpPost() {
  3941. $ct = ewrpt_ServerVar("CONTENT_TYPE");
  3942. if (empty($ct)) $ct = ewrpt_ServerVar("HTTP_CONTENT_TYPE");
  3943. return ($ct == "application/x-www-form-urlencoded");
  3944. }
  3945. // Strip slashes
  3946. function ewrpt_StripSlashes($value) {
  3947. if (!get_magic_quotes_gpc()) return $value;
  3948. if (is_array($value)) {
  3949. return array_map('ewrpt_StripSlashes', $value);
  3950. } else {
  3951. return stripslashes($value);
  3952. }
  3953. }
  3954. // Escape chars for XML
  3955. function ewrpt_XmlEncode($val) {
  3956. return htmlspecialchars(strval($val));
  3957. }
  3958. // Output SCRIPT tag
  3959. function ewrpt_AddClientScript($src, $attrs = NULL) {
  3960. $atts = array("type"=>"text/javascript", "src"=>$src);
  3961. if (is_array($attrs))
  3962. $atts = array_merge($atts, $attrs);
  3963. echo ewrpt_HtmlElement("script", $atts, "") . "\n";
  3964. }
  3965. // Output LINK tag
  3966. function ewrpt_AddStylesheet($href, $attrs = NULL) {
  3967. $atts = array("rel"=>"stylesheet", "type"=>"text/css", "href"=>$href);
  3968. if (is_array($attrs))
  3969. $atts = array_merge($atts, $attrs);
  3970. echo ewrpt_HtmlElement("link", $atts, "", FALSE) . "\n";
  3971. }
  3972. // Build HTML element
  3973. function ewrpt_HtmlElement($tagname, $attrs, $innerhtml = "", $endtag = TRUE) {
  3974. $html = "<" . $tagname;
  3975. if (is_array($attrs)) {
  3976. foreach ($attrs as $name => $attr) {
  3977. if (strval($attr) <> "")
  3978. $html .= " " . $name . "=\"" . ewrpt_HtmlEncode($attr) . "\"";
  3979. }
  3980. }
  3981. $html .= ">";
  3982. if (strval($innerhtml) <> "")
  3983. $html .= $innerhtml;
  3984. if ($endtag)
  3985. $html .= "</" . $tagname . ">";
  3986. return $html;
  3987. }
  3988. // Encode html
  3989. function ewrpt_HtmlEncode($exp) {
  3990. return htmlspecialchars(strval($exp));
  3991. }
  3992. // View Option Separator
  3993. function ewrpt_ViewOptionSeparator($rowcnt) {
  3994. return ", ";
  3995. }
  3996. // Functions for TEA encryption/decryption
  3997. function long2str($v, $w) {
  3998. $len = count($v);
  3999. $s = array();
  4000. for ($i = 0; $i < $len; $i++)
  4001. {
  4002. $s[$i] = pack("V", $v[$i]);
  4003. }
  4004. if ($w) {
  4005. return substr(join('', $s), 0, $v[$len - 1]);
  4006. } else {
  4007. return join('', $s);
  4008. }
  4009. }
  4010. function str2long($s, $w) {
  4011. $v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
  4012. $v = array_values($v);
  4013. if ($w) {
  4014. $v[count($v)] = strlen($s);
  4015. }
  4016. return $v;
  4017. }
  4018. function TEAencrypt($str, $key) {
  4019. if ($str == "") {
  4020. return "";
  4021. }
  4022. $v = str2long($str, true);
  4023. $k = str2long($key, false);
  4024. $cntk = count($k);
  4025. if ($cntk < 4) {
  4026. for ($i = $cntk; $i < 4; $i++) {
  4027. $k[$i] = 0;
  4028. }
  4029. }
  4030. $n = count($v) - 1;
  4031. $z = $v[$n];
  4032. $y = $v[0];
  4033. $delta = 0x9E3779B9;
  4034. $q = floor(6 + 52 / ($n + 1));
  4035. $sum = 0;
  4036. while (0 < $q--) {
  4037. $sum = int32($sum + $delta);
  4038. $e = $sum >> 2 & 3;
  4039. for ($p = 0; $p < $n; $p++) {
  4040. $y = $v[$p + 1];
  4041. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  4042. $z = $v[$p] = int32($v[$p] + $mx);
  4043. }
  4044. $y = $v[0];
  4045. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  4046. $z = $v[$n] = int32($v[$n] + $mx);
  4047. }
  4048. return ewrpt_UrlEncode(long2str($v, false));
  4049. }
  4050. function TEAdecrypt($str, $key) {
  4051. $str = ewrpt_UrlDecode($str);
  4052. if ($str == "") {
  4053. return "";
  4054. }
  4055. $v = str2long($str, false);
  4056. $k = str2long($key, false);
  4057. $cntk = count($k);
  4058. if ($cntk < 4) {
  4059. for ($i = $cntk; $i < 4; $i++) {
  4060. $k[$i] = 0;
  4061. }
  4062. }
  4063. $n = count($v) - 1;
  4064. $z = $v[$n];
  4065. $y = $v[0];
  4066. $delta = 0x9E3779B9;
  4067. $q = floor(6 + 52 / ($n + 1));
  4068. $sum = int32($q * $delta);
  4069. while ($sum != 0) {
  4070. $e = $sum >> 2 & 3;
  4071. for ($p = $n; $p > 0; $p--) {
  4072. $z = $v[$p - 1];
  4073. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  4074. $y = $v[$p] = int32($v[$p] - $mx);
  4075. }
  4076. $z = $v[$n];
  4077. $mx = int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
  4078. $y = $v[0] = int32($v[0] - $mx);
  4079. $sum = int32($sum - $delta);
  4080. }
  4081. return long2str($v, true);
  4082. }
  4083. function int32($n) {
  4084. while ($n >= 2147483648) $n -= 4294967296;
  4085. while ($n <= -2147483649) $n += 4294967296;
  4086. return (int)$n;
  4087. }
  4088. function ewrpt_UrlEncode($string) {
  4089. $data = base64_encode($string);
  4090. return str_replace(array('+','/','='), array('-','_','.'), $data);
  4091. }
  4092. function ewrpt_UrlDecode($string) {
  4093. $data = str_replace(array('-','_','.'), array('+','/','='), $string);
  4094. return base64_decode($data);
  4095. }
  4096. /**
  4097. * Pager item class
  4098. */
  4099. class crPagerItem {
  4100. var $Start;
  4101. var $Text;
  4102. var $Enabled;
  4103. }
  4104. /**
  4105. * Numeric pager class
  4106. */
  4107. class crNumericPager {
  4108. var $Items = array();
  4109. var $Count, $FromIndex, $ToIndex, $RecordCount, $PageSize, $Range;
  4110. var $FirstButton, $PrevButton, $NextButton, $LastButton;
  4111. var $ButtonCount = 0;
  4112. var $Visible = TRUE;
  4113. function crNumericPager($StartRec, $DisplayRecs, $TotalRecs, $RecRange)
  4114. {
  4115. $this->FirstButton = new crPagerItem;
  4116. $this->PrevButton = new crPagerItem;
  4117. $this->NextButton = new crPagerItem;
  4118. $this->LastButton = new crPagerItem;
  4119. $this->FromIndex = intval($StartRec);
  4120. $this->PageSize = intval($DisplayRecs);
  4121. $this->RecordCount = intval($TotalRecs);
  4122. $this->Range = intval($RecRange);
  4123. if ($this->PageSize == 0) return;
  4124. if ($this->FromIndex > $this->RecordCount)
  4125. $this->FromIndex = $this->RecordCount;
  4126. $this->ToIndex = $this->FromIndex + $this->PageSize - 1;
  4127. if ($this->ToIndex > $this->RecordCount)
  4128. $this->ToIndex = $this->RecordCount;
  4129. // setup
  4130. $this->SetupNumericPager();
  4131. // update button count
  4132. if ($this->FirstButton->Enabled) $this->ButtonCount++;
  4133. if ($this->PrevButton->Enabled) $this->ButtonCount++;
  4134. if ($this->NextButton->Enabled) $this->ButtonCount++;
  4135. if ($this->LastButton->Enabled) $this->ButtonCount++;
  4136. $this->ButtonCount += count($this->Items);
  4137. }
  4138. // Add pager item
  4139. function AddPagerItem($StartIndex, $Text, $Enabled)
  4140. {
  4141. $Item = new crPagerItem;
  4142. $Item->Start = $StartIndex;
  4143. $Item->Text = $Text;
  4144. $Item->Enabled = $Enabled;
  4145. $this->Items[] = $Item;
  4146. }
  4147. // Setup pager items
  4148. function SetupNumericPager()
  4149. {
  4150. if ($this->RecordCount > $this->PageSize) {
  4151. $Eof = ($this->RecordCount < ($this->FromIndex + $this->PageSize));
  4152. $HasPrev = ($this->FromIndex > 1);
  4153. // First Button
  4154. $TempIndex = 1;
  4155. $this->FirstButton->Start = $TempIndex;
  4156. $this->FirstButton->Enabled = ($this->FromIndex > $TempIndex);
  4157. // Prev Button
  4158. $TempIndex = $this->FromIndex - $this->PageSize;
  4159. if ($TempIndex < 1) $TempIndex = 1;
  4160. $this->PrevButton->Start = $TempIndex;
  4161. $this->PrevButton->Enabled = $HasPrev;
  4162. // Page links
  4163. if ($HasPrev || !$Eof) {
  4164. $x = 1;
  4165. $y = 1;
  4166. $dx1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->PageSize*$this->Range + 1;
  4167. $dy1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->Range + 1;
  4168. if (($dx1+$this->PageSize*$this->Range-1) > $this->RecordCount) {
  4169. $dx2 = intval($this->RecordCount/$this->PageSize)*$this->PageSize + 1;
  4170. $dy2 = intval($this->RecordCount/$this->PageSize) + 1;
  4171. } else {
  4172. $dx2 = $dx1 + $this->PageSize*$this->Range - 1;
  4173. $dy2 = $dy1 + $this->Range - 1;
  4174. }
  4175. while ($x <= $this->RecordCount) {
  4176. if ($x >= $dx1 && $x <= $dx2) {
  4177. $this->AddPagerItem($x, $y, $this->FromIndex<>$x);
  4178. $x += $this->PageSize;
  4179. $y++;
  4180. } elseif ($x >= ($dx1-$this->PageSize*$this->Range) && $x <= ($dx2+$this->PageSize*$this->Range)) {
  4181. if ($x+$this->Range*$this->PageSize < $this->RecordCount) {
  4182. $this->AddPagerItem($x, $y . "-" . ($y+$this->Range-1), TRUE);
  4183. } else {
  4184. $ny = intval(($this->RecordCount-1)/$this->PageSize) + 1;
  4185. if ($ny == $y) {
  4186. $this->AddPagerItem($x, $y, TRUE);
  4187. } else {
  4188. $this->AddPagerItem($x, $y . "-" . $ny, TRUE);
  4189. }
  4190. }
  4191. $x += $this->Range*$this->PageSize;
  4192. $y += $this->Range;
  4193. } else {
  4194. $x += $this->Range*$this->PageSize;
  4195. $y += $this->Range;
  4196. }
  4197. }
  4198. }
  4199. // Next Button
  4200. $TempIndex = $this->FromIndex + $this->PageSize;
  4201. $this->NextButton->Start = $TempIndex;
  4202. $this->NextButton->Enabled = !$Eof;
  4203. // Last Button
  4204. $TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
  4205. $this->LastButton->Start = $TempIndex;
  4206. $this->LastButton->Enabled = ($this->FromIndex < $TempIndex);
  4207. }
  4208. }
  4209. }
  4210. /**
  4211. * PrevNext pager class
  4212. */
  4213. class crPrevNextPager {
  4214. var $FirstButton, $PrevButton, $NextButton, $LastButton;
  4215. var $CurrentPage, $PageCount, $FromIndex, $ToIndex, $RecordCount;
  4216. var $Visible = TRUE;
  4217. function crPrevNextPager($StartRec, $DisplayRecs, $TotalRecs)
  4218. {
  4219. $this->FirstButton = new crPagerItem;
  4220. $this->PrevButton = new crPagerItem;
  4221. $this->NextButton = new crPagerItem;
  4222. $this->LastButton = new crPagerItem;
  4223. $this->FromIndex = intval($StartRec);
  4224. $this->PageSize = intval($DisplayRecs);
  4225. $this->RecordCount = intval($TotalRecs);
  4226. if ($this->PageSize == 0) return;
  4227. $this->CurrentPage = intval(($this->FromIndex-1)/$this->PageSize) + 1;
  4228. $this->PageCount = intval(($this->RecordCount-1)/$this->PageSize) + 1;
  4229. if ($this->FromIndex > $this->RecordCount)
  4230. $this->FromIndex = $this->RecordCount;
  4231. $this->ToIndex = $this->FromIndex + $this->PageSize - 1;
  4232. if ($this->ToIndex > $this->RecordCount)
  4233. $this->ToIndex = $this->RecordCount;
  4234. // First Button
  4235. $TempIndex = 1;
  4236. $this->FirstButton->Start = $TempIndex;
  4237. $this->FirstButton->Enabled = ($TempIndex <> $this->FromIndex);
  4238. // Prev Button
  4239. $TempIndex = $this->FromIndex - $this->PageSize;
  4240. if ($TempIndex < 1) $TempIndex = 1;
  4241. $this->PrevButton->Start = $TempIndex;
  4242. $this->PrevButton->Enabled = ($TempIndex <> $this->FromIndex);
  4243. // Next Button
  4244. $TempIndex = $this->FromIndex + $this->PageSize;
  4245. if ($TempIndex > $this->RecordCount)
  4246. $TempIndex = $this->FromIndex;
  4247. $this->NextButton->Start = $TempIndex;
  4248. $this->NextButton->Enabled = ($TempIndex <> $this->FromIndex);
  4249. // Last Button
  4250. $TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
  4251. $this->LastButton->Start = $TempIndex;
  4252. $this->LastButton->Enabled = ($TempIndex <> $this->FromIndex);
  4253. }
  4254. }
  4255. /**
  4256. * Email class
  4257. */
  4258. class crEmail {
  4259. // Class properties
  4260. var $Sender = ""; // Sender
  4261. var $Recipient = ""; // Recipient
  4262. var $Cc = ""; // Cc
  4263. var $Bcc = ""; // Bcc
  4264. var $Subject = ""; // Subject
  4265. var $Format = ""; // Format
  4266. var $Content = ""; // Content
  4267. var $AttachmentContent = ""; // Attachement content
  4268. var $AttachmentFileName = ""; // Attachment file name
  4269. var $Charset = ""; // Charset
  4270. var $SendErrDescription; // Send error description
  4271. // Method to load email from template
  4272. function Load($fn) {
  4273. $fn = ewrpt_ScriptFolder() . EWRPT_PATH_DELIMITER . $fn;
  4274. $sWrk = file_get_contents($fn); // Load text file content
  4275. if ($sWrk <> "") {
  4276. // Locate Header & Mail Content
  4277. if (EWRPT_IS_WINDOWS) {
  4278. $i = strpos($sWrk, "\r\n\r\n");
  4279. } else {
  4280. $i = strpos($sWrk, "\n\n");
  4281. if ($i === FALSE) $i = strpos($sWrk, "\r\n\r\n");
  4282. }
  4283. if ($i > 0) {
  4284. $sHeader = substr($sWrk, 0, $i);
  4285. $this->Content = trim(substr($sWrk, $i, strlen($sWrk)));
  4286. if (EWRPT_IS_WINDOWS) {
  4287. $arrHeader = explode("\r\n", $sHeader);
  4288. } else {
  4289. $arrHeader = explode("\n", $sHeader);
  4290. }
  4291. for ($j = 0; $j < count($arrHeader); $j++) {
  4292. $i = strpos($arrHeader[$j], ":");
  4293. if ($i > 0) {
  4294. $sName = trim(substr($arrHeader[$j], 0, $i));
  4295. $sValue = trim(substr($arrHeader[$j], $i+1, strlen($arrHeader[$j])));
  4296. switch (strtolower($sName))
  4297. {
  4298. case "subject":
  4299. $this->Subject = $sValue;
  4300. break;
  4301. case "from":
  4302. $this->Sender = $sValue;
  4303. break;
  4304. case "to":
  4305. $this->Recipient = $sValue;
  4306. break;
  4307. case "cc":
  4308. $this->Cc = $sValue;
  4309. break;
  4310. case "bcc":
  4311. $this->Bcc = $sValue;
  4312. break;
  4313. case "format":
  4314. $this->Format = $sValue;
  4315. break;
  4316. }
  4317. }
  4318. }
  4319. }
  4320. }
  4321. }
  4322. // Method to replace sender
  4323. function ReplaceSender($ASender) {
  4324. $this->Sender = str_replace('<!--$From-->', $ASender, $this->Sender);
  4325. }
  4326. // Method to replace recipient
  4327. function ReplaceRecipient($ARecipient) {
  4328. $this->Recipient = str_replace('<!--$To-->', $ARecipient, $this->Recipient);
  4329. }
  4330. // Method to add Cc email
  4331. function AddCc($ACc) {
  4332. if ($ACc <> "") {
  4333. if ($this->Cc <> "") $this->Cc .= ";";
  4334. $this->Cc .= $ACc;
  4335. }
  4336. }
  4337. // Method to add Bcc email
  4338. function AddBcc($ABcc) {
  4339. if ($ABcc <> "") {
  4340. if ($this->Bcc <> "") $this->Bcc .= ";";
  4341. $this->Bcc .= $ABcc;
  4342. }
  4343. }
  4344. // Method to replace subject
  4345. function ReplaceSubject($ASubject) {
  4346. $this->Subject = str_replace('<!--$Subject-->', $ASubject, $this->Subject);
  4347. }
  4348. // Method to replace content
  4349. function ReplaceContent($Find, $ReplaceWith) {
  4350. $this->Content = str_replace($Find, $ReplaceWith, $this->Content);
  4351. }
  4352. // Method to send email
  4353. function Send() {
  4354. global $gsEmailErrDesc;
  4355. $result = ewrpt_SendEmail($this->Sender, $this->Recipient, $this->Cc, $this->Bcc,
  4356. $this->Subject, $this->Content, $this->Format, $this->Charset, $this->AttachmentFileName, $this->AttachmentContent);
  4357. $this->SendErrDescription = $gsEmailErrDesc;
  4358. return $result;
  4359. }
  4360. }
  4361. // Include PHPMailer class
  4362. include_once("phpmailer51/class.phpmailer.php");
  4363. // Function to send email
  4364. function ewrpt_SendEmail($sFrEmail, $sToEmail, $sCcEmail, $sBccEmail, $sSubject, $sMail, $sFormat, $sCharset, $sAttachmentFileName = "", $sAttachmentContent = "") {
  4365. global $ReportLanguage, $gsEmailErrDesc;
  4366. $res = FALSE;
  4367. $mail = new PHPMailer();
  4368. $mail->IsSMTP();
  4369. $mail->Host = EWRPT_SMTP_SERVER;
  4370. $mail->SMTPAuth = (EWRPT_SMTP_SERVER_USERNAME <> "" && EWRPT_SMTP_SERVER_PASSWORD <> "");
  4371. $mail->Username = EWRPT_SMTP_SERVER_USERNAME;
  4372. $mail->Password = EWRPT_SMTP_SERVER_PASSWORD;
  4373. $mail->Port = EWRPT_SMTP_SERVER_PORT;
  4374. $mail->From = $sFrEmail;
  4375. $mail->FromName = $sFrEmail;
  4376. $mail->Subject = $sSubject;
  4377. $mail->Body = $sMail;
  4378. if ($sCharset <> "" && strtolower($sCharset) <> "iso-8859-1")
  4379. $mail->CharSet = $sCharset;
  4380. $sToEmail = str_replace(";", ",", $sToEmail);
  4381. $arrTo = explode(",", $sToEmail);
  4382. foreach ($arrTo as $sTo) {
  4383. $mail->AddAddress(trim($sTo));
  4384. }
  4385. if ($sCcEmail <> "") {
  4386. $sCcEmail = str_replace(";", ",", $sCcEmail);
  4387. $arrCc = explode(",", $sCcEmail);
  4388. foreach ($arrCc as $sCc) {
  4389. $mail->AddCC(trim($sCc));
  4390. }
  4391. }
  4392. if ($sBccEmail <> "") {
  4393. $sBccEmail = str_replace(";", ",", $sBccEmail);
  4394. $arrBcc = explode(",", $sBccEmail);
  4395. foreach ($arrBcc as $sBcc) {
  4396. $mail->AddBCC(trim($sBcc));
  4397. }
  4398. }
  4399. if (strtolower($sFormat) == "html") {
  4400. $mail->ContentType = "text/html";
  4401. } else {
  4402. $mail->ContentType = "text/plain";
  4403. }
  4404. if ($sAttachmentContent <> "" && $sAttachmentFileName <> "") {
  4405. $mail->AddStringAttachment($sAttachmentContent, $sAttachmentFileName);
  4406. } else if ($sAttachmentFileName <> "") {
  4407. $mail->AddAttachment($sAttachmentFileName);
  4408. }
  4409. $res = $mail->Send();
  4410. $gsEmailErrDesc = $mail->ErrorInfo;
  4411. // Uncomment to debug
  4412. // var_dump($mail); exit();
  4413. return $res;
  4414. }
  4415. // Load email count
  4416. function ewrpt_LoadEmailCount() {
  4417. // Read from log
  4418. if (EWRPT_EMAIL_WRITE_LOG) {
  4419. $ip = ewrpt_ServerVar("REMOTE_ADDR");
  4420. // Load from database
  4421. if (EWRPT_EMAIL_WRITE_LOG_TO_DATABASE) {
  4422. global $conn;
  4423. $dt1 = date("Y-m-d H:i:s", strtotime("- " . EWRPT_MAX_EMAIL_SENT_PERIOD . "minute"));
  4424. $dt2 = date("Y-m-d H:i:s");
  4425. $sEmailSql = "SELECT COUNT(*) FROM " . ewrpt_QuotedName(EWRPT_EMAIL_LOG_TABLE_NAME) .
  4426. " WHERE " . ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_DATETIME) .
  4427. " BETWEEN " . ewrpt_QuotedValue($dt1, EWRPT_DATATYPE_DATE) . " AND " . ewrpt_QuotedValue($dt2, EWRPT_DATATYPE_DATE) .
  4428. " AND " . ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_IP) .
  4429. " = " . ewrpt_QuotedValue($ip, EWRPT_DATATYPE_STRING);
  4430. $rscnt = $conn->Execute($sEmailSql);
  4431. if ($rscnt) {
  4432. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER] = ($rscnt->RecordCount()>1) ? $rscnt->RecordCount() : $rscnt->fields[0];
  4433. $rscnt->Close();
  4434. } else {
  4435. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER] = 0;
  4436. }
  4437. // Load from log file
  4438. } else {
  4439. $pfx = "email";
  4440. $sTab = "\t";
  4441. $sFolder = EWRPT_UPLOAD_DEST_PATH;
  4442. $randomkey = TEAencrypt(date("Ymd"), EWRPT_RANDOM_KEY);
  4443. $sFn = $pfx . "_" . date("Ymd") . "_" . $randomkey . ".txt";
  4444. $filename = ewrpt_UploadPathEx(TRUE, $sFolder) . $sFn;
  4445. if (file_exists($filename)) {
  4446. $arLines = file($filename);
  4447. $cnt = 0;
  4448. foreach ($arLines as $line) {
  4449. if ($line <> "") {
  4450. list($dtwrk, $ipwrk, $senderwrk, $recipientwrk, $subjectwrk, $messagewrk) = explode($sTab, $line);
  4451. $timediff = intval((strtotime("now") - strtotime($dtwrk,0))/60);
  4452. if ($ipwrk == $ip && $timediff < EWRPT_MAX_EMAIL_SENT_PERIOD) $cnt++;
  4453. }
  4454. }
  4455. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER] = $cnt;
  4456. } else {
  4457. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER] = 0;
  4458. }
  4459. }
  4460. }
  4461. if (!isset($_SESSION[EWRPT_EXPORT_EMAIL_COUNTER]))
  4462. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER] = 0;
  4463. return intval($_SESSION[EWRPT_EXPORT_EMAIL_COUNTER]);
  4464. }
  4465. // Add email log
  4466. function ewrpt_AddEmailLog($sender, $recipient, $subject, $message) {
  4467. $_SESSION[EWRPT_EXPORT_EMAIL_COUNTER]++;
  4468. // Save to email log
  4469. if (EWRPT_EMAIL_WRITE_LOG) {
  4470. $dt = date("Y-m-d H:i:s");
  4471. $ip = ewrpt_ServerVar("REMOTE_ADDR");
  4472. $senderwrk = ewrpt_TruncateText($sender);
  4473. $recipientwrk = ewrpt_TruncateText($recipient);
  4474. $subjectwrk = ewrpt_TruncateText($subject);
  4475. $messagewrk = ewrpt_TruncateText($message);
  4476. // Save to database
  4477. if (EWRPT_EMAIL_WRITE_LOG_TO_DATABASE) {
  4478. global $conn;
  4479. $sEmailSql = "INSERT INTO " . ewrpt_QuotedName(EWRPT_EMAIL_LOG_TABLE_NAME) .
  4480. " (" . ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_DATETIME) . ", " .
  4481. ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_IP) . ", " .
  4482. ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_SENDER) . ", " .
  4483. ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_RECIPIENT) . ", " .
  4484. ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_SUBJECT) . ", " .
  4485. ewrpt_QuotedName(EWRPT_EMAIL_LOG_FIELD_NAME_MESSAGE) . ") VALUES (" .
  4486. ewrpt_QuotedValue($dt, EWRPT_DATATYPE_DATE) . ", " .
  4487. ewrpt_QuotedValue($ip, EWRPT_DATATYPE_STRING) . ", " .
  4488. ewrpt_QuotedValue($senderwrk, EWRPT_DATATYPE_STRING) . ", " .
  4489. ewrpt_QuotedValue($recipientwrk, EWRPT_DATATYPE_STRING) . ", " .
  4490. ewrpt_QuotedValue($subjectwrk, EWRPT_DATATYPE_STRING) . ", " .
  4491. ewrpt_QuotedValue($messagewrk, EWRPT_DATATYPE_STRING) . ")";
  4492. $conn->Execute($sEmailSql);
  4493. // Save to log file
  4494. } else {
  4495. $pfx = "email";
  4496. $sTab = "\t";
  4497. $sHeader = "date/time" . $sTab . "ip" . $sTab . "sender" . $sTab . "recipient" . $sTab . "subject" . $sTab . "message";
  4498. $sMsg = $dt . $sTab . $ip . $sTab . $senderwrk . $sTab . $recipientwrk . $sTab . $subjectwrk . $sTab . $messagewrk;
  4499. $sFolder = EWRPT_UPLOAD_DEST_PATH;
  4500. $randomkey = TEAencrypt(date("Ymd"), EWRPT_RANDOM_KEY);
  4501. $sFn = $pfx . "_" . date("Ymd") . "_" . $randomkey . ".txt";
  4502. $filename = ewrpt_UploadPathEx(TRUE, $sFolder) . $sFn;
  4503. if (file_exists($filename)) {
  4504. $fileHandler = fopen($filename, "a+b");
  4505. } else {
  4506. $fileHandler = fopen($filename, "a+b");
  4507. fwrite($fileHandler,$sHeader."\r\n");
  4508. }
  4509. fwrite($fileHandler, $sMsg."\r\n");
  4510. fclose($fileHandler);
  4511. }
  4512. }
  4513. }
  4514. function ewrpt_TruncateText($v) {
  4515. $maxlen = EWRPT_EMAIL_LOG_SIZE_LIMIT;
  4516. $v = str_replace("\r\n", " ", $v);
  4517. $v = str_replace("\t", " ", $v);
  4518. if (strlen($v) > $maxlen)
  4519. $v = substr($v, 0, $maxlen-3) . "...";
  4520. return $v;
  4521. }
  4522. // Read global debug message
  4523. function ewrpt_DebugMsg() {
  4524. global $gsDebugMsg;
  4525. return ($gsDebugMsg <> "") ? "<p>" . $gsDebugMsg . "</p>" : "";
  4526. }
  4527. // Write global debug message
  4528. function ewrpt_SetDebugMsg($v, $newline = TRUE) {
  4529. global $gsDebugMsg;
  4530. if ($newline && $gsDebugMsg <> "")
  4531. $gsDebugMsg .= "<br>";
  4532. $gsDebugMsg .= $v;
  4533. }
  4534. /**
  4535. * Functions for converting encoding
  4536. */
  4537. function ewrpt_ConvertToUtf8($str) {
  4538. return ewrpt_Convert(EWRPT_ENCODING, "UTF-8", $str);
  4539. }
  4540. function ewrpt_ConvertFromUtf8($str) {
  4541. return ewrpt_Convert("UTF-8", EWRPT_ENCODING, $str);
  4542. }
  4543. function ewrpt_Convert($from, $to, $str) {
  4544. if ($from != "" && $to != "" && strtoupper($from) != strtoupper($to)) {
  4545. if (function_exists("iconv")) {
  4546. return iconv($from, $to, $str);
  4547. } elseif (function_exists("mb_convert_encoding")) {
  4548. return mb_convert_encoding($str, $to, $from);
  4549. } else {
  4550. return $str;
  4551. }
  4552. } else {
  4553. return $str;
  4554. }
  4555. }
  4556. // Encode value for single-quoted JavaScript string
  4557. function ewrpt_JsEncode($val) {
  4558. $val = str_replace("\\", "\\\\", strval($val));
  4559. $val = str_replace("'", "\\'", $val);
  4560. $val = str_replace("\r\n", "<br>", $val);
  4561. $val = str_replace("\r", "<br>", $val);
  4562. $val = str_replace("\n", "<br>", $val);
  4563. return $val;
  4564. }
  4565. // Encode value for double-quoted Javascript string
  4566. function ewrpt_JsEncode2($val) {
  4567. $val = str_replace("\\", "\\\\", strval($val));
  4568. $val = str_replace("\"", "\\\"", $val);
  4569. $val = str_replace("\r\n", "<br>", $val);
  4570. $val = str_replace("\r", "<br>", $val);
  4571. $val = str_replace("\n", "<br>", $val);
  4572. return $val;
  4573. }
  4574. // Get current page name
  4575. function ewrpt_CurrentPage() {
  4576. return ewrpt_GetPageName(ewrpt_ScriptName());
  4577. }
  4578. // Get page name
  4579. function ewrpt_GetPageName($url) {
  4580. $PageName = "";
  4581. if ($url <> "") {
  4582. $PageName = $url;
  4583. $p = strpos($PageName, "?");
  4584. if ($p !== FALSE)
  4585. $PageName = substr($PageName, 0, $p); // Remove QueryString
  4586. $p = strrpos($PageName, "/");
  4587. if ($p !== FALSE)
  4588. $PageName = substr($PageName, $p+1); // Remove path
  4589. }
  4590. return $PageName;
  4591. }
  4592. // Adjust text for caption
  4593. function ewrpt_BtnCaption($Caption) {
  4594. $Min = 10;
  4595. if (strlen($Caption) < $Min) {
  4596. $Pad = abs(intval(($Min - strlen($Caption))/2*-1));
  4597. $Caption = str_repeat(" ", $Pad) . $Caption . str_repeat(" ", $Pad);
  4598. }
  4599. return $Caption;
  4600. }
  4601. // Get script name (function name is prefix with "ew_" only for compatibility with PHPMaker)
  4602. function ew_ScriptName() {
  4603. $sn = ewrpt_ServerVar("PHP_SELF");
  4604. if (empty($sn)) $sn = ewrpt_ServerVar("SCRIPT_NAME");
  4605. if (empty($sn)) $sn = ewrpt_ServerVar("ORIG_PATH_INFO");
  4606. if (empty($sn)) $sn = ewrpt_ServerVar("ORIG_SCRIPT_NAME");
  4607. if (empty($sn)) $sn = ewrpt_ServerVar("REQUEST_URI");
  4608. if (empty($sn)) $sn = ewrpt_ServerVar("URL");
  4609. if (empty($sn)) $sn = "UNKNOWN";
  4610. return $sn;
  4611. }
  4612. // Get server variable by name
  4613. function ewrpt_ServerVar($Name) {
  4614. $str = @$_SERVER[$Name];
  4615. if (empty($str)) $str = @$_ENV[$Name];
  4616. return $str;
  4617. }
  4618. // YUI files host
  4619. function ewrpt_YuiHost() {
  4620. // Use files online
  4621. if (ewrpt_IsHttps()) {
  4622. return "https://ajax.googleapis.com/ajax/libs/yui/2.9.0/";
  4623. } else {
  4624. return "http://yui.yahooapis.com/2.9.0/";
  4625. }
  4626. }
  4627. // jQuery files host
  4628. function ewrpt_jQueryHost() {
  4629. // Use files online
  4630. if (ewrpt_IsHttps()) {
  4631. return "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/";
  4632. } else {
  4633. return "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/";
  4634. }
  4635. }
  4636. // Check if HTTPS
  4637. function ewrpt_IsHttps() {
  4638. return (ewrpt_ServerVar("HTTPS") <> "" && ewrpt_ServerVar("HTTPS") <> "off");
  4639. }
  4640. // Encrypt password
  4641. function ewrpt_EncryptPassword($input, $salt = '') {
  4642. return (strval($salt) <> "") ? md5($input . $salt) . ":" . $salt : md5($input);
  4643. }
  4644. // Compare password
  4645. // Note: If salted, password must be stored in '<hashedstring>:<salt>' format
  4646. function ewrpt_ComparePassword($pwd, $input) {
  4647. @list($crypt, $salt) = explode(":", $pwd, 2);
  4648. if (EWRPT_CASE_SENSITIVE_PASSWORD) {
  4649. if (EWRPT_ENCRYPTED_PASSWORD) {
  4650. return ($pwd == ewrpt_EncryptPassword($input, @$salt));
  4651. } else {
  4652. return ($pwd == $input);
  4653. }
  4654. } else {
  4655. if (EWRPT_ENCRYPTED_PASSWORD) {
  4656. return ($pwd == ewrpt_EncryptPassword(strtolower($input), @$salt));
  4657. } else {
  4658. return (strtolower($pwd) == strtolower($input));
  4659. }
  4660. }
  4661. }
  4662. // Get domain URL
  4663. function ewrpt_DomainUrl() {
  4664. $sUrl = "http";
  4665. $bSSL = (ewrpt_ServerVar("HTTPS") <> "" && ewrpt_ServerVar("HTTPS") <> "off");
  4666. $sPort = strval(ewrpt_ServerVar("SERVER_PORT"));
  4667. $defPort = ($bSSL) ? "443" : "80";
  4668. $sPort = ($sPort == $defPort) ? "" : ":$sPort";
  4669. $sUrl .= ($bSSL) ? "s" : "";
  4670. $sUrl .= "://";
  4671. $sUrl .= ewrpt_ServerVar("SERVER_NAME") . $sPort;
  4672. return $sUrl;
  4673. }
  4674. // Get full URL
  4675. function ewrpt_FullUrl() {
  4676. return ewrpt_DomainUrl() . ewrpt_ScriptName();
  4677. }
  4678. // Get current URL
  4679. function ewrpt_CurrentUrl() {
  4680. $s = ewrpt_ScriptName();
  4681. $q = ewrpt_ServerVar("QUERY_STRING");
  4682. if ($q <> "") $s .= "?" . $q;
  4683. return $s;
  4684. }
  4685. // Convert to full URL
  4686. function ewrpt_ConvertFullUrl($url) {
  4687. if ($url == "") return "";
  4688. if (strpos($url, "://") === FALSE && strpos($url, "\\") === FALSE) {
  4689. $sUrl = ewrpt_FullUrl();
  4690. return substr($sUrl, 0, strrpos($sUrl, "/")+1) . $url;
  4691. } else {
  4692. return $url;
  4693. }
  4694. }
  4695. // Get script name
  4696. function ewrpt_ScriptName() {
  4697. $sn = ewrpt_ServerVar("PHP_SELF");
  4698. if (empty($sn)) $sn = ewrpt_ServerVar("SCRIPT_NAME");
  4699. if (empty($sn)) $sn = ewrpt_ServerVar("ORIG_PATH_INFO");
  4700. if (empty($sn)) $sn = ewrpt_ServerVar("ORIG_SCRIPT_NAME");
  4701. if (empty($sn)) $sn = ewrpt_ServerVar("REQUEST_URI");
  4702. if (empty($sn)) $sn = ewrpt_ServerVar("URL");
  4703. if (empty($sn)) $sn = "UNKNOWN";
  4704. return $sn;
  4705. }
  4706. // Remove XSS
  4707. function ewrpt_RemoveXSS($val) {
  4708. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  4709. // this prevents some character re-spacing such as <java\0script>
  4710. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  4711. $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
  4712. // straight replacements, the user should never need these since they're normal characters
  4713. // 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>
  4714. $search = 'abcdefghijklmnopqrstuvwxyz';
  4715. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  4716. $search .= '1234567890!@#$%^&*()';
  4717. $search .= '~`";:?+/={}[]-_|\'\\';
  4718. for ($i = 0; $i < strlen($search); $i++) {
  4719. // ;? matches the ;, which is optional
  4720. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  4721. // &#x0040 @ search for the hex values
  4722. $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
  4723. // &#00064 @ 0{0,7} matches '0' zero to seven times
  4724. $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
  4725. }
  4726. // now the only remaining whitespace attacks are \t, \n, and \r
  4727. $ra = $GLOBALS["EWRPT_XSS_ARRAY"]; // Note: Customize $EWRPT_XSS_ARRAY in ewrcfg*.php
  4728. $found = true; // keep replacing as long as the previous round replaced something
  4729. while ($found == true) {
  4730. $val_before = $val;
  4731. for ($i = 0; $i < sizeof($ra); $i++) {
  4732. $pattern = '/';
  4733. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  4734. if ($j > 0) {
  4735. $pattern .= '(';
  4736. $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
  4737. $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
  4738. $pattern .= ')?';
  4739. }
  4740. $pattern .= $ra[$i][$j];
  4741. }
  4742. $pattern .= '/i';
  4743. $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
  4744. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  4745. if ($val_before == $val) {
  4746. // no replacements were made, so exit the loop
  4747. $found = false;
  4748. }
  4749. }
  4750. }
  4751. return $val;
  4752. }
  4753. // Load selection from a filter clause
  4754. function ewrpt_LoadSelectionFromFilter(&$fld, $filter, &$sel) {
  4755. $sel = "";
  4756. if ($filter <> "") {
  4757. $sSql = ewrpt_BuildReportSql($fld->SqlSelect, "", "", "", $fld->SqlOrderBy, $filter, "");
  4758. ewrpt_LoadArrayFromSql($sSql, $sel);
  4759. }
  4760. }
  4761. // Build dropdown filter
  4762. function ewrpt_BuildDropDownFilter(&$fld, &$FilterClause, $FldOpr) {
  4763. $FldVal = $fld->DropDownValue;
  4764. $sSql = "";
  4765. if (is_array($FldVal)) {
  4766. foreach ($FldVal as $val) {
  4767. $sWrk = ewrpt_GetDropDownfilter($fld, $val, $FldOpr);
  4768. if ($sWrk <> "") {
  4769. if ($sSql <> "")
  4770. $sSql .= " OR " . $sWrk;
  4771. else
  4772. $sSql = $sWrk;
  4773. }
  4774. }
  4775. } else {
  4776. $sSql = ewrpt_GetDropDownfilter($fld, $FldVal, $FldOpr);
  4777. }
  4778. if ($sSql <> "") {
  4779. if ($FilterClause <> "") $FilterClause = "(" . $FilterClause . ") AND ";
  4780. $FilterClause .= "(" . $sSql . ")";
  4781. }
  4782. }
  4783. function ewrpt_GetDropDownfilter(&$fld, $FldVal, $FldOpr) {
  4784. $FldName = $fld->FldName;
  4785. $FldExpression = $fld->FldExpression;
  4786. $FldDataType = $fld->FldDataType;
  4787. $sWrk = "";
  4788. if ($FldVal == EWRPT_NULL_VALUE) {
  4789. $sWrk = $FldExpression . " IS NULL";
  4790. } elseif ($FldVal == EWRPT_NOT_NULL_VALUE) {
  4791. $sWrk = $FldExpression . " IS NOT NULL";
  4792. } elseif ($FldVal == EWRPT_EMPTY_VALUE) {
  4793. $sWrk = $FldExpression . " = ''";
  4794. } else {
  4795. if (substr($FldVal, 0, 2) == "@@") {
  4796. $sWrk = ewrpt_GetCustomFilter($fld, $FldVal);
  4797. } else {
  4798. if ($FldVal <> "" && $FldVal <> EWRPT_INIT_VALUE && $FldVal <> EWRPT_ALL_VALUE) {
  4799. if ($FldDataType == EWRPT_DATATYPE_DATE && $FldOpr <> "") {
  4800. $sWrk = ewrpt_DateFilterString($FldOpr, $FldVal, $FldDataType);
  4801. } else {
  4802. $sWrk = ewrpt_FilterString("=", $FldVal, $FldDataType);
  4803. }
  4804. }
  4805. if ($sWrk <> "") $sWrk = $FldExpression . $sWrk;
  4806. }
  4807. }
  4808. return $sWrk;
  4809. }
  4810. // Get extended filter
  4811. function ewrpt_BuildExtendedFilter(&$fld, &$FilterClause) {
  4812. $FldName = $fld->FldName;
  4813. $FldExpression = $fld->FldExpression;
  4814. $FldDataType = $fld->FldDataType;
  4815. $FldDateTimeFormat = $fld->FldDateTimeFormat;
  4816. $FldVal1 = $fld->SearchValue;
  4817. $FldOpr1 = $fld->SearchOperator;
  4818. $FldCond = $fld->SearchCondition;
  4819. $FldVal2 = $fld->SearchValue2;
  4820. $FldOpr2 = $fld->SearchOperator2;
  4821. $sWrk = "";
  4822. $FldOpr1 = strtoupper(trim($FldOpr1));
  4823. if ($FldOpr1 == "") $FldOpr1 = "=";
  4824. $FldOpr2 = strtoupper(trim($FldOpr2));
  4825. if ($FldOpr2 == "") $FldOpr2 = "=";
  4826. $wrkFldVal1 = $FldVal1;
  4827. $wrkFldVal2 = $FldVal2;
  4828. if ($FldDataType == EWRPT_DATATYPE_BOOLEAN) {
  4829. if (EWRPT_IS_MSACCESS) {
  4830. if ($wrkFldVal1 <> "") $wrkFldVal1 = ($wrkFldVal1 == "1") ? "True" : "False";
  4831. if ($wrkFldVal2 <> "") $wrkFldVal2 = ($wrkFldVal2 == "1") ? "True" : "False";
  4832. } else {
  4833. //if ($wrkFldVal1 <> "") $wrkFldVal1 = ($wrkFldVal1 == "1") ? EWRPT_TRUE_STRING : EWRPT_FALSE_STRING;
  4834. //if ($wrkFldVal2 <> "") $wrkFldVal2 = ($wrkFldVal2 == "1") ? EWRPT_TRUE_STRING : EWRPT_FALSE_STRING;
  4835. if ($wrkFldVal1 <> "") $wrkFldVal1 = ($wrkFldVal1 == "1") ? "1" : "0";
  4836. if ($wrkFldVal2 <> "") $wrkFldVal2 = ($wrkFldVal2 == "1") ? "1" : "0";
  4837. }
  4838. } elseif ($FldDataType == EWRPT_DATATYPE_DATE) {
  4839. if ($wrkFldVal1 <> "") $wrkFldVal1 = ewrpt_UnFormatDateTime($wrkFldVal1, $FldDateTimeFormat);
  4840. if ($wrkFldVal2 <> "") $wrkFldVal2 = ewrpt_UnFormatDateTime($wrkFldVal2, $FldDateTimeFormat);
  4841. }
  4842. if ($FldOpr1 == "BETWEEN") {
  4843. $IsValidValue = ($FldDataType <> EWRPT_DATATYPE_NUMBER ||
  4844. ($FldDataType == EWRPT_DATATYPE_NUMBER && is_numeric($wrkFldVal1) && is_numeric($wrkFldVal2)));
  4845. if ($wrkFldVal1 <> "" && $wrkFldVal2 <> "" && $IsValidValue)
  4846. $sWrk = $FldExpression . " BETWEEN " . ewrpt_QuotedValue($wrkFldVal1, $FldDataType) .
  4847. " AND " . ewrpt_QuotedValue($wrkFldVal2, $FldDataType);
  4848. } elseif ($FldVal1 == EWRPT_NULL_VALUE || $FldOpr1 == "IS NULL") {
  4849. $sWrk = $FldExpression . " IS NULL";
  4850. } elseif ($FldVal1 == EWRPT_NOT_NULL_VALUE || $FldOpr1 == "IS NOT NULL") {
  4851. $sWrk = $FldExpression . " IS NOT NULL";
  4852. } else {
  4853. $IsValidValue = ($FldDataType <> EWRPT_DATATYPE_NUMBER ||
  4854. ($FldDataType == EWRPT_DATATYPE_NUMBER && is_numeric($wrkFldVal1)));
  4855. if ($wrkFldVal1 <> "" && $IsValidValue && ewrpt_IsValidOpr($FldOpr1, $FldDataType))
  4856. $sWrk = $FldExpression . ewrpt_FilterString($FldOpr1, $wrkFldVal1, $FldDataType);
  4857. $IsValidValue = ($FldDataType <> EWRPT_DATATYPE_NUMBER ||
  4858. ($FldDataType == EWRPT_DATATYPE_NUMBER && is_numeric($wrkFldVal2)));
  4859. if ($wrkFldVal2 <> "" && $IsValidValue && ewrpt_IsValidOpr($FldOpr2, $FldDataType)) {
  4860. if ($sWrk <> "")
  4861. $sWrk .= " " . (($FldCond == "OR") ? "OR" : "AND") . " ";
  4862. $sWrk .= $FldExpression . ewrpt_FilterString($FldOpr2, $wrkFldVal2, $FldDataType);
  4863. }
  4864. }
  4865. if ($sWrk <> "") {
  4866. if ($FilterClause <> "") $FilterClause .= " AND ";
  4867. $FilterClause .= "(" . $sWrk . ")";
  4868. }
  4869. }
  4870. // Return filter string
  4871. function ewrpt_FilterString($FldOpr, $FldVal, $FldType) {
  4872. if ($FldOpr == "LIKE" || $FldOpr == "NOT LIKE") {
  4873. return " " . $FldOpr . " " . ewrpt_QuotedValue("%$FldVal%", $FldType);
  4874. } elseif ($FldOpr == "STARTS WITH") {
  4875. return " LIKE " . ewrpt_QuotedValue("$FldVal%", $FldType);
  4876. } else {
  4877. return " $FldOpr " . ewrpt_QuotedValue($FldVal, $FldType);
  4878. }
  4879. }
  4880. // Return date search string
  4881. function ewrpt_DateFilterString($FldOpr, $FldVal, $FldType) {
  4882. $wrkVal1 = ewrpt_DateVal($FldOpr, $FldVal, 1);
  4883. $wrkVal2 = ewrpt_DateVal($FldOpr, $FldVal, 2);
  4884. if ($wrkVal1 <> "" && $wrkVal2 <> "") {
  4885. return " BETWEEN " . ewrpt_QuotedValue($wrkVal1, $FldType) . " AND " . ewrpt_QuotedValue($wrkVal2, $FldType);
  4886. } else {
  4887. return "";
  4888. }
  4889. }
  4890. /**
  4891. * Validation functions
  4892. */
  4893. // Check date format
  4894. // format: std/us/euro
  4895. function ewrpt_CheckDateEx($value, $format, $sep) {
  4896. if (strval($value) == "") return TRUE;
  4897. while (strpos($value, " ") !== FALSE)
  4898. $value = str_replace(" ", " ", $value);
  4899. $value = trim($value);
  4900. $arDT = explode(" ", $value);
  4901. if (count($arDT) > 0) {
  4902. $wrksep = "\\$sep";
  4903. switch ($format) {
  4904. case "std":
  4905. $pattern = '/^([0-9]{4})' . $wrksep . '([0]?[1-9]|[1][0-2])' . $wrksep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])$/';
  4906. break;
  4907. case "stdshort":
  4908. $pattern = '/^([0-9]{2})' . $wrksep . '([0]?[1-9]|[1][0-2])' . $wrksep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])$/';
  4909. break;
  4910. case "us":
  4911. $pattern = '/^([0]?[1-9]|[1][0-2])' . $wrksep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $wrksep . '([0-9]{4})$/';
  4912. break;
  4913. case "usshort":
  4914. $pattern = '/^([0]?[1-9]|[1][0-2])' . $wrksep . '([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $wrksep . '([0-9]{2})$/';
  4915. break;
  4916. case "euro":
  4917. $pattern = '/^([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $wrksep . '([0]?[1-9]|[1][0-2])' . $wrksep . '([0-9]{4})$/';
  4918. break;
  4919. case "euroshort":
  4920. $pattern = '/^([0]?[1-9]|[1|2][0-9]|[3][0|1])' . $wrksep . '([0]?[1-9]|[1][0-2])' . $wrksep . '([0-9]{2})$/';
  4921. break;
  4922. }
  4923. if (!preg_match($pattern, $arDT[0])) return FALSE;
  4924. $arD = explode(EWRPT_DATE_SEPARATOR, $arDT[0]);
  4925. switch ($format) {
  4926. case "std":
  4927. case "stdshort":
  4928. $sYear = ewrpt_UnformatYear($arD[0]);
  4929. $sMonth = $arD[1];
  4930. $sDay = $arD[2];
  4931. break;
  4932. case "us":
  4933. case "usshort":
  4934. $sYear = ewrpt_UnformatYear($arD[2]);
  4935. $sMonth = $arD[0];
  4936. $sDay = $arD[1];
  4937. break;
  4938. case "euro":
  4939. case "euroshort":
  4940. $sYear = ewrpt_UnformatYear($arD[2]);
  4941. $sMonth = $arD[1];
  4942. $sDay = $arD[0];
  4943. break;
  4944. }
  4945. if (!ewrpt_CheckDay($sYear, $sMonth, $sDay)) return FALSE;
  4946. }
  4947. if (count($arDT) > 1 && !ewrpt_CheckTime($arDT[1])) return FALSE;
  4948. return TRUE;
  4949. }
  4950. // Unformat 2 digit year to 4 digit year
  4951. function ewrpt_UnformatYear($yr) {
  4952. if (strlen($yr) == 2) {
  4953. if ($yr > EWRPT_UNFORMAT_YEAR)
  4954. return "19" . $yr;
  4955. else
  4956. return "20" . $yr;
  4957. } else {
  4958. return $yr;
  4959. }
  4960. }
  4961. // Check Date format (yyyy/mm/dd)
  4962. function ewrpt_CheckDate($value) {
  4963. return ewrpt_CheckDateEx($value, "std", EWRPT_DATE_SEPARATOR);
  4964. }
  4965. // Check Date format (yy/mm/dd)
  4966. function ewrpt_CheckShortDate($value) {
  4967. return ewrpt_CheckDateEx($value, "stdshort", EWRPT_DATE_SEPARATOR);
  4968. }
  4969. // Check US Date format (mm/dd/yyyy)
  4970. function ewrpt_CheckUSDate($value) {
  4971. return ewrpt_CheckDateEx($value, "us", EWRPT_DATE_SEPARATOR);
  4972. }
  4973. // Check US Date format (mm/dd/yy)
  4974. function ewrpt_CheckShortUSDate($value) {
  4975. return ewrpt_CheckDateEx($value, "usshort", EWRPT_DATE_SEPARATOR);
  4976. }
  4977. // Check Euro Date format (dd/mm/yyyy)
  4978. function ewrpt_CheckEuroDate($value) {
  4979. return ewrpt_CheckDateEx($value, "euro", EWRPT_DATE_SEPARATOR);
  4980. }
  4981. // Check Euro Date format (dd/mm/yy)
  4982. function ewrpt_CheckShortEuroDate($value) {
  4983. return ewrpt_CheckDateEx($value, "euroshort", EWRPT_DATE_SEPARATOR);
  4984. }
  4985. // Check day
  4986. function ewrpt_CheckDay($checkYear, $checkMonth, $checkDay) {
  4987. $maxDay = 31;
  4988. if ($checkMonth == 4 || $checkMonth == 6 || $checkMonth == 9 || $checkMonth == 11) {
  4989. $maxDay = 30;
  4990. } elseif ($checkMonth == 2) {
  4991. if ($checkYear % 4 > 0) {
  4992. $maxDay = 28;
  4993. } elseif ($checkYear % 100 == 0 && $checkYear % 400 > 0) {
  4994. $maxDay = 28;
  4995. } else {
  4996. $maxDay = 29;
  4997. }
  4998. }
  4999. return ewrpt_CheckRange($checkDay, 1, $maxDay);
  5000. }
  5001. // Check integer
  5002. function ewrpt_CheckInteger($value) {
  5003. if (strval($value) == "") return TRUE;
  5004. return preg_match('/^\-?\+?[0-9]+$/', $value);
  5005. }
  5006. // Check number range
  5007. function ewrpt_NumberRange($value, $min, $max) {
  5008. if ((!is_null($min) && $value < $min) ||
  5009. (!is_null($max) && $value > $max))
  5010. return FALSE;
  5011. return TRUE;
  5012. }
  5013. // Check number
  5014. function ewrpt_CheckNumber($value) {
  5015. if (strval($value) == "") return TRUE;
  5016. return is_numeric(trim($value));
  5017. }
  5018. // Check range
  5019. function ewrpt_CheckRange($value, $min, $max) {
  5020. if (strval($value) == "") return TRUE;
  5021. if (!ewrpt_CheckNumber($value)) return FALSE;
  5022. return ewrpt_NumberRange($value, $min, $max);
  5023. }
  5024. // Check time
  5025. function ewrpt_CheckTime($value) {
  5026. if (strval($value) == "") return TRUE;
  5027. return preg_match('/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $value);
  5028. }
  5029. // Check US phone number
  5030. function ewrpt_CheckPhone($value) {
  5031. if (strval($value) == "") return TRUE;
  5032. return preg_match('/^\(\d{3}\) ?\d{3}( |-)?\d{4}|^\d{3}( |-)?\d{3}( |-)?\d{4}$/', $value);
  5033. }
  5034. // Check US zip code
  5035. function ewrpt_CheckZip($value) {
  5036. if (strval($value) == "") return TRUE;
  5037. return preg_match('/^\d{5}$|^\d{5}-\d{4}$/', $value);
  5038. }
  5039. // Check credit card
  5040. function ewrpt_CheckCreditCard($value, $type="") {
  5041. if (strval($value) == "") return TRUE;
  5042. $creditcard = array("visa" => "/^4\d{3}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  5043. "mastercard" => "/^5[1-5]\d{2}[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  5044. "discover" => "/^6011[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  5045. "amex" => "/^3[4,7]\d{13}$/",
  5046. "diners" => "/^3[0,6,8]\d{12}$/",
  5047. "bankcard" => "/^5610[ -]?\d{4}[ -]?\d{4}[ -]?\d{4}$/",
  5048. "jcb" => "/^[3088|3096|3112|3158|3337|3528]\d{12}$/",
  5049. "enroute" => "/^[2014|2149]\d{11}$/",
  5050. "switch" => "/^[4903|4911|4936|5641|6333|6759|6334|6767]\d{12}$/");
  5051. if (empty($type)) {
  5052. $match = FALSE;
  5053. foreach ($creditcard as $type => $pattern) {
  5054. if (@preg_match($pattern, $value) == 1) {
  5055. $match = TRUE;
  5056. break;
  5057. }
  5058. }
  5059. return ($match) ? ewrpt_CheckSum($value) : FALSE;
  5060. } else {
  5061. if (!preg_match($creditcard[strtolower(trim($type))], $value)) return FALSE;
  5062. return ewrpt_CheckSum($value);
  5063. }
  5064. }
  5065. // Check sum
  5066. function ewrpt_CheckSum($value) {
  5067. $value = str_replace(array('-',' '), array('',''), $value);
  5068. $checksum = 0;
  5069. for ($i=(2-(strlen($value) % 2)); $i<=strlen($value); $i+=2)
  5070. $checksum += (int)($value[$i-1]);
  5071. for ($i=(strlen($value)%2)+1; $i <strlen($value); $i+=2) {
  5072. $digit = (int)($value[$i-1]) * 2;
  5073. $checksum += ($digit < 10) ? $digit : ($digit-9);
  5074. }
  5075. return ($checksum % 10 == 0);
  5076. }
  5077. // Check US social security number
  5078. function ewrpt_CheckSSC($value) {
  5079. if (strval($value) == "") return TRUE;
  5080. return preg_match('/^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}$/', $value);
  5081. }
  5082. // Check emails
  5083. function ewrpt_CheckEmailList($value, $email_cnt) {
  5084. if (strval($value) == "") return TRUE;
  5085. $emailList = str_replace(",", ";", $value);
  5086. $arEmails = explode(";", $emailList);
  5087. $cnt = count($arEmails);
  5088. if ($cnt > $email_cnt && $email_cnt > 0)
  5089. return FALSE;
  5090. foreach ($arEmails as $email) {
  5091. if (!ewrpt_CheckEmail($email))
  5092. return FALSE;
  5093. }
  5094. return TRUE;
  5095. }
  5096. // Check email
  5097. function ewrpt_CheckEmail($value) {
  5098. if (strval($value) == "") return TRUE;
  5099. //return preg_match('/^[A-Za-z0-9\._\-+]+@[A-Za-z0-9_\-+]+(\.[A-Za-z0-9_\-+]+)+$/', trim($value));
  5100. return preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i', trim($value));
  5101. }
  5102. // Check GUID
  5103. function ewrpt_CheckGUID($value) {
  5104. if (strval($value) == "") return TRUE;
  5105. $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}$/';
  5106. $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}$/';
  5107. return preg_match($p1, $value) || preg_match($p2, $value);
  5108. }
  5109. // Check by preg
  5110. function ewrpt_CheckByRegEx($value, $pattern) {
  5111. if (strval($value) == "") return TRUE;
  5112. return preg_match($pattern, $value);
  5113. }
  5114. /**
  5115. * End Validation functions
  5116. */
  5117. // Upload path
  5118. // If PhyPath is TRUE(1), return physical path on the server
  5119. // If PhyPath is FALSE(0), return relative URL
  5120. function ewrpt_UploadPathEx($PhyPath, $DestPath) {
  5121. if ($PhyPath) {
  5122. $Path = ewrpt_PathCombine(ewrpt_AppRoot(), str_replace("/", EWRPT_PATH_DELIMITER, $DestPath), TRUE);
  5123. } else {
  5124. $Path = EWRPT_ROOT_RELATIVE_PATH;
  5125. $Path = str_replace("\\\\", "/", $Path);
  5126. $Path = str_replace("\\", "/", $Path);
  5127. $Path = ewrpt_PathCombine(ewrpt_IncludeTrailingDelimiter($Path, FALSE), $DestPath, FALSE);
  5128. }
  5129. return ewrpt_IncludeTrailingDelimiter($Path, $PhyPath);
  5130. }
  5131. // Get a temp folder for temp file
  5132. function ewrpt_TmpFolder() {
  5133. $tmpfolder = NULL;
  5134. $folders = array();
  5135. if (EWRPT_IS_WINDOWS) {
  5136. $folders[] = ewrpt_ServerVar("TEMP");
  5137. $folders[] = ewrpt_ServerVar("TMP");
  5138. } else {
  5139. if (EWRPT_UPLOAD_TMP_PATH <> "") $folders[] = ewrpt_AppRoot() . str_replace("/", EWRPT_PATH_DELIMITER, EWRPT_UPLOAD_TMP_PATH);
  5140. $folders[] = '/tmp';
  5141. }
  5142. if (ini_get('upload_tmp_dir')) {
  5143. $folders[] = ini_get('upload_tmp_dir');
  5144. }
  5145. foreach ($folders as $folder) {
  5146. if (!$tmpfolder && is_dir($folder)) {
  5147. $tmpfolder = $folder;
  5148. }
  5149. }
  5150. //if ($tmpfolder) $tmpfolder = ewrpt_IncludeTrailingDelimiter($tmpfolder, TRUE);
  5151. return $tmpfolder;
  5152. }
  5153. // Application root
  5154. function ewrpt_AppRoot() {
  5155. // 1. use root relative path
  5156. if (EWRPT_ROOT_RELATIVE_PATH <> "") {
  5157. $Path = realpath(EWRPT_ROOT_RELATIVE_PATH);
  5158. $Path = str_replace("\\\\", EWRPT_PATH_DELIMITER, $Path);
  5159. }
  5160. // 2. if empty, use the document root if available
  5161. if (empty($Path)) $Path = ewrpt_ServerVar("DOCUMENT_ROOT");
  5162. // 3. if empty, use current folder
  5163. if (empty($Path)) $Path = realpath(".");
  5164. // 4. use custom path, uncomment the following line and enter your path
  5165. // e.g. $Path = 'C:\Inetpub\wwwroot\MyWebRoot'; // Windows
  5166. //$Path = 'enter your path here';
  5167. if (empty($Path)) die("Path of website root unknown.");
  5168. return ewrpt_IncludeTrailingDelimiter($Path, TRUE);
  5169. }
  5170. // Get path relative to application root
  5171. function ewrpt_ServerMapPath($Path) {
  5172. return ewrpt_PathCombine(ewrpt_AppRoot(), $Path, TRUE);
  5173. }
  5174. // Get path relative to a base path
  5175. function ewrpt_PathCombine($BasePath, $RelPath, $PhyPath) {
  5176. $BasePath = ewrpt_RemoveTrailingDelimiter($BasePath, $PhyPath);
  5177. if ($PhyPath) {
  5178. $Delimiter = EWRPT_PATH_DELIMITER;
  5179. $RelPath = str_replace('/', EWRPT_PATH_DELIMITER, $RelPath);
  5180. $RelPath = str_replace('\\', EWRPT_PATH_DELIMITER, $RelPath);
  5181. } else {
  5182. $Delimiter = '/';
  5183. $RelPath = str_replace('\\', '/', $RelPath);
  5184. }
  5185. if ($RelPath == '.' || $RelPath == '..') $RelPath .= $Delimiter;
  5186. $p1 = strpos($RelPath, $Delimiter);
  5187. $Path2 = "";
  5188. while ($p1 !== FALSE) {
  5189. $Path = substr($RelPath, 0, $p1 + 1);
  5190. if ($Path == $Delimiter || $Path == ".$Delimiter") {
  5191. // Skip
  5192. } elseif ($Path == "..$Delimiter") {
  5193. $p2 = strrpos($BasePath, $Delimiter);
  5194. if ($p2 !== FALSE) $BasePath = substr($BasePath, 0, $p2);
  5195. } else {
  5196. $Path2 .= $Path;
  5197. }
  5198. $RelPath = substr($RelPath, $p1+1);
  5199. if ($RelPath === FALSE)
  5200. $RelPath = "";
  5201. $p1 = strpos($RelPath, $Delimiter);
  5202. }
  5203. return ewrpt_IncludeTrailingDelimiter($BasePath, $PhyPath) . $Path2 . $RelPath;
  5204. }
  5205. // Remove the last delimiter for a path
  5206. function ewrpt_RemoveTrailingDelimiter($Path, $PhyPath) {
  5207. $Delimiter = ($PhyPath) ? EWRPT_PATH_DELIMITER : '/';
  5208. while (substr($Path, -1) == $Delimiter)
  5209. $Path = substr($Path, 0, strlen($Path)-1);
  5210. return $Path;
  5211. }
  5212. // Include the last delimiter for a path
  5213. function ewrpt_IncludeTrailingDelimiter($Path, $PhyPath) {
  5214. $Path = ewrpt_RemoveTrailingDelimiter($Path, $PhyPath);
  5215. $Delimiter = ($PhyPath) ? EWRPT_PATH_DELIMITER : '/';
  5216. return $Path . $Delimiter;
  5217. }
  5218. // Create folder
  5219. function ewrpt_CreateFolder($dir, $mode = 0777) {
  5220. if ($dir == "")
  5221. return TRUE;
  5222. if (is_dir($dir) || @mkdir($dir, $mode))
  5223. return TRUE;
  5224. if (!ewrpt_CreateFolder(dirname($dir), $mode))
  5225. return FALSE;
  5226. return @mkdir($dir, $mode);
  5227. }
  5228. // Save file
  5229. function ewrpt_SaveFile($folder, $fn, $filedata) {
  5230. $res = FALSE;
  5231. if (ewrpt_CreateFolder($folder)) {
  5232. if ($handle = fopen($folder . $fn, 'w')) { // P6
  5233. $res = fwrite($handle, $filedata);
  5234. fclose($handle);
  5235. }
  5236. if ($res)
  5237. chmod($folder . $fn, EWRPT_UPLOADED_FILE_MODE);
  5238. }
  5239. return $res;
  5240. }
  5241. // Init array
  5242. function &ewrpt_InitArray($len, $value) {
  5243. if ($len > 0)
  5244. $ar = array_fill(0, $len, $value);
  5245. else
  5246. $ar = array();
  5247. return $ar;
  5248. }
  5249. // Init 2D array
  5250. function &ewrpt_Init2DArray($len1, $len2, $value) {
  5251. return ewrpt_InitArray($len1, ewrpt_InitArray($len2, $value));
  5252. }
  5253. // function to generate random number
  5254. function ewrpt_Random() {
  5255. return mt_rand();
  5256. }
  5257. // Convert string to float
  5258. function ewrpt_StrToFloat($v) {
  5259. $v = str_replace(" ", "", $v);
  5260. if (!EWRPT_USE_DEFAULT_LOCALE) extract(localeconv()); // PHP 4 >= 4.0.5
  5261. if (empty($decimal_point)) $decimal_point = EWRPT_DEFAULT_DECIMAL_POINT;
  5262. $v = str_replace($decimal_point, ".", $v);
  5263. return $v;
  5264. }
  5265. // Convert different data type value
  5266. function ewrpt_Conv($v, $t) {
  5267. switch ($t) {
  5268. case 2:
  5269. case 3:
  5270. case 16:
  5271. case 17:
  5272. case 18:
  5273. case 19: // adSmallInt/adInteger/adTinyInt/adUnsignedTinyInt/adUnsignedSmallInt
  5274. return (is_null($v)) ? NULL : intval($v);
  5275. case 4:
  5276. Case 5:
  5277. case 6:
  5278. case 131:
  5279. case 139: // adSingle/adDouble/adCurrency/adNumeric/adVarNumeric
  5280. return (is_null($v)) ? NULL : (float)$v;
  5281. default:
  5282. return (is_null($v)) ? NULL : $v;
  5283. }
  5284. }
  5285. // Convert byte array to binary string
  5286. function ewrpt_BytesToStr($bytes) {
  5287. $str = "";
  5288. foreach ($bytes as $byte)
  5289. $str .= chr($byte);
  5290. return $str;
  5291. }
  5292. // Create temp image file from binary data
  5293. function ewrpt_TmpImage(&$filedata) {
  5294. global $gTmpImages;
  5295. // $f = tempnam(ew_TmpFolder(), "tmp");
  5296. $folder = ewrpt_AppRoot() . EWRPT_UPLOAD_DEST_PATH;
  5297. $f = tempnam($folder, "tmp");
  5298. $handle = fopen($f, 'w+');
  5299. fwrite($handle, $filedata);
  5300. fclose($handle);
  5301. $info = getimagesize($f);
  5302. switch ($info[2]) {
  5303. case 1:
  5304. rename($f, $f .= '.gif'); break;
  5305. case 2:
  5306. rename($f, $f .= '.jpg'); break;
  5307. case 3:
  5308. rename($f, $f .= '.png'); break;
  5309. default:
  5310. return "";
  5311. }
  5312. $tmpimage = basename($f);
  5313. $gTmpImages[] = $tmpimage;
  5314. return EWRPT_UPLOAD_DEST_PATH . $tmpimage;
  5315. }
  5316. // Delete temp images
  5317. function ewrpt_DeleteTmpImages() {
  5318. global $gTmpImages;
  5319. foreach ($gTmpImages as $tmpimage)
  5320. @unlink(ewrpt_AppRoot() . EWRPT_UPLOAD_DEST_PATH . $tmpimage);
  5321. }
  5322. // Create temp file
  5323. function ewrpt_TmpFile($file) {
  5324. global $gTmpImages;
  5325. if (file_exists($file)) { // Copy only
  5326. // $f = tempnam(ew_TmpFolder(), "tmp");
  5327. $folder = ewrpt_AppRoot() . EWRPT_UPLOAD_DEST_PATH;
  5328. $f = tempnam($folder, "tmp");
  5329. @unlink($f);
  5330. $info = pathinfo($file);
  5331. if ($info["extension"] <> "")
  5332. $f .= "." . $info["extension"];
  5333. copy($file, $f);
  5334. $tmpimage = basename($f);
  5335. $gTmpImages[] = $tmpimage;
  5336. return EWRPT_UPLOAD_DEST_PATH . $tmpimage;
  5337. } else {
  5338. return "";
  5339. }
  5340. }
  5341. ?>
  5342. <?php
  5343. /**
  5344. * Functions for image resize
  5345. */
  5346. // Resize binary to thumbnail
  5347. function ewrpt_ResizeBinary($filedata, &$width, &$height, $quality) {
  5348. return TRUE; // No resize
  5349. }
  5350. // Resize file to thumbnail file
  5351. function ewrpt_ResizeFile($fn, $tn, &$width, &$height, $quality) {
  5352. if (file_exists($fn)) { // Copy only
  5353. return ($fn <> $tn) ? copy($fn, $tn) : TRUE;
  5354. } else {
  5355. return FALSE;
  5356. }
  5357. }
  5358. // Resize file to binary
  5359. function ewrpt_ResizeFileToBinary($fn, &$width, &$height, $quality) {
  5360. return file_get_contents($fn); // Return original file content only
  5361. }
  5362. ?>