objDB=&$GLOBALS['oDB']; // use oDB global as database connection, if it exists } $this->options=array(); $this->options["TableSelectNew"]="___new___"; $this->options["TableSelectNone"]=""; $this->options["canAdd"]=true; $this->options["canEdit"]=true; $this->options["canDelete"]=true; $this->options["ConfirmDelete"]=true; $this->options["ConfirmDeleteCol"]=-1; $this->options["DebugFlag"]=isset($_GET["debug"]); $this->options["prefetchBuffer"]=true; $this->options["PanelNamesOnTabHdr"]=true; $this->options["highlightElem"]="menuRow"; $this->SvrOnly=array(); $this->SvrOnly["DropDownSelect"]=1; $this->SvrOnly["SelectSql"]=1; $this->SvrOnly["SelectFilter"]=1; $this->SvrOnly["Formula"]=1; $this->SvrOnly["TableIdx"]=1; $this->SvrOnly["AddQuotes"]=1; $this->SvrOnly["FilterFlag"]=1; $this->SvrOnly["XMLprovider"]=1; $this->xhtmlcloser=">"; $this->FieldCnt=-1; $this->CurrentPanel=-1; $this->TableCnt=-1; $this->AutoInit=true; $this->formView=true; $this->sessions=isset($_SESSION); $this->ErrorFlag=false; $this->ErrorMsg=""; $this->convertCharSet=false; $this->oParseMain= new sqlParse(); $this->oParseMain->Init(); } // ------------------------------------------------------------- // Class Destructor (only called if php5) // ------------------------------------------------------------- function __destruct() { for ($i=0; $iFields); $i++) { $this->Fields[$i]=NULL; } $this->options=NULL; $this->SvrOnly=NULL; } // returns field number if successful, false if error function AddEntryField($ColumnName, $Heading, $EntryTypeCode, $DefaultValue) { if (!in_array($EntryTypeCode, array("S", "N", "R", "H", "D", "DT", "I", "F", "B", "T", "TA", "SL", "RL", "CL", "tinyMCE"))) { $this->TableEditError("invalid EntryTypeCode in TableEditClass"); return false; } $this->IncrCurrentField(); $this->CurrentField["ColName"]=$ColumnName; $this->CurrentField["Hdg"]=$Heading; $this->CurrentField["EntryType"]=$EntryTypeCode; $this->CurrentField["ColData"]=$DefaultValue; switch ($EntryTypeCode) { case "D": $this->CurrentField["type"]="date"; break; case "DT": $this->CurrentField["type"]="datetime"; break; case "TA": case "tinyMCE": $this->CurrentField["TxtAreaRows"]=4; $this->CurrentField["TxtAreaCols"]=80; break; case "R": case "RL": $this->CurrentField["RadioBreak"]="xhtmlcloser; break; case "H": $this->CurrentField["visible"]=false; break; } $s=$this->Tables[$this->MainTbl]->alias.".".$ColumnName; if (in_array($EntryTypeCode, array("B", "T", "TA", "tinyMCE"))) $s="rtrim(" . $s . ")"; $this->oParseMain->AddColumn($s, "rico_col".$this->FieldCnt); return $this->FieldCnt; } // returns field number if successful, false if error function AddEntryFieldW($ColumnName, $Heading, $EntryTypeCode, $DefaultValue, $Width) { $retval=$this->AddEntryField($ColumnName, $Heading, $EntryTypeCode, $DefaultValue); if ($retval!==false) $this->CurrentField["width"]=$Width; return $retval; } // $DescColName is optional - pass empty if not used function AddLookupField($CodeColName,$DescColName,$CodeHdg,$DisplayHdg,$EntryTypeCode,$DefaultValue,$sql) { $retval=$this->AddEntryField($CodeColName,$CodeHdg,$EntryTypeCode,$DefaultValue); $this->CurrentField["visible"]=false; $this->CurrentField["SelectSql"]=$sql; if (!empty($DescColName)) $this->CurrentField["DescriptionField"]=$this->ExtFieldId($this->FieldCnt+1); $this->LookupField=&$this->Fields[$this->FieldCnt]; $oParseLookup= new sqlParse(); $alias="t" . $this->FieldCnt; $oParseLookup->ParseSelect($sql); if (count($oParseLookup->arSelList) == 2) { $codeField=$oParseLookup->arSelList[0]; $descField=$oParseLookup->arSelList[1]; $s="left join ".$oParseLookup->FromClause." ".$alias." on t.".$CodeColName."=".$alias.".".str_replace("%alias%","",str_replace("%aliasmain%","",$codeField)); if (!empty($oParseLookup->WhereClause)) $s.=" and " . str_replace("%alias%",$alias.".",$oParseLookup->WhereClause); $this->oParseMain->AddJoin($s); $this->IncrCurrentField(); $this->CurrentField["ColName"]="Lookup_".$this->FieldCnt; $this->CurrentField["Hdg"]=$DisplayHdg; if (!empty($DescColName)) { $descField=$this->Tables[$this->MainTbl]->alias & "." & $DescColName; $this->CurrentField["ColName"]=$DescColName; $this->CurrentField["FormView"]="hidden"; $this->CurrentField["EntryType"]="T"; } else if (preg_match("/^\\w+$/",$descField)) { $descField=$alias.".".$descField; } else { $descField=str_replace("%alias%",$alias . ".",str_replace("%aliasmain%","t.",$descField)); } $this->oParseMain->AddColumn($descField, "rico_col".$this->FieldCnt); } else { $this->TableEditError("Invalid lookup query (".$sql.")"); } } // returns field number if successful, false if error function AddCalculatedField($ColumnFormula, $Heading) { $this->IncrCurrentField(); if (substr($ColumnFormula,0,1) != "(") { $ColumnFormula="(".$ColumnFormula.")"; } $this->CurrentField["ColName"]="Calc_".$this->FieldCnt; $this->CurrentField["Hdg"]=$Heading; $this->oParseMain->AddColumn($ColumnFormula, "rico_col".$this->FieldCnt); return $this->FieldCnt; } function AddPanel($PanelHeading) { $this->CurrentPanel++; $this->Panels[$this->CurrentPanel]=$PanelHeading; } function DefineAltTable($AltTabName, $arFieldList, $arFieldData) { $this->TableCnt++; $this->Tables[$this->TableCnt]= new TableEditTable(); $_withval=$this->Tables[$this->TableCnt]; $_withval->TblName=$AltTabName; $_withval->alias="a" . $this->TableCnt; $_withval->arFields=$arFieldList; $_withval->arData=$arFieldData; if (count($_withval->arFields) != count($_withval->arData)) { $this->TableEditError("# of fields does not match # of data entries supplied for table ".$AltTabName); return false; } return $this->TableCnt; } function IncrCurrentField() { $this->FieldCnt++; $this->Fields[$this->FieldCnt]= array(); $this->CurrentField= &$this->Fields[$this->FieldCnt]; $this->CurrentField["panelIdx"]=($this->CurrentPanel >= 0) ? $this->CurrentPanel : 0; $this->CurrentField["AddQuotes"]=true; $this->CurrentField["ReadOnly"]=false; $this->CurrentField["TableIdx"]=$this->MainTbl; } function SetTableName($s) { $this->TableCnt++; $this->MainTbl=$this->TableCnt; $this->Tables[$this->TableCnt]= new TableEditTable(); $this->Tables[$this->MainTbl]->TblName=$s; $this->Tables[$this->MainTbl]->alias="t"; $this->oParseMain->FromClause=$s." t"; $this->gridID=strtolower(str_replace(" ","_",str_replace(".","_",$s))); $this->formVar=$this->gridID . "['edit']"; $this->gridVar=$this->gridID . "['grid']"; $this->bufferVar=$this->gridID . "['buffer']"; $this->optionsVar=$this->gridID . "['options']"; $actionparm="_action_".$this->gridID; $this->action=isset($_REQUEST[$actionparm]) ? trim($_REQUEST[$actionparm]) : ""; $this->action=($this->action == "") ? "table" : strtolower($this->action); } function AddSort($field,$direction) { if (!empty($this->DefaultSort)) $this->DefaultSort.=","; $this->DefaultSort.=$field . " " . $direction; } function SortCurrent($direction) { if (array_key_exists("Formula",$this->CurrentField)) $this->AddSort($this->CurrentField["Formula"],$direction); elseif (array_key_exists("ColName",$this->CurrentField)) $this->AddSort($this->Tables[$this->CurrentField["TableIdx"]]->alias . "." . $this->CurrentField["ColName"],$direction); $this->options["sortCol"]=$this->FieldCnt; $this->options["sortDir"]=$direction; } function SortAsc() { $this->SortCurrent("ASC"); } function SortDesc() { $this->SortCurrent("DESC"); } function ConfirmDeleteColumn() { $this->options["ConfirmDeleteCol"]=$this->FieldCnt; } function genXHTML() { $this->xhtmlcloser=" />"; } function SetDbConn(&$dbcls) { $this->objDB=&$dbcls; } //************************************************************************************* // Take appropriate action //************************************************************************************* function DisplayPage() { if (count($this->Fields) == 0) { return; } if (!$this->ErrorFlag) { $this->GetColumnInfo(); } if (!$this->ErrorFlag) { switch ($this->action) { case "del": if ($this->options["canDelete"]) { $this->TableDeleteRecord(); } break; case "ins": if ($this->options["canAdd"]) { $this->TableInsertRecord(); } break; case "upd": if ($this->options["canEdit"]) { $this->TableUpdateRecord(); } break; default: if ($this->sessions) $_SESSION[$this->gridID]=$this->SqlSelectData(); $this->TableDisplay(); break; } } if ($this->ErrorFlag) { echo "\n

ERROR ENCOUNTEREDxhtmlcloser.$this->ErrorMsg; } } // if AltTable has a multi-column key, then add those additional constraints function AltTableKeyWhereClause($AltTabIdx) { for ($i=0; $iTables[$AltTabIdx]->arFields); $i++) { if ($this->Tables[$AltTabIdx]->arColInfo[$i]->IsPKey) { $w.=" and ".$this->Tables[$AltTabIdx]->arFields[$i]."=".$this->Tables[$AltTabIdx]->arData[$i]; } } return $w; } function AltTableJoinClause($alias) { for ($i=0; $iFields); $i++) { if ($this->Fields[$i]["TableIdx"] == $this->MainTbl && !$this->IsCalculatedField($i)) { if ($this->Fields[$i]["ColInfo"]->IsPKey) { $this->objDB->AddCondition($w, $this->Fields[$i]["ColName"]."=".$alias.".".$this->Fields[$i]["ColName"]); } } } return $w; } // form where clause based on table's primary key function TableKeyWhereClause() { for ($i=0; $iFields); $i++) { if ($this->Fields[$i]["TableIdx"] == $this->MainTbl && !$this->IsCalculatedField($i)) { if ($this->Fields[$i]["ColInfo"]->IsPKey) { $this->objDB->AddCondition($w, $this->Fields[$i]["ColName"]."=".$this->FormatValue($_POST["_k".$i],$i)); } } } if (empty($w)) { $this->TableEditError("no key value"); } else { return " WHERE ".$w; } } // name used external to this script function ExtFieldId($i) { return $this->gridID."_".$i; } function IsCalculatedField($i) { return array_key_exists("Formula",$this->Fields[$i]); } //************************************************************************************* // Retrieves column info from database for main table and any alternate tables //************************************************************************************* function GetColumnInfo() { $Columns=array(); $dicColIdx=array(); for ($FieldNum=0; $FieldNumFields); $FieldNum++) { $dicColIdx[$this->Fields[$FieldNum]["TableIdx"].".".strtoupper($this->Fields[$FieldNum]["ColName"])]= $FieldNum; if ($this->options["canEdit"] == false && $this->options["canAdd"] == false) { $this->Fields[$FieldNum]["ReadOnly"]=true; } } //print_r($dicColIdx); for ($i=0; $i<=$this->TableCnt; $i++) { $Columns=$this->objDB->GetColumnInfo($this->Tables[$i]->TblName); if (!is_array($Columns)) { $this->TableEditError("unable to retrieve column info for ".$this->Tables[$i]->TblName."
".$this->objDB->LastErrorMsg); return; } //print_r($Columns); for ($c=0; $c < count($Columns); $c++) { $colname=strtoupper($Columns[$c]->ColName); if (array_key_exists($i.".".$colname,$dicColIdx)) { $FieldNum=$dicColIdx[$i.".".$colname]; $this->Fields[$FieldNum]["ColInfo"]=$Columns[$c]; } elseif ($i != $this->MainTbl) { for ($j=0; $j < count($this->Tables[$i]->arFields); $j++) { if ($colname == $this->Tables[$i]->arFields[$j]) { $this->Tables[$i]->arColInfo[$j]=$Columns[$c]; } } } elseif ($Columns[$c]->IsPKey) { $this->TableEditError("primary key field is not defined (".$this->Tables[$i]->TblName.".".$colname.")"); $dicColIdx=NULL; return; } } } $dicColIdx=NULL; } function TableUpdateDatabase($sqltext, $actiontxt) { if ($this->ErrorFlag) { return; } $cnt=$this->objDB->RunActionQueryReturnMsg($sqltext, $errmsg); if ($this->options["DebugFlag"]) echo "

".$sqltext."xhtmlcloser."Records affected: ".$cnt; if (!empty($errmsg)) $this->TableEditError("unable to update database!xhtmlcloser.$errmsg); else if ($cnt == 1) echo "

"; else $this->TableEditError("no data changed - update skipped"); } function FormatValue($v, $idx) { $fld=$this->Fields[$idx]; $addquotes=$fld["AddQuotes"]; if (substr($fld["EntryType"],0,1) == "D") { if ($v == "") { $addquotes=false; $v="NULL"; } } elseif ($fld["EntryType"] == "I" || $fld["EntryType"] == "F") { $addquotes=false; if ($v == "" || !is_numeric($v)) { $v="NULL"; } } elseif ($fld["EntryType"] == "N" && $v == $this->options["TableSelectNew"]) { $v=trim($_POST["textnew__".$this->ExtFieldId($idx)]); } elseif (strpos("SNR",substr($fld["EntryType"],0,1)) !== false && $v == $this->options["TableSelectNone"]) { $addquotes=false; $v="NULL"; } if ($addquotes) $v=$this->objDB->addQuotes($v); return $v; } function FormatFormValue($idx) { if (!array_key_exists("EntryType",$this->Fields[$idx])) return ""; $fldname=$this->ExtFieldId($idx); if ($this->Fields[$idx]["EntryType"] == "H" || (array_key_exists("FormView",$this->Fields[$idx]) && $this->Fields[$idx]["FormView"] == "exclude")) $v=$this->Fields[$idx]["ColData"]; elseif (isset($_POST[$fldname])) { $v=$_POST[$fldname]; if (get_magic_quotes_gpc()) $v=stripslashes($v); $v=($this->convertCharSet) ? utf8_decode($v) : urldecode($v); $v=trim($v); } return $this->FormatValue($v, $idx); } //************************************************************************************* // Deletes the specified record //************************************************************************************* function TableDeleteRecord() { $this->TableUpdateDatabase("DELETE FROM ".$this->Tables[$this->MainTbl]->TblName.$this->TableKeyWhereClause(), "deleted"); } function UpdateRecord($sqltext) { $this->objDB->RunActionQueryReturnMsg($sqltext, $errmsg); if (!empty($errmsg)) { $errmsg="unable to update database!xhtmlcloser.$errmsg; if ($this->options["DebugFlag"]) { $errmsg.="

SQL: ".$sqltext; } $this->TableEditError($errmsg); } elseif ($this->options["DebugFlag"]) { echo "
".$sqltext; } } function UpdateAltTableRecords($i) { if ($this->ErrorFlag) { return; } // delete existing record $sqltext="delete from ".$this->Tables[$i]->TblName; $sqltext.=$this->TableKeyWhereClause(); $sqltext.=$this->AltTableKeyWhereClause($i); $this->UpdateRecord($sqltext); // insert new record $colnames=""; $coldata=""; for ($j=0; $jFields); $j++) { if (!array_key_exists("ColInfo",$this->Fields[$j])) continue; if ($this->Fields[$j]["TableIdx"] == $i || $this->Fields[$j]["ColInfo"]->IsPKey) { $colnames.=",".$this->Fields[$j]["ColName"]; $coldata.=",".$this->FormatValue(trim($_POST[$this->ExtFieldId($j)]), $j); } } for ($j=0; $jTables[$i]->arFields); $j++) { $c=$this->Tables[$i]->arFields[$j]; $colnames.=",".$c; $coldata.=",".$this->Tables[$i]->arData[$j]; } $sqltext="insert into ".$this->Tables[$i]->TblName." (".substr($colnames,1).") values (".substr($coldata,1).")"; $this->UpdateRecord($sqltext); } //************************************************************************************* // Updates an existing record in the db //************************************************************************************* function TableUpdateRecord() { for ($i=0; $i<=$this->TableCnt; $i++) { if ($i != $this->MainTbl) { $this->UpdateAltTableRecords($i); } } for ($i=0,$sqltext=''; $iFields); $i++) { if (!$this->IsCalculatedField($i)) { if ($this->Fields[$i]["TableIdx"] == $this->MainTbl && $this->Fields[$i]["ColInfo"]->Writeable && !array_key_exists("InsertOnly",$this->Fields[$i])) { $sqltext.=",".$this->Fields[$i]["ColName"]."=".$this->FormatFormValue($i); } } } $sqltext="UPDATE ".$this->Tables[$this->MainTbl]->TblName." SET ".substr($sqltext,1); $sqltext.=$this->TableKeyWhereClause(); $this->TableUpdateDatabase($sqltext, "updated"); } //************************************************************************************* // Inserts a new record into the db //************************************************************************************* function TableInsertRecord() { $keyCnt=0; $sqlcol=""; $sqlval=""; for ($i=0; $iFields); $i++) { if (!$this->IsCalculatedField($i) && $this->Fields[$i]["TableIdx"] == $this->MainTbl && !array_key_exists("UpdateOnly",$this->Fields[$i])) { if ($this->Fields[$i]["ColInfo"]->IsPKey) { $keyCnt++; $keyIdx=$i; } if ($this->Fields[$i]["ColInfo"]->Writeable) { $sqlcol.=",".$this->Fields[$i]["ColName"]; $sqlval.=",".$this->FormatFormValue($i); } } } $sqltext="insert into ".$this->Tables[$this->MainTbl]->TblName." (".substr($sqlcol,1).") values (".substr($sqlval,1).")"; $this->TableUpdateDatabase($sqltext, "added"); } function TableEditError($msg) { $this->ErrorFlag=true; $this->ErrorMsg=$msg; } //************************************************************************************* // Do post-processing on sql query //************************************************************************************* function FinishQuery() { $oParseLookup= new sqlParse(); $this->oParseMain->AddWhereCondition($this->TableFilter); for ($i=0; $iFields); $i++) { if (array_key_exists("FilterFlag",$this->Fields[$i])) { // add any column filters to where clause $this->oParseMain->AddWhereCondition($this->Tables[$this->Fields[$i]["TableIdx"]]->alias.".".$this->Fields[$i]["ColName"]."='".$this->Fields[$i]["ColData"]."'"); } if (array_key_exists("EntryType",$this->Fields[$i])) { if (strpos("CSNR",substr($this->Fields[$i]["EntryType"],0,1)) !== false) { if (array_key_exists("SelectSql",$this->Fields[$i])) { $s=$this->Fields[$i]["SelectSql"]; if (array_key_exists("SelectFilter",$this->Fields[$i])) { $oParseLookup->ParseSelect($s); $oParseLookup->AddWhereCondition($this->Fields[$i]["SelectFilter"]); $s=$oParseLookup->UnparseSelect(); } $this->Fields[$i]["DropDownSelect"]=str_replace("%alias%","",str_replace("%aliasmain%","",$s)); } else { $this->Fields[$i]["DropDownSelect"]="select distinct ".$this->Fields[$i]["ColName"]." from ".$this->Tables[$this->Fields[$i]["TableIdx"]]->TblName." where ".$this->Fields[$i]["ColName"]." is not null"; } } } if ($this->Fields[$i]["TableIdx"] != $this->MainTbl) { // column from alt table - no avoiding subqueries here $s="(select " . $this->Fields[$i]["ColName"] . " from " . $this->Tables[$this->Fields[$i]["TableIdx"]]->TblName . " a" . $i . " where " . $this->AltTableJoinClause("t") . $this->AltTableKeyWhereClause($this->Fields[$i]["TableIdx"]) . ")"; if (substr($this->Fields[$i]["EntryType"],1) == "L" && array_key_exists("SelectSql",$this->Fields[$i])) { $oParseLookup->ParseSelect($this->Fields[$i]["SelectSql"]); if (count($oParseLookup->arSelList) == 2) { $codeField=$oParseLookup->arSelList[0]; $descField=$oParseLookup->arSelList[1]; $descQuery="select " . $descField . " from " . $oParseLookup->FromClause . " where " . $codeField . "=" . $s; if (!empty($oParseLookup->WhereClause)) $descQuery.=" and " . $oParseLookup->WhereClause; $this->oParseMain->arSelList[$i]="(" . $this->objDB->concat(array("(" . $descQuery . ")", "''", $this->objDB->Convert2Char($s), "''"), false) . ") as rico_col" . $i; } else { $this->TableEditError("Invalid lookup query (".$this->Fields[$i]["SelectSql"].")"); return; } } else { $this->oParseMain->arSelList[$i]=$s . " as rico_col" . $i; } } } if (empty($this->DefaultSort)) { $this->DefaultSort=$this->objDB->PrimaryKey($this->Tables[$this->MainTbl]->TblName); } $this->oParseMain->AddSort($this->DefaultSort); } //************************************************************************************* // returns details of sql query as an array //************************************************************************************* function SqlSelectData() { $this->FinishQuery(); $arr=$this->oParseMain->ToArray(); $SelectIdx=count($arr); array_push($arr, array()); $HdgIdx=count($arr); array_push($arr, array()); for ($i=0; $iFields); $i++) { if (array_key_exists("DropDownSelect",$this->Fields[$i])) { $arr[$SelectIdx][$i]=$this->Fields[$i]["DropDownSelect"]; } if (array_key_exists("Hdg",$this->Fields[$i])) { $arr[$HdgIdx][$i]=$this->Fields[$i]["Hdg"]; } } return $arr; } //************************************************************************************* // Displays a table //************************************************************************************* function TableDisplay() { echo "\n

"; echo ""; echo " "; echo ""; echo "

"; echo "\n
"; echo "\n"; } function FormatOption($s) { if (is_array($s)) return "{" . implode(",",$s) . "}"; switch (gettype($s)) { case 'string': return "\"".addslashes($s)."\""; case 'boolean': return $s ? 'true' : 'false'; case 'double': return str_replace(",",".",strval($s)); // make sure period is used as a decimal point default: return $s; } } function InitScript() { $CookieInfo = session_get_cookie_params(); $s="\n".$this->bufferVar."=new Rico.Buffer.AjaxSQL('" . $this->options["XMLprovider"] . "', {TimeOut:" . (array_shift($CookieInfo)/60) . "});"; $s.="\nif(typeof ".$this->gridID."_GridInit=='function') ".$this->gridID."_GridInit();"; $s.="\n".$this->gridVar."=new Rico.LiveGrid('".$this->gridID."',".$this->bufferVar.",".$this->optionsVar.");"; $s.="\n".$this->gridVar.".menu=new Rico.GridMenu();"; if ($this->formView) { $s.="\nif(typeof ".$this->gridID."_FormInit=='function') ".$this->gridID."_FormInit();"; $s.="\n".$this->formVar."=new Rico.TableEdit(".$this->gridVar.");"; } $s.="\nif(typeof ".$this->gridID."_InitComplete=='function') ".$this->gridID."_InitComplete();"; return $s; } } ?>