PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/cruddy_mysql/cruddy_mysql.php

https://github.com/davidrenne/cruddy_mysql
PHP | 4400 lines | 4166 code | 141 blank | 93 comment | 408 complexity | 14e8a6c0cc2f839665545141e25f6d3d MD5 | raw file

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

  1. <?php
  2. $pwd = dirname(__FILE__);
  3. define("ABS_PATH_TO_CRUDDY_MYSQL_FOLDER",dirname($_SERVER['PHP_SELF']).'/cruddy_mysql/');
  4. define("ABS_PATH_HASH",substr(md5(dirname($_SERVER['PHP_SELF']).'/cruddy_mysql/'),0,8));
  5. ini_set("memory_limit","256M");
  6. set_time_limit(0);
  7. set_magic_quotes_runtime(false); // -- dude just dont use magic quotes...
  8. function get_microtime_ms() {
  9. list($usec, $sec) = explode(" ",microtime());
  10. return ((float)$usec + (float)$sec);
  11. }
  12. /* constants */
  13. define("GET_COLUMNS_SQL", "show full columns from %s");
  14. define("GET_TABLES_SQL", "show full tables");
  15. define("GET_DATABASES_SQL", "show databases");
  16. define("UPDATE_SQL","update %s set %s where %s");
  17. define("INSERT_SQL","insert into %s(%s) values(%s)");
  18. define("TABLE_CONFIG","tableDef");
  19. define("CRUD_FIELD_CONFIG","crudConfig");
  20. // table level keys and configs
  21. define("OBJECT_DESC","description"); //high level table description (Keep short)
  22. define("OBJECT_ACTIONS","actions"); //array of possible CRUD actions used in switch of controller page
  23. define("OBJECT_DEFAULT_ORDER","defaultorder"); //for a generic_read function to handle how the records should be initially sorted
  24. define("OBJECT_READ_FILTER","filterrecords"); //initial filter that the main recordset loads as
  25. define("OBJECT_HIDE_NEW_LINK","hidenewlink"); //a flag to say whether the table should have a "New" link associated with it
  26. define("OBJECT_HIDE_VIEW_LINK","hideviewlink"); //a flag to say whether the table should have a "New" link associated with it
  27. define("OBJECT_HIDE_SEARCH_LINK","hidesearchlink");
  28. define("OBJECT_HIDE_DETAILS_LINK","hidedetailslink");
  29. define("OBJECT_HIDE_EDIT_LINK","hideeditlink");
  30. define("OBJECT_HIDE_DELETE_LINK","hidedeletelink");
  31. define("OBJECT_DELETE_CHECK_CONSTRAINTS","objdeleteconstraints"); //by default the crud class will loop through all tables and fields and if it finds an identical fieldname in any table in the database and there are records in that table, it will tell the user they cannot delete the only way to bypass this constraint is by setting this to false
  32. define("OBJECT_TABLE","table");//table name
  33. define("OBJECT_IS_AGGREGATE","aggregateview");//table name
  34. define("OBJECT_CONNECTION_STRING","connection");//dba connection string
  35. define("OBJECT_PK","primarykey");//primary key hard coded
  36. define("OBJECT_FILTER_DESC","filterrecordsdescription");//used when you want to describe what the data is filtered by inside your controller function
  37. define("OBJECT_PAGING","pagingenabled");//by default paging is enabled unless you say false here. paging is defaulted to 10 records per page but just need to add new configuration here when needing new functionality
  38. define("OBJECT_PAGING_NUM_ROWS_PER_PAGE","pagingrows");
  39. define("OBJECT_PAGING_SCROLL","pagingscroll");
  40. define("OTHER_OBJECTS", "otherobjects" );//otherobjects allows you to build supporting form objects that will be tacked on at the end of the form before the button to post/update
  41. define("REQUIRED_TEXT","requiredtext");
  42. define("OTHER_LINKS", "otherlinks" );
  43. define("EDIT_TEXT","edittext");
  44. define("DELETE_TEXT","deletetext");
  45. define("TABLE_TEXT","tabletext");
  46. define("ADD_TEXT","addtext");
  47. define("VIEW_TEXT","viewtext");
  48. define("SEARCH_TEXT","searchtext");
  49. define("EDIT_LINK", "editlink");
  50. define("DELETE_LINK", "deletelink");
  51. // field level keys and configs
  52. define("CAPTION","caption"); // what the user sees as the field name
  53. //these array keys/configurations are for the foreign key lookups definied at the field level
  54. define("ID","lookupid");
  55. define("TEXT", "lookuptext");
  56. define("TABLE", "lookuptable" );
  57. define("WHERE", "lookupwhere" );
  58. define("SELECT","select");
  59. define("SHOWCOLUMN","showcolumn");
  60. define("COLUMNPOSTTEXT","posttextc");
  61. define("SORTABLE","sortable");
  62. define("PRETEXTREAD","pretext");
  63. define("POSTTEXTREAD","posttext");
  64. define("REQUIRED","required");
  65. define("UPDATE_READ_ONLY","ronlyupdate");
  66. define("HIDE","inserthide");
  67. define("ROW_ID","number_0x45dsa4654das654da64dsa654da");
  68. define("INPUT_DOIT","submit_cruddy_mysql");
  69. define("INPUT_SUBMIT","submit_button");
  70. (include ("$pwd/dbal/dbal.php")) or die("This class require <a href='http://cesars.users.phpclasses.org/dba'>DBA</a> class. Please download it and copy the folder 'dbal' in $pwd");
  71. (include ("$pwd/forms.php")) or die("This class require <a href='http://cesars.users.phpclasses.org/formsgeneration'>Forms Generation Class</a> class. Please download it and copy the file 'forms.php' in $pwd");
  72. class cruddyMysql {
  73. function cruddyMysql($str,$table,$info=array()) {
  74. $pwd = dirname(__FILE__);
  75. $this->table = $info[TABLE_CONFIG][OBJECT_TABLE];
  76. $this->conn = $str;
  77. $this->dba = new dbal($str);
  78. $this->dba->setCacheDir( "${pwd}/cache/" );
  79. $this->tableDefinition = $info;
  80. $this->getTableInformation();
  81. }
  82. function doQuery($filter) {
  83. $methodStartTime = get_microtime_ms();
  84. $res = &$this->result;
  85. $dba = &$this->dba;
  86. $info = &$this->formParams;
  87. $definitions = &$this->tableDefinition;
  88. if (!empty($filter)) {
  89. if ( ( stristr($filter,'=') || stristr($filter,'IN (') || stristr($filter,'IN(') ) && !stristr($filter,'where') ) {
  90. $f = $filter == '' ? '' : ' WHERE '.$filter;
  91. } else {
  92. $f = $filter;
  93. }
  94. } else {
  95. $f = $filter;
  96. }
  97. $query = "select count(*) as count from ".$this->table." $f";
  98. $result = @mysql_query($query,$dba->dbm->dbh);
  99. if ($result) {
  100. $row = mysql_fetch_array($result);
  101. $total_records = $row['count'];
  102. } else {
  103. $total_records = 0;
  104. }
  105. $scroll_page = ($definitions[TABLE_CONFIG][OBJECT_PAGING_NUM_ROWS_PER_PAGE]) ? $definitions[TABLE_CONFIG][OBJECT_PAGING_SCROLL] : 5 ;
  106. $per_page = ($definitions[TABLE_CONFIG][OBJECT_PAGING_NUM_ROWS_PER_PAGE]) ? $definitions[TABLE_CONFIG][OBJECT_PAGING_NUM_ROWS_PER_PAGE] : 10 ;
  107. $current_page = $_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['page']];
  108. $pager_url = $_SERVER['PHP_SELF']."?action=".strtolower($definitions[TABLE_CONFIG][OBJECT_ACTIONS]['read'].$this->object_key).'&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_field'].'='.$_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_field']].'&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_direction'].'='.$_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_direction']].'&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['page'].'=';
  109. $inactive_page_tag = 'id="current_page"';
  110. $previous_page_text = '&lt; Previous';
  111. $next_page_text = 'Next &gt;';
  112. $first_page_text = '&lt;&lt; First';
  113. $last_page_text = 'Last &gt;&gt;';
  114. $crudPage = new cruddyMysqlPager();
  115. $crudPage->pager_set($pager_url, $total_records, $scroll_page, $per_page, $current_page, $inactive_page_tag, $previous_page_text, $next_page_text, $first_page_text, $last_page_text,'');
  116. $result = mysql_query(str_replace("count(*) as count","*",$query)." LIMIT ".$crudPage->start.", ".$crudPage->per_page."",$dba->dbm->dbh);
  117. $definitions[TABLE_CONFIG][OBJECT_PAGING] = $crudPage;
  118. if ($result) {
  119. while ($row = mysql_fetch_assoc($result)) {
  120. $res[] = $row;
  121. }
  122. } else {
  123. //if ($this->cruddyAdministrator) {
  124. echo ("ERROR: ".$dba->getLastError());
  125. //}
  126. }
  127. $total = (get_microtime_ms() - $methodStartTime);
  128. $this->performance['doQuery'][] = $total ." sql:".$query;
  129. }
  130. /**
  131. * Creates a new row.
  132. *
  133. * Show the form for create a new row.
  134. */
  135. function create() {
  136. $this->getTableInformation(true);
  137. return $this->buildGenericForm(array(),false,"");
  138. }
  139. /**
  140. * search
  141. */
  142. function search() {
  143. $this->getTableInformation("search");
  144. return $this->buildGenericForm(array(),false,"",false,true);
  145. }
  146. /**
  147. * Generic Form
  148. *
  149. * @access private
  150. */
  151. function buildGenericForm($default=array(),$update=false,$update_condition="",$readOnly=false,$search=false) {
  152. $methodStartTime = get_microtime_ms();
  153. $form = new form_class;
  154. $form->NAME= $this->table."_form";
  155. $form->METHOD="POST";
  156. $form->ACTION="";
  157. $form->ENCTYPE="multipart/form-data";
  158. $form->InvalidCLASS="invalid";
  159. $form->ResubmitConfirmMessage="Are you sure you want to submit this form again?";
  160. $form->OptionsSeparator="<br />\n";
  161. $form->ErrorMessagePrefix="- ";
  162. $form->ErrorMessageSuffix="";
  163. foreach($this->formParams as $k => $input) {
  164. if ( is_array($default) && count($default) > 0) {
  165. $input["VALUE"] = $default[$k];
  166. }
  167. if ($input["NAME"]) {
  168. echo $form->AddInput( $input );
  169. }
  170. }
  171. $form->LoadInputValues($form->WasSubmitted(INPUT_DOIT));
  172. $verify=array();
  173. $doit=false;
  174. $error_message="";
  175. if($form->WasSubmitted(INPUT_DOIT)) {
  176. if(($error_message=$form->Validate($verify))!="") {
  177. $doit=false;
  178. } else {
  179. $doit=true;
  180. }
  181. }
  182. if($doit) {
  183. $dba = &$this->dba;
  184. // -- get a list of fields that the table can take skip anything else in the post
  185. $sql = sprintf(GET_COLUMNS_SQL,$this->table);
  186. $record = $dba->query($sql);
  187. if ( !$record )
  188. return false;
  189. $Field = & $record->bindColumn('Field');
  190. while ( $foo=$record->getNext() ) {
  191. $tableFields[$Field] = $Field;
  192. }
  193. $sql = "";
  194. $columns=array();
  195. foreach($this->formParams as $k=>$v) {
  196. if ( $k == ROW_ID || $k == INPUT_DOIT || $k == INPUT_SUBMIT) continue;
  197. if (!in_array($k,$tableFields)) {
  198. // -- found another form element see if there is something to do with it
  199. continue;
  200. } else {
  201. if (strtoupper($v['TYPE']) == 'FILE') {
  202. $form->GetFileValues($k,$userfile_values);
  203. if ($userfile_values["name"]) {
  204. // -- for files, user should be mapping the MIME, MOVE_TO, and SIZE to other fields
  205. $columns[$k] = $k;
  206. $values[$k] = $k;
  207. $_POST[$k] = $userfile_values["name"];
  208. // -- users can store the MIME and FILE_SIZE attributes into a custom field mapping
  209. // -- FYI there is no edit facility for MIME/SIZE you must convert your config to an array and manually add them to the $field_name_"config" section of the array
  210. // -- MIME is meant to update another field with the MIME type of the fileupload and expects a field name as the value of the key
  211. if ($v['MIME']) {
  212. $columns[$v['MIME']] = $v['MIME'];
  213. $values[$v['MIME']] = $v['MIME'];
  214. $_POST[$v['MIME']] = $userfile_values["type"];
  215. }
  216. if ($v['FILE_SIZE']) {
  217. $columns[$v['FILE_SIZE']] = $v['FILE_SIZE'];
  218. $values[$v['FILE_SIZE']] = $v['FILE_SIZE'];
  219. $_POST[$v['FILE_SIZE']] = $userfile_values["size"];
  220. }
  221. if (isset($v['MOVE_TO'])) {
  222. if (@is_uploaded_file($userfile_values["tmp_name"])) {
  223. if (substr($v['MOVE_TO'],-1))
  224. if (substr($v['MOVE_TO'],-1) != '/' && strtoupper(substr(PHP_OS,0,3)!='WIN')) {
  225. $v['MOVE_TO'] .= "/";
  226. } elseif (substr($v['MOVE_TO'],-1) != "\\" && strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  227. $v['MOVE_TO'] .= "\\";
  228. }
  229. if (!@move_uploaded_file($userfile_values["tmp_name"], $v['MOVE_TO'].$userfile_values["name"])) {
  230. die("File Upload Failed. Ensure that {$v['MOVE_TO']} is chmod 777 for new files to overwrite.");
  231. }
  232. }
  233. } else {
  234. die("Missing MOVE_TO value to move the file");
  235. }
  236. } else {
  237. }
  238. } elseif (strtoupper($v['CustomClass']) == 'FORM_DATE_CLASS') {
  239. $dateValue = $_POST["p_".$k."_year"]."-".$_POST["p_".$k."_month"]."-".$_POST["p_".$k."_day"];
  240. if (empty($_POST["p_".$k."_year"]) || empty($_POST["p_".$k."_month"])) {
  241. $dateValue = "";
  242. }
  243. $_POST[$k] = $dateValue;
  244. $values[$k] = $k;
  245. $columns[$k] = $k;
  246. } else {
  247. if ($v["UsesAutoFormName"] ==! false) {
  248. // -- custom flag for use when widget calls $forms->GenerateInputID()
  249. $columns[$k] = $k;
  250. $values[$k] = "p_".$k."_".$v["UsesAutoFormName"];
  251. } else {
  252. $columns[$k] = $k;
  253. $values[$k] = $k;
  254. }
  255. }
  256. }
  257. }
  258. if ( $update ) {
  259. $updatx = array();
  260. foreach($columns as $k=>$v) {
  261. if (isset($_POST[$k])) {
  262. $updatx[] = " $v = :$values[$k]";
  263. }
  264. }
  265. $sql = sprintf(UPDATE_SQL, $this->table,implode(" , ",$updatx),$update_condition);
  266. } else {
  267. foreach($columns as $k=>$v) {
  268. if (intval(substr($k,0,1)) > 0) {
  269. // -- column starts with a number - unsupported
  270. unset($columns[$k],$values[$k]);
  271. }
  272. if (!isset($_POST[$k])) {
  273. unset($columns[$k],$values[$k]);
  274. }
  275. }
  276. $sql = sprintf(INSERT_SQL, $this->table,implode(", ",$columns),":".implode(", :",$values));
  277. }
  278. $dba->compile($sql);
  279. // -- support multi-value inserts/updates
  280. $multi=false;
  281. foreach ($_POST as $postKey=>$postValue) {
  282. if (is_array($postValue)) {
  283. $cnt++;
  284. $multi=true;
  285. $multiArray = $postValue;
  286. $multiArrayKey = $postKey;
  287. }
  288. }
  289. if ($cnt != 1 && $multi === true) {
  290. $error_message="You can only have 1 multi select for each row.";
  291. return false;
  292. }
  293. if ($multi === false ) {
  294. $f = $dba->execute($_POST);
  295. } else {
  296. foreach ($multiArray as $insertValue) {
  297. $_POST[$multiArrayKey] = $insertValue;
  298. $f = $dba->execute($_POST);
  299. }
  300. }
  301. if ( $f ) {
  302. if ($update) {
  303. return true;
  304. } else {
  305. $lastInsert = mysql_insert_id($this->dba->dbm->dbh);
  306. $_POST[$this->tableDefinition[TABLE_CONFIG][OBJECT_PK]] = $lastInsert;
  307. return $lastInsert;
  308. }
  309. } else {
  310. $str = $dba->getLastError();
  311. if ( substr(strtolower($str),0,9) == "duplicate") {
  312. $error_message="Duplicated data";
  313. $s = strpos($str,"'")+1;
  314. $e = strpos($str,"'",$s);
  315. $err = trim( substr($str,$s,$e-$s) );
  316. foreach($columns as $k => $v) {
  317. if ( $err == $_POST[$v]) {
  318. $verify[$v] = $v;
  319. }
  320. }
  321. } else {
  322. $error_message="There was a database error that occurred in saving this record.";
  323. if ($this->cruddyAdministrator) {
  324. $error_message = $str;
  325. echo $dba->__sql;
  326. }
  327. }
  328. }
  329. }
  330. $total = (get_microtime_ms() - $methodStartTime);
  331. $this->performance['buildGenericForm'][] = $total;
  332. $this->autoTemplate($form,$error_message,$verify,$update,$readOnly,$search);
  333. return false;
  334. }
  335. function update($arr) {
  336. if ( !is_array($arr) ) return false;
  337. $filter=Array();
  338. foreach($arr as $k=>$v) {
  339. $filter[] ="$k = \"".addslashes($v)."\"";
  340. }
  341. $this->doQuery(implode(" && ",$filter));
  342. return$this->buildGenericForm($this->result[0], true, implode(" && ",$filter) );
  343. }
  344. function view($arr) {
  345. if ( !is_array($arr) ) return false;
  346. $filter=Array();
  347. foreach($arr as $k=>$v) {
  348. $filter[] ="$k = \"".addslashes($v)."\"";
  349. }
  350. $this->doQuery(implode(" && ",$filter));
  351. return$this->buildGenericForm($this->result[0], true, implode(" && ",$filter),true);
  352. }
  353. function delete($arr) {
  354. if ( !is_array($arr) ) return false;
  355. $filter=Array();
  356. foreach($arr as $k=>$v) {
  357. $filter[] ="$k = \"".addslashes($v)."\"";
  358. }
  359. $filter = implode(" && ",$filter);
  360. $dba = &$this->dba;
  361. $definitions = &$this->tableDefinition;
  362. $f = $filter == '' ? 'XXXXXXXXX Unsupported XXXXXXXXX' : ' where '.$filter;
  363. $r = $dba->query(GET_TABLES_SQL);
  364. if (empty($r)) {
  365. $parts = explode("/",$this->conn);
  366. $database = $parts[sizeof($parts)-1];
  367. $r = $dba->query(GET_TABLES_SQL." from $database");
  368. if (empty($r)) {
  369. $r = $dba->query("SHOW TABLES FROM $database");
  370. if (empty($r)) {
  371. die("<div class=\"error\">Could not get table listing from $database</div>");
  372. }
  373. }
  374. }
  375. if ( $r ) {
  376. $Table = & $r->bindColumn('Tables_in_'.$dba->info['db']);
  377. $Type = & $r->bindColumn('Table_type');
  378. $dependentRecords = false;
  379. while ( $foo=$r->getNext() ) {
  380. if (strtolower($Table) == strtolower($definitions[TABLE_CONFIG][OBJECT_TABLE])) {
  381. // -- dont check current table
  382. continue;
  383. }
  384. $record2 = $dba->query(sprintf(GET_COLUMNS_SQL,$Table));
  385. if ( $record2 ) {
  386. $Field2 = & $record2->bindColumn('Field');
  387. while ( $foo2=$record2->getNext() ) {
  388. if ($definitions[TABLE_CONFIG][OBJECT_PK] == $Field2) {
  389. // -- rules are if you have a table with the same field name and you didnt specify to OBJECT__CHECK_CONSTRAINTS => false
  390. if ($definitions[TABLE_CONFIG][OBJECT_DELETE_CHECK_CONSTRAINTS] == 1) {
  391. if ($Type == 'BASE TABLE') {
  392. foreach($arr as $k=>$v) {
  393. if ($k == $Field2) {
  394. $valueWhere = $v;
  395. break;
  396. }
  397. }
  398. $record3 = $dba->query("SELECT * FROM ".$Table." WHERE ".$Field2." = '".$valueWhere."'");
  399. if ( $record3->_result != null ) {
  400. if ($_GET['confirm']==1 && $_GET['table']==$Table) {
  401. $dba->query("DELETE FROM ".$Table." WHERE ".$Field2." = '".$valueWhere."'");
  402. header("Location: ".rawurldecode($_GET['redir']));
  403. } else {
  404. $dependentRecords = "There are dependent records in \"".$Table."\" and you cannot delete this ".$Field2.". Would you like to delete these dependent records too? <a href='".$_SERVER['REQUEST_URI']."&table=$Table&confirm=1&redir=".rawurlencode($_SERVER['REQUEST_URI'])."'>Yes</a>";
  405. }
  406. }
  407. }
  408. }
  409. }
  410. }
  411. }
  412. }
  413. if ($dependentRecords==false) {
  414. $r = $dba->execute("delete from ".$this->table." $f");
  415. } else {
  416. $r = false;
  417. echo $dependentRecords;
  418. }
  419. }
  420. return $r != false;
  421. }
  422. function buildSearchWhere($currentTable='') {
  423. $definitions = &$this->tableDefinition;
  424. if ($currentTable!='') {
  425. $definitions = $this->currentAdminDB[CRUD_FIELD_CONFIG][$currentTable];
  426. }
  427. foreach($_COOKIE as $k=>$v) {
  428. if (stristr($k,$definitions[TABLE_CONFIG]['alias']."~")) {
  429. $column = str_replace($definitions[TABLE_CONFIG]['alias']."~","",$k);
  430. if (!empty($v) && $v != "null") {
  431. if (isset($definitions[$column])) {
  432. // -- valid column config with a search cookie value
  433. $where .= " AND `$column` like '%".mysql_real_escape_string($v)."%' ";
  434. // if ($definitions[$column][TABLE]) {
  435. // $res = mysql_query("select ".$definitions[$column][TEXT]." from ".$definitions[$column][TABLE]." WHERE `$column` = '".mysql_real_escape_string($v)."'");
  436. // var_dump(mysql_fetch_assoc($res));
  437. // }
  438. $desc .= "<div style='-moz-border-radius:8px 8px 8px 8px;border: 3px ridge #485254; float: left;cursor:pointer;' onclick='if (window.confirm(\"Do you want to remove the `".$definitions[$column][CAPTION]."` filter?\")) { eraseCookie(\"$k\"); document.location = document.location; } '><span style='font-size: 19px;color:#7F7F7F;'>".$definitions[$column][CAPTION]."</span>&rarr;<span style='font-size: 19px;color:#7F7F7F;'>\"".$v."\"</span></div><div style='float:left;margin-top:7px;'> + </div>";
  439. }
  440. if (!isset($definitions[$column]) && $currentTable!='') {
  441. $desc = '';
  442. $where = '';
  443. }
  444. }
  445. }
  446. }
  447. $desc = substr($desc,0,-49);
  448. return array($where,$desc);
  449. }
  450. /**
  451. * READ
  452. * @param string $filter SQL filter.
  453. */
  454. function read($filter='') {
  455. $methodStartTime = get_microtime_ms();
  456. $definitions = &$this->tableDefinition;
  457. list($wh,$desc) = $this->buildSearchWhere();
  458. if (!stristr($filter,"order")) {
  459. $filter .= $wh;
  460. } elseif ($wh) {
  461. $filter = str_replace("1=1","1=1 $wh", $filter);
  462. }
  463. if (!empty($definitions[TABLE_CONFIG][OBJECT_DEFAULT_ORDER]) && !stristr($filter,"order")) {
  464. $filter .= " ORDER BY `".$definitions[TABLE_CONFIG][OBJECT_DEFAULT_ORDER]."`";
  465. }
  466. $this->doQuery($filter);
  467. $res = &$this->result;
  468. $info = &$this->formParams;
  469. echo "<table>\n";
  470. if ( is_array($res) ) {
  471. echo "<thead>
  472. <tr>";
  473. if ($definitions[TABLE_CONFIG][OBJECT_IS_AGGREGATE]) {
  474. echo "<th>Database</th>";
  475. }
  476. foreach($definitions as $key => $value) {
  477. if ( !is_array($value) || $value[SHOWCOLUMN] == 0 || !isset($value[SHOWCOLUMN])) continue;
  478. // -- if the field doesnt say to NOT sort
  479. if ( ($definitions[TABLE_CONFIG][SORTABLE] == 1 || !isset($definitions[TABLE_CONFIG][SORTABLE])) && !$definitions[TABLE_CONFIG][OBJECT_IS_AGGREGATE]) {
  480. if ($_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_direction']] == 'ASC') {
  481. $direction = 'DESC';
  482. $directionAscii = '&darr;';
  483. } else {
  484. $direction = 'ASC';
  485. $directionAscii = '&uarr;';
  486. }
  487. // -- only set direction arrow if on current field
  488. if (strtoupper($_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_field']]) == strtoupper($key)) {
  489. if ($_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_direction']] == 'ASC') {
  490. $directionAscii = '&uarr;';
  491. } else {
  492. $directionAscii = '&darr;';
  493. }
  494. } else {
  495. $directionAscii = '';
  496. }
  497. if (!empty($_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['page']])) {
  498. $direction .= '&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['page'].'='.$_GET[$definitions[OBJECT_ACTIONS]['page']];
  499. }
  500. $sortLinkStart = "<a href='?action=".strtolower($definitions[TABLE_CONFIG][OBJECT_ACTIONS]['read'].$this->object_key).'&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_field'].'='.$key.'&'.$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['order_direction'].'='.$direction;
  501. if ($this->isPageInclude) {
  502. $sortLinkStart .= "&conf=$this->current_config";
  503. }
  504. $sortLinkStart .= "'>$directionAscii";
  505. $sortLinkEnd = "</a>";
  506. }
  507. echo " <th>".$sortLinkStart.$value[CAPTION].$sortLinkEnd."</th>\n";
  508. $sortLinkStart = $sortLinkEnd = '';
  509. }
  510. echo "</tr>
  511. </thead>";
  512. //
  513. $databases = array();
  514. if ($definitions[TABLE_CONFIG][OBJECT_IS_AGGREGATE]) {
  515. foreach ($definitions[TABLE_CONFIG]['all_databases'] as $server=>$values) {
  516. foreach ($values as $database) {
  517. $databases[$database]['db_name'] = $database;
  518. //$databases[$database]['db_port'] = $definitions[TABLE_CONFIG]['all_ports'][$server];
  519. $databases[$database]['db_password'] = $definitions[TABLE_CONFIG]['all_passwords'][$server];
  520. $databases[$database]['db_server'] = $definitions[TABLE_CONFIG]['all_servers'][$server];
  521. $databases[$database]['db_user'] = $definitions[TABLE_CONFIG]['all_users'][$server];
  522. }
  523. }
  524. } else {
  525. $database = $this->dba->info['db'];
  526. $databases[$database]['db_name'] = $database;
  527. $databases[$database]['db_port'] = $this->dba->info['user'];
  528. $databases[$database]['db_password'] = $this->dba->info['pass'];
  529. $databases[$database]['db_server'] = $this->dba->info['host'];
  530. $databases[$database]['db_user'] = $this->dba->info['user'];
  531. }
  532. $aggregateTotals = array();
  533. foreach ($databases as $dbId=>$dbAttribs) {
  534. $this->dba->setHost($dbAttribs['db_server']);
  535. $this->dba->setPass($dbAttribs['db_password']);
  536. $this->dba->setUser($dbAttribs['db_user']);
  537. $this->dba->connectToNewDB($dbAttribs['db_name']);
  538. $res = array();
  539. $this->doQuery($filter);
  540. $res = &$this->result;
  541. foreach($res as $k => $r) {
  542. $pagedResults = (array)$r;
  543. echo " <tr>\n";
  544. if ($definitions[TABLE_CONFIG][OBJECT_IS_AGGREGATE]) {
  545. echo "<td>{$dbAttribs['db_name']}</td>";
  546. }
  547. $edit_url = $definitions[TABLE_CONFIG][EDIT_LINK];
  548. $del_url = $definitions[TABLE_CONFIG][DELETE_LINK];
  549. if ($definitions[TABLE_CONFIG][OBJECT_HIDE_EDIT_LINK] == 1) {
  550. $edit_url = "";
  551. }
  552. if ($definitions[TABLE_CONFIG][OBJECT_HIDE_DELETE_LINK] == 1) {
  553. $del_url = "";
  554. }
  555. foreach($pagedResults as $k2 => $v2) {
  556. $edit_url = str_replace('%'.$k2.'%', $v2, $edit_url);
  557. $del_url = str_replace('%'.$k2.'%', $v2, $del_url);
  558. }
  559. $count=0;
  560. foreach($definitions as $k => $v) {
  561. if (!is_array($v)) {continue;}
  562. if ( ! isset($v[SHOWCOLUMN]) || $v[SHOWCOLUMN] == 0) continue;
  563. $count++;
  564. $text = "";
  565. if (isset($v[PRETEXTREAD])) {
  566. $processedText = $v[PRETEXTREAD];
  567. foreach($pagedResults as $k2 => $v2) {
  568. $processedText = str_replace('%'.$k2.'%', $v2, rawurldecode($processedText));
  569. }
  570. $text .= $processedText;
  571. }
  572. $dataElementValue = (isset($info[$k]["OPTIONS"][$r[$k]]) && !empty($r[$k])) ? $info[$k]["OPTIONS"][$r[$k]] : $r[$k];
  573. if (is_numeric($dataElementValue)) {
  574. $aggregateTotals[$k] += $dataElementValue;
  575. } /*else {
  576. $aggregateTotals[$k] = 'N/A';
  577. }*/
  578. $text .= htmlentities($dataElementValue);
  579. if (isset($v[POSTTEXTREAD])) {
  580. $processedText = $v[POSTTEXTREAD];
  581. foreach($pagedResults as $k2 => $v2) {
  582. $processedText = str_replace('%'.$k2.'%', $v2, rawurldecode($processedText));
  583. }
  584. $text .= $processedText;
  585. }
  586. if (empty($text) && $text !=='0') {
  587. $text .= "<span style='color:#EBEBEB'>(No ".$v[CAPTION].")</span>";
  588. }
  589. $linkStart = $linkEnd = "";
  590. if ($definitions[TABLE_CONFIG][OBJECT_HIDE_DETAILS_LINK] == 0 && $count == 1) {
  591. $linkStart = "<a href='".str_replace("update_","view_",$edit_url);
  592. if ($this->isPageInclude) {
  593. $linkStart .= "&conf=$this->current_config";
  594. }
  595. $linkStart .= "'>";
  596. $linkEnd = "</a>";
  597. }
  598. if (strlen($text) > 30 && preg_match("|<[^>]+>(.*)</[^>]+>|U",$text)==0 && !stristr($text,"<img") && !stristr($text,"<input")) {
  599. $text = substr($text,0,30)."...";
  600. }
  601. if ($info[$k]["TYPE"] == 'select') {
  602. $parts = parse_url($definitions[TABLE_CONFIG]['connection']);
  603. if (!$this->isPageInclude) {
  604. $text .= " <strong style=\"color:black;\">(<a href=\"?action=view_".str_replace("/","",$parts['path'])."_".$v[TABLE]."&". $v[ID] . "=". $r[$k] ."\">{$r[$k]}</a>)</strong>";
  605. }
  606. }
  607. echo "<td>".$linkStart.stripslashes($text).$linkEnd."</td>\n";
  608. // -- debug the row
  609. //echo "<td>".var_export($r,true)."</td>";
  610. }
  611. if (!empty($edit_url)) {
  612. $edTxt = ($definitions[TABLE_CONFIG][EDIT_TEXT]) ? $definitions[TABLE_CONFIG][EDIT_TEXT] : 'Edit';
  613. $edit = '<a title="Edit this '.$definitions[TABLE_CONFIG][OBJECT_DESC].'" href="'.$edit_url;
  614. if ($this->isPageInclude) {
  615. $linkStart .= "&conf=$this->current_config";
  616. }
  617. $edit .= '">'.$edTxt.'</a> - ';
  618. }
  619. if (!empty($del_url)) {
  620. $delTxt = ($definitions[TABLE_CONFIG][DELETE_TEXT]) ? $definitions[TABLE_CONFIG][DELETE_TEXT] : "Delete";
  621. $delete = '<a title="Delete this '.$definitions[TABLE_CONFIG][OBJECT_DESC].'" href="javascript:if(window.confirm(\'Are you sure you wish to delete this '.$this->object_name.'?\')){document.location=\''.$del_url.'\';}">'.$delTxt.'</a>';
  622. }
  623. if (is_array($definitions[TABLE_CONFIG][OTHER_LINKS])) {
  624. $other = '';
  625. foreach ($definitions[TABLE_CONFIG][OTHER_LINKS] as $key=>$value) {
  626. $other_url = $value;
  627. foreach($r as $k2 => $v2) {
  628. $other_url = str_replace('%'.$k2.'%', $v2, rawurldecode($other_url));
  629. }
  630. $other .= ' - <a href="'.$other_url.'">'.$key.'</a>';
  631. }
  632. }
  633. echo '<td><nobr>'.$edit.$delete.$other.'</nobr></td>'."\n";
  634. echo "</tr>\n";
  635. }
  636. }
  637. if ($definitions[TABLE_CONFIG][OBJECT_IS_AGGREGATE]) {
  638. echo "<tr>";
  639. echo "<td>Totals</td>";
  640. foreach ($aggregateTotals as $kAgg=>$vAgg) {
  641. echo "<td>$vAgg</td>";
  642. }
  643. echo "</tr>\n\n";
  644. }
  645. } else {
  646. echo "<tr> \n";
  647. if ($_COOKIE['current_db']) {
  648. list($void,$db) = explode('-',$_COOKIE['current_db']);
  649. $db .= " ";
  650. }
  651. echo "<td><h2>No ".$db.$definitions[TABLE_CONFIG][OBJECT_DESC]."'s found.</h2></td>";
  652. echo "</tr> \n";
  653. }
  654. echo '</table>';
  655. echo '<p id="paging_links">';
  656. if ($definitions[TABLE_CONFIG][OBJECT_PAGING] -> next_page != "" || !empty($_GET[$definitions[TABLE_CONFIG][OBJECT_ACTIONS]['page']])) {
  657. echo $definitions[TABLE_CONFIG][OBJECT_PAGING] -> first_page;
  658. echo $definitions[TABLE_CONFIG][OBJECT_PAGING] -> previous_page;
  659. echo $definitions[TABLE_CONFIG][OBJECT_PAGING] -> page_links;
  660. echo $definitions[TABLE_CONFIG][OBJECT_PAGING] -> next_page;
  661. echo $definitions[TABLE_CONFIG][OBJECT_PAGING] -> last_page;
  662. }
  663. $this->performance['readGeneric'][] = (get_microtime_ms() - $methodStartTime);
  664. echo '</p>';
  665. }
  666. /**
  667. * Generate a basic template for the form.
  668. *
  669. * @param object $form Form object
  670. * @access private
  671. */
  672. function autoTemplate($form,$error_message,$verify,$update,$readOnly=false,$search=false) {
  673. $methodStartTime = get_microtime_ms();
  674. $def = &$this->tableDefinition;
  675. $formParams = &$this->formParams;
  676. $formParams[INPUT_SUBMIT] = $this->button;
  677. $form->StartLayoutCapture();
  678. if (!empty($error_message)) {
  679. echo '<div class="error">'.$error_message.'</div>';
  680. }
  681. // -- logic to hide/show based on cookies (also show a post text to unset the search cookie)
  682. if ($search == true) {
  683. $disp = "style=\"display:none;\" id=\"{$def[TABLE_CONFIG]['alias']}_search\"";
  684. }
  685. echo '<table '.$disp.' summary="Input fields table">';
  686. if ($search == true) {
  687. $jsSearch = array();
  688. foreach($this->formParams as $inpName => $i) {
  689. $form->inputs[$inpName]['VALUE'] = '';
  690. $p = '';
  691. if (substr($inpName,2) == 'p_') {
  692. $p = 'p_';
  693. }
  694. $newSearchId = $p.$inpName."_search";
  695. $form->inputs[$inpName]['NAME'] = $newSearchId;
  696. $form->inputs[$inpName]['ID'] = $newSearchId;
  697. $form->inputs[$newSearchId] = $form->inputs[$inpName];
  698. unset($form->inputs[$inpName]);
  699. $possibleSearchKey = $def[TABLE_CONFIG]['alias']."~".$inpName;
  700. $possibleSearchVal = $_COOKIE[$possibleSearchKey];
  701. if ($possibleSearchVal) {
  702. $form->inputs[$newSearchId]['VALUE'] = $possibleSearchVal;
  703. }
  704. $jsAll .= "if ($('$newSearchId')) { createCookie('$possibleSearchKey',$('$newSearchId').value,500);} ";
  705. $jsSearch[$inpName.'_search'] = "$('$newSearchId').value='';eraseCookie('$possibleSearchKey');";
  706. }
  707. }
  708. foreach($this->formParams as $inpName => $i) {
  709. $continue = true;
  710. if ($search == true) {
  711. $originalInputName = $inpName;
  712. $inpName = $inpName . "_search";
  713. }
  714. if (is_array($def[TABLE_CONFIG][OTHER_OBJECTS])) {
  715. foreach ($def[TABLE_CONFIG][OTHER_OBJECTS] as $key=>$value) {
  716. if ($key == $inpName) {
  717. $continue = false;
  718. }
  719. }
  720. }
  721. if ( $inpName == INPUT_DOIT || $inpName == INPUT_SUBMIT) {
  722. $continue = false;
  723. }
  724. if (!isset($i['NAME'])) {
  725. $continue = false;
  726. }
  727. if ($continue === true) {
  728. if ( isset($def[$inpName][HIDE]) && $def[$inpName][HIDE] ) {
  729. echo "<tr style=\"display:none;\">\n";
  730. } else {
  731. echo "<tr>\n";
  732. }
  733. echo "<th align=\"right\">";
  734. if ($search) {
  735. echo "<label for=\"$inpName\">".$def[$originalInputName][CAPTION]."</label>";
  736. echo " (<a style=\"cursor:pointer;\" onclick=\"{$jsSearch[$inpName]}\">X</a>)";
  737. } else {
  738. echo $form->AddLabelPart(array("FOR"=>$inpName));
  739. }
  740. echo "</th>\n";
  741. echo "<td>";
  742. if ( isset($def[$inpName][UPDATE_READ_ONLY]) && $def[$inpName][UPDATE_READ_ONLY] || $readOnly === true) {
  743. $form->AddInputReadOnlyPart( $inpName );
  744. } else {
  745. $form->AddInputPart($inpName);
  746. }
  747. if ($search) {
  748. echo " <a style=\"cursor:pointer;\" onclick=\"$('{$def[TABLE_CONFIG]['alias']}_bttn').onclick();\">&rArr;</a>";
  749. }
  750. echo $def[$inpName][COLUMNPOSTTEXT]."</td>\n";
  751. echo "<td>". (IsSet($verify[$inpName]) ? "[Verify]" : "")."</td>\n";
  752. echo "</tr>\n";
  753. }
  754. }
  755. if ( isset($def[TABLE_CONFIG][OTHER_OBJECTS]) && is_array($def[TABLE_CONFIG][OTHER_OBJECTS])) {
  756. // -- for now additional elements draw right before the input box
  757. foreach ($def[TABLE_CONFIG][OTHER_OBJECTS] as $key=>$value) {
  758. echo "<tr>";
  759. if (strtoupper($value['TYPE']) != 'HIDDEN') {
  760. echo '<th align="right">';
  761. echo $this->formParams[$key]['LABEL'];
  762. echo ':</th>';
  763. }
  764. echo "\n<td>";
  765. $form->AddInputPart($key);
  766. echo "</td>\n";
  767. echo "<td></td>\n";
  768. echo "</tr>\n";
  769. }
  770. }
  771. if ($readOnly === false && $search == false) {
  772. echo '<tr><th align="right"></th>';
  773. echo "\n";
  774. echo '<td>';
  775. echo '<input name="'.INPUT_DOIT.'" value="1" TYPE="hidden"/><input name="'.INPUT_SUBMIT.'" value="'.$this->formParams[INPUT_SUBMIT]["VALUE"].'" onclick="if(this.disabled || typeof(this.disabled)==\'boolean\') this.disabled=true ; form_submitted_test=form_submitted ; form_submitted=true ; form_submitted=(!form_submitted_test || confirm(\''.$form->ResubmitConfirmMessage.'\')) ; if(this.disabled || typeof(this.disabled)==\'boolean\') this.disabled=false ; sub_form=\'\' ; return true" id="'.INPUT_SUBMIT.'" type="submit">';
  776. echo "</td>\n";
  777. echo "<td></td>\n";
  778. echo "</tr>\n";
  779. } elseif ($search == true) {
  780. foreach ($jsSearch as $k=>$v) {
  781. $tmp .= $v;
  782. }
  783. echo '<tr><th><input value="Clear All" onclick="'.$tmp.'" type="button"></th>';
  784. echo '<td>';
  785. echo '<input value="Search" id="'.$def[TABLE_CONFIG]['alias'].'_bttn" onclick="'.$jsAll.'document.location = location.pathname + \'?action=show_'.$def[TABLE_CONFIG]['alias'].'\';" type="button">';
  786. echo "</td>";
  787. echo "<td></td>";
  788. echo "</tr>";
  789. }
  790. echo '</table>';
  791. $form->EndLayoutCapture();
  792. $form->DisplayOutput();
  793. $total = (get_microtime_ms() - $methodStartTime);
  794. $this->performance['autoTemplate'][] = $total;
  795. }
  796. /**
  797. * Get information about the table
  798. *
  799. * @access private.
  800. */
  801. function getTableInformation($insert=false) {
  802. $methodStartTime = get_microtime_ms();
  803. $dba = &$this->dba;
  804. $info = &$this->tableDefinition;
  805. unset($this->formParams);
  806. $formParams = &$this->formParams;
  807. $sql = sprintf(GET_COLUMNS_SQL,$this->table);
  808. $record = $dba->query($sql);
  809. if ( !$record )
  810. return false;
  811. $Field = & $record->bindColumn('Field');
  812. $Type = & $record->bindColumn('Type');
  813. $Null = & $record->bindColumn('Null');
  814. $Key = & $record->bindColumn('Key');
  815. $Extra = & $record->bindColumn('Extra');
  816. $Default = & $record->bindColumn('Default');
  817. $Comment = & $record->bindColumn('Comment');
  818. while ( $foo=$record->getNext() ) {
  819. $actInfo = & $info[$Field];
  820. if (stristr($Comment,"lookup")) {
  821. list($type,$table,$field,$value) = explode(",",$Comment);
  822. $actInfo[TABLE] = trim($table);
  823. $actInfo[ID] = trim($field);
  824. $actInfo[TEXT] = trim($value);
  825. }
  826. $actInfoFormOverRides = & $info[$Field."_config"];
  827. /* reseting form information */
  828. $form = array();
  829. if ($Extra == 'auto_increment') {
  830. continue;
  831. }
  832. /**
  833. * If the field is autoincrement, we
  834. * do not need to show it on the form.
  835. */
  836. $display = "";
  837. if ( isset($actInfo[HIDE]) && $actInfo[HIDE] ) {
  838. $form["READONLY"] = "true";
  839. }
  840. $this->comments[$Field] = $Comment;
  841. $this->datatypes[$Field] = $Type;
  842. $autoType = $this->parseColumnInfo($Type,$foo['Default'],$Field);
  843. $form["NAME"] = trim($Field);
  844. $form["ID"] = $form["NAME"];
  845. // -- if table is configured as not null then user has to enter something
  846. /*if (strtoupper($Null) == 'NO') {
  847. $form["ValidateAsNotEmpty"] = 1;
  848. }*/
  849. // -- if developer tells class that the field is non-required then set dont set as required
  850. if($actInfo[REQUIRED] == 1 && isset($actInfo[REQUIRED])) {
  851. $form["ValidateAsNotEmpty"] = 1;
  852. $form["Optional"] = false;
  853. $form["LABEL"] .="<span class='required'>".$info[TABLE_CONFIG][REQUIRED_TEXT]."</span>";
  854. } else {
  855. $form["Optional"] = true;
  856. unset($form["ValidateAsNotEmpty"]);
  857. }
  858. $form["LABEL"] = isset($actInfo[CAPTION]) ? $actInfo[CAPTION] : $Field;
  859. if (isset($actInfo[TABLE]) && isset($actInfo[ID]) && isset($actInfo[TEXT])) {
  860. $form["TYPE"] = "select";
  861. $opt = & $form["OPTIONS"];
  862. if (isset($actInfo[WHERE])) {
  863. $where = " where ".$actInfo[WHERE]." order by `".$actInfo[TEXT]."` ASC";
  864. }
  865. if (substr($actInfo[ID],0,23) == '___distinct___lookup___' || substr($actInfo[TEXT],0,23) == '___distinct___lookup___') {
  866. $distinct = "distinct";
  867. $actInfo[ID] = substr($actInfo[ID],23);
  868. $actInfo[TEXT] = substr($actInfo[TEXT],23);
  869. }
  870. $rec1 = $dba->query("select ".$distinct." ".$actInfo[ID].",".$actInfo[TEXT]." from ".$actInfo[TABLE].$where);
  871. if ( !$rec1 ) {
  872. continue;
  873. }
  874. //@ToDo - say couldnt join if admin
  875. $opt[""] = "Select a : ".$form["LABEL"];
  876. while ( $f = $rec1->getNext() ) {
  877. if ( !isset($form["VALUE"]) ) $form["VALUE"]= "";
  878. if (strlen($f[ $actInfo[TEXT] ]) > 300 ) {
  879. $val = substr($f[ $actInfo[TEXT] ],0,300)."...";
  880. } else {
  881. $val = $f[ $actInfo[TEXT] ];
  882. }
  883. $this->cachedLookup[$hash]["ID"] = $f[$actInfo[ID] ];
  884. $this->cachedLookup[$hash]["VALUE"] = $val;
  885. $opt[ $f[$actInfo[ID] ] ] = $val;
  886. }
  887. if ($actInfoFormOverRides['TYPE'] != 'select_multi') {
  888. unset($actInfoFormOverRides['TYPE']);
  889. }
  890. } else if ( isset($actInfo[SELECT]) ){
  891. $form["TYPE"] = "select";
  892. $form["OPTIONS"] = array_merge(array(""=>"Select: ".$form["LABEL"]),$actInfo[SELECT]);
  893. $form["VALUE"] = array_shift( array_keys($actInfo[SELECT]) );
  894. } else {
  895. $form["TYPE"] = $autoType["TYPE"];
  896. }
  897. $form["ValidationErrorMessage"] = "'".$form["LABEL"]."' is required.";
  898. if (is_array($autoType)) {
  899. foreach ($autoType as $autoTypeKey=>$autoTypeVal) {
  900. if (!isset($form[$autoTypeKey])) {
  901. $form[$autoTypeKey] = $autoType[$autoTypeKey];
  902. }
  903. }
  904. }
  905. if ( $type["TYPE"]=="select" ) {
  906. $form["VALUE"] = strlen($Default)>0? $Default : current($form["OPTIONS"]);
  907. }
  908. /**
  909. * Override Field Configuration based on field_config array
  910. */
  911. if (!empty($actInfoFormOverRides)) {
  912. foreach ($actInfoFormOverRides as $option=>$optionValue) {
  913. $form[$option] = $optionValue;
  914. }
  915. }
  916. if (isset($form['ValidateAsURL'])) {
  917. unset($form['ValidateAsURL']);
  918. $form["ReplacePatterns"] = array(
  919. "^[ \t\r\n]+"=>"",
  920. "[ \t\r\n]+\$"=>"",
  921. "^([wW]{3}\\.)"=>"http://\\1",
  922. "^([^:]+)\$"=>"http://\\1",
  923. "^(http|https)://(([-!#\$%&'*+.0-9=?A-Z^_`a-z{|}~]+\.)+[A-Za-z]{2,6}(:[0-9]+)?)\$"=>"\\1://\\2/"
  924. );
  925. $form["ValidateRegularExpression"] = '^(http|https)\://(([-!#\$%&\'*+.0-9=?A-Z^_`a-z{|}~]+\.)+[A-Za-z]{2,6})(\:[0-9]+)?(/)?/';
  926. $form["ValidationErrorMessage"] = (!isset($form["ValidateAsURLErrorMessage"])) ? "This is not a valid URL" : $form["ValidateAsURLErrorMessage"];;
  927. }
  928. if ($actInfoFormOverRides['TYPE'] == 'select_multi') {
  929. $form["TYPE"] = "select";
  930. $form["SIZE"] = "8";
  931. $form["NAME"] = $Field."[]";
  932. $form["ValidateOnlyOnClientSide"] = true;
  933. $form["ExtraAttributes"] = array("multiple"=>"multiple");
  934. }
  935. if ($form['TYPE'] == 'wysiwyg' || $actInfoFormOverRides['TYPE'] == 'wysiwyg') {
  936. unset($form['TYPE']);
  937. require_once("form_FCKEditor.php");
  938. $form["TYPE"] = "custom";
  939. $form["CustomClass"] = "form_FCKEditor";
  940. $form["BasePath"] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."fck/";
  941. $form["HEIGHT"] = 400;
  942. $form["WIDTH"] = 800;
  943. $form["Skin"] = "silver";
  944. $form["UsesAutoFormName"] = "instance";
  945. }
  946. if ($form['TYPE'] == 'date' || $form['TYPE'] == 'timestamp') {
  947. $form["TYPE"] = "custom";
  948. $form["CustomClass"] = "form_date_class";
  949. if ($insert=='search') {
  950. $form["VALUE"] = '';
  951. $form["ChooseControl"] = 0;
  952. } else {
  953. $form["VALUE"] = 'now';
  954. $form["ChooseControl"] = 1;
  955. }
  956. $form["Format"] = "{day}/{month}/{year}";
  957. $form["Months"] = array(
  958. ""=>"Select A Month",
  959. "01"=>"January",
  960. "02"=>"February",
  961. "03"=>"March",
  962. "04"=>"April",
  963. "05"=>"May",
  964. "06"=>"June",
  965. "07"=>"July",
  966. "08"=>"August",
  967. "09"=>"September",
  968. "10"=>"October",
  969. "11"=>"November",
  970. "12"=>"December"
  971. );
  972. }
  973. if (!isset($form["STYLE"]) && $form['TYPE'] == 'textarea') {
  974. $form["STYLE"] = "WIDTH:500px;HEIGHT:250px;";
  975. }
  976. if ($form['TYPE'] == 'select' && $actInfoFormOverRides['TYPE'] != 'select_multi' && isset($form['SIZE'])) {
  977. unset($form['SIZE']);
  978. }
  979. $formParams[$Field] = $form;
  980. }
  981. if ( isset($info[TABLE_CONFIG][OTHER_OBJECTS]) && is_array($info[TABLE_CONFIG][OTHER_OBJECTS]) ) {
  982. // -- for now additional elements draw right before the input box
  983. foreach ($info[TABLE_CONFIG][OTHER_OBJECTS] as $key=>$value) {
  984. $formParams[$key] = $value;
  985. }
  986. }
  987. $this->performance['getTableInfo'][] = (get_microtime_ms() - $methodStartTime);
  988. }
  989. /**
  990. * Analyze the column type, parse it, and return
  991. * to the class for prepare the form.
  992. *
  993. * @access private
  994. * @param string $type MySQL column description
  995. * @return array Parsed information
  996. */
  997. function parseColumnInfo($type,$Default,$Field) {
  998. $type = trim($type);
  999. $pos = strpos($type,'(');
  1000. if ( $pos !== false) {
  1001. $extra = substr($type,$pos+1);
  1002. $extra[strlen($extra)-1] = ' ';
  1003. $type = substr($type,0,$pos);
  1004. }
  1005. $return = array();
  1006. if (!empty($Default)) {
  1007. $return["VALUE"] = $Default;
  1008. }
  1009. switch( strtolower($type) ) {
  1010. case "int":
  1011. $return["TYPE"] = "text";
  1012. $return["MAXLENGTH"] = $extra;
  1013. $return["SIZE"] = (floor($extra/1.5) > 50) ? 50 : floor($extra/1.5);
  1014. if ($Field == $this->tableDefinition[TABLE_CONFIG][OBJECT_PK]) {
  1015. $return["ValidateAsInteger"] = 1;
  1016. }
  1017. break;
  1018. case "float":
  1019. $t=explode(",",$extra);
  1020. $return["TYPE"] = "text";
  1021. $return["MAXLENGTH"] = $t[0]+$t[1]+1;
  1022. $return["SIZE"] = (floor($t[0]+$t[1]+1/1.5) > 50) ? 50 : floor($t[0]+$t[1]+1/1.5);;
  1023. if ($Field == $this->tableDefinition[TABLE_CONFIG][OBJECT_PK]) {
  1024. $return["ValidateAsFloat"] = 1;
  1025. }
  1026. break;
  1027. case "varchar":
  1028. $return["TYPE"] = "text";
  1029. $return["MAXLENGTH"] = $extra;
  1030. $return["SIZE"] = (floor($extra/1.5) > 50) ? 50 : floor($extra/1.5);
  1031. if ($Field == $this->tableDefinition[TABLE_CONFIG][OBJECT_PK]) {
  1032. $return["ValidateAsNotEmpty"] = 1;
  1033. }
  1034. break;
  1035. case "mediumtext":
  1036. case "longtext":
  1037. $return["TYPE"] = "textarea";
  1038. $return["STYLE"] = "WIDTH:500px;HEIGHT:250px;";
  1039. $return["MAXLENGTH"] = ($type == 'mediumtext') ? 16777215 : 4294967296;
  1040. break;
  1041. case "date":
  1042. require_once("form_date.php");
  1043. $return["TYPE"] = "custom";
  1044. $return["CustomClass"] = "form_date_class";
  1045. $return["VALUE"] = 'now';
  1046. $return["ChooseControl"] = 1;
  1047. $return["Format"] = "{day}/{month}/{year}";
  1048. $return["Months"] = array(
  1049. ""=>"Select A Month",
  1050. "01"=>"January",
  1051. "02"=>"February",
  1052. "03"=>"March",
  1053. "04"=>"April",
  1054. "05"=>"May",
  1055. "06"=>"June",
  1056. "07"=>"July",
  1057. "08"=>"August",
  1058. "09"=>"September",
  1059. "10"=>"October",
  1060. "11"=>"November",
  1061. "12"=>"December"
  1062. );
  1063. break;
  1064. case "timestamp":
  1065. case "datetime":
  1066. require_once("form_date.php");
  1067. $return["TYPE"] = "custom";
  1068. $return["CustomClass"] = "form_date_class";
  1069. $return["VALUE"] = 'now';
  1070. $return["ChooseControl"] = 1;
  1071. $return["Format"] = "{day}/{month}/{year}";
  1072. $return["Months"] = array(
  1073. ""=>"Select A Month",
  1074. "01"=>"January",
  1075. "02"=>"February",
  1076. "03"=>"March",
  1077. "04"=>"April",
  1078. "05"=>"May",
  1079. "06"=>"June",
  1080. "07"=>"July",
  1081. "08"=>"August",
  1082. "09"=>"September",
  1083. "10"=>"October",
  1084. "11"=>"November",
  1085. "12"=>"December"
  1086. );
  1087. break;
  1088. case "enum":
  1089. $return["TYPE"] = "select";
  1090. $options = & $return["OPTIONS"];
  1091. $return["OPTIONS"][""] = "Select One";
  1092. $max = strlen($extra);
  1093. $buf = "";
  1094. for($i=0; $i < $max; $i++)
  1095. switch ( $extra[$i] ) {
  1096. case "'":
  1097. case '"':
  1098. $end = $extra[$i++];
  1099. for(;$i < $max && $extra[$i] != $end; $i++) {
  1100. if ( $extra[$i] == "\\") {
  1101. $buf .= $extra[$i+1];
  1102. $i++;
  1103. continue;
  1104. }
  1105. $buf .= $extra[$i];
  1106. }
  1107. break;
  1108. case ",":
  1109. $options[$buf] = $buf;
  1110. $buf = "";
  1111. break;
  1112. }
  1113. if ( $buf!='') {
  1114. $return["OPTIONS"][$buf] = $buf;
  1115. }
  1116. break;
  1117. default:
  1118. $return["TYPE"] = "text";
  1119. break;
  1120. }
  1121. return $return;
  1122. }
  1123. }
  1124. class cruddyMysqlAdmin extends cruddyMysql {
  1125. function cruddyMysqlAdmin() {
  1126. if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  1127. $this->isWindows = true;
  1128. $this->systemDirectorySeparator = '\\';
  1129. } else {
  1130. $this->isWindows = false;
  1131. $this->systemDirectorySeparator = '/';
  1132. }
  1133. $this->paintedHead = false;
  1134. $this->adminFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator."crud_".$_SERVER['SERVER_NAME']."_".ABS_PATH_HASH.".config.php";
  1135. $this->functionsFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator."crud_".$_SERVER['SERVER_NAME']."_".ABS_PATH_HASH.".custom.functions.php";
  1136. $this->functionsDrawFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator."crud_".$_SERVER['SERVER_NAME']."_".ABS_PATH_HASH.".draw.functions.php";
  1137. $this->databaseConnectionFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator."crud_".$_SERVER['SERVER_NAME']."_".ABS_PATH_HASH.".connections.php";
  1138. if ($this->adminDBExists()) {
  1139. $this->currentAdminDB = $this->readAdminDB();
  1140. }
  1141. $this->steps[1] = 'initialize_server';
  1142. $this->steps[2] = 'select_database';
  1143. $this->steps[3] = 'select_tables';
  1144. $this->steps[4] = 'select_groups';
  1145. $this->steps[5] = 'select_roles';
  1146. $this->steps[6] = 'select_users';
  1147. $this->steps[7] = 'select_theme';
  1148. $this->cruddyAdministrator = (isset($_COOKIE['current_role'])) ? $this->currentAdminDB['crud']['roles'][$_COOKIE['current_role']]['admin_role'] : false;
  1149. $this->dateTime = date("Y-m-j H:i:s");
  1150. // -- update these to whayou want your get string to look like with concatenated TABLE by the time the user clicks
  1151. $this->actionTypes = array();
  1152. $this->actionTypes['new'] = "new_"; // + {TABLENAME} will be concatenated to match the action
  1153. $this->actionTypes['delete'] = "delete_"; // + {TABLENAME}
  1154. $this->actionTypes['update'] = "update_"; // + {TABLENAME}
  1155. $this->actionTypes['read'] = "show_"; // + {TABLENAME}
  1156. $this->actionTypes['view'] = "view_"; // + {TABLENAME}
  1157. $this->actionTypes['order_field'] = "sort_by"; // no additional
  1158. $this->actionTypes['order_direction'] = "direction"; // no additional
  1159. $this->actionTypes['page'] = "page"; // no additional
  1160. $this->tableControlDefaults = array();
  1161. $this->tableControlDefaults[EDIT_TEXT] = "Edit";
  1162. $this->tableControlDefaults[DELETE_TEXT] = "Delete";
  1163. $this->tableControlDefaults[ADD_TEXT] = "Add New {table_desc}";
  1164. $this->tableControlDefaults[TABLE_TEXT] = "{table_desc} Administration";
  1165. $this->tableControlDefaults[VIEW_TEXT] = "View";
  1166. $this->tableControlDefaults[SEARCH_TEXT] = "Search";
  1167. $this->tableControlDefaults[OBJECT_DELETE_CHECK_CONSTRAINTS] = 0;
  1168. $this->tableControlDefaults[OBJECT_HIDE_DELETE_LINK] = 0;
  1169. $this->tableControlDefaults[OBJECT_HIDE_EDIT_LINK] = 0;
  1170. $this->tableControlDefaults[OBJECT_HIDE_NEW_LINK] = 0;
  1171. $this->tableControlDefaults[OBJECT_HIDE_VIEW_LINK] = 0;
  1172. $this->tableControlDefaults[OBJECT_HIDE_SEARCH_LINK] = 0;
  1173. $this->tableControlDefaults[OBJECT_HIDE_DETAILS_LINK] = 0;
  1174. $this->tableControlDefaults[OBJECT_DELETE_CHECK_CONSTRAINTS] = 0;
  1175. $this->tableControlDefaults[OBJECT_PAGING] = 1;
  1176. $this->tableControlDefaults[OBJECT_ACTIONS] = $this->actionTypes;
  1177. $this->tableControlDefaults[REQUIRED_TEXT] = "*";
  1178. $this->tableControlDefaults[OBJECT_PAGING_NUM_ROWS_PER_PAGE] = 10;
  1179. $this->tableControlDefaults[OBJECT_PAGING_SCROLL] = 5;
  1180. $this->tableControlType = array();
  1181. $this->tableControlType[0]['desc'] = "Table Name";
  1182. $this->tableControlType[0]['type'] = "";
  1183. $this->tableControlType[OBJECT_DESC]['desc'] = "Table Desc.";
  1184. $this->tableControlType[OBJECT_DESC]['type'] = "text";
  1185. $this->tableControlType[TABLE_TEXT]['desc'] = "Table Name Text";
  1186. $this->tableControlType[TABLE_TEXT]['type'] = "text";
  1187. $this->tableControlType[EDIT_TEXT]['desc'] = "Edit Link Text or Image Src";
  1188. $this->tableControlType[EDIT_TEXT]['type'] = "text";
  1189. $this->tableControlType[ADD_TEXT]['desc'] = "Add Link Text or Image Src";
  1190. $this->tableControlType[ADD_TEXT]['type'] = "text";
  1191. $this->tableControlType[VIEW_TEXT]['desc'] = "View Link Text or Image Src";
  1192. $this->tableControlType[VIEW_TEXT]['type'] = "text";
  1193. $this->tableControlType[SEARCH_TEXT]['desc'] = "Search Link Text or Image Src";
  1194. $this->tableControlType[SEARCH_TEXT]['type'] = "text";
  1195. $this->tableControlType[DELETE_TEXT]['desc'] = "Delete Link Text or Image Src";
  1196. $this->tableControlType[DELETE_TEXT]['type'] = "text";
  1197. $this->tableControlType[OBJECT_DELETE_CHECK_CONSTRAINTS]['desc'] = "Referential Integrity<br/>On Same Fields?";
  1198. $this->tableControlType[OBJECT_DELETE_CHECK_CONSTRAINTS]['type'] = "checkbox";
  1199. /*$this->tableControlType[OBJECT_PK]['desc'] = "Primary Key";
  1200. $this->tableControlType[OBJECT_PK]['type'] = "text";*/
  1201. $this->tableControlType[OBJECT_DEFAULT_ORDER]['desc'] = "Default Order<br/>{FIELDNAME} DESC/ASC";
  1202. $this->tableControlType[OBJECT_DEFAULT_ORDER]['type'] = "text";
  1203. $this->tableControlType[OBJECT_READ_FILTER]['desc'] = "WHERE Clause Filter On Read";
  1204. $this->tableControlType[OBJECT_READ_FILTER]['type'] = "text";
  1205. $this->tableControlType[OBJECT_FILTER_DESC]['desc'] = "Description of Filter";
  1206. $this->tableControlType[OBJECT_FILTER_DESC]['type'] = "text";
  1207. $this->tableControlType[OBJECT_HIDE_NEW_LINK]['desc'] = "Hide \"Create\" Link";
  1208. $this->tableControlType[OBJECT_HIDE_NEW_LINK]['type'] = "checkbox";
  1209. $this->tableControlType[OBJECT_HIDE_DELETE_LINK]['desc'] = "Hide \"Delete\" Link";
  1210. $this->tableControlType[OBJECT_HIDE_DELETE_LINK]['type'] = "checkbox";
  1211. $this->tableControlType[OBJECT_HIDE_EDIT_LINK]['desc'] = "Hide \"Edit\" Link";
  1212. $this->tableControlType[OBJECT_HIDE_EDIT_LINK]['type'] = "checkbox";
  1213. $this->tableControlType[OBJECT_HIDE_VIEW_LINK]['desc'] = "Hide \"View\" Link";
  1214. $this->tableControlType[OBJECT_HIDE_VIEW_LINK]['type'] = "checkbox";
  1215. $this->tableControlType[OBJECT_HIDE_SEARCH_LINK]['desc'] = "Hide \"Search\…

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