PageRenderTime 57ms CodeModel.GetById 23ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 1ms

/osj-phpfn50.php

http://osjobber.googlecode.com/
PHP | 2162 lines | 1655 code | 229 blank | 278 comment | 504 complexity | 14591bd150a92ab839234598b74f953c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2
   3/**
   4 * PHPMaker functions and classes
   5 * (C) 2002-2007 e.World Technology Limited. All rights reserved.
   6*/
   7
   8/**
   9 * Functions to init arrays
  10 */
  11
  12function ew_InitArray($iLen, $vValue) {
  13	if (function_exists('array_fill')) { // PHP 4 >= 4.2.0,
  14		return array_fill(0, $iLen, $vValue);
  15	} else {
  16		$aResult = array();
  17		for ($iCount = 0; $iCount < $iLen; $iCount++)
  18			$aResult[] = $vValue;
  19		return $aResult;
  20	}
  21}
  22
  23function ew_Init2DArray($iLen1, $iLen2, $vValue) {
  24	return ew_InitArray($iLen1, ew_InitArray($iLen2, $vValue));
  25}
  26
  27/**
  28 * Functions for converting encoding
  29 */
  30
  31function ew_ConvertToUtf8($str) {
  32	return ew_Convert(EW_ENCODING, "UTF-8", $str);
  33}
  34
  35function ew_ConvertFromUtf8($str) {
  36	return ew_Convert("UTF-8", EW_ENCODING, $str);
  37}
  38
  39function ew_Convert($from, $to, $str)
  40{
  41	if ($from != "" && $to != "" && $from != $to) {
  42		if (function_exists("iconv")) {
  43			return iconv($from, $to, $str);
  44		} elseif (function_exists("mb_convert_encoding")) {
  45			return mb_convert_encoding($str, $to, $from);
  46		} else {
  47			return $str;
  48		}
  49	} else {
  50	return $str;
  51	}
  52}
  53
  54/**
  55 * XML document class
  56 */
  57
  58class cXMLDocument {
  59	var $Encoding = EW_XML_ENCODING;
  60	var $RootTagName  = 'table';
  61	var $RowTagName = 'row';
  62	var $XmlDoc;
  63	var $XmlTbl;
  64	var $XmlRow;
  65	var $XML = '';
  66	var $NullValue = 'NULL';
  67
  68	function cXMLDocument() {
  69		if (EW_IS_PHP5) {
  70			$this->XmlDoc = new DOMDocument("1.0", $this->Encoding);
  71			$this->XmlTbl = $this->XmlDoc->createElement($this->RootTagName);
  72			$this->XmlDoc->appendChild($this->XmlTbl);
  73		}
  74	}
  75
  76	function BeginRow() {
  77		if (EW_IS_PHP5) {
  78			$this->XmlRow = $this->XmlDoc->createElement($this->RowTagName);
  79			$this->XmlTbl->appendChild($this->XmlRow);
  80		} else {
  81			$this->XML .= "<$this->RowTagName>";
  82		}
  83	}
  84
  85	function EndRow() {
  86		if (!EW_IS_PHP5) {
  87			$this->XML .= "</$this->RowTagName>";
  88		}
  89	}
  90
  91	function AddField($name, $value) {
  92		if (is_null($value)) $value = $this->NullValue;
  93		if (EW_IS_PHP5) {
  94			$value = ew_ConvertToUtf8($value); // Convert to UTF-8
  95			$xmlfld = $this->XmlDoc->createElement($name);
  96			$this->XmlRow->appendChild($xmlfld);
  97			$xmlfld->appendChild($this->XmlDoc->createTextNode($value));
  98		} else {
  99			$value = ew_Convert(EW_ENCODING, EW_XML_ENCODING, $value); // Convert to output encoding
 100			$this->XML .= "<$name>" . htmlspecialchars($value) . "</$name>";
 101		}
 102	}
 103
 104	function XML() {
 105		if (EW_IS_PHP5) {
 106			return $this->XmlDoc->saveXML();
 107		} else {
 108			return "<?xml version=\"1.0\"". (($this->Encoding <> "") ? " encoding=\"$this->Encoding\"" : "") .
 109				" ?>\n<$this->RootTagName>$this->XML</$this->RootTagName>";
 110		}
 111	}
 112}
 113
 114/**
 115 * QueryString class
 116 */
 117
 118class cQueryString {
 119	var $values = array();
 120	var $Count;
 121
 122	function cQueryString() {
 123		$ar = explode("&", ew_ServerVar("QUERY_STRING"));
 124		foreach ($ar as $p) {
 125			$arp = explode("=", $p);
 126			if (count($arp) == 2) $this->values[urldecode($arp[0])] = $arp[1];
 127		}
 128		$this->Count = count($this->values);
 129	}
 130
 131	function getValue($name) {
 132		return (array_key_exists($name, $this->values)) ? $this->values[$name] : "";
 133	}
 134
 135	function getUrlDecodedValue($name) {
 136		return urldecode($this->getValue($name));
 137	}
 138
 139	function getRawUrlDecodedValue($name) {
 140		return rawurldecode($this->getValue($name));
 141	}
 142
 143	function getConvertedValue($name) {
 144		return ew_ConvertFromUtf8($this->getRawUrlDecodedValue($name));
 145	}
 146}
 147
 148/**
 149 * Email class
 150 */
 151
 152class cEmail {
 153
 154	// Class properties
 155	var $Sender; // Sender
 156	var $Recipient; // Recipient
 157	var $Cc; // Cc
 158	var $Bcc; // Bcc
 159	var $Subject; // Subject
 160	var $Format; // Format
 161	var $Content; // Content
 162
 163	function cEmail() {
 164		$this->Sender = "";
 165		$this->Recipient = "";
 166		$this->Cc = "";
 167		$this->Bcc = "";
 168		$this->Subject = "";
 169		$this->Format = "";
 170		$this->Content = "";
 171	}
 172
 173	// Method to load email from template
 174	function Load($fn) {
 175		$fn = realpath(".") . EW_PATH_DELIMITER . $fn;
 176		$sWrk = ew_ReadFile($fn); // Load text file content
 177		if ($sWrk <> "") {
 178
 179			// Locate Header & Mail Content
 180			if (EW_IS_WINDOWS) {
 181				$i = strpos($sWrk, "\r\n\r\n");
 182			} else {
 183				$i = strpos($sWrk, "\n\n");
 184				if ($i === FALSE) $i = strpos($sWrk, "\r\n\r\n");
 185			}
 186			if ($i > 0) {
 187				$sHeader = substr($sWrk, 0, $i);
 188				$this->Content = trim(substr($sWrk, $i, strlen($sWrk)));
 189				if (EW_IS_WINDOWS) {
 190					$arrHeader = explode("\r\n", $sHeader);
 191				} else {
 192					$arrHeader = explode("\n", $sHeader);
 193				}
 194				for ($j = 0; $j < count($arrHeader); $j++) {
 195					$i = strpos($arrHeader[$j], ":");
 196					if ($i > 0) {
 197						$sName = trim(substr($arrHeader[$j], 0, $i));
 198						$sValue = trim(substr($arrHeader[$j], $i+1, strlen($arrHeader[$j])));
 199						switch (strtolower($sName))
 200						{
 201							case "subject":
 202								$this->Subject = $sValue;
 203								break;
 204							case "from":
 205								$this->Sender = $sValue;
 206								break;
 207							case "to":
 208								$this->Recipient = $sValue;
 209								break;
 210							case "cc":
 211								$this->Cc = $sValue;
 212								break;
 213							case "bcc":
 214								$this->Bcc = $sValue;
 215								break;
 216							case "format":
 217								$this->Format = $sValue;
 218								break;
 219						}
 220					}
 221				}
 222			}
 223		}
 224	}
 225
 226	// Method to replace sender
 227	function ReplaceSender($ASender) {
 228		$this->Sender = str_replace('<!--$From-->', $ASender, $this->Sender);
 229	}
 230
 231	// Method to replace recipient
 232	function ReplaceRecipient($ARecipient) {
 233		$this->Recipient = str_replace('<!--$To-->', $ARecipient, $this->Recipient);
 234	}
 235
 236	// Method to add Cc email
 237	function AddCc($ACc) {
 238		if ($ACc <> "") {
 239			if ($this->Cc <> "") $this->Cc .= ";";
 240			$this->Cc .= $ACc;
 241		}
 242	}
 243
 244	// Method to add Bcc email
 245	function AddBcc($ABcc) {
 246		if ($ABcc <> "")  {
 247			if ($this->Bcc <> "") $this->Bcc .= ";";
 248			$this->Bcc .= $ABcc;
 249		}
 250	}
 251
 252	// Method to replace subject
 253	function ReplaceSubject($ASubject) {
 254		$this->Subject = str_replace('<!--$Subject-->', $ASubject, $this->Subject);
 255	}
 256
 257	// Method to replace content
 258	function ReplaceContent($Find, $ReplaceWith) {
 259		$this->Content = str_replace($Find, $ReplaceWith, $this->Content);
 260	}
 261
 262	// Method to send email
 263	function Send() {
 264		return ew_SendEmail($this->Sender, $this->Recipient, $this->Cc, $this->Bcc,
 265			$this->Subject, $this->Content, $this->Format);
 266	}
 267}
 268
 269/**
 270 * Pager item class
 271 */
 272
 273class cPagerItem {
 274	var $Start;
 275	var $Text;
 276	var $Enabled;
 277}
 278
 279/**
 280 * Numeric pager class
 281 */
 282
 283class cNumericPager {
 284	var $Items = array();
 285	var $Count, $FromIndex, $ToIndex, $RecordCount, $PageSize, $Range;
 286	var $FirstButton, $PrevButton, $NextButton, $LastButton;
 287	var $ButtonCount = 0;
 288
 289	function cNumericPager($StartRec, $DisplayRecs, $TotalRecs, $RecRange)
 290	{
 291		$this->FirstButton = new cPagerItem;
 292		$this->PrevButton = new cPagerItem;
 293		$this->NextButton = new cPagerItem;
 294		$this->LastButton = new cPagerItem;
 295    $this->FromIndex = intval($StartRec);
 296		$this->PageSize = intval($DisplayRecs);
 297		$this->RecordCount = intval($TotalRecs);
 298		$this->Range = intval($RecRange);
 299		if ($this->PageSize == 0) return;
 300		if ($this->FromIndex > $this->RecordCount)
 301			$this->FromIndex = $this->RecordCount;
 302		$this->ToIndex = $this->FromIndex + $this->PageSize - 1;
 303		if ($this->ToIndex > $this->RecordCount)
 304			$this->ToIndex = $this->RecordCount;
 305
 306		// setup
 307		$this->SetupNumericPager();
 308
 309		// update button count
 310		if ($this->FirstButton->Enabled) $this->ButtonCount++;
 311		if ($this->PrevButton->Enabled) $this->ButtonCount++;
 312		if ($this->NextButton->Enabled) $this->ButtonCount++;
 313		if ($this->LastButton->Enabled) $this->ButtonCount++;
 314		$this->ButtonCount += count($this->Items);
 315  }
 316
 317	// Add pager item
 318	function AddPagerItem($StartIndex, $Text, $Enabled)
 319	{
 320		$Item = new cPagerItem;
 321		$Item->Start = $StartIndex;
 322		$Item->Text = $Text;
 323		$Item->Enabled = $Enabled;
 324		$this->Items[] = $Item;
 325	}
 326
 327	// Setup pager items
 328	function SetupNumericPager()
 329	{
 330		if ($this->RecordCount > $this->PageSize) {
 331			$Eof = ($this->RecordCount < ($this->FromIndex + $this->PageSize));
 332			$HasPrev = ($this->FromIndex > 1);
 333
 334			// First Button
 335			$TempIndex = 1;
 336			$this->FirstButton->Start = $TempIndex;
 337			$this->FirstButton->Enabled = ($this->FromIndex > $TempIndex);
 338
 339			// Prev Button
 340			$TempIndex = $this->FromIndex - $this->PageSize;
 341			if ($TempIndex < 1) $TempIndex = 1;
 342			$this->PrevButton->Start = $TempIndex;
 343			$this->PrevButton->Enabled = $HasPrev;
 344
 345			// Page links
 346			if ($HasPrev || !$Eof) {
 347				$x = 1;
 348				$y = 1;
 349				$dx1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->PageSize*$this->Range + 1;
 350				$dy1 = intval(($this->FromIndex-1)/($this->PageSize*$this->Range))*$this->Range + 1;
 351				if (($dx1+$this->PageSize*$this->Range-1) > $this->RecordCount) {
 352					$dx2 = intval($this->RecordCount/$this->PageSize)*$this->PageSize + 1;
 353					$dy2 = intval($this->RecordCount/$this->PageSize) + 1;
 354				} else {
 355					$dx2 = $dx1 + $this->PageSize*$this->Range - 1;
 356					$dy2 = $dy1 + $this->Range - 1;
 357				}
 358				while ($x <= $this->RecordCount) {
 359					if ($x >= $dx1 && $x <= $dx2) {
 360						$this->AddPagerItem($x, $y, $this->FromIndex<>$x);
 361						$x += $this->PageSize;
 362						$y++;
 363					} elseif ($x >= ($dx1-$this->PageSize*$this->Range) && $x <= ($dx2+$this->PageSize*$this->Range)) {
 364						if ($x+$this->Range*$this->PageSize < $this->RecordCount) {
 365							$this->AddPagerItem($x, $y . "-" . ($y+$this->Range-1), TRUE);
 366						} else {
 367							$ny = intval(($this->RecordCount-1)/$this->PageSize) + 1;
 368							if ($ny == $y) {
 369								$this->AddPagerItem($x, $y, TRUE);
 370							} else {
 371								$this->AddPagerItem($x, $y . "-" . $ny, TRUE);
 372							}
 373						}
 374						$x += $this->Range*$this->PageSize;
 375						$y += $this->Range;
 376					} else {
 377						$x += $this->Range*$this->PageSize;
 378						$y += $this->Range;
 379					}
 380				}
 381			}
 382
 383			// Next Button
 384			$TempIndex = $this->FromIndex + $this->PageSize;
 385			$this->NextButton->Start = $TempIndex;
 386			$this->NextButton->Enabled = !$Eof;
 387
 388			// Last Button
 389			$TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
 390			$this->LastButton->Start = $TempIndex;
 391			$this->LastButton->Enabled = ($this->FromIndex < $TempIndex);
 392		}
 393	}
 394}
 395
 396/**
 397 * PrevNext pager class
 398 */
 399
 400class cPrevNextPager {
 401	var $FirstButton, $PrevButton, $NextButton, $LastButton;
 402	var $CurrentPage, $PageCount, $FromIndex, $ToIndex, $RecordCount;
 403
 404	function cPrevNextPager($StartRec, $DisplayRecs, $TotalRecs)
 405	{
 406		$this->FirstButton = new cPagerItem;
 407		$this->PrevButton = new cPagerItem;
 408		$this->NextButton = new cPagerItem;
 409		$this->LastButton = new cPagerItem;
 410		$this->FromIndex = intval($StartRec);
 411		$this->PageSize = intval($DisplayRecs);
 412		$this->RecordCount = intval($TotalRecs);
 413		if ($this->PageSize == 0) return;
 414		$this->CurrentPage = intval(($this->FromIndex-1)/$this->PageSize) + 1;
 415		$this->PageCount = intval(($this->RecordCount-1)/$this->PageSize) + 1;
 416		if ($this->FromIndex > $this->RecordCount)
 417			$this->FromIndex = $this->RecordCount;
 418		$this->ToIndex = $this->FromIndex + $this->PageSize - 1;
 419		if ($this->ToIndex > $this->RecordCount)
 420			$this->ToIndex = $this->RecordCount;
 421
 422		// First Button
 423		$TempIndex = 1;
 424		$this->FirstButton->Start = $TempIndex;
 425		$this->FirstButton->Enabled = ($TempIndex <> $this->FromIndex);
 426
 427		// Prev Button
 428		$TempIndex = $this->FromIndex - $this->PageSize;
 429		if ($TempIndex < 1) $TempIndex = 1;
 430		$this->PrevButton->Start = $TempIndex;
 431		$this->PrevButton->Enabled = ($TempIndex <> $this->FromIndex);
 432
 433		// Next Button
 434		$TempIndex = $this->FromIndex + $this->PageSize;
 435		if ($TempIndex > $this->RecordCount)
 436			$TempIndex = $this->FromIndex;
 437		$this->NextButton->Start = $TempIndex;
 438		$this->NextButton->Enabled = ($TempIndex <> $this->FromIndex);
 439
 440		// Last Button
 441		$TempIndex = intval(($this->RecordCount-1)/$this->PageSize)*$this->PageSize + 1;
 442		$this->LastButton->Start = $TempIndex;
 443		$this->LastButton->Enabled = ($TempIndex <> $this->FromIndex);
 444  }
 445}
 446
 447/**
 448 * Field class
 449 */
 450
 451class cField {
 452	var $TblVar; // Table var
 453	var $FldName; // Field name
 454	var $FldVar; // Field var
 455	var $FldExpression; // Field expression (used in sql)
 456	var $FldType; // Field type
 457	var $FldDataType; // PHPMaker Field type
 458	var $AdvancedSearch; // AdvancedSearch Object
 459	var $Upload; // Upload Object
 460	var $FldDateTimeFormat; // Date time format
 461	var $CssStyle; // Css style
 462	var $CssClass; // Css class
 463	var $ImageAlt; // Image alt
 464	var $ImageWidth = 0; // Image width
 465	var $ImageHeight = 0; // Image height
 466	var $ViewCustomAttributes; // View custom attributes
 467	var $EditCustomAttributes; // Edit custom attributes
 468	var $Count; // Count
 469	var $Total; // Total
 470	var $TrueValue = '1';
 471	var $FalseValue = '0';
 472
 473	function cField($tblvar, $fldvar, $fldname, $fldexpression, $fldtype, $flddtfmt, $upload = FALSE) {
 474		$this->TblVar = $tblvar;
 475		$this->FldVar = $fldvar;
 476		$this->FldName = $fldname;
 477		$this->FldExpression = $fldexpression;
 478		$this->FldType = $fldtype;
 479		$this->FldDataType = ew_FieldDataType($fldtype);
 480		$this->FldDateTimeFormat = $flddtfmt;
 481		$this->AdvancedSearch = new cAdvancedSearch();
 482		if ($upload) $this->Upload = new cUpload($this->TblVar, $this->FldVar, ($this->FldDataType == EW_DATATYPE_BLOB));
 483	}
 484
 485	// View Attributes
 486	function ViewAttributes() {
 487		$sAtt = "";
 488		if (trim($this->CssStyle) <> "") {
 489			$sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
 490		}
 491		if (trim($this->CssClass) <> "") {
 492			$sAtt .= " class=\"" . trim($this->CssClass) . "\"";
 493		}
 494		if (trim($this->ImageAlt) <> "") {
 495			$sAtt .= " alt=\"" . trim($this->ImageAlt) . "\"";
 496		}
 497		if (intval($this->ImageWidth) > 0) {
 498			$sAtt .= " width=\"" . intval($this->ImageWidth) . "\"";
 499		}
 500		if (intval($this->ImageHeight) > 0) {
 501			$sAtt .= " height=\"" . intval($this->ImageHeight) . "\"";
 502		}
 503		if (trim($this->ViewCustomAttributes) <> "") {
 504			$sAtt .= " " . trim($this->ViewCustomAttributes);
 505		}
 506		return $sAtt;
 507	}
 508
 509	// Edit Attributes
 510	function EditAttributes() {
 511		$sAtt = "";
 512		if (trim($this->CssStyle) <> "") {
 513			$sAtt .= " style=\"" . trim($this->CssStyle) . "\"";
 514		}
 515		if (trim($this->CssClass) <> "") {
 516			$sAtt .= " class=\"" . trim($this->CssClass) . "\"";
 517		}
 518		if (trim($this->EditCustomAttributes) <> "") {
 519			$sAtt .= " " . trim($this->EditCustomAttributes);
 520		}
 521		return $sAtt;
 522	}
 523	var $CellCssClass; // Cell Css class
 524	var $CellCssStyle; // Cell Css style
 525
 526	// Cell Attributes
 527	function CellAttributes() {
 528		$sAtt = "";
 529		if (trim($this->CellCssStyle) <> "") {
 530			$sAtt .= " style=\"" . trim($this->CellCssStyle) . "\"";
 531		}
 532		if (trim($this->CellCssClass) <> "") {
 533			$sAtt .= " class=\"" . trim($this->CellCssClass) . "\"";
 534		}
 535		return $sAtt;
 536	}
 537
 538	// Sort Attributes
 539	function getSort() {
 540		return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar];
 541	}
 542
 543	function setSort($v) {
 544		if (@$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] <> $v) {
 545			$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . EW_TABLE_SORT . "_" . $this->FldVar] = $v;
 546		}
 547	}
 548
 549	function ReverseSort() {
 550		return ($this->getSort() == "ASC") ? "DESC" : "ASC";
 551	}
 552	var $MultiUpdate; // Multi update
 553	var $CurrentValue; // Current value
 554	var $ViewValue; // View value
 555	var $EditValue; // Edit value
 556	var $EditValue2; // Edit value 2 (search)
 557	var $HrefValue; // Href value
 558
 559	// Form value
 560	var $FormValue;
 561
 562	function setFormValue($v) {
 563		$this->FormValue = ew_StripSlashes($v);
 564		if (is_array($this->FormValue)) $this->FormValue = implode(",", $this->FormValue);
 565		$this->CurrentValue = $this->FormValue;
 566	}
 567
 568	// QueryString value
 569	var $QueryStringValue;
 570
 571	function setQueryStringValue($v) {
 572		$this->QueryStringValue = ew_StripSlashes($v);
 573		$this->CurrentValue = $this->QueryStringValue;
 574	}
 575
 576	// Database Value
 577	var $DbValue;
 578
 579	function setDbValue($v) {
 580		$this->DbValue = $v;
 581		$this->CurrentValue = $this->DbValue;
 582	}
 583
 584	// Set database value with error default
 585	function SetDbValueDef($value, $default) {
 586		switch ($this->FldType) {
 587			case 2:
 588			case 3:
 589			case 16:
 590			case 17:
 591			case 18:  // Int
 592				$value = trim($value);
 593				$DbValue = (is_numeric($value)) ? intval($value) : $default;
 594				break;
 595			case 19:
 596			case 20:
 597			case 21: // Big Int
 598				$value = trim($value);
 599				$DbValue = (is_numeric($value)) ? $value : $default;
 600				break;
 601			case 5:
 602			case 6:
 603			case 14:
 604			case 131: // Double
 605			case 4: // Single
 606				$value = trim($value);
 607				if (function_exists('floatval')) { // PHP 4 >= 4.2.0
 608					$DbValue = (is_numeric($value)) ? floatval($value) : $default;
 609				} else {
 610					$DbValue = (is_numeric($value)) ? (float)$value : $default;
 611				}
 612				break;
 613			case 7:
 614			case 133:
 615			case 134:
 616			case 135: //Date
 617			case 201:
 618			case 203:
 619			case 129:
 620			case 130:
 621			case 200:
 622			case 202: // String
 623				$value = trim($value);
 624				$DbValue = ($value == "") ? $default : $value;
 625				break;
 626			case 128:
 627			case 204:
 628			case 205: // Binary
 629				$DbValue = is_null($value) ? $default : $value;
 630				break;
 631			case 72: // GUID
 632				$value = trim($value);
 633				if (function_exists('preg_match')) {
 634					$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}$/';
 635					$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}$/';
 636					$DbValue = (preg_match($p1, $value) || preg_match($p2, $value)) ? $value : $default;
 637				} else {
 638					$DbValue = (is_string($value) && ((strlen($value) == 38 && strspn($value, '{}-0123456789abcdefABCDEF') == 38)) ||
 639						(strlen($value) == 36 && strspn($value, '-0123456789abcdefABCDEF') == 36)) ? $value : $default;
 640				}
 641				break;
 642			default:
 643				$DbValue = $value;
 644		}
 645		$this->setDbValue($DbValue);
 646	}
 647
 648	// Session Value
 649	function getSessionValue() {
 650		return @$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"];
 651	}
 652
 653	function setSessionValue($v) {
 654		$_SESSION[EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_SessionValue"] = $v;
 655	}
 656}
 657?>
 658<?php
 659
 660/**
 661 * Advanced Search class
 662 */
 663
 664class cAdvancedSearch {
 665	var $SearchValue; // Search value
 666	var $SearchOperator; // Search operator
 667	var $SearchCondition; // Search condition
 668	var $SearchValue2; // Search value 2
 669	var $SearchOperator2; // Search operator 2
 670}
 671?>
 672<?php
 673
 674/**
 675 * Upload class
 676 */
 677
 678class cUpload {
 679	var $Index = 0; // Index to handle multiple form elements
 680	var $TblVar; // Table variable
 681	var $FldVar; // Field variable
 682	var $Message; // Error message
 683	var $DbValue; // Value from database
 684	var $Value = NULL; // Upload value
 685	var $Binary = NULL; // Temporary file
 686	var $IsBinary; // Is BLOB field
 687	var $Action; // Upload action
 688	var $UploadPath; // Upload path
 689	var $FileName; // Upload file name
 690	var $FileSize; // Upload file size
 691	var $ContentType; // File content type
 692	var $ImageWidth; // Image width
 693	var $ImageHeight; // Image height	
 694
 695	// Class initialize
 696	function cUpload($TblVar, $FldVar, $Binary = FALSE) {
 697		$this->TblVar = $TblVar;
 698		$this->FldVar = $FldVar;
 699		$this->IsBinary = $Binary;
 700	}
 701
 702	function getSessionID() {
 703		return EW_PROJECT_NAME . "_" . $this->TblVar . "_" . $this->FldVar . "_" . $this->Index;
 704	}
 705
 706	// Save Db value to Session
 707	function SaveDbToSession() {
 708		$sSessionID = $this->getSessionID();
 709		$_SESSION[$sSessionID . "_DbValue"] = $this->DbValue;
 710	}
 711
 712	// Restore Db value from Session
 713	function RestoreDbFromSession() {
 714		$sSessionID = $this->getSessionID();
 715		$this->DbValue = @$_SESSION[$sSessionID . "_DbValue"];
 716	}
 717
 718	// Remove Db value from Session
 719	function RemoveDbFromSession() {
 720		$sSessionID = $this->getSessionID();
 721		unset($_SESSION[$sSessionID . "_DbValue"]);
 722	}
 723
 724	// Save Upload values to Session
 725	function SaveToSession() {
 726		$sSessionID = $this->getSessionID();
 727		$_SESSION[$sSessionID . "_Action"] = $this->Action;
 728		$_SESSION[$sSessionID . "_FileSize"] = $this->FileSize;
 729		$_SESSION[$sSessionID . "_FileName"] = $this->FileName;
 730		$_SESSION[$sSessionID . "_ContentType"] = $this->ContentType;
 731		$_SESSION[$sSessionID . "_ImageWidth"] = $this->ImageWidth;
 732		$_SESSION[$sSessionID . "_ImageHeight"] = $this->ImageHeight;
 733		$path = pathinfo($this->FileName);
 734		$ext = @$path['extension'];
 735		if ($ext == '') $ext = 'tmp';
 736		$f = tempnam(ew_TmpFolder(), 'tmp') . '.' . $ext;
 737		if (!is_null($this->Value)) {
 738			if (@rename($this->Value, $this->Value . '.' . $ext)) {
 739		 		$this->Value .= '.' . $ext;
 740			} elseif (@move_uploaded_file($this->Value, $f)) {
 741				$this->Value = $f;
 742			}
 743		}
 744		$_SESSION[$sSessionID . "_Value"] = $this->Value;
 745	}
 746
 747	// Restore Upload values from Session
 748	function RestoreFromSession() {
 749		$sSessionID = $this->getSessionID();
 750		$this->Action = @$_SESSION[$sSessionID . "_Action"];
 751		$this->FileSize = @$_SESSION[$sSessionID . "_FileSize"];
 752		$this->FileName = @$_SESSION[$sSessionID . "_FileName"];
 753		$this->ContentType = @$_SESSION[$sSessionID . "_ContentType"];
 754		$this->ImageWidth = @$_SESSION[$sSessionID . "_ImageWidth"];
 755		$this->ImageHeight = @$_SESSION[$sSessionID . "_ImageHeight"];
 756		$this->Value = @$_SESSION[$sSessionID . "_Value"];
 757	}
 758
 759	// Remove Upload values from Session
 760	function RemoveFromSession() {
 761		$sSessionID = $this->getSessionID();
 762		unset($_SESSION[$sSessionID . "_Action"]);
 763		unset($_SESSION[$sSessionID . "_FileSize"]);
 764		unset($_SESSION[$sSessionID . "_FileName"]);
 765		unset($_SESSION[$sSessionID . "_ContentType"]);
 766		unset($_SESSION[$sSessionID . "_ImageWidth"]);
 767		unset($_SESSION[$sSessionID . "_ImageHeight"]);
 768		if (is_file($this->Value)) @unlink($this->Value);
 769		unset($_SESSION[$sSessionID . "_Value"]);
 770	}
 771
 772	// function to check the file type of the uploaded file
 773	function UploadAllowedFileExt($filename) {
 774		if (trim($filename) == "") return TRUE;
 775		$extension = substr(strtolower(strrchr($filename, ".")), 1);
 776		$allowExt = explode(",", strtolower(EW_UPLOAD_ALLOWED_FILE_EXT));
 777		return in_array($extension, $allowExt);
 778	}
 779
 780	// Get upload file
 781	function UploadFile() {
 782		global $objForm;
 783		$this->Value = NULL; // Reset first
 784		$sFldVar = $this->FldVar;
 785		$sFldVarAction = "a" . substr($sFldVar, 1);
 786		$sFldVarWidth = "wd" . substr($sFldVar, 1);
 787		$sFldVarHeight = "ht" . substr($sFldVar, 1);
 788
 789		// Get action
 790		$this->Action = $objForm->GetValue($sFldVarAction);
 791
 792		// Get and check the upload file size
 793		$this->FileSize = $objForm->GetUploadFileSize($sFldVar);
 794		if ($this->FileSize > 0 && intval(EW_MAX_FILE_SIZE) > 0) {
 795			if ($this->FileSize > intval(EW_MAX_FILE_SIZE)) {
 796				$this->Message = str_replace("%s", EW_MAX_FILE_SIZE, "Max. file size (%s bytes) exceeded.");
 797				return FALSE;
 798			}
 799		}
 800
 801		// Get and check the upload file type
 802		$this->FileName = $objForm->GetUploadFileName($sFldVar);
 803		$this->FileName = str_replace(" ", "_", $this->FileName); // Replace space with underscore
 804		if (!$this->UploadAllowedFileExt($this->FileName)) {
 805			$this->Message = "File type is not allowed.";
 806			return FALSE;
 807		}
 808
 809		// Get upload file content type
 810		$this->ContentType = $objForm->GetUploadFileContentType($sFldVar);
 811
 812		// Get upload value
 813		//$this->Value = $objForm->GetUploadFileData($sFldVar);
 814
 815		if ($objForm->IsUploadedFile($sFldVar)) {
 816			$this->Value = $objForm->GetUploadFileTmpName($sFldVar); // store the tmp file name only
 817		}
 818
 819		// Get image width and height
 820		$this->ImageWidth = $objForm->GetUploadImageWidth($sFldVar);
 821		$this->ImageHeight = $objForm->GetUploadImageHeight($sFldVar);
 822		if ($this->ImageWidth < 0 || $this->ImageHeight < 0) {
 823			$this->ImageWidth = $objForm->GetValue($sFldVarWidth);
 824			$this->ImageHeight = $objForm->GetValue($sFldVarHeight);
 825		}
 826		return TRUE; // Normal return
 827	}
 828
 829	// Resize image
 830	function Resize($width, $height, $quality) {
 831		if (!is_null($this->Value)) {
 832			$wrkwidth = $width;
 833			$wrkheight = $height;
 834			if ($this->IsBinary) {
 835				$this->Binary = ew_ResizeFileToBinary($this->Value, $wrkwidth, $wrkheight, $quality);
 836				$this->FileSize = strlen($this->Binary);
 837			} else {
 838				ew_ResizeFile($this->Value, $this->Value, $wrkwidth, $wrkheight, $quality);
 839				$this->FileSize = filesize($this->Value);
 840			}
 841			$this->ImageWidth = $wrkwidth;
 842			$this->ImageHeight = $wrkheight;
 843		}
 844	}
 845
 846	// Get binary date
 847	function GetBinary() {
 848		if (is_null($this->Binary)) {
 849			if (!is_null($this->Value)) return ew_ReadFile($this->Value);
 850		} else {
 851			return $this->Binary;
 852		}
 853		return NULL;
 854	}
 855}
 856?>
 857<?php
 858
 859/**
 860 * Advanced Security class
 861 */
 862
 863class cAdvancedSecurity {
 864	var $UserLevel = array();
 865	var $UserLevelPriv = array();
 866
 867	// Current user name
 868	function getCurrentUserName() {
 869		return strval(@$_SESSION[EW_SESSION_USER_NAME]);
 870	}
 871
 872	function setCurrentUserName($v) {
 873		$_SESSION[EW_SESSION_USER_NAME] = $v;
 874	}
 875
 876	function CurrentUserName() {
 877		return $this->getCurrentUserName();
 878	}
 879
 880	// Current User ID
 881	function getCurrentUserID() {
 882		return strval(@$_SESSION[EW_SESSION_USER_ID]);
 883	}
 884
 885	function setCurrentUserID($v) {
 886		$_SESSION[EW_SESSION_USER_ID] = $v;
 887	}
 888
 889	function CurrentUserID() {
 890		return $this->getCurrentUserID();
 891	}
 892
 893	// Current parent User ID
 894	function getCurrentParentUserID() {
 895		return strval(@$_SESSION[EW_SESSION_PARENT_USER_ID]);
 896	}
 897
 898	function setCurrentParentUserID($v) {
 899		$_SESSION[EW_SESSION_PARENT_USER_ID] = $v;
 900	}
 901
 902	function CurrentParentUserID() {
 903		return $this->getCurrentParentUserID();
 904	}
 905
 906	// Current User Level id
 907	function getCurrentUserLevelID() {
 908		return @$_SESSION[EW_SESSION_USER_LEVEL_ID];
 909	}
 910
 911	function setCurrentUserLevelID($v) {
 912		$_SESSION[EW_SESSION_USER_LEVEL_ID] = $v;
 913	}
 914
 915	function CurrentUserLevelID() {
 916		return $this->getCurrentUserLevelID();
 917	}
 918
 919	// Current User Level value
 920	function getCurrentUserLevel() {
 921		return @$_SESSION[EW_SESSION_USER_LEVEL];
 922	}
 923
 924	function setCurrentUserLevel($v) {
 925		$_SESSION[EW_SESSION_USER_LEVEL] = $v;
 926	}
 927
 928	function CurrentUserLevel() {
 929		return $this->getCurrentUserLevel();
 930	}
 931
 932	// Can add
 933	function CanAdd() {
 934		return (($this->CurrentUserLevel() & EW_ALLOW_ADD) == EW_ALLOW_ADD);
 935	}
 936
 937	// Can delete
 938	function CanDelete() {
 939		return (($this->CurrentUserLevel() & EW_ALLOW_DELETE) == EW_ALLOW_DELETE);
 940	}
 941
 942	// Can edit
 943	function CanEdit() {
 944		return (($this->CurrentUserLevel() & EW_ALLOW_EDIT) == EW_ALLOW_EDIT);
 945	}
 946
 947	// Can view
 948	function CanView() {
 949		return (($this->CurrentUserLevel() & EW_ALLOW_VIEW) == EW_ALLOW_VIEW);
 950	}
 951
 952	// Can list
 953	function CanList() {
 954		return (($this->CurrentUserLevel() & EW_ALLOW_LIST) == EW_ALLOW_LIST);
 955	}
 956
 957	// Can report
 958	function CanReport() {
 959		return (($this->CurrentUserLevel() & EW_ALLOW_REPORT) == EW_ALLOW_REPORT);
 960	}
 961
 962	// Can search
 963	function CanSearch() {
 964		return (($this->CurrentUserLevel() & EW_ALLOW_SEARCH) == EW_ALLOW_SEARCH);
 965	}
 966
 967	// Can admin
 968	function CanAdmin() {
 969		return (($this->CurrentUserLevel() & EW_ALLOW_ADMIN) == EW_ALLOW_ADMIN);
 970	}
 971
 972	// Last url
 973	function LastUrl() {
 974		return @$_COOKIE[EW_PROJECT_NAME]['LastUrl'];
 975	}
 976
 977	// Save last url
 978	function SaveLastUrl() {
 979		$s = ew_ServerVar("SCRIPT_NAME");
 980		$q = ew_ServerVar("QUERY_STRING");
 981		if ($q <> "") $s .= "?" . $q;
 982		if ($this->LastUrl() == $s) $s = "";
 983		@setcookie(EW_PROJECT_NAME . '[LastUrl]', $s);
 984	}
 985
 986	// Auto login
 987	function AutoLogin() {
 988		if (@$_COOKIE[EW_PROJECT_NAME]['AutoLogin'] == "autologin") {
 989			$usr = @$_COOKIE[EW_PROJECT_NAME]['UserName'];
 990			$pwd = @$_COOKIE[EW_PROJECT_NAME]['Password'];
 991			$pwd = TEAdecrypt($pwd, EW_RANDOM_KEY);
 992			$AutoLogin = $this->ValidateUser($usr, $pwd);
 993			if ($AutoLogin) ew_WriteAuditTrailOnLogInOut("autologin");
 994		} else {
 995			$AutoLogin = FALSE;
 996		}
 997		return $AutoLogin;
 998	}
 999
1000	// Validate user
1001	function ValidateUser($usr, $pwd) {
1002		global $conn;
1003		global $osj2Dusers;
1004		$ValidateUser = FALSE;
1005
1006		// Check hard coded admin first
1007		if (EW_CASE_SENSITIVE_PASSWORD) {
1008			$ValidateUser = (EW_ADMIN_USER_NAME == $usr && EW_ADMIN_PASSWORD == $pwd);
1009		} else {
1010			$ValidateUser = (strtolower(EW_ADMIN_USER_NAME) == strtolower($usr) &&
1011				strtolower(EW_ADMIN_PASSWORD) == strtolower($pwd));
1012		}
1013		if ($ValidateUser) {
1014			$_SESSION[EW_SESSION_STATUS] = "login";
1015			$_SESSION[EW_SESSION_SYS_ADMIN] = 1; // System Administrator
1016			$this->setCurrentUserName("Administrator"); // Load user name
1017			$this->setCurrentUserID(-1); // System Administrator
1018			$this->setCurrentUserLevelID(-1); // System Administrator
1019			$this->SetUpUserLevel();
1020		}
1021
1022		// Check other users
1023		if (!$ValidateUser) {
1024			$sFilter = "(`user_email` = '" . ew_AdjustSql($usr) . "')";
1025			$sFilter .= " AND (`user_status` = 1)";
1026
1027			// Set up filter (Sql Where Clause) and get Return Sql
1028			// Sql constructor in <UseTable> class, <UserTable>info.php
1029
1030			$osj2Dusers->CurrentFilter = $sFilter;
1031			$sSql = $osj2Dusers->SQL();
1032			if ($rs = $conn->Execute($sSql)) {
1033				if (!$rs->EOF) {
1034					if (EW_CASE_SENSITIVE_PASSWORD) {
1035						if (EW_MD5_PASSWORD) {
1036							$ValidateUser = ($rs->fields('user_password') == md5($pwd));
1037						} else {
1038							$ValidateUser = ($rs->fields('user_password') == $pwd);
1039						}
1040					} else {
1041						if (EW_MD5_PASSWORD) {
1042							$ValidateUser = ($rs->fields('user_password') == md5(strtolower($pwd)));
1043						} else {
1044							$ValidateUser = (strtolower($rs->fields('user_password')) == strtolower($pwd));
1045						}
1046					}
1047					if ($ValidateUser) {
1048						$_SESSION[EW_SESSION_STATUS] = "login";
1049						$_SESSION[EW_SESSION_SYS_ADMIN] = 0; // Non System Administrator
1050						$this->setCurrentUserName($rs->fields('user_email')); // Load user name
1051						$this->setCurrentUserID($rs->fields('user_id')); // Load User ID
1052						if (is_null($rs->fields('user_level'))) {
1053							$this->setCurrentUserLevelID(0);
1054						} else {
1055							$this->setCurrentUserLevelID(intval($rs->fields('user_level'))); // Load User Level
1056						}
1057						$this->SetUpUserLevel();
1058					}
1059				}
1060				$rs->Close();
1061			}
1062		}
1063		return $ValidateUser;
1064	}
1065
1066	//' Dynamic User Level security
1067	// Get current User Level settings from database
1068	function SetUpUserLevel() {
1069		if ($this->IsLoggedIn()) {
1070			$this->SetUpUserLevelEx($this->CurrentUserLevelID());
1071
1072		//} else {
1073			//$this->SetUpUserLevelEx(0);
1074
1075		}
1076
1077		// Save the User Level to session variable
1078		$this->SaveUserLevel();
1079	}
1080
1081	// function to get (all) User Level settings from database
1082	function SetUpUserLevelEx($UserLevelID) {
1083		global $conn;
1084		if (strval($UserLevelID) == "" || !is_numeric($UserLevelID)) return;
1085
1086		// Get the User Level definitions
1087		$Sql = "SELECT " . EW_USER_LEVEL_ID_FIELD . ", " . EW_USER_LEVEL_NAME_FIELD . " FROM " . EW_USER_LEVEL_TABLE;
1088		if ($UserLevelID >= -1) $Sql .= " WHERE " . EW_USER_LEVEL_ID_FIELD . "=" . $UserLevelID;
1089		if ($rs = $conn->Execute($Sql)) {
1090			$this->UserLevel = $rs->GetRows();
1091			$rs->Close();
1092		}
1093
1094		// Get the User Level privileges
1095		$Sql = "SELECT " . EW_USER_LEVEL_PRIV_TABLE_NAME_FIELD . ", " . EW_USER_LEVEL_PRIV_USER_LEVEL_ID_FIELD . ", " . EW_USER_LEVEL_PRIV_PRIV_FIELD . " FROM " . EW_USER_LEVEL_PRIV_TABLE;
1096		if ($UserLevelID >= -1) $Sql .= " WHERE " . EW_USER_LEVEL_PRIV_USER_LEVEL_ID_FIELD . "=" . $UserLevelID;
1097		if ($rs = $conn->Execute($Sql)) {
1098			$this->UserLevelPriv = $rs->GetRows();
1099			$rs->Close();
1100		}
1101	}
1102
1103	// Load current User Level
1104	function LoadCurrentUserLevel($Table) {
1105		$this->LoadUserLevel();
1106		$this->setCurrentUserLevel($this->CurrentUserLevelPriv($Table));
1107	}
1108
1109	// Get current user privilege
1110	function CurrentUserLevelPriv($TableName) {
1111		if ($this->IsLoggedIn()) {
1112			return $this->GetUserLevelPrivEx($TableName, $this->CurrentUserLevelID());
1113		} else {
1114
1115			//return $this->GetUserLevelPrivEx($TableName, 0);
1116			return 0;
1117		}
1118	}
1119
1120	// Get user privilege based on table name and User Level
1121	function GetUserLevelPrivEx($TableName, $UserLevelID) {
1122		if (strval($UserLevelID) == "-1") { // System Administrator
1123			if (defined("EW_USER_LEVEL_COMPAT")) {
1124				return 31; // Use old User Level values
1125			} else {
1126				return 127; // Use new User Level values (separate View/Search)
1127			}
1128		} elseif ($UserLevelID >= 0) {
1129			if (is_array($this->UserLevelPriv)) {
1130				foreach ($this->UserLevelPriv as $row) {
1131					list($table, $levelid, $priv) = $row;
1132					if (strtolower($table) == strtolower($TableName) && strval($levelid) == strval($UserLevelID)) {
1133						if (is_null($priv) || !is_numeric($priv)) return 0;
1134						return intval($priv);
1135					}
1136				}
1137			}
1138		}
1139		return 0;
1140	}
1141
1142	// Get current User Level name
1143	function CurrentUserLevelName() {
1144		return $this->GetUserLevelName($this->CurrentUserLevelID());
1145	}
1146
1147	// Get User Level name based on User Level
1148	function GetUserLevelName($UserLevelID) {
1149		if (strval($UserLevelID) == "-1") {
1150			return "Administrator";
1151		} elseif ($UserLevelID >= 0) {
1152			if (is_array($this->UserLevel)) {
1153				foreach ($this->UserLevel as $row) {
1154					list($levelid, $name) = $row;
1155					if (strval($levelid) == strval($UserLevelID))	return $name;
1156				}
1157			}
1158		}
1159		return "";
1160	}
1161
1162	// function to display all the User Level settings (for debug only)
1163	function ShowUserLevelInfo() {
1164		echo "<pre class=\"phpmaker\">";
1165		print_r($this->UserLevel);
1166		print_r($this->UserLevelPriv);
1167		echo "</pre>";
1168		echo "<p>CurrentUserLevel = " . $this->CurrentUserLevel() . "</p>";
1169	}
1170
1171	// function to check privilege for List page (for menu items)
1172	function AllowList($TableName) {
1173		return ($this->CurrentUserLevelPriv($TableName) & EW_ALLOW_LIST);
1174	}
1175
1176	// Check if user is logged in
1177	function IsLoggedIn() {
1178		return (@$_SESSION[EW_SESSION_STATUS] == "login");
1179	}
1180
1181	// Check if user is system administrator
1182	function IsSysAdmin() {
1183		return (@$_SESSION[EW_SESSION_SYS_ADMIN] == 1);
1184	}
1185
1186	// Check if user is administrator
1187	function IsAdmin() {
1188		return ($this->CurrentUserLevelID() == -1 || $this->IsSysAdmin());
1189	}
1190
1191	// Save User Level to session
1192	function SaveUserLevel() {
1193		$_SESSION[EW_SESSION_AR_USER_LEVEL] = $this->UserLevel;
1194		$_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV] = $this->UserLevelPriv;
1195	}
1196
1197	// Load User Level from session
1198	function LoadUserLevel() {
1199		if (!is_array(@$_SESSION[EW_SESSION_AR_USER_LEVEL])) {
1200			$this->SetupUserLevel();
1201			$this->SaveUserLevel();
1202		} else {
1203			$this->UserLevel = $_SESSION[EW_SESSION_AR_USER_LEVEL];
1204			$this->UserLevelPriv = $_SESSION[EW_SESSION_AR_USER_LEVEL_PRIV];
1205		}
1206	}
1207
1208	// function to get user email
1209	function CurrentUserEmail() {
1210		return $this->CurrentUserInfo("user_email");
1211	}
1212
1213	// function to get user info
1214	function CurrentUserInfo($fieldname) {		
1215		$info = NULL;
1216		if ($this->CurrentUserName() == "") return $info;
1217		global $conn, $osj2Dusers;
1218
1219		// Set up filter (Sql Where Clause) and get Return Sql
1220		// Sql constructor in <UseTable> class, <UserTable>info.php
1221
1222		$sFilter = "(`user_email` = '" . ew_AdjustSql($this->CurrentUserName()) . "')";
1223		$osj2Dusers->CurrentFilter = $sFilter;
1224		$sSql = $osj2Dusers->SQL();
1225		if ($rs = $conn->Execute($sSql)) {
1226			if (!$rs->EOF) $info = $rs->fields($fieldname);
1227			$rs->Close();
1228		}
1229		return $info;
1230	}
1231
1232	// list of allowed user ids for this user
1233	function IsValidUserID($userid) {
1234		global $conn, $osj2Dusers;
1235		if ($this->IsLoggedIn()) {
1236			return (strval($this->CurrentUserID()) == strval($userid));
1237		}
1238	}
1239}
1240?>
1241<?php
1242
1243/**
1244 * Common functions
1245 */
1246
1247// Connection/Query error handler
1248function ew_ErrorFn($DbType, $ErrorType, $ErrorNo, $ErrorMsg, $Param1, $Param2, $Object) {
1249	if ($ErrorType == 'CONNECT') {
1250		$msg = "Failed to connect to $Param2 at $Param1. Error: " . $ErrorMsg;
1251	} elseif ($ErrorType == 'EXECUTE') {
1252		$msg = "Failed to execute SQL: $Param1. Error: " . $ErrorMsg;
1253	} 
1254	$_SESSION[EW_SESSION_MESSAGE] = $msg;
1255}
1256
1257// Connect to database
1258function &ew_Connect() {
1259	$object =& new mysqlt_driver_ADOConnection();
1260	if (defined("EW_DEBUG_ENABLED")) $object->debug = TRUE;
1261	$object->port = EW_CONN_PORT;
1262	$object->raiseErrorFn = 'ew_ErrorFn';
1263	$object->Connect(EW_CONN_HOST, EW_CONN_USER, EW_CONN_PASS, EW_CONN_DB);
1264	if (EW_MYSQL_CHARSET <> "") $object->Execute("SET NAMES '" . EW_MYSQL_CHARSET . "'");
1265	$object->raiseErrorFn = '';
1266	return $object;
1267}
1268
1269// Get server variable by name
1270function ew_ServerVar($Name) {
1271	$str = @$_SERVER[$Name];
1272	if (empty($str)) $str = @$_ENV[$Name];
1273	return $str;
1274}
1275
1276// Check if HTTP POST
1277function ew_IsHttpPost() {
1278	$ct = ew_ServerVar("CONTENT_TYPE");
1279	if (empty($ct)) $ct = ew_ServerVar("HTTP_CONTENT_TYPE");
1280	return ($ct == "application/x-www-form-urlencoded");
1281}
1282
1283// Get script name
1284function ew_ScriptName() {
1285	$sn = ew_ServerVar("PHP_SELF");
1286	if (empty($sn)) $sn = ew_ServerVar("SCRIPT_NAME");
1287	if (empty($sn)) $sn = ew_ServerVar("ORIG_PATH_INFO");
1288	if (empty($sn)) $sn = ew_ServerVar("ORIG_SCRIPT_NAME");
1289	if (empty($sn)) $sn = ew_ServerVar("REQUEST_URI");
1290	if (empty($sn)) $sn = ew_ServerVar("URL");
1291	if (empty($sn)) $sn = "UNKNOWN";
1292	return $sn;
1293}
1294
1295// Check if valid operator
1296function ew_IsValidOpr($Opr, $FldType) {
1297	$Valid = ($Opr == "=" || $Opr == "<" || $Opr == "<=" ||
1298		$Opr == ">" || $Opr == ">=" || $Opr == "<>");
1299	if ($FldType == EW_DATATYPE_STRING || $FldType == EW_DATATYPE_MEMO) {
1300		$Valid = ($Valid || $Opr == "LIKE" || $Opr == "NOT LIKE" ||
1301			$Opr == "STARTS WITH");
1302	}
1303	return $Valid; 
1304}
1305
1306// quote field values
1307function ew_QuotedValue($Value, $FldType) {
1308	if (is_null($Value)) return "NULL";
1309	switch ($FldType) {
1310	case EW_DATATYPE_STRING:
1311	case EW_DATATYPE_MEMO:
1312	case EW_DATATYPE_TIME:
1313		if (EW_REMOVE_XSS) {
1314			return "'" . ew_AdjustSql(ew_RemoveXSS($Value)) . "'";
1315		} else {
1316			return "'" . ew_AdjustSql($Value) . "'";
1317		}
1318	case EW_DATATYPE_BLOB:
1319		return "'" . ew_AdjustSql($Value) . "'";
1320	case EW_DATATYPE_DATE:
1321		return (EW_IS_MSACCESS) ? "#" . ew_AdjustSql($Value) . "#" :
1322			"'" . ew_AdjustSql($Value) . "'";
1323	case EW_DATATYPE_GUID:
1324		if (EW_IS_MSACCESS) {
1325			if (strlen($Value) == 38) {
1326				return "{guid " . $Value . "}";
1327			} elseif (strlen($Value) == 36) {
1328				return "{guid {" . $Value . "}}";
1329			}
1330		} else {
1331		  return "'" . $Value . "'";
1332		}
1333	case EW_DATATYPE_BOOLEAN: // enum('Y'/'N') or enum('1'/'0')
1334		return "'" . $Value . "'";
1335	default:
1336		return $Value;
1337	}
1338}
1339
1340// Convert different data type value
1341function ew_Conv($v, $t) {
1342	switch ($t) {
1343	case 2:
1344	case 3:
1345	case 16:
1346	case 17:
1347	case 18:
1348	case 19: // adSmallInt/adInteger/adTinyInt/adUnsignedTinyInt/adUnsignedSmallInt
1349		return (is_null($v)) ? NULL : intval($v);
1350	case 4:
1351	Case 5:
1352	case 6:
1353	case 131: // adSingle/adDouble/adCurrency/adNumeric
1354		if (function_exists('floatval')) { // PHP 4 >= 4.2.0
1355			return (is_null($v)) ? NULL : floatval($v);
1356		} else {
1357			return (is_null($v)) ? NULL : (float)$v;
1358		}
1359	default:
1360		return (is_null($v)) ? NULL : $v;
1361	}
1362}
1363
1364// function for debug
1365function ew_Trace($msg) {
1366	$filename = "debug.txt";
1367	if (!$handle = fopen($filename, 'a')) exit;
1368	if (is_writable($filename)) fwrite($handle, $msg . "\n");
1369	fclose($handle);
1370}
1371
1372// function to compare values with special handling for null values
1373function ew_CompareValue($v1, $v2) {
1374	if (is_null($v1) && is_null($v2)) {
1375		return TRUE;
1376	} elseif (is_null($v1) || is_null($v2)) {
1377		return FALSE;
1378	} else {
1379		return ($v1 == $v2);
1380	}
1381}
1382
1383// Strip slashes
1384function ew_StripSlashes($value) {
1385	if (!get_magic_quotes_gpc()) return $value;
1386	if (is_array($value)) { 
1387		return array_map('ew_StripSlashes', $value);
1388	} else {
1389		return stripslashes($value);
1390	}
1391}
1392
1393// Add slashes for SQL
1394function ew_AdjustSql($val) {
1395	$val = addslashes(trim($val));
1396	return $val;
1397}
1398
1399// Build sql based on different sql part
1400function ew_BuildSql($sSelect, $sWhere, $sGroupBy, $sHaving, $sOrderBy, $sFilter, $sSort) {
1401	$sDbWhere = $sWhere;
1402	if ($sDbWhere <> "") $sDbWhere = "(" . $sDbWhere . ")";
1403	if ($sFilter <> "") {
1404		if ($sDbWhere <> "") $sDbWhere .= " AND ";
1405		$sDbWhere .= "(" . $sFilter . ")";
1406	}
1407	$sDbOrderBy = $sOrderBy;
1408	if ($sSort <> "") $sDbOrderBy = $sSort;
1409	$sSql = $sSelect;
1410	if ($sDbWhere <> "") $sSql .= " WHERE " . $sDbWhere;
1411	if ($sGroupBy <> "") $sSql .= " GROUP BY " . $sGroupBy;
1412	if ($sHaving <> "") $sSql .= " HAVING " . $sHaving;
1413	if ($sDbOrderBy <> "") $sSql .= " ORDER BY " . $sDbOrderBy;
1414	return $sSql;
1415}
1416
1417// Executes the query, and returns the first column of the first row
1418function ew_ExecuteScalar($SQL) {
1419	global $conn;
1420	if ($conn) {
1421		if ($rs = $conn->Execute($SQL)) {
1422			if (!$rs->EOF && $rs->FieldCount() > 0)
1423				return $rs->fields[0];
1424		}
1425	}
1426	return NULL;
1427}
1428
1429// Write Audit Trail (login/logout)
1430function ew_WriteAuditTrailOnLogInOut($logtype) {
1431	$table = $logtype;
1432	$sKey = "";
1433
1434	// Write Audit Trail
1435	$filePfx = "log";
1436	$curDate = date("Y/m/d");
1437	$curTime = date("H:i:s");
1438	$id = ew_ScriptName();
1439	$user = CurrentUserName();
1440	$action = $logtype;
1441	ew_WriteAuditTrail($filePfx, $curDate, $curTime, $id, $user, $action, $table, "", "", "", "");
1442}
1443
1444// Function for writing audit trail
1445function ew_WriteAuditTrail($pfx, $curDate, $curTime, $id, $user, $action, $table, $field, $keyvalue, $oldvalue, $newvalue) {
1446	global $conn;
1447	$sFolder = "";
1448	$sFolder = str_replace("/", EW_PATH_DELIMITER, $sFolder);
1449	$ewFilePath = ew_AppRoot() . $sFolder;
1450	$sTab = "\t";
1451	$userwrk = $user;
1452	if ($userwrk == "") $userwrk = "-1"; // assume Administrator if no user
1453	$sHeader = "date" . $sTab . "time" . $sTab . "id" . 
1454				$sTab .	"user" . $sTab . "action" . $sTab . "table" . 
1455				$sTab . "field" . $sTab . "key value" . $sTab . "old value" . 
1456				$sTab . "new value";
1457	$sMsg = $curDate . $sTab . $curTime . $sTab . 
1458			$id . $sTab . $userwrk . $sTab . 
1459			$action . $sTab . $table . $sTab . 
1460			$field . $sTab . $keyvalue . $sTab . 
1461			$oldvalue . $sTab . $newvalue;
1462	$sFolder = EW_AUDIT_TRAIL_PATH;
1463	$sFn = $pfx . "_" . date("Ymd") . ".txt";
1464	$filename = ew_UploadPathEx(TRUE, $sFolder) . $sFn;
1465	if (file_exists($filename)) {
1466		$fileHandler = fopen($filename, "a+b");
1467	} else {
1468		$fileHandler = fopen($filename, "a+b");
1469		fwrite($fileHandler,$sHeader."\r\n");
1470	}
1471	fwrite($fileHandler, $sMsg."\r\n");
1472	fclose($fileHandler);
1473
1474	// Sample code to write audit trail to database
1475	// (change the table and names according to your table schema)
1476//	$sAuditSql = "INSERT INTO AuditTrailTable (`date`, `time`, `id`, `user`, " .
1477//		"`action`, `table`, `field`, `keyvalue`, `oldvalue`, `newvalue`) VALUES (" .
1478//		"'" . ew_AdjustSql($curDate) . "', " .
1479//		"'" . ew_AdjustSql($curTime) . "', " .
1480//		"'" . ew_AdjustSql($id) . "', " .
1481//		"'" . ew_AdjustSql($userwrk) . "', " .
1482//		"'" . ew_AdjustSql($action) . "', " .
1483//		"'" . ew_AdjustSql($table) . "', " .
1484//		"'" . ew_AdjustSql($field) . "', " .
1485//		"'" . ew_AdjustSql($keyvalue) . "', " .
1486//		"'" . ew_AdjustSql($oldvalue) . "', " .
1487//		"'" . ew_AdjustSql($newvalue) . "')";
1488//		// echo sAuditSql; // uncomment to debug
1489//	$conn->Execute($sAuditSql);
1490
1491}
1492
1493// Unformat date time based on format type
1494function ew_UnFormatDateTime($dt, $namedformat) {
1495	$dt = trim($dt);
1496	while (strpos($dt, "  ") !== FALSE) $dt = str_replace("  ", " ", $dt);
1497	$arDateTime = explode(" ", $dt);
1498	if (count($arDateTime) == 0) return $dt;
1499	$arDatePt = explode(EW_DATE_SEPARATOR, $arDateTime[0]);
1500	if ($namedformat == 0 || $namedformat == 1 || $namedformat == 2 || $namedformat == 8) {
1501		$arDefFmt = explode(EW_DATE_SEPARATOR, EW_DEFAULT_DATE_FORMAT);
1502		if ($arDefFmt[0] == "yyyy") {
1503			$namedformat = 9;
1504		} elseif ($arDefFmt[0] == "mm") {
1505			$namedformat = 10;
1506		} elseif ($arDefFmt[0] == "dd") {
1507			$namedformat = 11;
1508		}
1509	}
1510	if (count($arDatePt) == 3) {
1511		switch ($namedformat) {
1512		case 5:
1513		case 9: //yyyymmdd
1514			list($year, $month, $day) = $arDatePt;
1515			break;
1516		case 6:
1517		case 10: //mmddyyyy
1518			list($month, $day, $year) = $arDatePt;
1519			break;
1520		case 7:
1521		case 11: //ddmmyyyy
1522			list($day, $month, $year) = $arDatePt;
1523			break;
1524		default:
1525			return $dt;
1526		}
1527		if (strlen($year) <= 4 && strlen($month) <= 2 && strlen($day) <= 2) {
1528			return $year . "-" . str_pad($month, 2, "0", STR_PAD_LEFT) . "-" .
1529				 str_pad($day, 2, "0", STR_PAD_LEFT) .
1530				((count($arDateTime) > 1) ? " " . $arDateTime[1] : "");
1531		} else {
1532			return $dt;
1533		}
1534	} else {
1535		return $dt;
1536	}
1537}
1538
1539// Unformat number
1540function ew_UnformatNumber($v, $dp, $sep) {
1541	$v = str_replace(" ", "", $v);
1542	$v = str_replace($sep, "", $v);
1543	$v = str_replace($dp, ".", $v);
1544	return $v;
1545}
1546
1547//-------------------------------------------------------------------------------
1548// Functions for default date format
1549// FormatDateTime
1550//Format a timestamp, datetime, date or time field from MySQL
1551//$namedformat:
1552//0 - General Date,
1553//1 - Long Date,
1554//2 - Short Date (Default),
1555//3 - Long Time,
1556//4 - Short Time (hh:mm:ss),
1557//5 - Short Date (yyyy/mm/dd),
1558//6 - Short Date (mm/dd/yyyy),
1559//7 - Short Date (dd/mm/yyyy),
1560//8 - Short Date (Default) + Short Time (if not 00:00:00)
1561//9 - Short Date (yyyy/mm/dd) + Short Time (hh:mm:ss),
1562//10 - Short Date (mm/dd/yyyy) + Short Time (hh:mm:ss),
1563//11 - Short Date (dd/mm/yyyy) + Short Time (hh:mm:ss)
1564function ew_FormatDateTime($ts, $namedformat) {
1565	$DefDateFormat = str_replace("yyyy", "%Y", EW_DEFAULT_DATE_FORMAT);
1566	$DefDateFormat = str_replace("mm", "%m", $DefDateFormat);
1567	$DefDateFormat = str_replace("dd", "%d", $DefDateFormat);
1568	if (is_numeric($ts)) // timestamp
1569	{
1570		switch (strlen($ts)) {
1571			case 14:
1572				$patt = '/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
1573				break;
1574			case 12:
1575				$patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
1576				break;
1577			case 10:
1578				$patt = '/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/';
1579				break;
1580			case 8:
1581				$patt = '/(\d{4})(\d{2})(\d{2})/';
1582				break;
1583			case 6:
1584				$patt = '/(\d{2})(\d{2})(\d{2})/';
1585				break;
1586			case 4:
1587				$patt = '/(\d{2})(\d{2})/';
1588				break;
1589			case 2:
1590				$patt = '/(\d{2})/';
1591				break;
1592			default:
1593				return $ts;
1594		}
1595		if ((isset($patt))&&(preg_match($patt, $ts, $matches)))
1596		{
1597			$year = $matches[1];
1598			$month = @$matches[2];
1599			$day = @$matches[3];
1600			$hour = @$matches[4];
1601			$min = @$matches[5];
1602			$sec = @$matches[6];
1603		}
1604		if (($namedformat==0)&&(strlen($ts)<10)) $namedformat = 2;
1605	}
1606	elseif (is_string($ts))
1607	{
1608		if (preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // datetime
1609		{
1610			$year = $matches[1];
1611			$month = $matches[2];
1612			$day = $matches[3];
1613			$hour = $matches[4];
1614			$min = $matches[5];
1615			$sec = $matches[6];
1616		}
1617		elseif (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $ts, $matches)) // date
1618		{
1619			$year = $matches[1];
1620			$month = $matches[2];
1621			$day = $matches[3];
1622			if ($namedformat==0) $namedformat = 2;
1623		}
1624		elseif (preg_match('/(^|\s)(\d{2}):(\d{2}):(\d{2})/', $ts, $matches)) // time
1625		{
1626			$hour = $matches[2];
1627			$min = $matches[3];
1628			$sec = $matches[4];
1629			if (($namedformat==0)||($namedformat==1)) $namedformat = 3;
1630			if ($namedformat==2) $namedformat = 4;
1631		}
1632		else
1633		{
1634			return $ts;
1635		}
1636	}
1637	else
1638	{
1639		return $ts;
1640	}
1641	if (!isset($year)) $year = 0; // dummy value for times
1642	if (!isset($month)) $month = 1;
1643	if (!isset($day)) $day = 1;
1644	if (!isset($hour)) $hour = 0;
1645	if (!isset($min)) $min = 0;
1646	if (!isset($sec)) $sec = 0;
1647	$uts = @mktime($hour, $min, $sec, $month, $day, $year);
1648	if ($uts < 0 || $uts == FALSE || // failed to convert
1649		(intval($year) == 0 && intval($month) == 0 && intval($day) == 0)) {
1650		$year = substr_replace("0000", $year, -1 * strlen($year));
1651		$month = substr_replace("00", $month, -1 * strlen($month));
1652		$day = substr_replace("00", $day, -1 * strlen($day));
1653		$hour = substr_replace("00", $hour, -1 * strlen($hour));
1654		$min = substr_replace("00", $min, -1 * strlen($min));
1655		$sec = substr_replace("00", $sec, -1 * strlen($sec));
1656		$DefDateFormat = str_replace("yyyy", $year, EW_DEFAULT_DATE_FORMAT);
1657		$DefDateFormat = str_replace("mm", $month, $DefDateFormat);
1658		$DefDateFormat = str_replace("dd", $day, $DefDateFormat);
1659		switch ($namedformat) {
1660			case 0:
1661				return $DefDateFormat." $hour:$min:$sec";
1662				break;
1663			case 1://unsupported, return general date
1664				return $DefDateFormat." $hour:$min:$sec";
1665				break;
1666			case 2:
1667				return $DefDateFormat;
1668				break;
1669			case 3:
1670				if (intval($hour)==0)
1671					return "12:$min:$sec AM";
1672				elseif (intval($hour)>0 && intval($hour)<12)
1673					return "$hour:$min:$sec AM";
1674				elseif (intval($hour)==12)
1675					return "$hour:$min:$sec PM";
1676				elseif (intval($hour)>12 && intval($hour)<=23)
1677					return (intval($hour)-12).":$min:$sec PM";
1678				else
1679					return "$hour:$min:$sec";
1680				break;
1681			case 4:
1682				return "$hour:$min:$sec";
1683				break;
1684			case 5:
1685				return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day";
1686				break;
1687			case 6:
1688				return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year";
1689				break;
1690			case 7:
1691				return "$day" . EW_DATE_SEPARATOR ."$month" . EW_DATE_SEPARATOR . "$year";
1692				break;
1693			case 8:
1694				return $DefDateFormat . (($hour == 0 && $min == 0 && $sec == 0) ? "" : " $hour:$min:$sec");
1695				break;
1696			case 9:
1697				return "$year". EW_DATE_SEPARATOR . "$month" . EW_DATE_SEPARATOR . "$day $hour:$min:$sec";
1698				break;
1699			case 10:
1700				return "$month". EW_DATE_SEPARATOR ."$day" . EW_DATE_SEPARATOR . "$year $hour:$min:$sec";
1701				break;
1702			case 11:
1703				return "$day" . EW_DATE_SEPARATOR ."$…

Large files files are truncated, but you can click here to view the full file