PageRenderTime 44ms CodeModel.GetById 18ms 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
  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\" Link";
  1216. $this->tableControlType[OBJECT_HIDE_SEARCH_LINK]['type'] = "checkbox";
  1217. $this->tableControlType[OBJECT_HIDE_DETAILS_LINK]['desc'] = "Hide \"Details\" Link";
  1218. $this->tableControlType[OBJECT_HIDE_DETAILS_LINK]['type'] = "checkbox";
  1219. $this->tableControlType[OBJECT_PAGING]['desc'] = "Show Paging<br/>(Default 10 Records/Page)";
  1220. $this->tableControlType[OBJECT_PAGING]['type'] = "checkbox";
  1221. $this->tableControlType[OBJECT_PAGING_NUM_ROWS_PER_PAGE]['desc'] = "# of Rows<br/>Per Page";
  1222. $this->tableControlType[OBJECT_PAGING_NUM_ROWS_PER_PAGE]['type'] = "text";
  1223. $this->tableControlType[OBJECT_PAGING_SCROLL]['desc'] = "Number of Pages<br/>Linked Ahead";
  1224. $this->tableControlType[OBJECT_PAGING_SCROLL]['type'] = "text";
  1225. $this->tableControlType[REQUIRED_TEXT]['desc'] = "Required<br/>Post Text";
  1226. $this->tableControlType[REQUIRED_TEXT]['type'] = "text";
  1227. //uneditable tableControlTypes not avail in the interface for now and are managed in the core class logic
  1228. // OBJECT_CONNECTION_STRING - automatically set - @todo autoupdate when old server and password change
  1229. // OBJECT_ACTIONS - based on actions in constructor
  1230. // OBJECT_TABLE - automatically set
  1231. // OTHER_OBJECTS -- this could and should be populated manually as an advanced config in your pre_process_load_ function if you want other objects available in the DOM of the crud form. Dont worry about storing it in the serialized array
  1232. $this->fieldControlDefaults = array();
  1233. $this->fieldControlDefaults[SORTABLE] = 1;
  1234. $this->fieldControlDefaults[REQUIRED] = 0;
  1235. $this->fieldControlDefaults[SHOWCOLUMN] = 1;
  1236. $this->fieldControlType = array();
  1237. $this->fieldControlType[CAPTION]['desc'] = "Field Caption";
  1238. $this->fieldControlType[CAPTION]['type'] = "text";
  1239. $this->fieldControlType[SHOWCOLUMN]['desc'] = "Show Column On Read";
  1240. $this->fieldControlType[SHOWCOLUMN]['type'] = "checkbox";
  1241. $this->fieldControlType[UPDATE_READ_ONLY]['desc'] = "Read Only";
  1242. $this->fieldControlType[UPDATE_READ_ONLY]['type'] = "checkbox";
  1243. $this->fieldControlType[HIDE]['desc'] = "Hide On Insert";
  1244. $this->fieldControlType[HIDE]['type'] = "checkbox";
  1245. $this->fieldControlType[REQUIRED]['desc'] = "Required Field";
  1246. $this->fieldControlType[REQUIRED]['type'] = "checkbox";
  1247. $this->fieldControlType[TABLE]['desc'] = "Lookup Table";
  1248. $this->fieldControlType[TABLE]['type'] = "text";
  1249. $this->fieldControlType[ID]['desc'] = "Lookup Field (Key/ID)";
  1250. $this->fieldControlType[ID]['type'] = "text";
  1251. $this->fieldControlType[TEXT]['desc'] = "Lookup Field <br/>(Description)";
  1252. $this->fieldControlType[TEXT]['type'] = "text";
  1253. $this->fieldControlType[COLUMNPOSTTEXT]['desc'] = "Post Text<br/>(Add/Update)";
  1254. $this->fieldControlType[COLUMNPOSTTEXT]['type'] = "text";
  1255. $this->fieldControlType[PRETEXTREAD]['desc'] = "Pre-Text<br/>(On Read)";
  1256. $this->fieldControlType[PRETEXTREAD]['type'] = "text";
  1257. $this->fieldControlType[POSTTEXTREAD]['desc'] = "Post-Text<br/>(On Read)";
  1258. $this->fieldControlType[POSTTEXTREAD]['type'] = "text";
  1259. $this->fieldControlType[SORTABLE]['desc'] = "Sortable";
  1260. $this->fieldControlType[SORTABLE]['type'] = "checkbox";
  1261. $this->fieldConfigType = array();
  1262. $this->fieldConfigType["TYPE"]['desc'] = "Input Type";
  1263. $this->fieldConfigType["TYPE"]['type'] = "link";
  1264. $this->fieldConfigType["VALUE"]['desc'] = "Default Value";
  1265. $this->fieldConfigType["VALUE"]['type'] = "text";
  1266. $this->fieldObjectTypes = array();
  1267. $this->fieldObjectTypes['file']['desc'] = "File Upload";
  1268. $this->fieldObjectTypes['text']['desc'] = "Text";
  1269. $this->fieldObjectTypes['password']['desc'] = "Password";
  1270. $this->fieldObjectTypes['checkbox']['desc'] = "Checkbox";
  1271. //$this->fieldObjectTypes['radio']['desc'] = "Radio";
  1272. $this->fieldObjectTypes['hidden']['desc'] = "Hidden";
  1273. $this->fieldObjectTypes['textarea']['desc'] = "Text Area";
  1274. $this->fieldObjectTypes['select']['desc'] = "Select Box";
  1275. $this->fieldObjectTypes['select_multi']['desc'] = "Select Box (Multi)";
  1276. $this->fieldObjectTypes['wysiwyg']['desc'] = "HTML Editor";
  1277. $this->fieldObjectTypes['date']['desc'] = "Date";
  1278. $this->fieldObjectTypes['timestamp']['desc'] = "Time Stamp";
  1279. $this->fieldValidationTypes = array();
  1280. $this->fieldValidationTypes['ValidateAsEmail']['desc'] = "Validate As Email";
  1281. $this->fieldValidationTypes['ValidateRegularExpression']['desc'] = "Validate Regular Expression (Match Found)";
  1282. $this->fieldValidationTypes['ValidateAsURL']['desc'] = "Validate As URL";
  1283. $this->fieldValidationTypes['ValidateAsNotRegularExpression']['desc'] = "Validate Regular Expression (Match Not Found)";
  1284. $this->fieldValidationTypes['ValidateAsNotEmpty']['desc'] = "Validate as Not Empty";
  1285. $this->fieldValidationTypes['ValidateMinimumLength']['desc'] = "Validate Minimum Length";
  1286. $this->fieldValidationTypes['ValidateAsEqualTo']['desc'] = "Validate As Equal To";
  1287. $this->fieldValidationTypes['ValidateAsDifferentFrom']['desc'] = "Validate As Different From";
  1288. $this->fieldValidationTypes['ValidateAsInteger']['desc'] = "Validate As Integer";
  1289. $this->fieldValidationTypes['ValidateAsFloat']['desc'] = "Validate As Float";
  1290. $this->fieldValidationTypes['DiscardInvalidValues']['desc'] = "Discard Invalid Values";
  1291. $this->fieldValidationTypes['ReplacePatterns']['desc'] = "Replace Patterns";
  1292. $this->fieldValidationTypes['Capitalization']['desc'] = "Capitalization";
  1293. $this->fieldEventTypes = array();
  1294. $this->fieldEventTypes['ONBLUR']['desc'] = "On Blur";
  1295. $this->fieldEventTypes['ONCLICK']['desc'] = "On Click";
  1296. $this->fieldEventTypes['ONCHANGE']['desc'] = "On Change";
  1297. $this->fieldEventTypes['ONDBLCLICK']['desc'] = "On Double Click";
  1298. $this->fieldEventTypes['ONFOCUS']['desc'] = "On Focus";
  1299. $this->fieldEventTypes['ONKEYDOWN']['desc'] = "On Key Down";
  1300. $this->fieldEventTypes['ONKEYUP']['desc'] = "On Key Up";
  1301. $this->fieldEventTypes['ONMOUSEDOWN']['desc'] = "On Mouse Down";
  1302. $this->fieldEventTypes['ONMOUSEMOVE']['desc'] = "On Mouse Move";
  1303. $this->fieldEventTypes['ONMOUSEOUT']['desc'] = "On Mouse Out";
  1304. $this->fieldEventTypes['ONMOUSEOVER']['desc'] = "On Mouse Over";
  1305. $this->fieldEventTypes['ONMOUSEUP']['desc'] = "On Mouse Up";
  1306. $this->fieldMiscTypes = array();
  1307. $this->fieldMiscTypes['TITLE']['desc'] = "Title";
  1308. $this->fieldMiscTypes['TITLE']['type'] = "text";
  1309. $this->fieldMiscTypes['TABINDEX']['desc'] = "Table Index";
  1310. $this->fieldMiscTypes['TABINDEX']['testdata'] = "5";
  1311. $this->fieldMiscTypes['TABINDEX']['type'] = "text";
  1312. $this->fieldMiscTypes['STYLE']['desc'] = "Inline Style";
  1313. $this->fieldMiscTypes['STYLE']['testdata'] = "background-color:black;color:white;";
  1314. $this->fieldMiscTypes['STYLE']['type'] = "textarea";
  1315. $this->fieldMiscTypes['CLASS']['desc'] = "Class Name";
  1316. $this->fieldMiscTypes['CLASS']['testdata'] = "none";
  1317. $this->fieldMiscTypes['CLASS']['type'] = "text";
  1318. $this->fieldMiscTypes['LABEL']['desc'] = "Label Name";
  1319. $this->fieldMiscTypes['LABEL']['type'] = "text";
  1320. $this->fieldMiscTypes['MOVE_TO']['desc'] = "Location To Move:";
  1321. $this->fieldMiscTypes['MOVE_TO']['type'] = "text";
  1322. $this->fieldMiscTypes['MIME']['desc'] = "Mime Type Field Storage:";
  1323. $this->fieldMiscTypes['MIME']['type'] = "text";
  1324. $this->fieldMiscTypes['FILE_SIZE']['desc'] = "File Size Field Storage:";
  1325. $this->fieldMiscTypes['FILE_SIZE']['type'] = "text";
  1326. $this->fieldMiscTypes['ACCESSKEY']['desc'] = "Access Key";
  1327. $this->fieldMiscTypes['ACCESSKEY']['testdata'] = "t";
  1328. $this->fieldMiscTypes['ACCESSKEY']['type'] = "text";
  1329. $this->fieldMiscTypes['ExtraAttributes']['desc'] = "Extra Attributes";
  1330. $this->fieldMiscTypes['ExtraAttributes']['testdata'] = "";
  1331. $this->fieldMiscTypes['ExtraAttributes']['type'] = "text";
  1332. }
  1333. function paintHead() {
  1334. if ($this->paintedHead !== true) {
  1335. $this->paintedHead = true;
  1336. if (isset($crudAdmin->currentAdminDB['crud']['console_name'])) {
  1337. $desc = $crudAdmin->currentAdminDB['crud']['console_name']." Administrator";
  1338. }
  1339. /*else {
  1340. $extra = (isset($_GET['admin'])) ? " Configuration Setup" : "";
  1341. $desc = "CRUDDY MYSQL " . $extra;
  1342. }*/
  1343. if (!isset($_GET['admin'])) {
  1344. $bodyOnKeyPress = "onkeypress=\"handleEscapeKey(event);\"";
  1345. } else {
  1346. $bodyOnKeyPress = "";
  1347. }
  1348. if ($this->currentAdminDB['crud']['theme'] != 'None') {
  1349. $themeCSS = '<link rel="stylesheet" type="text/css" href="'.$this->displayThemeCSS().'" />';
  1350. }
  1351. $scriptsAndCss = '
  1352. <link rel="stylesheet" type="text/css" href="'.$this->displayGlobalCSS().'" />
  1353. '.$themeCSS.'
  1354. <script type="text/javascript" src="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/crud_admin.js"></script>
  1355. <link type="text/css" href="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/css/ui-lightness/jquery-ui-1.8.11.custom.css" rel="stylesheet" />
  1356. <script type="text/javascript" src="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/js/jquery-1.5.1.min.js"></script>
  1357. <script type="text/javascript" src="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/js/jquery-ui-1.8.11.custom.min.js"></script>
  1358. <script type="text/javascript">
  1359. var cruddy = jQuery.noConflict();
  1360. </script>
  1361. <script type="text/javascript" src="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/prototype.js"></script>
  1362. <script type="text/javascript" src="'.ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'scripts/cruddy_mysql.js"></script>';
  1363. if (!$this->isPageInclude) {
  1364. echo '
  1365. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1366. <html xmlns="http://www.w3.org/1999/xhtml">
  1367. <head>
  1368. <title>'.$desc.'</title>
  1369. '.$scriptsAndCss.'
  1370. </head>
  1371. <body '.$bodyOnKeyPress.'>
  1372. ';
  1373. } else {
  1374. echo $scriptsAndCss;
  1375. }
  1376. //if (isset($_GET['msg'])) {
  1377. echo "<h3 style='color:#E63C1E;font-size:1.5em' id='response'>".$_GET['msg']."</h3>";
  1378. //}
  1379. if (isset($crudAdmin->currentAdminDB['crud']['console_name'])) {
  1380. echo "<div style=\"float:left;padding-right:16px;\"><h1>";
  1381. echo (isset($_GET['admin'])) ? "" : "<a href=\"$_SERVER[PHP_SELF]\">";
  1382. echo $desc;
  1383. echo (isset($_GET['admin'])) ? "" : "</a>";
  1384. echo "</h1></div><div id=\"clear\"></div>";
  1385. }
  1386. }
  1387. $this->paintAdminAndGroupLinks();
  1388. }
  1389. function paintAdminAndGroupLinks() {
  1390. //if ($this->paintedAdminAndGroups !== true || $this->isPageInclude) {
  1391. // $this->paintedAdminAndGroups = true;
  1392. if ($this->cruddyAdministrator) {
  1393. if (is_array($this->currentAdminDB['crud']['mysql_server_names'])) {
  1394. $serverOptions = "<option value=\"\" selected>Select a Server</option>";
  1395. foreach ($this->currentAdminDB['crud']['mysql_server_names'] as $key=>$value) {
  1396. $serverOptions .= "<option value=\"$key\">Edit: $key</option>";
  1397. }
  1398. $serverOptions .= "<option value=\"add\">Add a new server</option>";
  1399. }
  1400. if (is_array($this->currentAdminDB['crud']['mysql_databases'])) {
  1401. $databaseOptions = "<option value=\"\" selected>Select a Database</option>";
  1402. foreach ($this->currentAdminDB['crud']['mysql_databases'] as $values) {
  1403. foreach ($values as $database) {
  1404. if (strlen($this->currentAdminDB['crud']['mysql_master_database_configuration']) > 0 && $database != $this->currentAdminDB['crud']['mysql_master_database_configuration']) {
  1405. continue;
  1406. }
  1407. $databaseOptions .= "<option value=\"$database\">Edit: $database</option>";
  1408. }
  1409. }
  1410. }
  1411. $fieldsOptions = "<option value=\"\" selected>Select a Table</option>";
  1412. if (is_array($this->currentAdminDB['crud']['mysql_databases'])) {
  1413. foreach ($this->currentAdminDB['crud']['mysql_databases'] as $server=>$values) {
  1414. foreach ($values as $database) {
  1415. if (strlen($this->currentAdminDB['crud']['mysql_master_database_configuration']) > 0 && $database != $this->currentAdminDB['crud']['mysql_master_database_configuration']) {
  1416. continue;
  1417. }
  1418. $fieldsOptions .= "<optgroup label='$server -> $database'>";
  1419. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $key=>$value) {
  1420. //if (stristr($key,$database."_")) {
  1421. $fieldsOptions .= "<option class=\"$database\" value=\"".$key."\" title=\"".$server."\">Edit fields: ".$key."</option>";
  1422. //}
  1423. }
  1424. $fieldsOptions .= "</optgroup>";
  1425. }
  1426. }
  1427. }
  1428. if (!$this->isPageInclude) {
  1429. $editThemeLink = (isset($this->currentAdminDB['crud']['theme'])) ? "&edit=".$this->currentAdminDB['crud']['theme'] : "";
  1430. }
  1431. }
  1432. if ($_COOKIE['current_user']) {
  1433. if (strlen($this->currentAdminDB['crud']['mysql_master_database_configuration']) > 0) {
  1434. $databaseList = "<li><a>Select a DB:</a><select style='width:77px;position:absolute;margin-left: -35px; margin-top: -17px;' onchange=\"createCookie('current_db',this.value,1);document.location=document.location;\">";
  1435. foreach ($this->currentAdminDB['crud']['mysql_databases'] as $mySQLServerHash=>$allDBs) {
  1436. foreach ($allDBs as $db) {
  1437. $selected = '';
  1438. if ( ($_COOKIE['current_db'] == "$mySQLServerHash-$db") || (empty($_COOKIE['current_db']) && $db == $this->currentAdminDB['crud']['mysql_master_database_configuration']) ) {
  1439. if (empty($_COOKIE['current_db'])) {
  1440. $redirect=true;
  1441. setcookie("current_db", "$mySQLServerHash-$db", time()+3600*24*7,"/");
  1442. }
  1443. $selected = 'selected';
  1444. }
  1445. $databaseList .= "<option $selected value=\"$mySQLServerHash-$db\">$db</option>";
  1446. }
  1447. }
  1448. $databaseList .= "</select></li>";
  1449. }
  1450. $groupLinks = "
  1451. <div style=\"float:left\" id=\"menu1\" class=\"menu\">
  1452. <div id=\"m-top\">
  1453. <ul id=\"m-top-ul1\">
  1454. <li><a href=\"?\">Home</a></li>\n";
  1455. if (isset($this->currentAdminDB['crud']['groups']) && $this->currentAdminDB['crud']['group_tables'] == 1) {
  1456. foreach ($this->currentAdminDB['crud']['groups'] as $k=>$v) {
  1457. if (!in_array($k,$this->currentAdminDB['crud']['roles'][$_COOKIE['current_role']]['groups'])) {
  1458. continue;
  1459. }
  1460. $groupLinks .= "\t\t\t\t\t<li><a href=\"?group=$k\">$k</a></li>\n";
  1461. }
  1462. }
  1463. $groupLinks .= "
  1464. $databaseList
  1465. <li><a onclick=\"javascript:eraseCookie ('current_user');eraseCookie ('current_role');document.location= '$_SERVER[PHP_SELF]';\" href=\"#\">Log Out</a></li>
  1466. </ul>
  1467. </div>
  1468. <div id=\"m-slider\">
  1469. <div id=\"slider1\"></div>
  1470. </div>
  1471. </div>";
  1472. echo $groupLinks;
  1473. if ($redirect) {
  1474. echo "<script>document.location=document.location;</script>";
  1475. }
  1476. }
  1477. if (!$this->isPageInclude) {
  1478. $logOutLink = "";
  1479. if ($this->cruddyAdministrator) {
  1480. $logOutLink = "
  1481. <li><a onclick=\"document.location= 'pages';\" href=\"#\">Drop-In<br/>Includes</a></li>
  1482. ";
  1483. }
  1484. $logOutLink .= "
  1485. <li><a onclick=\"javascript:eraseCookie ('current_user');eraseCookie ('current_role');document.location= '$_SERVER[PHP_SELF]';\" href=\"#\">Log Out</a></li>
  1486. ";
  1487. }
  1488. if ($this->cruddyAdministrator) {
  1489. $themes = "<li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]?admin=true&select_theme=true$editThemeLink';\" href=\"#\">Themes</a></li>";
  1490. if (!$this->isPageInclude) {
  1491. $serversAndDatabases = "
  1492. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);$('serverList').style.left = $('slider2').style.marginLeft;$('serverList').style.display = 'inline';\" href=\"#\">Servers</a></li>
  1493. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]?admin=true&select_database=true&edit=true';\" href=\"#\">Databases</a></li>
  1494. ";
  1495. $groupsRolesUsers = "
  1496. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]?admin=true&select_groups=true&edit=true';\" href=\"#\">Groups</a></li>
  1497. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]?admin=1&select_roles&edit=true';\" href=\"#\">Roles</a></li>
  1498. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]?admin=1&select_users&edit=true';\" href=\"#\">Users</a></li>";
  1499. $fieldsOnClick = "$('FieldList').style.left = $('slider2').style.marginLeft;$('FieldList').style.display = 'inline';";
  1500. $tablesOnClick = "$('databaseList').style.left = $('slider2').style.marginLeft;$('databaseList').style.display = 'inline';";
  1501. } else {
  1502. $fieldsOnClick = "document.location = '$_SERVER[PHP_SELF]?admin=true&select_fields&edit={$_REQUEST['tablePointer']}&conf={$this->current_config}';";
  1503. $tablesOnClick = "document.location = '$_SERVER[PHP_SELF]?admin=true&select_tables&edit={$_REQUEST['tablePointer']}&conf={$this->current_config}';";
  1504. }
  1505. if ($this->isProductionized===false) {
  1506. // -- if array is still a security risk, make sure user converts into PHP array file for inclusion
  1507. $productionizeLink = "<li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location = '$_SERVER[PHP_SELF]?admin=true&productionize&conf={$this->current_config}'\" href=\"#\">Production<br/>Finalize</a></li>";
  1508. }
  1509. echo "
  1510. <select id=\"serverList\" style=\"display:none;position:absolute;\" onchange=\"if (this.value != 'new'){document.location = '$_SERVER[PHP_SELF]?admin=true&initialize_server&edit=' + this.value;}else{document.location = '$_SERVER[PHP_SELF]?admin=true&newserver=1';}\">
  1511. $serverOptions
  1512. </select>
  1513. <select id=\"databaseList\" style=\"display:none;position:absolute;\" onchange=\"document.location = '$_SERVER[PHP_SELF]?admin=true&select_tables&edit=' + this.value;\">
  1514. $databaseOptions
  1515. </select>
  1516. <select id=\"FieldList\" style=\"display:none;position:absolute;\" onchange=\"document.location = '$_SERVER[PHP_SELF]?admin=true&select_fields&edit=' + this.value + '&server=' + this.options[this.selectedIndex].title + '&database=' + this.options[this.selectedIndex].className;\">
  1517. $fieldsOptions
  1518. </select>
  1519. <div style=\"clear:both;\"></div>
  1520. <div style=\"float:left\" id=\"menu2\" class=\"menu2\">
  1521. <div id=\"m-top\">
  1522. <ul id=\"m-top-ul2\">
  1523. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]';\" href=\"#\">Home</a></li>
  1524. $serversAndDatabases
  1525. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);$tablesOnClick\" href=\"#\">Tables</a></li>
  1526. $groupsRolesUsers
  1527. $themes
  1528. <!--<li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location = '$_SERVER[PHP_SELF]?admin=true&export_phpGrids&edit={$_REQUEST['tablePointer']}';\" href=\"#\">phpGrids</a></li>-->
  1529. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);$fieldsOnClick\" href=\"#\">Fields</a></li>
  1530. $productionizeLink
  1531. $logOutLink
  1532. </ul>
  1533. </div>
  1534. <div id=\"m-slider\">
  1535. <div id=\"slider2\"></div>
  1536. </div>
  1537. </div>
  1538. ";
  1539. if ($this->isPageInclude) {
  1540. echo "<div style=\"float:right\"><a onclick=\"javascript:alert('The links to the left are to configure $this->current_config configuration.')\" href=\"#\">($this->current_config)</a></div>";
  1541. }
  1542. } elseif ( (isset($this->currentAdminDB['crud']['groups']) && $this->currentAdminDB['crud']['group_tables'] == 1) == false && $_COOKIE['current_user'] && !isset($_COOKIE['tempAdmin'])) {
  1543. echo
  1544. "<div style=\"clear:both;\"></div>
  1545. <div style=\"float:left\" id=\"menu2\" class=\"menu2\">
  1546. <div id=\"m-top\">
  1547. <ul id=\"m-top-ul2\">
  1548. <li><a onclick=\"javascript:createCookie('redirect','$_SERVER[REQUEST_URI]',1);document.location= '$_SERVER[PHP_SELF]';\" href=\"#\">Home</a></li>
  1549. $logOutLink
  1550. </ul>
  1551. </div>
  1552. <div id=\"m-slider\">
  1553. <div id=\"slider2\"></div>
  1554. </div>
  1555. </div>";
  1556. }
  1557. echo "<div id=\"clear\"></div>";
  1558. //}
  1559. }
  1560. function replaceTokens($search,$config) {
  1561. return str_replace(array("{table_desc}","{table_name}"),array($config[OBJECT_DESC],$config[OBJECT_TABLE]),$search);
  1562. }
  1563. function paint($currentTable,$mysqlServer='',$mysqlUsername='',$mysqlPassword='',$mysqlDatabase='',$configurationFile='') {
  1564. if (isset($_GET['group'])) {
  1565. if (!in_array($currentTable,$this->currentAdminDB['crud']['groups'][$_GET['group']])) {
  1566. return;
  1567. }
  1568. }
  1569. if ($mysqlServer && !$configurationFile) {
  1570. $configurationFile = $currentTable;
  1571. }
  1572. if ($configurationFile) {
  1573. /*
  1574. * you can manage a table completely without storing mySQL credentials in the configuration and can simply call paint directly pointing to your servername and telling it the name of your configuration like so
  1575. *
  1576. * include("cruddy_mysql/cruddy_mysql.php");
  1577. * $crudAdmin = new cruddyMysqlAdmin();
  1578. * $crudAdmin->paint('table','localhost','root','root','database','file_configuration_name');
  1579. */
  1580. $this->isPageInclude = true;
  1581. $this->adminFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator.$configurationFile.".config.php";
  1582. $this->functionsFile = getcwd().$this->systemDirectorySeparator."configurations".$this->systemDirectorySeparator.$configurationFile.".custom.functions.php";
  1583. if ($this->adminDBExists()) {
  1584. $this->currentAdminDB = $this->readAdminDB();
  1585. } else {
  1586. $this->currentAdminDB = array();
  1587. $this->override['select_fields'] = true;
  1588. }
  1589. if (isset($this->configs[$configurationFile])) {
  1590. die("It is recommended to pass different configuration files for each table you are showing on a page. \"$configurationFile\" is already used. Pass a different filename.");
  1591. }
  1592. $this->configs[$configurationFile] = $configurationFile;
  1593. $this->current_config = $configurationFile;
  1594. } else {
  1595. $this->isPageInclude = false;
  1596. }
  1597. $crudTableControl = $this->currentAdminDB[CRUD_FIELD_CONFIG];
  1598. if ($this->currentAdminDB['crud']['group_tables'] == 0 || count($_GET) != 0) {
  1599. $crudActions = array(
  1600. 'new'=>strtolower($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['new'].$currentTable),
  1601. 'delete'=>strtolower($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['delete'].$currentTable),
  1602. 'update'=>strtolower($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['update'].$currentTable),
  1603. 'view'=>strtolower($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['view'].$currentTable),
  1604. 'read'=>strtolower($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['read'].$currentTable),
  1605. );
  1606. if (in_array($_GET['action'],$crudActions) || !isset($_GET['action']) ) {
  1607. eval("
  1608. if (function_exists('pre_process_load_".$currentTable."')) {
  1609. \$crudTableControl[\$currentTable] = pre_process_load_".$currentTable."(\$crudTableControl[\$currentTable]);
  1610. }");
  1611. if (isset($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_CONNECTION_STRING])) {
  1612. unset($_GET['msg']);
  1613. if (strlen($this->currentAdminDB['crud']['mysql_master_database_configuration']) > 0) {
  1614. list($server,$database) = explode('-',$_COOKIE['current_db']);
  1615. $port = $this->currentAdminDB['crud']['mysql_ports'][$server];
  1616. $serverName = $this->currentAdminDB['crud']['mysql_server_names'][$server];
  1617. $user = $this->currentAdminDB['crud']['mysql_user_names'][$server];
  1618. $pass = $this->currentAdminDB['crud']['mysql_passwords'][$server];
  1619. $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_CONNECTION_STRING] = "mysql://$user:$pass@$serverName:$port/$database";
  1620. $crudTableControl[$currentTable][TABLE_CONFIG]['all_databases'] = $this->currentAdminDB['crud']['mysql_databases'];
  1621. $crudTableControl[$currentTable][TABLE_CONFIG]['all_ports'] = $this->currentAdminDB['crud']['mysql_ports'];
  1622. $crudTableControl[$currentTable][TABLE_CONFIG]['all_servers'] = $this->currentAdminDB['crud']['mysql_server_names'];
  1623. $crudTableControl[$currentTable][TABLE_CONFIG]['all_users'] = $this->currentAdminDB['crud']['mysql_user_names'];
  1624. $crudTableControl[$currentTable][TABLE_CONFIG]['all_passwords'] = $this->currentAdminDB['crud']['mysql_passwords'];
  1625. }
  1626. $crudObject = new cruddyMysql($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_CONNECTION_STRING],$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_TABLE],$crudTableControl[$currentTable]);
  1627. } else {
  1628. if (!$mysqlServer) {
  1629. die("'$currentTable' is not a valid CRUD table config and does not exist in the crud configuration '".basename($this->currentAdminDB)."'");
  1630. } else {
  1631. if ($_GET['edit'] != $currentTable && isset($_GET['edit']) || ($_POST['tablePointer'] != $currentTable) && isset($_POST['tablePointer'])) {
  1632. return;
  1633. }
  1634. $_GET['server'] = $mysqlServer;
  1635. $_GET['database'] = $mysqlDatabase;
  1636. $_GET['username'] = $mysqlUsername;
  1637. $_GET['password'] = $mysqlPassword;
  1638. if (!isset($_GET['edit'])) {
  1639. $_GET['edit'] = $currentTable;
  1640. $_REQUEST['tablePointer'] = $currentTable;
  1641. } else {
  1642. $_REQUEST['tablePointer'] = $_GET['edit'];
  1643. }
  1644. $this->paintHead();
  1645. if (!file_exists($this->adminFile) || isset($_GET['admin'])) {
  1646. $this->handleAdminPages();
  1647. unset($_GET['server'],$_GET['database'],$_GET['username'],$_GET['password'],$_REQUEST['tablePointer'],$_GET['edit']);
  1648. return;
  1649. } else {
  1650. $crudObject = new cruddyMysql("mysql://$mysqlUsername:$mysqlPassword@$mysqlServer:3306/$mysqlDatabase",$currentTable,$crudTableControl[$currentTable]);
  1651. if ($configurationFile) {
  1652. $crudObject->isPageInclude = true;
  1653. $crudObject->current_config = $configurationFile;
  1654. }
  1655. unset($_GET['server'],$_GET['database'],$_GET['username'],$_GET['password'],$_REQUEST['tablePointer'],$_GET['edit']);
  1656. }
  1657. }
  1658. }
  1659. // -- object_name can be used to describe your table
  1660. if ($_COOKIE['current_db']) {
  1661. list($void,$db) = explode('-',$_COOKIE['current_db']);
  1662. $name = $db." ";
  1663. }
  1664. $crudObject->object_name = $name.$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_DESC];
  1665. $crudObject->cruddyAdministrator = $this->cruddyAdministrator;
  1666. $crudObject->object_key = $currentTable;
  1667. $viewUrl = (!isset($_GET['action'])) ? 'action='.$crudActions['read'].'' : '';
  1668. if ($this->isPageInclude) {
  1669. $viewUrl .= "&conf=$this->current_config";
  1670. }
  1671. $viewText = (!isset($_GET['action'])) ? $this->replaceTokens($crudTableControl[$currentTable][TABLE_CONFIG][VIEW_TEXT],$crudTableControl[$currentTable][TABLE_CONFIG]) : '&larr; Back';
  1672. $amp = (stristr($_SERVER['PHP_SELF'],"?")) ? '&' : '?';
  1673. $newLink = '';
  1674. list($wh,$filterDesc) = $this->buildSearchWhere($currentTable);
  1675. if (isset($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_FILTER_DESC]) || !empty($filterDesc)) {
  1676. if ($filterDesc) {
  1677. $filterTxt = "<div style='float: left; margin-top: 7px;'>Filtered By:</div>".$filterDesc."<div style='clear:both;'></div>";
  1678. } else {
  1679. $filterTxt = $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_FILTER_DESC];
  1680. }
  1681. $desc = "<h4 style='color:#333'>".$filterTxt."</h4>";
  1682. }
  1683. if ($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_NEW_LINK] == 0 || $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_NEW_LINK] == 0) {
  1684. // -- custom logic for each object on how it draws its links can go here by utilizing case statements of $currentTable
  1685. $theLink = "<a href='?action=".strtolower($crudActions['new']);
  1686. if ($this->isPageInclude) {
  1687. $theLink .= "&conf=$this->current_config";
  1688. }
  1689. $theLink .= "'>".$this->replaceTokens($crudTableControl[$currentTable][TABLE_CONFIG][ADD_TEXT],$crudTableControl[$currentTable][TABLE_CONFIG])."</a> | ";
  1690. if ($definitions[TABLE_CONFIG][OBJECT_HIDE_EDIT_LINK] != 1 && substr($_GET['action'],0,4) == "view") {
  1691. $theLink = "<a href='".str_replace("action=view_","action=update_",$_SERVER['REQUEST_URI'])."'>Update This $crudObject->object_name</a> | ";
  1692. } elseif (substr($_GET['action'],0,4) == "view") {
  1693. // -- user cannot see the update link
  1694. $theLink = "";
  1695. }
  1696. $newLink .= $theLink;
  1697. $break = "<br/>";
  1698. }
  1699. if (!isset($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_VIEW_LINK]) || $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_VIEW_LINK] == 0 ) {
  1700. $viewLink = "<a href='?".$viewUrl."'>$viewText</a>";
  1701. }
  1702. if (!isset($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_SEARCH_LINK]) || $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_HIDE_SEARCH_LINK] == 0 ) {
  1703. if ($_GET['action'] != $crudActions['new'] && $_GET['action'] != $crudActions['update']) {
  1704. $searchTxt = $this->replaceTokens($crudTableControl[$currentTable][TABLE_CONFIG][SEARCH_TEXT],$crudTableControl[$currentTable][TABLE_CONFIG]);
  1705. $searchLink = "<a style='cursor:pointer' onclick='if ($(\"{$currentTable}_search\").style.display==\"none\") { $(\"{$currentTable}_search\").style.display=\"block\"; this.innerHTML = \"Hide $searchTxt\"; } else { $(\"{$currentTable}_search\").style.display=\"none\"; this.innerHTML = \"".$searchTxt."\"; } '>".$searchTxt."</a> | ";
  1706. }
  1707. }
  1708. if ($configurationFile == '') {
  1709. $tableTxt = $this->replaceTokens($crudTableControl[$currentTable][TABLE_CONFIG][TABLE_TEXT],$crudTableControl[$currentTable][TABLE_CONFIG]);
  1710. echo "<h2 style='color:#E63C1E;'>$tableTxt</h2>";
  1711. }
  1712. echo "
  1713. $desc
  1714. $newLink$searchLink$viewLink$break
  1715. ";
  1716. if ($this->isPageInclude && $_GET['action'] != $crudActions['read']) {
  1717. if (isset($_GET['conf']) && $_GET['conf'] != $this->current_config) {
  1718. return;
  1719. }
  1720. }
  1721. if ( $_GET['action'] != $crudActions['new'] && $_GET['action'] != $crudActions['update']) {
  1722. $crudObject->search();
  1723. }
  1724. switch ( $_GET['action'] ) {
  1725. case $crudActions['new']:
  1726. $crudObject->button = array("TYPE"=>"submit","LABEL"=>"Add New ".$crudObject->object_name,"VALUE"=>"Add New ".$crudObject->object_name,"ID"=>INPUT_SUBMIT ,"NAME"=>INPUT_SUBMIT);
  1727. eval("
  1728. if (function_exists('new_pre_process_".$currentTable."')) {
  1729. \$retPre = new_pre_process_".$currentTable."();
  1730. } else {
  1731. \$retPre = true;
  1732. }");
  1733. if ($retPre === true) {
  1734. if ( $id = $crudObject->create() ) {
  1735. eval("
  1736. if (function_exists('new_post_process_".$currentTable."')) {
  1737. \$retPost = new_post_process_".$currentTable."();
  1738. } else {
  1739. \$retPost = true;
  1740. }");
  1741. if ($retPost === true) {
  1742. $msg = "A new ".$crudObject->object_name." was added (%23$id)";
  1743. } else {
  1744. $msg = $retPost;
  1745. }
  1746. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurldecode($msg);
  1747. }
  1748. } else {
  1749. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurldecode($retPre);
  1750. }
  1751. break;
  1752. case $crudActions['delete'];
  1753. eval("
  1754. if (function_exists('delete_pre_process_".$currentTable."')) {
  1755. \$retPre = delete_pre_process_".$currentTable."();
  1756. } else {
  1757. \$retPre = true;
  1758. }
  1759. ");
  1760. if ($retPre === true) {
  1761. if ( $crudObject->delete(array($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK] => $_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK]])) == true) {
  1762. eval("
  1763. if (function_exists('delete_post_process_".$currentTable."')) {
  1764. \$retPost = delete_post_process_".$currentTable."();
  1765. } else {
  1766. \$retPost = true;
  1767. }
  1768. ");
  1769. if ($retPost === true) {
  1770. if (intval($_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK]]) != 0) {
  1771. $pound = "#";
  1772. }
  1773. $msg = "Your ".$crudObject->object_name." (".$pound.$_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK]].") has been deleted";
  1774. } else {
  1775. $msg = $retPost;
  1776. }
  1777. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurlencode($msg);
  1778. }
  1779. } else {
  1780. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurldecode($retPre);
  1781. }
  1782. break;
  1783. case $crudActions['update']:
  1784. $crudObject->button = array("TYPE"=>"submit","LABEL"=>"Update ".$crudObject->object_name,"VALUE"=>"Update ".$crudObject->object_name,"ID"=>INPUT_SUBMIT ,"NAME"=>INPUT_SUBMIT);
  1785. eval("
  1786. if (function_exists('update_pre_process_".$currentTable."')) {
  1787. \$retPre = update_pre_process_".$currentTable."();
  1788. } else {
  1789. \$retPre = true;
  1790. }
  1791. ");
  1792. if ($retPre === true) {
  1793. if ( $crudObject->update(array($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK] => $_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK]])) == true) {
  1794. eval("
  1795. if (function_exists('update_post_process_".$currentTable."')) {
  1796. \$retPost = update_post_process_".$currentTable."();
  1797. } else {
  1798. \$retPost = true;
  1799. }");
  1800. if ($retPost === true) {
  1801. $msg = $crudObject->object_name." has been updated";
  1802. } else {
  1803. $msg = $retPost;
  1804. }
  1805. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurldecode($msg);
  1806. }
  1807. } else {
  1808. $url = $_SERVER['PHP_SELF'].$amp."msg=".rawurldecode($retPre);
  1809. }
  1810. break;
  1811. case $crudActions['view']:
  1812. // -- to do view
  1813. $crudObject->view(array($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK] => $_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_PK]]));
  1814. break;
  1815. case $crudActions['read']:
  1816. default:
  1817. $orderBy = (!empty($_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['order_field']])) ? ' ORDER BY `' . $_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['order_field']] . '` ' . $_GET[$crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_ACTIONS]['order_direction']] : '';
  1818. if ($crudObject->isPageInclude) {
  1819. if (isset($_GET['conf']) && $_GET['conf'] != $crudObject->current_config) {
  1820. $orderBy = '';
  1821. }
  1822. }
  1823. if (empty($crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_READ_FILTER])) {
  1824. $where = " WHERE 1=1 ";
  1825. } else {
  1826. $where = $crudTableControl[$currentTable][TABLE_CONFIG][OBJECT_READ_FILTER];
  1827. }
  1828. $crudObject->read($where.$orderBy);
  1829. break;
  1830. }
  1831. $this->redirect($url);
  1832. echo "<hr />";
  1833. if ($this->cruddyAdministrator) {
  1834. foreach ($crudObject->performance as $k=>$v) {
  1835. // -- if slow queries/methods greater than 10 seconds show warning
  1836. if ($v[0] > 10) {
  1837. echo "<div class=\"error\"><strong>Performance Issues Encountered</strong><br/><pre>";
  1838. print_r($crudObject->performance);
  1839. echo "</pre></div>";
  1840. }
  1841. }
  1842. }
  1843. }
  1844. }
  1845. }
  1846. function redirect($url) {
  1847. // -- handle URL redirects
  1848. if ($url) {
  1849. if (!headers_sent()) {
  1850. header ("Location: ".$url);
  1851. } else {
  1852. echo "<script type='text/javascript'>document.location='".$url."';</script>";
  1853. }
  1854. }
  1855. }
  1856. function paintGroups() {
  1857. if ($this->currentAdminDB['crud']['group_tables'] == 1 && count($_GET) == 0) {
  1858. foreach ($this->currentAdminDB['crud']['groups'] as $k=>$v) {
  1859. // -- show groups listing for user selection
  1860. if (!is_array($this->currentAdminDB['crud']['roles'][$_COOKIE['current_role']]['groups'])) {
  1861. continue;
  1862. } elseif (!in_array($k,$this->currentAdminDB['crud']['roles'][$_COOKIE['current_role']]['groups'])) {
  1863. continue;
  1864. }
  1865. echo "<a href=\"?group=$k\"><div class=\"groupBox\">View Records:<br/><strong>$k</strong><img style=\"margin-left:15px;\" src=\"".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/database.png\"/></div></a>";
  1866. }
  1867. }
  1868. }
  1869. function handleDatabaseListResultSet($result) {
  1870. $data = mysql_fetch_array($result, 2);
  1871. return $data;
  1872. }
  1873. function queryDatabase($query, $link = null) {
  1874. $resultrows = array();
  1875. if (is_string($query)) {
  1876. $result = @mysql_query($query, $link);
  1877. }
  1878. // return empty array if result is empty or false
  1879. if (! $result) {
  1880. return $resultrows;
  1881. }
  1882. while ($row = @mysql_fetch_assoc($result)) {
  1883. $resultrows[] = $row;
  1884. }
  1885. mysql_free_result($result);
  1886. return $resultrows;
  1887. }
  1888. function connectDatabase($hash,$database='') {
  1889. if (isset($this->currentAdminDB['crud']['mysql_server_names'][$hash])) {
  1890. $conn = @mysql_connect($this->currentAdminDB['crud']['mysql_server_names'][$hash].":".$this->currentAdminDB['crud']['mysql_ports'][$hash],$this->currentAdminDB['crud']['mysql_user_names'][$hash],$this->currentAdminDB['crud']['mysql_passwords'][$hash]);
  1891. } else {
  1892. $conn = @mysql_connect($_GET['server'].":3306",$_GET['username'],$_GET['password']);
  1893. }
  1894. if (!empty($database)) {
  1895. if (mysql_select_db($database) == false) {
  1896. die('<script>$("response").innerHTML="Invalid Database ('.$database.')";</script>');
  1897. }
  1898. }
  1899. if (!$conn) {
  1900. die('<script>$("response").innerHTML="Could not connect to database";</script>');
  1901. }
  1902. return $conn;
  1903. }
  1904. function closeDatabase($conn) {
  1905. @mysql_close(closeDatabase);
  1906. }
  1907. function displayLoginForm() {
  1908. echo $this->displayGenericObjects();
  1909. echo
  1910. "
  1911. <script>
  1912. function login(username,password) {
  1913. var url = \"".$_SERVER['PHP_SELF']."?\";
  1914. var params = \"username=\" + username + \"&password=\" + password;
  1915. new Ajax.Request( url + params,
  1916. {
  1917. method: 'post',
  1918. onSuccess: function(transport) {
  1919. var response = transport.responseText || false;
  1920. if (response != false) {
  1921. $(\"results\").innerHTML = response;
  1922. } else {
  1923. document.location = 'index.php';
  1924. }
  1925. },
  1926. onFailure: function() { alert('An unexpected error occurred.'); }
  1927. });
  1928. }
  1929. </script>
  1930. <div id='serverinfo'>
  1931. Login To <strong>".$this->currentAdminDB['crud']['console_name']."</strong>
  1932. <table>
  1933. <tr>
  1934. <td>Username: </td>
  1935. <td><input type='text' class='admin' id='username' value=''/></td>
  1936. </tr>
  1937. <tr>
  1938. <td>Password: </td>
  1939. <td><input class='admin' type='password' id='password' value=''/></td>
  1940. </tr>
  1941. <tr>
  1942. <td></td>
  1943. <td><a class='button' onclick='login($(\"username\").value,$(\"password\").value);'><span>Login</span></a></td>
  1944. </tr>
  1945. </table>
  1946. </div>
  1947. ";
  1948. }
  1949. function LoginToCruddyMysql($username,$password) {
  1950. ob_end_clean();
  1951. $loggedIn = false;
  1952. foreach ($this->currentAdminDB['crud']['users'] as $k=>$v) {
  1953. if (strtoupper($v['user_name']) == strtoupper($username) && strtoupper($v['password']) == strtoupper($password)) {
  1954. $loggedIn = true;
  1955. setcookie("current_user", $k, time()+3600*24*7,"/");
  1956. setcookie("current_role", $v['role'], time()+3600*24*7,"/");
  1957. break;
  1958. }
  1959. }
  1960. if ($loggedIn === false) {
  1961. echo "Invalid username or password.";
  1962. }
  1963. exit;
  1964. }
  1965. #1 Step
  1966. function displayDatabaseConnectionForm() {
  1967. echo $this->displayGenericObjects();
  1968. if ($_GET['edit']) {
  1969. $defaultPort = $this->currentAdminDB['crud']['mysql_ports'][$_GET['edit']];
  1970. $defaultServer = $this->currentAdminDB['crud']['mysql_server_names'][$_GET['edit']];
  1971. $defaultUserName = $this->currentAdminDB['crud']['mysql_user_names'][$_GET['edit']];
  1972. $defaultPassword = $this->currentAdminDB['crud']['mysql_passwords'][$_GET['edit']];
  1973. } else {
  1974. $defaultPort = '3306';
  1975. $defaultServer = 'localhost';
  1976. $defaultUserName = 'root';
  1977. }
  1978. if ($_GET['mode']=='edit' || !isset($_GET['newserver'])) {
  1979. $adminHTML = "<tr>
  1980. <td>Name of Administration: </td>
  1981. <td><input type='text' class='admin' id='adminname' value='".$this->currentAdminDB['crud']['console_name']."'/></td>
  1982. </tr>";
  1983. } else {
  1984. $adminHTML = "<tr><td>Name of Administration: </td><input type='hidden' id='adminname' value='".$this->currentAdminDB['crud']['console_name']."'/><td>".$this->currentAdminDB['crud']['console_name']."</td>
  1985. </tr>";
  1986. }
  1987. echo
  1988. "
  1989. <div id='serverinfo'>
  1990. Step 1: CruddyMySQL Server Connections
  1991. <table>
  1992. $adminHTML
  1993. <tr>
  1994. <td>MySQL Server: </td>
  1995. <td><input type='text' class='admin' id='server' value='$defaultServer'/></td>
  1996. </tr>
  1997. <tr>
  1998. <td>MySQL Port: </td>
  1999. <td><input type='text' class='admin' id='port' value='$defaultPort'/></td>
  2000. </tr>
  2001. <tr>
  2002. <td>MySQL Username:</td>
  2003. <td><input type='text' class='admin' id='username' value='$defaultUserName'/></td>
  2004. </tr>
  2005. <tr>
  2006. <td>MySQL Password:</td>
  2007. <td><input type='password' class='admin' id='password' value='$defaultPassword'/></td>
  2008. </tr>
  2009. <tr>
  2010. <td>Cruddy mySQL Instance Name:</td>
  2011. <td>\"crud_".$_SERVER["SERVER_NAME"]."_".ABS_PATH_HASH."\"<br/>(dont change your path \"".dirname($_SERVER['PHP_SELF'])."\" or you'll have to rename /configuration files)</td>
  2012. </tr>
  2013. <tr>
  2014. <td><a class='button' onclick='storeConnectionInfo(1)'><span>Add Another Server</span></a></td>
  2015. <td><a class='button' onclick='storeConnectionInfo(0)'><span>Store Connection Info And Proceed</span></a></td>
  2016. </tr>
  2017. </table>
  2018. </div>
  2019. ";
  2020. }
  2021. function storeDatabaseConnectionForm() {
  2022. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  2023. $this->currentAdminDB['crud']['completed_step'] = 1;
  2024. }
  2025. ob_end_clean();
  2026. if (!@mysql_connect($_GET['server'].":".$_GET['port'],$_GET['username'],$_GET['password'])) {
  2027. echo "Error: Connection settings incorrect. Please try again.";
  2028. } else {
  2029. $serverHash = $_GET['server'].':'.$_GET['port'];
  2030. $this->currentAdminDB['crud']['console_name'] = $_GET['adminname'];
  2031. $this->currentAdminDB['crud']['mysql_server_names'][$serverHash] = $_GET['server'];
  2032. $this->currentAdminDB['crud']['mysql_user_names'][$serverHash] = $_GET['username'];
  2033. $this->currentAdminDB['crud']['mysql_passwords'][$serverHash] = $_GET['password'];
  2034. $this->currentAdminDB['crud']['mysql_ports'][$serverHash] = $_GET['port'];
  2035. if (isset($this->currentAdminDB[CRUD_FIELD_CONFIG])) {
  2036. // -- update connections for each matching DB
  2037. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $k=>$v) {
  2038. $parts = explode('/',$this->currentAdminDB[CRUD_FIELD_CONFIG][$k][TABLE_CONFIG][OBJECT_CONNECTION_STRING]);
  2039. if (stristr($this->currentAdminDB[CRUD_FIELD_CONFIG][$k][TABLE_CONFIG][OBJECT_CONNECTION_STRING] ,$_GET['server'])) {
  2040. $this->currentAdminDB[CRUD_FIELD_CONFIG][$k][TABLE_CONFIG][OBJECT_CONNECTION_STRING] = "mysql://".$_GET['username'].":".$_GET['password']."@".$_GET['server'].":".$_GET['port']."/".$parts[sizeof($parts)-1];
  2041. }
  2042. }
  2043. }
  2044. $this->writeAdminDB();
  2045. foreach ($this->currentAdminDB['crud']['mysql_server_names'] as $mySQLServerHash=>$mySQLServer) {
  2046. $phpCode .= "\$connection['$mySQLServerHash']['server'] = '{$this->currentAdminDB['crud']['mysql_server_names'][$mySQLServerHash]}';\n";
  2047. $phpCode .= "\$connection['$mySQLServerHash']['username'] = '{$this->currentAdminDB['crud']['mysql_user_names'][$mySQLServerHash]}';\n";
  2048. $phpCode .= "\$connection['$mySQLServerHash']['password'] = '{$this->currentAdminDB['crud']['mysql_passwords'][$mySQLServerHash]}';\n";
  2049. $phpCode .= "\$connection['$mySQLServerHash']['port'] = '{$this->currentAdminDB['crud']['mysql_ports'][$mySQLServerHash]}';\n";
  2050. }
  2051. $this->writeFile($this->databaseConnectionFile,
  2052. "<?php\n// -- all of your server connections\n$phpCode\n?>"
  2053. );
  2054. }
  2055. exit;
  2056. }
  2057. #2 Step
  2058. function displayDatabaseSelectionForm() {
  2059. foreach ($this->currentAdminDB['crud']['mysql_server_names'] as $mySQLServerHash=>$mySQLServer) {
  2060. $conn = $this->connectDatabase($mySQLServerHash);
  2061. $resultrows = $this->queryDatabase(GET_DATABASES_SQL,$conn);
  2062. foreach ($resultrows as $key=>$value) {
  2063. $selected = "";
  2064. $db = $this->currentAdminDB['crud']['mysql_databases'][$this->currentAdminDB['crud']['mysql_server_names'][$mySQLServerHash].":".$this->currentAdminDB['crud']['mysql_ports'][$mySQLServerHash]];
  2065. if (!empty($db)) {
  2066. $keys = array_keys($db);
  2067. if ($db == $value['Database'] || in_array($value['Database'],$keys) || !isset($_GET['edit'])) {
  2068. $selected = "selected";
  2069. }
  2070. } else {
  2071. $selected = "selected";
  2072. }
  2073. if ($value['Database'] == 'information_schema' || $value['Database'] == 'mysql') { continue; }
  2074. $options .= "<option value='$mySQLServer".":".$this->currentAdminDB['crud']['mysql_ports'][$mySQLServerHash]."' $selected title='$mySQLServer -> {$value['Database']}'>".$value['Database']."</option>";
  2075. }
  2076. }
  2077. if (!isset($_GET['edit'])) {
  2078. $additionalText = "(All Are Selected CTRL+CLICK to deselect)<br/>";
  2079. }
  2080. echo $this->displayGenericObjects();
  2081. $valMaster = ($this->currentAdminDB['crud']['mysql_master_database_configuration']) ? $this->currentAdminDB['crud']['mysql_master_database_configuration'] : "0";
  2082. $valMaster2 = ($this->currentAdminDB['crud']['mysql_master_database_configuration']) ? $this->currentAdminDB['crud']['mysql_master_database_configuration'] : "Off";
  2083. echo
  2084. "
  2085. <div id='serverinfo'>
  2086. Step 2: Database Selection
  2087. <table>
  2088. <tr>
  2089. <td>Please select a database:</td>
  2090. <td>
  2091. $additionalText
  2092. <select style='background-color:white;color:black;' class='admin' multiple='multiple' id='database' name='database[]'>
  2093. $options
  2094. </select>
  2095. </td>
  2096. </tr>
  2097. </table>
  2098. <a class='button' onclick='storeDatabaseInfo()'><span>Select A Database</span></a>
  2099. <span style=\"cursor:pointer;\" title=\"If you have multiple databases with the same schema,use this mode to point one configuration against all DBs\">Master Config Mode</span><input style='display: none;' onclick=\"toggleObj('masterMode');\" name='masterMode' id='masterMode' value='$valMaster' type='checkbox'><span id='masterMode[onoff]' class='off' onclick=\"toggleObj('masterMode');if ($('masterMode').value == 1) { var val = window.prompt('Enter the master database name'); $('masterMode').value = val;} \">$valMaster2</span>
  2100. </div>
  2101. ";
  2102. $this->closeDatabase($conn);
  2103. }
  2104. function storeDatabaseSelectionForm() {
  2105. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  2106. $this->currentAdminDB['crud']['completed_step'] = 2;
  2107. }
  2108. ob_end_clean();
  2109. $masterMode = $_GET['masterMode'];
  2110. unset($_GET['masterMode'],$_GET['admin'],$_GET['select_database'],$_GET['store_database'],$this->currentAdminDB['crud']['mysql_databases']);
  2111. $this->currentAdminDB['crud']['mysql_master_database_configuration'] = false;
  2112. if (is_array($_GET)) {
  2113. $i=0;
  2114. $databasesLeft = $this->currentAdminDB['crud']['mysql_tables_to_config'];
  2115. foreach ($_GET as $key=>$value) {
  2116. if (strtolower($masterMode) == strtolower($key)) {
  2117. $this->currentAdminDB['crud']['mysql_master_database_configuration'] = $key;
  2118. }
  2119. $this->currentAdminDB['crud']['mysql_databases'][$value][$key] = $key;
  2120. $i++;
  2121. unset($databasesLeft[$key]);
  2122. }
  2123. if (!empty($databasesLeft)) {
  2124. foreach ($databasesLeft as $database) {
  2125. foreach ($database as $configuration) {
  2126. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$configuration]);
  2127. }
  2128. }
  2129. }
  2130. $this->writeAdminDB();
  2131. } else {
  2132. echo "Please select 1 or more databases";
  2133. }
  2134. exit;
  2135. }
  2136. function createDisplayName($name) {
  2137. $fieldCaption = str_replace(array("_","-",".","[","]","<",">"),array(" "," "," "," "," "," "," "),$name);
  2138. $parts = explode(" ",$fieldCaption);
  2139. if (sizeof($parts) > 1) {
  2140. foreach ($parts as $word) {
  2141. $newFieldCaption .= ucwords($word)." ";
  2142. }
  2143. $fieldCaption = substr($newFieldCaption,0,-1);
  2144. } else {
  2145. $fieldCaption = ucwords($fieldCaption);
  2146. }
  2147. return $fieldCaption;
  2148. }
  2149. #3 Step
  2150. function displayTableSelectionForm($mysqlServers,$mysqlDatabases) {
  2151. if ($this->isPageInclude) {
  2152. if (isset($_GET['conf']) && $_GET['conf'] != $this->current_config) {
  2153. return;
  2154. }
  2155. }
  2156. foreach ($mysqlServers as $mySQLServerHash=>$mySQLServer) {
  2157. $tableControlFlagDisplay = false;
  2158. foreach ($mysqlDatabases[$mySQLServerHash] as $database) {
  2159. if ($this->currentAdminDB['crud']['mysql_master_database_configuration'] !== false && $this->currentAdminDB['crud']['mysql_master_database_configuration'] != $database) {
  2160. continue;
  2161. }
  2162. $failure = false;
  2163. $conn = $this->connectDatabase($mySQLServerHash,$database);
  2164. $resultrows = $this->queryDatabase(GET_TABLES_SQL,$conn);
  2165. if (empty($resultrows)) {
  2166. $resultrows = $this->queryDatabase(GET_TABLES_SQL." from $database",$conn);
  2167. if (empty($resultrows)) {
  2168. $resultrows = $this->queryDatabase("SHOW TABLES FROM $database",$conn);
  2169. if (empty($resultrows)) {
  2170. $failure = true;
  2171. $errors .= "<div class=\"error\">Could not get table listing from $mySQLServer.$database</div>";
  2172. }
  2173. }
  2174. }
  2175. if ($failure === false) {
  2176. if ($tableControlFlagDisplay === false) {
  2177. $tableControlFlagDisplay = true;
  2178. $options .= "<tr>";
  2179. if (!isset($_GET['edit'])) {
  2180. $options .= "<td></td><td>Table Name</td>";
  2181. } else {
  2182. $options .= "<td></td>";
  2183. }
  2184. $options .= "<td></td>";
  2185. $options .= "<td></td>";
  2186. foreach ($this->tableControlType as $type=>$text) {
  2187. if (!isset($_GET['edit']) && $type == OBJECT_PK) {
  2188. // -- dont let user try and edit PK. these will be set on next page
  2189. continue;
  2190. }
  2191. $options .= "<td>".$text['desc']."</td>";
  2192. }
  2193. $master = '';
  2194. if ($this->currentAdminDB['crud']['mysql_master_database_configuration'] == $database) {
  2195. $master = ' (MASTER CONFIG)';
  2196. }
  2197. $options .= "</tr>
  2198. <tr>
  2199. <td style=\"font-size:1.5em;\" colspan=\"20\">Tables in $mySQLServerHash</td>
  2200. </tr>
  2201. <tr>
  2202. <td style=\"font-size:1.2em;\" colspan=\"20\">Database:$database $master</td>
  2203. </tr>
  2204. ";
  2205. } else {
  2206. $options .= "</tr>
  2207. <tr>
  2208. <td style=\"font-size:1.2em;\" colspan=\"20\">Database:$database $master</td>
  2209. </tr>";
  2210. }
  2211. $options .= "
  2212. <tr>
  2213. <td></td>
  2214. <td><a onclick='if (this.innerHTML==\"Uncheck All\") { cruddy(\".tableNames\").attr(\"checked\",false); this.innerHTML = \"Check All\";} else { cruddy(\".tableNames\").attr(\"checked\",true); this.innerHTML = \"Uncheck All\"; }'>Uncheck All</a></td>
  2215. <td></td>
  2216. <td></td>
  2217. <td></td>
  2218. ";
  2219. foreach ($this->tableControlType as $key=>$text) {
  2220. if (empty($text["type"]) ) { continue;}
  2221. if ( (!isset($_GET['edit']) && $key == OBJECT_PK) ) {
  2222. continue;
  2223. }
  2224. $rowOutPut = '';
  2225. $checked2 = '';
  2226. $value = $this->tableControlDefaults[$key];
  2227. if ($text['type'] == 'checkbox' && ($value === true || $value == '1')) {
  2228. $checked2 = 'Off';
  2229. } else if ($text['type'] == 'checkbox' && $value === false) {
  2230. $checked2 = 'On';
  2231. } else if ($text['type'] == 'checkbox') {
  2232. $checked2 = 'On';
  2233. }
  2234. if ($checked2 != '') {
  2235. $rowOutPut .= 'Turn all '.$checked2;
  2236. $click = "if (this.innerHTML==\"Turn all Off\") { cruddy(\"input[$key]\").attr(\"checked\",false);cruddy(\"span[{$key}_onoff]\").html(\"Off\"); cruddy(\"input[$key]\").val(0); this.innerHTML = \"Turn all On\";} else { cruddy(\"input[$key]\").attr(\"checked\",true); cruddy(\"input[$key]\").val(1); cruddy(\"span[{$key}_onoff]\").html(\"On\");this.innerHTML = \"Turn all Off\"; }";
  2237. } else {
  2238. $rowOutPut .= 'Replace All Text';
  2239. $click = "var val = window.prompt(\"Enter the replacement value\",\"\");cruddy(\"input[$key]\").val(val);";
  2240. }
  2241. $options .= "<td><a onclick='$click'>".$rowOutPut."</a></td>";
  2242. }
  2243. $option .= "
  2244. </tr>
  2245. ";
  2246. if ($this->isPageInclude) {
  2247. $tableHash = $_GET['edit'];
  2248. } else {
  2249. $tableHash = $database."_".$table;
  2250. }
  2251. if (is_array($this->currentAdminDB[CRUD_FIELD_CONFIG])) {
  2252. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $confName=>$objectCrud) {
  2253. if (isset($objectCrud[TABLE_CONFIG]['is_clone']) && $objectCrud[TABLE_CONFIG]['is_clone'] == true) {
  2254. array_unshift($resultrows, array('Tables_in_'.$database=>$confName));
  2255. }
  2256. }
  2257. }
  2258. foreach ($resultrows as $key=>$value) {
  2259. $selected = "";
  2260. $tableName = $value['Tables_in_'.$database];
  2261. $tableType = $value['Table_type'];
  2262. if (empty($tableType) || $tableType == 'BASE TABLE') {
  2263. $tableType = 'Table';
  2264. } elseif ($tableType == 'VIEW') {
  2265. $tableType = 'View';
  2266. } else {
  2267. $tableType = 'Unsupported';
  2268. }
  2269. if ($this->currentAdminDB[CRUD_FIELD_CONFIG][$value['Tables_in_'.$database]][TABLE_CONFIG]['is_clone'] == true) {
  2270. $tableType = 'Clone';
  2271. $isClone = true;
  2272. $tableName = $this->currentAdminDB[CRUD_FIELD_CONFIG][$value['Tables_in_'.$database]][TABLE_CONFIG][OBJECT_TABLE];
  2273. $tableHash = $value['Tables_in_'.$database];
  2274. } else {
  2275. $isClone = false;
  2276. if (!$this->isPageInclude) {
  2277. $tableHash = $database."_".$tableName;
  2278. }
  2279. }
  2280. if ($this->isPageInclude && $_GET['edit'] != $tableName) {
  2281. continue;
  2282. }
  2283. $resultPK = $this->getPrimaryKey($database,$tableName,$conn);
  2284. if (isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash])) {
  2285. $selected = "checked";
  2286. if ($_GET['edit']) {
  2287. // -- warn user if editing
  2288. $extraJS = "uncheckedTable=true;";
  2289. } else {
  2290. $extraJS = "uncheckedTable=false;";
  2291. }
  2292. } else {
  2293. $selected = "";
  2294. $extraJS = "uncheckedTable=false;";
  2295. }
  2296. if (!$_GET['edit']) {
  2297. $selected = "checked";
  2298. $extraJS = "uncheckedTable=false;";
  2299. }
  2300. if (empty($resultPK[0]['column_name']) && $tableType == 'Table') {
  2301. $errorsCount++;
  2302. $errors .= "<div class=\"error\">\"$mySQLServer.$database.$tableName\" has no unique primary key! Please define and refresh this page. You cannot use this table in the CRUD system. (ALTER TABLE `$tableName` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;)</div>";
  2303. } elseif ($tableType == 'Unsupported') {
  2304. $errorsCount++;
  2305. $errors .= "<div class=\"error\">\"$mySQLServer.$database.$tableName\" is an unsupported object. (Only VIEWS and TABLE objects)</div>";
  2306. } else {
  2307. $viewIsAggregateHTML = '';
  2308. if ($tableType == 'View' && strlen($this->currentAdminDB['crud']['mysql_master_database_configuration']) > 0) {
  2309. $disp = 'none';
  2310. $aggregateClick = '$("'.$tableHash.'_aggregate").style.display = "block";';
  2311. if ($selected != '')
  2312. {
  2313. $disp = 'block';
  2314. }
  2315. $aggTxt = 'Aggregate<br>All DBs';
  2316. $aggVal = '0';
  2317. if ( $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_IS_AGGREGATE] == '1'){
  2318. $aggTxt = 'Remove Aggregate';
  2319. $aggVal = '1';
  2320. }
  2321. $viewIsAggregateHTML = '<td><a id="'.$tableHash.'_aggregate" style="display:'.$disp.'"
  2322. onclick="
  2323. if (this.innerHTML == \'Aggregate<br>All DBs\')
  2324. {
  2325. $(\''.$tableHash.'_aggregate_hidden\').value=1;
  2326. this.innerHTML=\'Remove Aggregate\';
  2327. }
  2328. else
  2329. {
  2330. $(\''.$tableHash.'_aggregate_hidden\').value=0;
  2331. this.innerHTML=\'Aggregate<br>All DBs\';
  2332. }
  2333. ">'.$aggTxt.'</a></td>';
  2334. $viewIsAggregateHTML .= "<input type=\"hidden\" value=\"$aggVal\" name=\"tables[$mySQLServerHash][$database][$tableHash][Aggregate]\" id=\"{$tableHash}_aggregate_hidden\"/>";
  2335. } else {
  2336. $viewIsAggregateHTML = '<td></td>';
  2337. }
  2338. $additionalHTML = " style='cursor:pointer;' onclick='{$aggregateClick}toggleObj(\"tables[$mySQLServerHash][$database][$tableHash][use]\");$(\"tables[$mySQLServerHash][$database][$tableHash][use]\").value=\"$tableName\";$extraJS'><input value='$tableName' type='checkbox' name='tables[$mySQLServerHash][$database][$tableHash][use]' class='tableNames' id='tables[$mySQLServerHash][$database][$tableHash][use]' $selected >";
  2339. if (isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash]) && $isClone === false) {
  2340. $cloneLink = "<td><a style='cursor:pointer;' onclick='cloneTable(\"$tableHash\");'>Clone<br/>$tableType<br/>Config</a></td>";
  2341. } elseif ($isClone === true) {
  2342. $cloneLink = "<td>Cloned..</td>";
  2343. } else {
  2344. $cloneLink = "<td></td>";
  2345. }
  2346. $options .= "
  2347. <tr id='$tableHash'>
  2348. $cloneLink<td $additionalHTML $tableHash $viewIsAggregateHTML<input type=\"hidden\" value=\"".$resultPK[0]['column_name']."\" name=\"tables[$mySQLServerHash][$database][$tableHash][PK]\"/></td>
  2349. ";
  2350. foreach ($this->tableControlType as $key=>$text) {
  2351. if (empty($text["type"]) ) { continue;}
  2352. if (!isset($_GET['edit']) && $key == OBJECT_PK) {
  2353. // -- dont let user try and edit PK. these will be set on next page
  2354. continue;
  2355. }
  2356. $checked = '';
  2357. $value = '';
  2358. $extra = '';
  2359. $checked2 = '';
  2360. $extra2 = '';
  2361. if ($this->currentAdminDB['crud']['completed_step'] != 'All' && !$this->isPageInclude) {
  2362. // -- pull from default to pre-populate values
  2363. $value = $this->tableControlDefaults[$key];
  2364. if ($key == OBJECT_DESC) {
  2365. $value = str_replace(array('_','-'),array(' ',' '),ucfirst($tableName));
  2366. $value = $this->createDisplayName($value);
  2367. }
  2368. } else {
  2369. $value = $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][$key];
  2370. }
  2371. if (empty($value)) {
  2372. if ($key == OBJECT_DESC) {
  2373. $value = str_replace(array('_','-'),array(' ',' '),ucfirst($tableName));
  2374. $value = $this->createDisplayName($value);
  2375. } else {
  2376. $value = $this->tableControlDefaults[$key];
  2377. }
  2378. }
  2379. //var_dump($this->currentAdminDB,$tableHash,$table);
  2380. if ($text['type'] == 'checkbox' && ($value === true || $value == '1')) {
  2381. $checked = 'checked';
  2382. $checked2 = 'On';
  2383. } else if ($text['type'] == 'checkbox' && $value === false) {
  2384. $checked2 = "Off";
  2385. } else if ($text['type'] == 'checkbox') {
  2386. $checked2 = "Off";
  2387. }
  2388. if ($text['type'] == 'checkbox') {
  2389. $extra = "style='cursor:pointer;' onclick='toggleObj(\"tableConfig[$mySQLServerHash][$database][$tableHash][$key]\")'";
  2390. $extra2 = "style='display:none;'";
  2391. }
  2392. $disabled = "";
  2393. if ($tableType == 'View' && $this->currentAdminDB['crud']['completed_step'] != 'All') {
  2394. switch ($key) {
  2395. case EDIT_TEXT:
  2396. $value = "N/A";
  2397. $disabled = " disabled ";
  2398. break;
  2399. case DELETE_TEXT:
  2400. $value = "N/A";
  2401. $disabled = " disabled ";
  2402. break;
  2403. case ADD_TEXT:
  2404. $value = "N/A";
  2405. $disabled = " disabled ";
  2406. break;
  2407. case VIEW_TEXT:
  2408. $value = "N/A";
  2409. $disabled = " disabled ";
  2410. break;
  2411. case OBJECT_HIDE_DELETE_LINK:
  2412. $extra = "onclick='alert(\"This is a view, you cannot enable this\")'";
  2413. $value = 1;
  2414. break;
  2415. case OBJECT_HIDE_NEW_LINK:
  2416. $value = 1;
  2417. $extra = "onclick='alert(\"This is a view, you cannot enable this\")'";
  2418. break;
  2419. case OBJECT_HIDE_EDIT_LINK:
  2420. $value = 1;
  2421. $extra = "onclick='alert(\"This is a view, you cannot enable this\")'";
  2422. break;
  2423. case OBJECT_PAGING_NUM_ROWS_PER_PAGE:
  2424. $value = 100;
  2425. break;
  2426. case TABLE_TEXT:
  2427. $value = "{table_desc} Listing";
  2428. break;
  2429. }
  2430. }
  2431. $options .= "<td $extra><input $key $disabled $extra2 $extra type=\"$text[type]\" name=\"tableConfig[$mySQLServerHash][$database][$tableHash][$key]\" id=\"tableConfig[$mySQLServerHash][$database][$tableHash][$key]\" value=\"$value\" $checked/><span id=\"tableConfig[$mySQLServerHash][$database][$tableHash][$key][onoff]\" {$key}_onoff class=\"".strtolower($checked2)."\">$checked2</span></td>";
  2432. }
  2433. $option .= "
  2434. </tr>
  2435. ";
  2436. }
  2437. }
  2438. }
  2439. $this->closeDatabase($conn);
  2440. }
  2441. }
  2442. if ($errors) {
  2443. $allErrors = "
  2444. <div class=\"error\" style=\"cursor:pointer;\" onclick=\"if ($('allerrors').style.display == 'none') { $('allerrors').style.display = 'inline';} else { $('allerrors').style.display = 'none';}\">There were tables that could not be used because Primary Keys Dont Exist. Click For more Info.</div>
  2445. <span id=\"allerrors\" style=\"display:none\">
  2446. $errors
  2447. </span>";
  2448. }
  2449. echo
  2450. "
  2451. <script>
  2452. var uncheckedTable=false;
  2453. </script>
  2454. <form action='$_SERVER[PHP_SELF]?admin=1&select_tables=1&store_database=1' id='tableForm{$_GET['edit']}' method='post'>
  2455. ".$this->displayGenericObjects()."
  2456. <div id='serverinfo'>
  2457. Step 3: Table Selection
  2458. $allErrors
  2459. <table style='width:1500px;'>
  2460. $options
  2461. </table>
  2462. <a class='button' onclick='
  2463. if (uncheckedTable==true) {
  2464. if (window.confirm(\"Are you sure you want to remove a table from the listing? Doing so will delete all field configuration for this table.\")) {
  2465. $(\"tableForm{$_GET['edit']}\").action= $(\"tableForm{$_GET['edit']}\").action + \"&conf=$this->current_config\";
  2466. $(\"tableForm{$_GET['edit']}\").submit();
  2467. }
  2468. } else {
  2469. $(\"tableForm{$_GET['edit']}\").action= $(\"tableForm{$_GET['edit']}\").action + \"&conf=$this->current_config\";
  2470. $(\"tableForm{$_GET['edit']}\").submit();
  2471. }'><span>Select These Tables</span></a>
  2472. </div>
  2473. </form>
  2474. ";
  2475. }
  2476. function handleAdminPages() {
  2477. echo '<span style="font-size:1.2em;">';
  2478. // -- step 1
  2479. if (isset($_GET['initialize_server']) || $this->override['initialize_server']) {
  2480. if (isset($_GET['store_database'])) {
  2481. $this->storeDatabaseConnectionForm();
  2482. } else {
  2483. $this->displayDatabaseConnectionForm();
  2484. }
  2485. }
  2486. // -- step 2
  2487. if (isset($_GET['select_database']) || $this->override['select_database']) {
  2488. if (isset($_GET['store_database'])) {
  2489. $this->storeDatabaseSelectionForm();
  2490. } else {
  2491. $this->displayDatabaseSelectionForm();
  2492. }
  2493. }
  2494. // -- step 3
  2495. if (isset($_GET['select_tables']) || $this->override['select_tables']) {
  2496. if (isset($_GET['store_database'])) {
  2497. $this->storeTableSelectionForm();
  2498. } else {
  2499. if ($this->isPageInclude) {
  2500. $mySqlArray = array($_GET['server']=>$_GET['server']);
  2501. $mysqlDbArray = array($_GET['server']=>array($_GET['database']=>$_GET['database']));
  2502. } else {
  2503. $mySqlArray = $this->currentAdminDB['crud']['mysql_server_names'];
  2504. $mysqlDbArray = $this->currentAdminDB['crud']['mysql_databases'];
  2505. }
  2506. $this->displayTableSelectionForm($mySqlArray,$mysqlDbArray);
  2507. }
  2508. }
  2509. // -- step 4
  2510. if (isset($_GET['select_groups']) || $this->override['select_groups']) {
  2511. if (isset($_GET['store_database'])) {
  2512. $this->storeGroupSelectionForm();
  2513. } else {
  2514. $this->displayGroupSelectionForm();
  2515. }
  2516. }
  2517. // -- step 5
  2518. if (isset($_GET['select_roles']) || $this->override['select_roles']) {
  2519. if (isset($_GET['store_database'])) {
  2520. $this->storeRolesSelectionForm();
  2521. } else {
  2522. $this->displayRolesSelectionForm();
  2523. }
  2524. }
  2525. // -- step 6
  2526. if (isset($_GET['select_users']) || $this->override['select_users']) {
  2527. if (isset($_GET['store_database'])) {
  2528. $this->storeUserSelectionForm();
  2529. } else {
  2530. $this->displayUserSelectionForm();
  2531. }
  2532. }
  2533. // -- step 7
  2534. if (isset($_GET['select_theme']) || $this->override['select_themes']) {
  2535. if (isset($_GET['store_database'])) {
  2536. $this->storeThemeSelectionForm();
  2537. } else {
  2538. $this->displayThemeSelectionForm();
  2539. }
  2540. }
  2541. // -- step 8 (done after everything on a per table basis)
  2542. if (isset($_GET['select_fields']) || $this->override['select_fields']) {
  2543. if (isset($_GET['store_database'])) {
  2544. $this->storeFieldSelectionForm();
  2545. } else {
  2546. $this->displayFieldSelectionForm();
  2547. }
  2548. }
  2549. // -- step 9 finalize your local serialized array for production use
  2550. if (isset($_GET['productionize'])) {
  2551. $this->productionizeAdminDB();
  2552. }
  2553. // -- ajax fields
  2554. if (isset($_GET['find_fields'])) {
  2555. $this->displayFieldsAJAX();
  2556. }
  2557. // -- ajax clone
  2558. if (isset($_GET['clone_table'])) {
  2559. $this->cloneObject($_GET['original_pointer'],$_GET['new_name']);
  2560. }
  2561. echo '</span>';
  2562. }
  2563. function getPrimaryKey($database,$tableName,$conn) {
  2564. $resultPK = $this->queryDatabase(
  2565. "SELECT k.column_name
  2566. FROM information_schema.table_constraints t
  2567. JOIN information_schema.key_column_usage k
  2568. USING(constraint_name,table_schema,table_name)
  2569. WHERE t.constraint_type='PRIMARY KEY'
  2570. AND t.table_schema='$database'
  2571. AND t.table_name='$tableName'
  2572. UNION
  2573. ",$conn);
  2574. if (empty($resultPK)) {
  2575. // -- developers might not have access to information_schema
  2576. $resultPK2 = $this->queryDatabase(sprintf(GET_COLUMNS_SQL,$tableName),$conn);
  2577. if (is_array($resultPK2)) {
  2578. foreach ($resultPK2 as $key=>$row) {
  2579. if ($row['Key'] == 'PRI') {
  2580. $resultPK[0]['column_name'] = $row['Field'];
  2581. }
  2582. }
  2583. }
  2584. }
  2585. return $resultPK;
  2586. }
  2587. function storeTableSelectionForm() {
  2588. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  2589. $this->currentAdminDB['crud']['completed_step'] = 3;
  2590. }
  2591. if ($this->isPageInclude) {
  2592. if (isset($_GET['conf']) && $_GET['conf'] != $this->current_config) {
  2593. return;
  2594. }
  2595. }
  2596. ob_end_clean();
  2597. if(is_array($_REQUEST['tables'])) {
  2598. $drawFunctions = "<?php\n";
  2599. foreach ($_REQUEST['tables'] as $server=>$selectedDatabase) {
  2600. foreach ($selectedDatabase as $database=>$tableValues) {
  2601. foreach ($tableValues as $table=>$primaryKey) {
  2602. $tableOriginal = $primaryKey['use'];
  2603. if ($this->isPageInclude) {
  2604. $tableHash = $tableOriginal;
  2605. } else {
  2606. $tableHash = $table;
  2607. }
  2608. $addNew = false;
  2609. if (!isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG])) {
  2610. $addNew = true;
  2611. }
  2612. if (!is_dir(getcwd().$this->systemDirectorySeparator."pages")) {
  2613. mkdir(getcwd().$this->systemDirectorySeparator."pages",0777);
  2614. }
  2615. $pages[] = "pages_".$_SERVER['SERVER_NAME'].".$table.php";
  2616. $this->writeFile( getcwd().$this->systemDirectorySeparator."pages".$this->systemDirectorySeparator."pages_".$_SERVER['SERVER_NAME'].".$table.php","<?php
  2617. ob_start();
  2618. echo
  2619. ' <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
  2620. <html xmlns=\"http://www.w3.org/1999/xhtml\">
  2621. <head>
  2622. <title></title>
  2623. <meta http-equiv=\"Content-Language\" content=\"English\" />
  2624. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />
  2625. <body>
  2626. <h4>Copy/paste or modify this template in any application to manage your data for \"{$primaryKey['use']}\" configuration</h4>
  2627. <h4>Once you are done configuring {$primaryKey['use']}.config.php, click Productionize to ensure security on your database connections and then set \$crudAdmin->cruddyAdministrator = false; to disble configuration changes any further</h4>
  2628. ';
  2629. // -- all requests for cruddy mysql must start one path below the \"cruddy_mysql\" libs driectory to pick up the config files and connections
  2630. chdir(\"".getcwd()."\");
  2631. require_once(\"configurations/crud_".$_SERVER['SERVER_NAME'].".connections.php\");
  2632. require_once(\"cruddy_mysql/cruddy_mysql.php\");
  2633. \$crudAdmin = new cruddyMysqlAdmin();
  2634. \$serverHash = \"$server\";
  2635. \$tableName = \"{$primaryKey['use']}\";
  2636. \$databaseName = \"$database\";
  2637. // -- set to true or false when you wish to make changes to the crud configuration for the table
  2638. \$crudAdmin->cruddyAdministrator = true;
  2639. \$crudAdmin->paint(\$tableName, \$connection[\$serverHash]['server'], \$connection[\$serverHash]['username'], \$connection[\$serverHash]['password'], \$databaseName, \$tableName);
  2640. echo
  2641. '
  2642. </body>
  2643. </html>
  2644. ';
  2645. ob_end_flush();
  2646. ?>"
  2647. );
  2648. $this->currentAdminDB['crud']['mysql_tables_to_config'][$database][$tableHash] = $tableHash;
  2649. if (!isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG])) {
  2650. foreach ($this->tableControlDefaults as $systemKey=>$text) {
  2651. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][$systemKey] = $text;
  2652. }
  2653. foreach ($this->tableControlType as $systemKey=>$text) {
  2654. if (empty($text["type"]) ) { continue;}
  2655. if ($_REQUEST['tableConfig'][$server][$database][$tableHash][$systemKey]) {
  2656. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][$systemKey] = $_REQUEST['tableConfig'][$server][$database][$tableHash][$systemKey];
  2657. } else {
  2658. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][$systemKey]);
  2659. }
  2660. }
  2661. }
  2662. if (!$this->isPageInclude) {
  2663. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_CONNECTION_STRING] = "mysql://".$this->currentAdminDB['crud']['mysql_user_names'][$server].":".$this->currentAdminDB['crud']['mysql_passwords'][$server]."@".$this->currentAdminDB['crud']['mysql_server_names'][$server].":".$this->currentAdminDB['crud']['mysql_ports'][$server]."/".$database;
  2664. // -- add default field behavior now
  2665. $conn = $this->connectDatabase($this->currentAdminDB['crud']['mysql_server_names'][$server].":".$this->currentAdminDB['crud']['mysql_ports'][$server],$database);
  2666. if ($addNew == true) {
  2667. $this->addDefaultFieldData($tableOriginal,$conn,$tableHash);
  2668. }
  2669. $this->closeDatabase($conn);
  2670. }
  2671. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_ACTIONS] = $this->tableControlDefaults[OBJECT_ACTIONS];
  2672. if (!$this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG]['is_clone']) {
  2673. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_TABLE] = $tableOriginal;
  2674. }
  2675. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_DESC] = $_REQUEST['tableConfig'][$server][$database][$tableHash][OBJECT_DESC];
  2676. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_IS_AGGREGATE] = $_REQUEST['tables'][$server][$database][$tableHash]['Aggregate'];
  2677. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_DEFAULT_ORDER] = $_REQUEST['tableConfig'][$server][$database][$tableHash]['defaultorder'];
  2678. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_READ_FILTER] = $_REQUEST['tableConfig'][$server][$database][$tableHash]['filterrecords'];
  2679. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_FILTER_DESC] = $_REQUEST['tableConfig'][$server][$database][$tableHash]['filterrecordsdescription'];
  2680. $pk = $primaryKey['PK'];
  2681. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OBJECT_PK] = $pk;
  2682. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG]['alias'] = $tableHash;
  2683. $linkEdit = "?action=".strtolower($this->actionTypes['update'].$tableHash)."&".$pk."=%".$pk."%";
  2684. $linkDelete = "?action=".strtolower($this->actionTypes['delete'].$tableHash)."&".$pk."=%".$pk."%";
  2685. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][EDIT_LINK] = $linkEdit;
  2686. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][DELETE_LINK] = $linkDelete;
  2687. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][TABLE_CONFIG][OTHER_LINKS] = "";
  2688. if (!isset($primaryKey['use'])) {
  2689. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash]);
  2690. continue;
  2691. }
  2692. }
  2693. }
  2694. }
  2695. foreach ($pages as $page) {
  2696. $pageIndexHTML .= "<h5><a href=\"$page\">$page</a></h5>";
  2697. }
  2698. $this->writeFile( getcwd().$this->systemDirectorySeparator."pages".$this->systemDirectorySeparator."index.php","
  2699. <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
  2700. <html xmlns=\"http://www.w3.org/1999/xhtml\">
  2701. <head>
  2702. <title></title>
  2703. <meta http-equiv=\"Content-Language\" content=\"English\" />
  2704. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />
  2705. <body>
  2706. <h4>Here are all of your cruddy_mysql configuration pages that you can drop in ANYWHERE with ANY APPLICATION!</h4>
  2707. <h4>Just step through the fields configuration as to how you want it to behave and productionize.</h4>
  2708. $pageIndexHTML
  2709. </body>
  2710. </html>
  2711. "
  2712. );
  2713. // -- turning off comments in the files to conserve size
  2714. $showComments = false;
  2715. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $tableHash=>$obj) {
  2716. $drawFunctions .= "\$crudAdmin->paint('$tableHash');\n\n";
  2717. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." PRE PROCESSES BEFORE LOADING A TABLE RECORDSET (Primarily used to overwrite parts of the serialized array with \$_SESSION vars and application specific logic)\n*/";}
  2718. $functionsIncludes .= "if (file_exists(\$_SERVER['DOCUMENT_ROOT'].'".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."custom_processors/".$this->cleanTableNames($tableHash).".php'))\n\t require_once(\$_SERVER['DOCUMENT_ROOT'].'".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."custom_processors/".$this->cleanTableNames($tableHash).".php');\n";
  2719. $functions = "<?php\n";
  2720. $functions .= "\n\nif(!function_exists('pre_process_load_".$this->cleanTableNames($tableHash)."')){\n\tfunction pre_process_load_".$this->cleanTableNames($tableHash)."(\$pointer){\n\t";
  2721. if ($showComments) { $functions .= "//--add your custom logic here such as changing \$pointer[TABLE_CONFIG][OBJECT_READ_FILTER] with a dynamic where clause or \$pointer['fieldname_config']['VALUE'] for overriding values or any attributes possible in the config array "; }
  2722. $functions .= "\n\t\treturn \$pointer;\n\t}\n}\n\n";
  2723. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." PRE PROCESSES BEFORE INSERTING A RECORD\n*/ "; }
  2724. $functions .= "\n\nif(!function_exists('pre_process_load_".$this->cleanTableNames($tableHash)."')){\n\tfunction new_pre_process_".$this->cleanTableNames($tableHash)."(){\n\t";
  2725. if ($showComments) { $functions .= "//--add your custom logic here before inserting a record in $tableHash -- return false if not wanting to add new "; }
  2726. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2727. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." POST PROCESSES AFTER INSERTING A RECORD\n*/ "; }
  2728. $functions .= "\n\nif(!function_exists('new_post_process_".$this->cleanTableNames($tableHash)."')){\n\tfunction new_post_process_".$this->cleanTableNames($tableHash)."(){\n\t";
  2729. if ($showComments) { $functions .= "//--add your custom logic here after inserting a record in $tableHash "; }
  2730. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2731. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." PRE PROCESSES BEFORE UPDATING A RECORD\n*/ "; }
  2732. $functions .= "\n\nif(!function_exists('update_pre_process_".$this->cleanTableNames($tableHash)."')){\n\tfunction update_pre_process_".$this->cleanTableNames($tableHash)."(){";
  2733. if ($showComments) { $functions .= "\n\t//--add your custom logic here before updating a record in $tableHash -- return false if not wanting to update the record because of logical checks "; }
  2734. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2735. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." POST PROCESSES AFTER UPDATING A RECORD\n*/ "; }
  2736. $functions .= "\n\nif(!function_exists('update_post_process_".$this->cleanTableNames($tableHash)."')){\n\tfunction update_post_process_".$this->cleanTableNames($tableHash)."(){";
  2737. if ($showComments) { $functions .= "\n\t//--add your custom logic here after updating a record in $tableHash "; }
  2738. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2739. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." PRE PROCESSES BEFORE DELETING A RECORD\n*/ "; }
  2740. $functions .= "\n\nif(!function_exists('delete_pre_process_".$this->cleanTableNames($tableHash)."')){\nfunction delete_pre_process_".$this->cleanTableNames($tableHash)."(){";
  2741. if ($showComments) { $functions .= "\n\t//--add your custom logic here before deleing a record in $tableHash -- return false if not wanting to delete the record based on logic you add "; }
  2742. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2743. if ($showComments) { $functions .= "/*\n* ".strtoupper($tableHash)." POST PROCESSES AFTER DELETING A RECORD\n*/ "; }
  2744. $functions .= "\n\nif(!function_exists('delete_post_process_".$this->cleanTableNames($tableHash)."')){\n\tfunction delete_post_process_".$this->cleanTableNames($tableHash)."(){";
  2745. if ($showComments) { $functions .= "\n\t//--add your custom logic here after deleing a record in $tableHash "; }
  2746. $functions .= "\n\t\treturn true;\n\t}\n}\n\n";
  2747. $functions .= "\n\n?>";
  2748. if (!is_dir(getcwd().$this->systemDirectorySeparator."custom_processors")) {
  2749. mkdir(getcwd().$this->systemDirectorySeparator."custom_processors",0777);
  2750. }
  2751. $funcFile = getcwd().$this->systemDirectorySeparator."custom_processors".$this->systemDirectorySeparator.$this->cleanTableNames($tableHash).".php";
  2752. if (!file_exists($funcFile)) {
  2753. // -- write once to unique table configuration pre/post processor functions so people can confidently know that cruddy will not kill any custom changes.
  2754. $this->writeFile($funcFile,$functions);
  2755. }
  2756. }
  2757. $drawFunctions .= "\$crudAdmin->paintGroups();\n\n";
  2758. $drawFunctions .= "\n\n?>";
  2759. if (!file_exists($this->functionsFile)) {
  2760. // -- no file modifications have been done or file doesnt exist
  2761. $this->writeFile($this->functionsFile,"<?php\n\n".$functionsIncludes."\n\n?>");
  2762. $this->currentAdminDB['crud']['functionsfile_mtime'] = filemtime($this->functionsFile);
  2763. }
  2764. if (!$this->isPageInclude) {
  2765. $this->writeFile($this->functionsDrawFile,$drawFunctions);
  2766. }
  2767. $this->currentAdminDB['crud']['drawfile_mtime'] = filemtime($this->functionsFile);
  2768. $this->writeAdminDB();
  2769. if ($_GET['mode'] != 'edit' ) {
  2770. if (!isset($_COOKIE['redirect']) || $this->currentAdminDB['crud']['completed_step'] != 'All') {
  2771. if ($this->isPageInclude) {
  2772. $this->redirect($_SERVER['PHP_SELF']);
  2773. } else {
  2774. $this->redirect($_SERVER['PHP_SELF']."?admin=1&select_groups");
  2775. }
  2776. } else {
  2777. $this->redirect($_COOKIE['redirect']);
  2778. }
  2779. }
  2780. } else {
  2781. echo "No Tables Selected";
  2782. }
  2783. exit;
  2784. }
  2785. function addDefaultFieldData($table,$conn,$tableHash) {
  2786. $fieldResults = $this->queryDatabase(sprintf(GET_COLUMNS_SQL,$table),$conn);
  2787. if (is_array($fieldResults)) {
  2788. foreach ($fieldResults as $key=>$row) {
  2789. $fieldCaption = $this->createDisplayName($row['Field']);
  2790. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][CAPTION] = $fieldCaption;
  2791. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][SORTABLE] = true;
  2792. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']."_config"] = array();
  2793. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][SHOWCOLUMN] = true;
  2794. if (stristr($row['Comment'],"lookup")) {
  2795. // -- if you initially put lookup,tableName,fieldThatStoresKey,fieldThatStoresTextLookup in your comments they will be automatically initialized
  2796. list($type,$table,$field,$value) = explode(",",$row['Comment']);
  2797. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][TABLE] = trim($table);
  2798. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][ID] = trim($field);
  2799. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][TEXT] = trim($value);
  2800. }
  2801. if ($row['Field'] == $pk) {
  2802. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][SHOWCOLUMN] = false;
  2803. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][READONLY] = true;
  2804. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][UPDATE_READ_ONLY] = true;
  2805. $this->currentAdminDB[CRUD_FIELD_CONFIG][$tableHash][$row['Field']][HIDE] = true;
  2806. continue;
  2807. }
  2808. }
  2809. }
  2810. }
  2811. function displayFieldsAJAX() {
  2812. ob_end_clean();
  2813. $conn = $this->connectDatabase($_GET['server'],$_GET['database']);
  2814. $fieldRows = $this->queryDatabase(sprintf(GET_COLUMNS_SQL,$_GET['table']),$conn);
  2815. echo "<select name=\"fields[".$_GET['k1']."][<FIELD_TOKEN>]\">";
  2816. foreach ($fieldRows as $fieldKey=>$fieldValue) {
  2817. echo "<option value=\"___distinct___lookup___".$fieldValue['Field']."\">" . $fieldValue['Field'] . " (Unique Values)</option>";
  2818. echo "<option value=\"".$fieldValue['Field']."\">" . $fieldValue['Field'] . "</option>";
  2819. }
  2820. echo "</select>";
  2821. $this->closeDatabase($conn);
  2822. exit;
  2823. }
  2824. function cloneObject($pointer,$name) {
  2825. ob_end_clean();
  2826. $name = $this->cleanTableNames($name);
  2827. $this->currentAdminDB[CRUD_FIELD_CONFIG][$name] = $this->currentAdminDB[CRUD_FIELD_CONFIG][$pointer];
  2828. $this->currentAdminDB[CRUD_FIELD_CONFIG][$name][TABLE_CONFIG]['is_clone'] = true;
  2829. $this->currentAdminDB[CRUD_FIELD_CONFIG][$name][TABLE_CONFIG]['clone_of'] = $pointer;
  2830. $this->writeAdminDB();
  2831. echo "SUCCESS";
  2832. exit;
  2833. }
  2834. #4 Step
  2835. function displayFieldSelectionForm() {
  2836. $conn = $this->connectDatabase($_GET['server'],$_GET['database']);
  2837. $database = $_GET['database'];
  2838. if (!$this->isPageInclude) {
  2839. $configPointer = $_GET['edit'];
  2840. } else {
  2841. if (isset($_GET['conf']) && $_GET['conf'] != $this->current_config) {
  2842. return;
  2843. }
  2844. $configPointer = $_REQUEST['tablePointer'];
  2845. }
  2846. $options .= "<tr><td></td><td></td><td></td>";
  2847. foreach ($this->fieldControlType as $key=>$text) {
  2848. if ($key == TABLE || $key == ID || $key == TEXT ) {
  2849. $options .= "<td></td>";
  2850. continue;
  2851. }
  2852. $rowOutPut = '';
  2853. $checked2 = '';
  2854. $value = $this->tableControlDefaults[$key];
  2855. if ($text['type'] == 'checkbox' && ($value === true || $value == '1')) {
  2856. $checked2 = 'Off';
  2857. } else if ($text['type'] == 'checkbox' && $value === false) {
  2858. $checked2 = 'On';
  2859. } else if ($text['type'] == 'checkbox') {
  2860. $checked2 = 'On';
  2861. }
  2862. if ($checked2 != '') {
  2863. $rowOutPut .= 'Turn all ';
  2864. if ($checked2 == 'On') {
  2865. $rowOutPut .= 'Off';
  2866. } else {
  2867. $rowOutPut .= 'On';
  2868. }
  2869. $click = "if (this.innerHTML==\"Turn all Off\") { cruddy(\"input[$key]\").attr(\"checked\",false);cruddy(\"span[{$key}_onoff]\").html(\"Off\"); cruddy(\"input[$key]\").val(0); this.innerHTML = \"Turn all On\";} else { cruddy(\"input[$key]\").attr(\"checked\",true); cruddy(\"input[$key]\").val(1); cruddy(\"span[{$key}_onoff]\").html(\"On\");this.innerHTML = \"Turn all Off\"; }";
  2870. } else {
  2871. $rowOutPut .= 'Replace All Text';
  2872. $click = "var val = window.prompt(\"Enter the replacement value\",\"\");cruddy(\"input[$key]\").val(val);";
  2873. }
  2874. $options .= "<td><a onclick='$click'>".$rowOutPut."</a></td>";
  2875. }
  2876. $options .= "</tr>";
  2877. $options .= "<tr>";
  2878. $options .= "<td>Field Name</td>";
  2879. foreach ($this->fieldConfigType as $type=>$text) {
  2880. $options .= "<td>".$text['desc']."</td>";
  2881. }
  2882. foreach ($this->fieldControlType as $type=>$text) {
  2883. $options .= "<td>".$text['desc']."</td>";
  2884. }
  2885. $options .= "</tr>";
  2886. $table = $this->currentAdminDB[CRUD_FIELD_CONFIG][$_GET['edit']][TABLE_CONFIG][OBJECT_TABLE];
  2887. if (!$table) {
  2888. $table = $_GET['edit'];
  2889. }
  2890. $fieldRows = $this->queryDatabase(sprintf(GET_COLUMNS_SQL,$table),$conn);
  2891. foreach ($fieldRows as $fieldKey=>$fieldValue) {
  2892. $options .= "
  2893. <tr id=\"".$fieldValue['Field']."_tr\">
  2894. <td>$fieldValue[Field]<input type=\"hidden\" value=\"".$fieldValue['Field']."\" name=\"fields[".$fieldValue['Field']."][name]\"/></td>
  2895. ";
  2896. foreach ($this->fieldConfigType as $key=>$text) {
  2897. $checked = '';
  2898. $value = '';
  2899. $extra = '';
  2900. $checked2 = '';
  2901. $extra2 = '';
  2902. if ($key == "VALUE") {
  2903. $value;
  2904. }
  2905. $value = $this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][$fieldValue['Field']."_config"][$key];
  2906. if ($text['type'] == 'checkbox' && ($value === true || $value == '1')) {
  2907. $checked = 'checked';
  2908. $checked2 = 'On';
  2909. } else if ($text['type'] == 'checkbox' && $value === false) {
  2910. $checked2 = "Off";
  2911. } else if ($text['type'] == 'checkbox') {
  2912. $checked2 = "Off";
  2913. }
  2914. if ($text['type'] == 'checkbox') {
  2915. $extra = "style='cursor:pointer;' onclick='toggleObj(\"fields_config[".$fieldValue['Field']."][$key]\")'";
  2916. //$extra2 = "style='display:none;'";
  2917. }
  2918. if ($text['type'] != 'link') {
  2919. $options .= "<td $extra><input $extra2 $extra type=\"$text[type]\" name=\"fields_config[".$fieldValue['Field']."][$key]\" $key id=\"fields_config[".$fieldValue['Field']."][$key]\" value=\"$value\" $checked/><span {$key}_onoff id=\"fields_config[".$fieldValue['Field']."][$key][onoff]\" class=\"".strtolower($checked2)."\">$checked2</span></td>";
  2920. } else {
  2921. $value = $this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][$fieldValue['Field']."_config"];
  2922. $autoObject = parent::parseColumnInfo($fieldValue['Type'],$fieldValue['Default'],$fieldValue['Field']);
  2923. $optionsObjectTypes = '<option>Select a Field Type</option>';
  2924. foreach ($this->fieldObjectTypes as $key2=>$text2) {
  2925. $selected = "";
  2926. if ($fieldValue['Type'] == "date") {
  2927. $value['TYPE'] = "date";
  2928. }
  2929. if ($fieldValue['Type'] == "datetime" || $fieldValue['Type'] == "timestamp") {
  2930. $value['TYPE'] = "timestamp";
  2931. }
  2932. if ($value['TYPE'] == $key2) {
  2933. $selected = "selected";
  2934. }
  2935. if ($autoObject['TYPE'] == $key2 && empty($value['TYPE'])) {
  2936. $selected = "selected";
  2937. }
  2938. $optionsObjectTypes .= "<option value=\"".$key2."\" $selected>".$text2['desc']."</option>";
  2939. }
  2940. $noneAvailable = true;
  2941. $optionsMiscTypes = '<option>Add A New Misc. Config</option>';
  2942. foreach ($this->fieldMiscTypes as $key2=>$text2) {
  2943. if (isset($value[$key2])) { continue;}
  2944. $noneAvailable = false;
  2945. $optionsMiscTypes .= "<option value=\"".$key2."\">".$text2['desc']."</option>";
  2946. }
  2947. if ($noneAvailable===true) {
  2948. $optionsMiscTypes .= "<option>There are no Validation Rules Available</option>";
  2949. }
  2950. $noneAvailable = true;
  2951. $optionsValidationTypes = '<option>Add A New Validation Type</option>';
  2952. foreach ($this->fieldValidationTypes as $key2=>$text2) {
  2953. if (isset($value[$key2])) { continue;}
  2954. $noneAvailable = false;
  2955. $optionsValidationTypes .= "<option value=\"".$key2."\">".$text2['desc']."</option>";
  2956. }
  2957. if ($noneAvailable===true) {
  2958. $optionsValidationTypes .= "<option>There are no Validation Rules Available</option>";
  2959. }
  2960. $noneAvailable = true;
  2961. $optionsEventTypes = '<option>Add A New Javascript Event</option>';
  2962. foreach ($this->fieldEventTypes as $key2=>$text2) {
  2963. if (isset($value[$key2])) { continue; }
  2964. $noneAvailable = false;
  2965. $optionsEventTypes .= "<option value=\"".$key2."\">".$text2['desc']."</option>";
  2966. }
  2967. if ($noneAvailable===true) {
  2968. $optionsEventTypes .= "<option>There are no Events Left</option>";
  2969. }
  2970. $attributes = $value;
  2971. unset($attributes['TYPE']);
  2972. if (is_array($attributes) && sizeof($attributes) > 0) {
  2973. $existingEntriesTop = '<td valign="top">Edit:</td>';
  2974. $existingEntriesBottom = '<td valign="top"></td>';
  2975. foreach ($attributes as $optionKey=>$optionValue) {
  2976. if ($optionKey == 'TYPE') {
  2977. continue;
  2978. }
  2979. if ($this->fieldMiscTypes[$optionKey]) {
  2980. $desc = $this->fieldMiscTypes[$optionKey]['desc'];
  2981. $type = $this->fieldMiscTypes[$optionKey]['type'];
  2982. } elseif ($this->fieldValidationTypes[$optionKey]) {
  2983. $desc = $this->fieldValidationTypes[$optionKey]['desc'];
  2984. $type = "checkbox";
  2985. } elseif ($this->fieldEventTypes[$optionKey]) {
  2986. $desc = $this->fieldEventTypes[$optionKey]['desc'];
  2987. $type = "textarea";
  2988. }
  2989. $checked = '';
  2990. $value = '';
  2991. $extra = '';
  2992. $checked2 = '';
  2993. $extra2 = '';
  2994. if ($type == 'checkbox' && ($optionValue === true || $optionValue == '1')) {
  2995. $checked = 'checked';
  2996. $checked2 = 'On';
  2997. } else if ($type == 'checkbox' && $optionValue === false) {
  2998. $checked2 = "Off";
  2999. } else if ($type == 'checkbox') {
  3000. $checked2 = "Off";
  3001. }
  3002. if ($type == 'checkbox') {
  3003. $extra = "style='cursor:pointer;' onclick='toggleObj(\"fields_config[".$fieldValue['Field']."][$optionKey]\")'";
  3004. $extra2 = "style='display:none;'";
  3005. }
  3006. $existingEntriesTop .= "<td valign=\"top\"><span id=\"".$fieldValue['Field'].$optionKey."_top\">$desc:</td>";
  3007. $deleteButton = "<a style='cursor:pointer;' class='button' onclick='$(\"fields_config[".$fieldValue['Field']."][$optionKey]\").style.display = \"none\";$(\"fields_config[".$fieldValue['Field']."][$optionKey]\").value = \"!!DELETE_TOKEN!!\";this.style.display=\"none\";$(\"".$fieldValue['Field'].$optionKey."_top\").style.textDecoration = \"line-through\";$(\"".$fieldValue['Field'].$optionKey."_top\").style.color = \"red\";'><span>Delete</span></a>";
  3008. if ($type != 'textarea') {
  3009. if (!is_array($optionValue)) {
  3010. $existingEntriesBottom .= "<td valign=\"top\"><input $extra2 $extra type=\"$text[type]\" name=\"fields_config[".$fieldValue['Field']."][$optionKey]\" id=\"fields_config[".$fieldValue['Field']."][$optionKey]\" value=\"$optionValue\" $checked/><span id=\"fields_config[".$fieldValue['Field']."][$optionKey][onoff]\" class=\"".strtolower($checked2)."\">$checked2</span><br/>$deleteButton</td>";
  3011. } else {
  3012. $existingEntriesBottom .= "<td valign=\"top\">";
  3013. foreach ($optionValue as $k=>$v) {
  3014. $existingEntriesBottom .= "<input $extra2 $extra type=\"$text[type]\" name=\"fields_config[".$fieldValue['Field']."][$optionKey][key][]\" id=\"fields_config[".$fieldValue['Field']."][$optionKey][key][]\" value=\"$k\" $checked/>=><input $extra2 $extra type=\"$text[type]\" name=\"fields_config[".$fieldValue['Field']."][$optionKey][value][]\" id=\"fields_config[".$fieldValue['Field']."][$optionKey][value][]\" value=\"$v\" $checked/><br/><span id='".$fieldValue['Field']."additional'></span><span id='".$fieldValue['Field']."additional'></span>";
  3015. }
  3016. $existingEntriesBottom .= "<a style='cursor:pointer;' class='button' onclick='if (msgDebug === false) {alert(\"Known issue, please click add however many times before entering the attribute name and value (otherwise it clears out)\");}msgDebug=true;$(\"".$fieldValue['Field']."additional\").innerHTML += \"<input type=text name=fields_config[".$fieldValue['Field']."][$optionKey][key][]/>=><input type=text name=fields_config[".$fieldValue['Field']."][$optionKey][value][] /><br/>\";'><span>Add</span></a></td>";
  3017. }
  3018. } else {
  3019. $existingEntriesBottom .= "<td valign=\"top\"><textarea style=\"height:100px;\" name=\"fields_config[".$fieldValue['Field']."][$optionKey]\" id=\"fields_config[".$fieldValue['Field']."][$optionKey]\">$optionValue</textarea>$deleteButton</td>";
  3020. }
  3021. }
  3022. } else {
  3023. $existingEntriesTop = "";
  3024. }
  3025. $extra = "style='cursor:pointer;' onclick='toggleObj(\"fields_config[".$fieldValue['Field']."][$optionKey]\")'";
  3026. $extra2 = "style='display:none;'";
  3027. $options .= "
  3028. <td>
  3029. <!--<a onclick=\"addRow('".$fieldValue['Field']."_tr','".$fieldValue['Field']."_span',this);\" style=\"cursor:pointer;\">Configure</a>-->
  3030. <div style=\"float:left\" id=\"".$fieldValue['Field']."_span_copy\" >
  3031. <h3 style=\"margin:0px\">".$fieldValue['Field']." control</h3>
  3032. <table style=\"border:none;\">
  3033. <tr>
  3034. <td>Input Type:</td>
  3035. <td>
  3036. <span id=\"additionalParameters\"></span>
  3037. <select name=\"fields_config[".$fieldValue['Field']."][TYPE]\" id=\"fields_config[".$fieldValue['Field']."][TYPE]\" onchange=\"handleWidgetChange(this,'{$fieldValue['Field']}')\">
  3038. $optionsObjectTypes
  3039. </select>
  3040. </td>
  3041. </tr>
  3042. <tr>
  3043. <td> Validations: </td>
  3044. <td> <select onchange=\"onChangeValidations('".$fieldValue['Field']."',this);\" id=\"fields_config[".$fieldValue['Field']."][events]\" id=\"fields_config[".$fieldValue['Field']."][validations]\">
  3045. $optionsValidationTypes
  3046. </select>
  3047. </td>
  3048. </tr>
  3049. <tr>
  3050. <td> Events:</td>
  3051. <td> <select onchange=\"addTD('".$fieldValue['Field']."_new','".$fieldValue['Field']."_' + this.value);$('".$fieldValue['Field']."_' + this.value).innerHTML = this.value + ' Event:<br/><textarea name=fields_config[".$fieldValue['Field']."][' + this.value + ']></textarea>';this.removeChild(this[this.selectedIndex]);\" id=\"fields_config[".$fieldValue['Field']."][events]\">
  3052. $optionsEventTypes
  3053. </select>
  3054. </td>
  3055. </tr>
  3056. <tr>
  3057. <td> Misc:</td>
  3058. <td> <select onchange=\"addTD('".$fieldValue['Field']."_new','".$fieldValue['Field']."_' + this.value);var HTML = this.options[this.selectedIndex].text + '<br/><input type=text name=fields_config[".$fieldValue['Field']."][' + this.value + ']';if(this.value=='ExtraAttributes'){ $('".$fieldValue['Field']."_' + this.value).innerHTML += HTML + '[key][]/>=><input name=fields_config[".$fieldValue['Field']."][' + this.value + '][value][]>';} else { $('".$fieldValue['Field']."_' + this.value).innerHTML += HTML + '/>';}this.removeChild(this[this.selectedIndex]);\" id=\"fields_config[".$fieldValue['Field']."][misc]\">
  3059. $optionsMiscTypes
  3060. </select>
  3061. </td>
  3062. </tr>
  3063. </table>
  3064. </div>
  3065. <div style=\"float:left\" id=\"".$fieldValue['Field']."_span_copy2\">
  3066. <table style=\"border:none;\">
  3067. <tr>
  3068. <td valign=\"top\" style=\"display:none;\" id=\"".$fieldValue['Field']."_new\"></td>
  3069. <td>
  3070. <table style=\"border:none;\">
  3071. <tr>
  3072. $existingEntriesTop
  3073. </tr>
  3074. <tr>
  3075. $existingEntriesBottom
  3076. </tr>
  3077. </table>
  3078. </td>
  3079. </tr>
  3080. </table>
  3081. </div>
  3082. </td>";
  3083. }
  3084. }
  3085. foreach ($this->fieldControlType as $key=>$text) {
  3086. if (empty($text["type"]) ) { continue;}
  3087. $checked = '';
  3088. $value = '';
  3089. $extra = '';
  3090. $checked2 = '';
  3091. $extra2 = '';
  3092. if (!isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][$fieldValue['Field']][$key]) && !isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][TABLE_CONFIG]['configuredfields'])) {
  3093. // -- pull from default
  3094. $value = $this->fieldControlDefaults[$key];
  3095. if ($key == CAPTION) {
  3096. $value = str_replace(array('_','-'),array(' ',' '),ucfirst($fieldValue['Field']));
  3097. }
  3098. $value = $this->createDisplayName($value);
  3099. } elseif (isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][$fieldValue['Field']][$key])) {
  3100. $value = $this->currentAdminDB[CRUD_FIELD_CONFIG][$configPointer][$fieldValue['Field']][$key];
  3101. }
  3102. if ($text['type'] == 'checkbox' && ($value === true || $value == '1')) {
  3103. $checked = 'checked';
  3104. $checked2 = 'On';
  3105. } else if ($text['type'] == 'checkbox' && $value === false) {
  3106. $checked2 = "Off";
  3107. } else if ($text['type'] == 'checkbox') {
  3108. $checked2 = "Off";
  3109. }
  3110. if ($text['type'] == 'checkbox') {
  3111. $extra = "style='cursor:pointer;' onclick='toggleObj(\"fields[".$fieldValue['Field']."][$key]\")'";
  3112. $extra2 = "style='display:none;'";
  3113. }
  3114. if (TEXT == $key || ID == $key || TABLE == $key) {
  3115. $optionsFieldsTables = "";
  3116. if (TABLE == $key) {
  3117. $failure = false;
  3118. $resultrows = $this->queryDatabase(GET_TABLES_SQL,$conn);
  3119. if (empty($resultrows)) {
  3120. $resultrows = $this->queryDatabase(GET_TABLES_SQL." from $database",$conn);
  3121. if (empty($resultrows)) {
  3122. $resultrows = $this->queryDatabase("SHOW TABLES FROM $database",$conn);
  3123. if (empty($resultrows)) {
  3124. $failure = true;
  3125. }
  3126. }
  3127. }
  3128. $optionsFieldsTables .= "<option value=\"\">No Lookup Table Defined</option>";
  3129. if ($failure === false) {
  3130. foreach ($resultrows as $kk=>$vv) {
  3131. $selected = "";
  3132. $tableName = $vv['Tables_in_'.$database];
  3133. if ($value == $tableName) {
  3134. $tableNameSelected = $tableName;
  3135. $selected = "selected";
  3136. }
  3137. $optionsFieldsTables .= "<option $selected value=\"$tableName\">$tableName</option>";
  3138. }
  3139. }
  3140. $input = "<select onchange=\"lookupFieldsFromTable(this.value,'$_GET[server]','$_GET[database]','$fieldValue[Field]','$key');\" name=\"fields[".$fieldValue['Field']."][$key]\" id=\"fields[".$fieldValue['Field']."][$key]\">$optionsFieldsTables</select>";
  3141. } else {
  3142. if (empty($value)) {
  3143. $input = "<span id=\"fields[".$fieldValue['Field']."][$key][span]\">Select A Table</span>";
  3144. } else {
  3145. $input = "<span id=\"fields[".$fieldValue['Field']."][$key][span]\">";
  3146. $fieldRows2 = $this->queryDatabase(sprintf(GET_COLUMNS_SQL,$tableNameSelected),$conn);
  3147. if (is_array($fieldRows2)) {
  3148. $input .= "<select name=\"fields[$fieldValue[Field]][$key]\">";
  3149. foreach ($fieldRows2 as $fieldKey2=>$fieldValue2) {
  3150. $selected = "";
  3151. $selected2 = "";
  3152. if ($value == $fieldValue2['Field']) {
  3153. $selected = "selected";
  3154. }
  3155. if ($value == "___distinct___lookup___".$fieldValue2['Field']) {
  3156. $selected2 = "selected";
  3157. }
  3158. $input .= "<option $selected2 value=\"___distinct___lookup___".$fieldValue2['Field']."\">".$fieldValue2['Field']." (Distinct Values)</option>";
  3159. $input .= "<option $selected value=\"".$fieldValue2['Field']."\">" . $fieldValue2['Field'] . "</option>";
  3160. }
  3161. $input .= "</select></span>";
  3162. }
  3163. }
  3164. }
  3165. } else {
  3166. $input = "<input $extra2 $extra {$key} type=\"$text[type]\" name=\"fields[".$fieldValue['Field']."][$key]\" id=\"fields[".$fieldValue['Field']."][$key]\" value=\"$value\" $checked/><span {$key}_onoff id=\"fields[".$fieldValue['Field']."][$key][onoff]\" class=\"".strtolower($checked2)."\">$checked2</span>";
  3167. }
  3168. $options .= "<td $extra>$input</td>";
  3169. }
  3170. echo "</tr>";
  3171. }
  3172. $i=0;
  3173. if (is_array($this->currentAdminDB[CRUD_FIELD_CONFIG])) {
  3174. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $values) {
  3175. $sameFields[$i++] = array_keys($values);
  3176. }
  3177. }
  3178. $break=false;
  3179. if (is_array($sameFields)) {
  3180. foreach ($sameFields as $key=>$array) {
  3181. foreach ($sameFields as $key2=>$array2) {
  3182. if ($key!=$key2) {
  3183. if ($array == $array2) {
  3184. $recurseOnOff =
  3185. "<input style='display: none;' onclick='toggleObj('recurse')' name='recurse' id='recurse' value='0' checked='checked' type='checkbox'><span id='recurse[onoff]' class='off' onclick=\"toggleObj('recurse');\">Off</span> (Sync off because exact table mapping would overwrite another config)";
  3186. $break=true;
  3187. break;
  3188. }
  3189. }
  3190. }
  3191. if ($break===true) {
  3192. break;
  3193. }
  3194. }
  3195. }
  3196. if ($break===false) {
  3197. $recurseOnOff =
  3198. "<input style='display: none;' onclick='toggleObj('recurse')' name='recurse' id='recurse' value='1' checked='checked' type='checkbox'><span id='recurse[onoff]' class='on' onclick=\"toggleObj('recurse');\">On</span>";
  3199. }
  3200. if (!$this->isPageInclude) {
  3201. $recurse = "<br/>";
  3202. //$recurse = "(<span style=\"cursor:pointer;\" onclick=\"toggleObj('recurse');\">Sync To Same Name Fields In Other Tables? </span>$recurseOnOff)";
  3203. } else {
  3204. $recurse = "<br/>";
  3205. }
  3206. echo
  3207. "
  3208. <script>
  3209. var msgDebug = false;
  3210. function insertAfter( referenceNode, newNode ) {
  3211. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  3212. }
  3213. function addRow(id,spanid,obj){
  3214. obj.onclick='';
  3215. var tbody = document.getElementById(id);
  3216. var row = document.createElement('TR');
  3217. var td1 = document.createElement('TD');
  3218. var td2 = document.createElement('TD');
  3219. td2.colSpan = '50';
  3220. var span = document.createElement('span');
  3221. span.id = spanid;
  3222. td1.appendChild(span);
  3223. var span = document.createElement('span');
  3224. span.id = spanid + '2';
  3225. td2.appendChild(span);
  3226. row.appendChild(td1);
  3227. row.appendChild(td2);
  3228. insertAfter(tbody,row);
  3229. $(spanid).innerHTML = $(spanid + \"_copy\").innerHTML;
  3230. $(spanid + '2').innerHTML = $(spanid + \"_copy2\").innerHTML;
  3231. $(spanid + \"_copy\").innerHTML = \"\";
  3232. $(spanid + \"_copy2\").innerHTML = \"\";
  3233. }
  3234. function addTD(id,spanid){
  3235. var tbody = document.getElementById(id);
  3236. var td1 = document.createElement('TD');
  3237. td1.vAlign = 'top';
  3238. td1.style.borderRight = '2px solid black';
  3239. var span = document.createElement('span');
  3240. span.id = spanid;
  3241. td1.appendChild(span);
  3242. insertAfter(tbody,td1);
  3243. }
  3244. function handleWidgetChange(obj,name) {
  3245. if (obj.value == 'file') {
  3246. var response = window.prompt(\"Please enter the path for the files to upload\",\"../uploads/\");
  3247. $('additionalParameters').innerHTML += \"<input name='fields_config[\" + name + \"][MOVE_TO]' id='fields_config[\" + name + \"][MOVE_TO]' value='\" + response + \"'/>\";
  3248. }
  3249. }
  3250. function onChangeValidations(id,obj) {
  3251. addTD(id + '_new',id + '_' + obj.value);
  3252. $(id + '_' + obj.value).innerHTML = obj.options[obj.selectedIndex].text + ':<br/><input type=hidden name=fields_config[' + id + '][' + obj.value + '] value=true><span class=on>On</span>';
  3253. if (obj.value == 'ValidateMinimumLength') {
  3254. $(id + '_' + obj.value).innerHTML = obj.options[obj.selectedIndex].text + ':<br/><input type=text name=fields_config[' + id + '][' + obj.value + ']';
  3255. }
  3256. $(id + '_' + obj.value).innerHTML += '<br/><br/>Error Message:<br/><input type=text name=fields_config[' + id + '][' + obj.value + 'ErrorMessage]';
  3257. obj.removeChild(obj[obj.selectedIndex]);
  3258. }
  3259. </script>
  3260. <form action='".$_SERVER['PHP_SELF']."?admin=1&select_fields=1&store_database=1' id='tableForm{$_GET['edit']}' method='post'>
  3261. ".$this->displayGenericObjects()."
  3262. <div id='serverinfo'>
  3263. <strong>{$_GET['edit']}</strong> Field Configuration
  3264. $errors
  3265. <input type=\"hidden\" name=\"tablePointer\" value=\"".$configPointer."\"/>
  3266. <table style='width:1500px;'>
  3267. $options
  3268. </table>
  3269. <a class='button' onclick='$(\"tableForm{$_GET['edit']}\").action= $(\"tableForm{$_GET['edit']}\").action + \"&conf=$this->current_config\";$(\"tableForm{$_GET['edit']}\").submit();'><span>Configure Fields</span></a> $recurse
  3270. </div>
  3271. </form>
  3272. ";
  3273. $this->closeDatabase($conn);
  3274. }
  3275. function storeFieldSelectionForm() {
  3276. ob_end_clean();
  3277. if ($this->isPageInclude) {
  3278. if ($_GET['conf'] != $this->current_config) {
  3279. return;
  3280. }
  3281. $this->currentAdminDB[CRUD_FIELD_CONFIG][TABLE_CONFIG]['alias'] = $configurationFile;
  3282. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']] as $k=>$v) {
  3283. if ($k!=TABLE_CONFIG) {
  3284. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$k]);
  3285. }
  3286. }
  3287. }
  3288. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG]['configuredfields'] = '1';
  3289. if (!isset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OBJECT_ACTIONS])) {
  3290. //default data in step 2 is not set
  3291. $conn = $this->connectDatabase($_GET['server'],$_GET['database']);
  3292. foreach ($this->tableControlDefaults as $systemKey=>$text) {
  3293. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][$systemKey] = $text;
  3294. }
  3295. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OBJECT_ACTIONS] = $this->tableControlDefaults[OBJECT_ACTIONS];
  3296. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OBJECT_TABLE] = $_REQUEST['tablePointer'];
  3297. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OBJECT_DESC] = $this->createDisplayName($_REQUEST['tablePointer']);
  3298. $resultPK = $this->getPrimaryKey($_GET['database'],$_REQUEST['tablePointer'],$conn);
  3299. $pk = $resultPK[0]['column_name'];
  3300. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OBJECT_PK] = $pk;
  3301. $linkEdit = "?action=".strtolower($this->actionTypes['update'].$_REQUEST['tablePointer'])."&".$pk."=%".$pk."%";
  3302. $linkDelete = "?action=".strtolower($this->actionTypes['delete'].$_REQUEST['tablePointer'])."&".$pk."=%".$pk."%";
  3303. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][EDIT_LINK] = $linkEdit;
  3304. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][DELETE_LINK] = $linkDelete;
  3305. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][TABLE_CONFIG][OTHER_LINKS] = "";
  3306. $this->addDefaultFieldData($_REQUEST['tablePointer'],$conn,$_REQUEST['tablePointer']);
  3307. $this->closeDatabase($conn);
  3308. }
  3309. $deleteToken = '!!DELETE_TOKEN!!';
  3310. foreach ($_REQUEST['fields'] as $key=>$selected) {
  3311. foreach ($this->fieldControlType as $systemKey=>$text) {
  3312. if ($_REQUEST['fields'][$key][$systemKey]) {
  3313. if ($_REQUEST['fields'][$key][$systemKey] != $deleteToken) {
  3314. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key][$systemKey] = $_REQUEST['fields'][$key][$systemKey];
  3315. } else {
  3316. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key][$systemKey]);
  3317. }
  3318. } else {
  3319. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key][$systemKey]);
  3320. }
  3321. }
  3322. }
  3323. foreach ($_REQUEST['fields_config'] as $key=>$selected) {
  3324. if (!isset($_REQUEST['fields_config'][$key][TABLE])) {
  3325. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"]["TYPE"] = $_REQUEST['fields_config'][$key]["TYPE"];
  3326. } else {
  3327. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"]["TYPE"]);
  3328. }
  3329. foreach ($this->fieldMiscTypes as $key2=>$text2) {
  3330. if ($_REQUEST['fields_config'][$key][$key2]) {
  3331. if ($key2 == 'ExtraAttributes') {
  3332. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3333. foreach ($_REQUEST['fields_config'][$key][$key2]['key'] as $kk=>$vv) {
  3334. if (!empty($vv) && !empty($kk)) {
  3335. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2][$vv] = $_REQUEST['fields_config'][$key][$key2]['value'][$kk];
  3336. }
  3337. }
  3338. } else {
  3339. if ($_REQUEST['fields_config'][$key][$key2] != $deleteToken) {
  3340. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2] = $_REQUEST['fields_config'][$key][$key2];
  3341. } else {
  3342. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3343. }
  3344. }
  3345. }
  3346. }
  3347. foreach ($this->fieldValidationTypes as $key2=>$text2) {
  3348. if ($_REQUEST['fields_config'][$key][$key2] || $_REQUEST['fields_config'][$key][$key2.'ErrorMessage']) {
  3349. if ($_REQUEST['fields_config'][$key][$key2] != $deleteToken) {
  3350. if ($_REQUEST['fields_config'][$key][$key2] != $deleteToken) {
  3351. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2] = $_REQUEST['fields_config'][$key][$key2];
  3352. } else {
  3353. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3354. }
  3355. if (isset($_REQUEST['fields_config'][$key][$key2.'ErrorMessage'])) {
  3356. if ($_REQUEST['fields_config'][$key][$key2.'ErrorMessage'] != $deleteToken) {
  3357. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2.'ErrorMessage'] = $_REQUEST['fields_config'][$key][$key2.'ErrorMessage'];
  3358. } else {
  3359. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2.'ErrorMessage']);
  3360. }
  3361. }
  3362. } else {
  3363. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3364. }
  3365. }
  3366. }
  3367. foreach ($this->fieldEventTypes as $key2=>$text2) {
  3368. if ($_REQUEST['fields_config'][$key][$key2]) {
  3369. if ($_REQUEST['fields_config'][$key][$key2] != $deleteToken) {
  3370. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2] = $_REQUEST['fields_config'][$key][$key2];
  3371. } else {
  3372. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3373. }
  3374. }
  3375. }
  3376. foreach ($this->fieldConfigType as $key2=>$text2) {
  3377. if ($_REQUEST['fields_config'][$key][$key2]) {
  3378. if ($_REQUEST['fields_config'][$key][$key2] != $deleteToken) {
  3379. $this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2] = $_REQUEST['fields_config'][$key][$key2];
  3380. } else {
  3381. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3382. }
  3383. } else {
  3384. unset($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']][$key."_config"][$key2]);
  3385. }
  3386. }
  3387. }
  3388. if ($_REQUEST['recurse'] == 1) {
  3389. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG][$_REQUEST['tablePointer']] as $key=>$fieldConfigs) {
  3390. if ($key == 'tableDef') {continue;}
  3391. foreach ($this->currentAdminDB[CRUD_FIELD_CONFIG] as $section=>$configs) {
  3392. foreach ($configs as $fieldOption=>$options) {
  3393. if ($fieldOption == 'tableDef') {continue;}
  3394. if ($fieldOption == $key) {
  3395. $this->currentAdminDB[CRUD_FIELD_CONFIG][$section][$fieldOption] = $fieldConfigs;
  3396. }
  3397. }
  3398. }
  3399. }
  3400. }
  3401. $this->writeAdminDB();
  3402. if (!isset($_COOKIE['redirect']) || $this->currentAdminDB['crud']['completed_step'] != 'All') {
  3403. $this->redirect($_SERVER['PHP_SELF']);
  3404. } else {
  3405. $this->redirect($_COOKIE['redirect']);
  3406. }
  3407. exit;
  3408. }
  3409. #5 Step
  3410. function displayGroupSelectionForm() {
  3411. if ($_GET['edit']) {
  3412. $display = "inline";
  3413. $list = $this->currentAdminDB[CRUD_FIELD_CONFIG];
  3414. foreach ($this->currentAdminDB['crud']['groups'] as $key=>$value) {
  3415. if ($key == 'Other' || $key == 'group_id') {continue;}
  3416. $database = $key;
  3417. $groupHash[$database] = $key;
  3418. foreach ($value as $table) {
  3419. $i++;
  3420. $groupedVariables[$database][$table]['group_name'] = $database;
  3421. $groupedVariables[$database][$table]['option_value'] = $table;
  3422. $groupedVariables[$database][$table]['option_desc'] = $table;
  3423. unset($list[$table]);
  3424. }
  3425. }
  3426. } else {
  3427. $display = "none";
  3428. $list = $this->currentAdminDB[CRUD_FIELD_CONFIG];
  3429. foreach ($list as $key=>$value) {
  3430. $i++;
  3431. $parts = explode("/",$value[TABLE_CONFIG][OBJECT_CONNECTION_STRING]);
  3432. $database = $parts[sizeof($parts)-1];
  3433. $groupHash[$database] = $key;
  3434. $groupedVariables[$database][$key]['group_name'] = $database;
  3435. $groupedVariables[$database][$key]['option_value'] = $key;
  3436. $groupedVariables[$database][$key]['option_desc'] = $key;
  3437. unset($list[$key]);
  3438. }
  3439. }
  3440. if (($i > 30 && !isset($_GET['edit'])) || $this->currentAdminDB['crud']['group_tables'] == 1 && $this->currentAdminDB['crud']['group_tables'] != 0) {
  3441. $defaultGroup = "1";
  3442. $defaultGroupTxt = "On";
  3443. } else {
  3444. $defaultGroup = "0";
  3445. $defaultGroupTxt = "Off";
  3446. }
  3447. if (is_array($list)) {
  3448. foreach ($list as $key=>$value) {
  3449. $variableOptions .= "<option value='$key'>".$key."</option>";
  3450. }
  3451. }
  3452. if (is_array($groupHash)) {
  3453. foreach ($groupHash as $hash=>$void) {
  3454. $cnt++;
  3455. if (!isset($_GET['edit'])) {
  3456. $hashText = str_replace(array("-","_","."),array(" "," "," "),$hash);
  3457. } else {
  3458. $hashText = $hash;
  3459. }
  3460. $additionalTDsToLoad .= '
  3461. <td align="center" valign="middle">
  3462. <a href="javascript:moveSelectedOptions($(\'GroupMain\'),$(\'groupName['.$hash.']\'));">&gt;&gt;</a>
  3463. </td>
  3464. <td>
  3465. Name: <input type="text" name="groupName['.$hash.'][name]" value="'.$hashText.'" style="width:115px"/><br/><br/>
  3466. <select name="groupName['.$hash.'][]" id="groupName['.$hash.']" multiple="multiple" size="10" ondblclick="moveSelectedOptions($(\'groupName['.$hash.']\'),$(\'GroupMain\'),false);$(\'GroupMain\').style.display = \'block\';" title="Double Click to Remove" style="width:175px">';
  3467. $turnOnGroups .= 'moveSelectedOptions($(\'groupName['.$hash.']\'),$(\'GroupMain\'),false);';
  3468. foreach ($groupedVariables as $hashKey => $valuesArray) {
  3469. if ($hash == $hashKey) {
  3470. foreach ($valuesArray as $k=>$v) {
  3471. $additionalTDsToLoad .= '<option value="'.$v['option_value'].'">'.$v['option_desc'].'</option>';
  3472. }
  3473. }
  3474. }
  3475. $additionalTDsToLoad .= '</select></td>';
  3476. if ($cnt == 4 || ($cnt==3 && !isset($secondRow))) {
  3477. $cnt=0;
  3478. $secondRow=true;
  3479. $additionalTDsToLoad .= "</tr><tr>";
  3480. }
  3481. }
  3482. }
  3483. $genericObjects = $this->displayGenericObjects();
  3484. echo <<<EOD
  3485. Step 4: Table Groups (Organize Things Logically)
  3486. <form action='{$_SERVER['PHP_SELF']}?admin=1&select_groups=1&store_database=1' name='tableForm' id='tableForm' method='post'>
  3487. $genericObjects
  3488. <table>
  3489. <tbody>
  3490. <tr id="groupedTable">
  3491. <td>
  3492. Table Configs:<br/>
  3493. <select id="GroupMain" name="groupName[Other][]" multiple="multiple" size="10" style="display:$display">
  3494. $variableOptions
  3495. </select>
  3496. <input type="hidden" name="hasAddedNewGroup" id="hasAddedNewGroup"/>
  3497. <input type="hidden" name="edit" id="edit" value="{$_GET['edit']}"/>
  3498. </td>
  3499. <td>
  3500. <button type="button" style="background-color:#D8FFD5;cursor:pointer;font-size:14px;font-weight:bold;" onclick="addNewVariableGroup()">Add New Group</button>
  3501. </td>
  3502. $additionalTDsToLoad
  3503. </tr>
  3504. </tbody>
  3505. </table>
  3506. <br/>
  3507. <a class='button' onclick="
  3508. var elms = document.body.getElementsByTagName('select');
  3509. for(var p = 0, maxI = elms.length; p < maxI; ++p) {
  3510. for(var i=0; i<elms[p].length; i++) {
  3511. if (elms[p].title == 'Double Click to Remove' || elms[p].multiple == true) {
  3512. // -- if typical attribs are found, these are the ones we need selected
  3513. elms[p].options[i].selected = true;
  3514. }
  3515. }
  3516. }
  3517. $('tableForm').action= $('tableForm').action + '&conf=$this->current_config';
  3518. if ($('edit').value == 'true' && $('hasAddedNewGroup').value == 1)
  3519. {
  3520. alert('Since you added a new group, you need to edit the user roles and who gets to see this new grouping');
  3521. }
  3522. document.tableForm.submit();
  3523. "><span>Save Groupings</span></a>
  3524. <span style="cursor:pointer;" onclick="toggleGroupings();$turnOnGroups">Group Tables</span><input style='display: none;' onclick=\"toggleGroupings();$turnOnGroups\" name='showGroups' id='showGroups' value='$defaultGroup' checked='checked' type='checkbox'><span id='showGroups[onoff]' class='on' onclick="toggleGroupings();$turnOnGroups">$defaultGroupTxt</span>
  3525. </form>
  3526. EOD;
  3527. }
  3528. function storeGroupSelectionForm() {
  3529. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  3530. $this->currentAdminDB['crud']['completed_step'] = 4;
  3531. }
  3532. ob_end_clean();
  3533. foreach ($_POST['groupName'] as $section=>$groups) {
  3534. if ($groups['name'] != $section && !empty($groups['name'])) {
  3535. // -- user changed the name of the group unset and re-index
  3536. $_POST['groupName'][$groups['name']] = $_POST['groupName'][$section];
  3537. unset($_POST['groupName'][$section]);
  3538. unset($_POST['groupName'][$groups['name']]['name']);
  3539. }
  3540. unset($_POST['groupName'][$section]['name']);
  3541. if (sizeof($_POST['groupName'][$section]) == 0) {
  3542. unset($_POST['groupName'][$section]);
  3543. }
  3544. }
  3545. $this->currentAdminDB['crud']['groups'] = $_POST['groupName'];
  3546. $this->currentAdminDB['crud']['group_tables'] = $_POST['showGroups'];
  3547. $this->writeAdminDB();
  3548. if ( ($_POST['edit'] == 'true' && $_POST['hasAddedNewGroup'] == 1) || !isset($_COOKIE['redirect']) || $this->currentAdminDB['crud']['completed_step'] != 'All') {
  3549. $this->redirect($_SERVER['PHP_SELF']."?admin=1&select_roles");
  3550. } else {
  3551. $this->redirect($_COOKIE['redirect']);
  3552. }
  3553. exit;
  3554. }
  3555. #6 Step
  3556. function displayRolesSelectionForm() {
  3557. $groupOptions = "<select TOKN2 name=\"role[TOKEN][groups][]\" multiple=\"multiple\" size=\"5\">";
  3558. if (isset($this->currentAdminDB['crud']['groups'])) {
  3559. foreach ($this->currentAdminDB['crud']['groups'] as $k=>$v) {
  3560. $groupOptions .= "<option value=\"$k\" selected>$k</option>";
  3561. }
  3562. $groupOptions .= "</select>";
  3563. }
  3564. if (!isset($_GET['edit'])) {
  3565. if (isset($this->currentAdminDB['crud']['roles'] )) {
  3566. die('<script>document.location = "'.$_SERVER['PHP_SELF'].'?admin=1&select_roles=1&edit=true";</script>');
  3567. }
  3568. $form = "
  3569. <tr id='1'>
  3570. <td><img onclick='removeRow(\"1\",\"allroles\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3571. <td><input type='text' class='admin' name='role[1][role_name]' value='Super Admin'/></td>
  3572. <td align='center'><input type='checkbox' name='role[1][admin_role]' value='1' checked/></td>
  3573. <td align='center'><input type='checkbox' name='role[1][delete_role]' value='1' checked/></td>
  3574. <td align='center'><input type='checkbox' name='role[1][update_role]' value='1' checked/></td>
  3575. <td align='center'><input type='checkbox' name='role[1][insert_role]' value='1' checked/></td>
  3576. <td align='center'><input type='checkbox' name='role[1][search_role]' value='1' checked/></td>
  3577. <td align='center'>".str_replace(array('TOKEN','TOKN2'),array('1',''),$groupOptions)."</td>
  3578. </tr>
  3579. <tr id='2'>
  3580. <td><img onclick='removeRow(\"2\",\"allroles\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3581. <td><input type='text' class='admin' name='role[2][role_name]' value='Admin'/></td>
  3582. <td align='center'><input type='checkbox' name='role[2][admin_role]' value='0'/></td>
  3583. <td align='center'><input type='checkbox' name='role[2][delete_role]' value='1' checked/></td>
  3584. <td align='center'><input type='checkbox' name='role[2][update_role]' value='1' checked/></td>
  3585. <td align='center'><input type='checkbox' name='role[2][insert_role]' value='1' checked/></td>
  3586. <td align='center'><input type='checkbox' name='role[2][search_role]' value='1' checked/></td>
  3587. <td align='center'>".str_replace(array('TOKEN','TOKN2'),array('2',''),$groupOptions)."</td>
  3588. </tr>
  3589. <tr id='cloner'>
  3590. <td><img onclick='removeRow(\"cloner\",\"allroles\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3591. <td> <input id='cloner_name' type='text' class='admin' name='role[3][role_name]' value='Publisher'/></td>
  3592. <td align='center'><input id='cloner_admin_role' type='checkbox' name='role[3][admin_role]' value='0'/></td>
  3593. <td align='center'><input id='cloner_delete_role' type='checkbox' name='role[3][delete_role]' value='0'/></td>
  3594. <td align='center'><input id='cloner_update_role' type='checkbox' name='role[3][update_role]' value='1' checked/></td>
  3595. <td align='center'><input id='cloner_insert_role' type='checkbox' name='role[3][insert_role]' value='1' checked/></td>
  3596. <td align='center'><input id='cloner_search_role' type='checkbox' name='role[3][search_role]' value='1' checked/></td>
  3597. <td align='center'>".str_replace(array('TOKEN','TOKN2'),array('3','id="cloner_group_roles"'),$groupOptions)."</td>
  3598. </tr>";
  3599. $i=3;
  3600. } else {
  3601. $i=0;
  3602. foreach ($this->currentAdminDB['crud']['roles'] as $roleID=>$roleObject) {
  3603. if (!isset($roleObject['admin_role'])) {
  3604. $adminRoleValue = 0;
  3605. $adminRoleChecked = '';
  3606. } else {
  3607. $adminRoleValue = 1;
  3608. $adminRoleChecked = 'checked';
  3609. }
  3610. if (!isset($roleObject['delete_role'])) {
  3611. $deleteRoleValue = 0;
  3612. $deleteRoleChecked = '';
  3613. } else {
  3614. $deleteRoleValue = 1;
  3615. $deleteRoleChecked = 'checked';
  3616. }
  3617. if (!isset($roleObject['update_role'])) {
  3618. $updateRoleValue = 0;
  3619. $updateRoleChecked = '';
  3620. } else {
  3621. $updateRoleValue = 1;
  3622. $updateRoleChecked = 'checked';
  3623. }
  3624. if (!isset($roleObject['insert_role'])) {
  3625. $insertRoleValue = 0;
  3626. $insertRoleChecked = '';
  3627. } else {
  3628. $insertRoleValue = 1;
  3629. $insertRoleChecked = 'checked';
  3630. }
  3631. if (!isset($roleObject['search_role'])) {
  3632. $searchRoleValue = 0;
  3633. $searchRoleChecked = '';
  3634. } else {
  3635. $searchRoleValue = 1;
  3636. $searchRoleChecked = 'checked';
  3637. }
  3638. if ($i == sizeof($this->currentAdminDB['crud']['roles'])-1) {
  3639. $id0="cloner";
  3640. $id1="id='cloner'";
  3641. $id2="id='cloner_name'";
  3642. $id3="id='cloner_admin_role'";
  3643. $id4="id='cloner_delete_role'";
  3644. $id5="id='cloner_update_role'";
  3645. $id6="id='cloner_insert_role'";
  3646. $id7="id='cloner_search_role'";
  3647. $id8="id='cloner_group_roles'";
  3648. } else {
  3649. $id1="id='$i'";
  3650. $id0=$i;
  3651. }
  3652. $groupOptions = "<select $id8 name=\"role[$roleID][groups][]\" multiple=\"multiple\" size=\"5\">";
  3653. if (isset($this->currentAdminDB['crud']['groups'])) {
  3654. foreach ($this->currentAdminDB['crud']['groups'] as $k=>$v) {
  3655. $sel = '';
  3656. if (in_array($k,$roleObject['groups'])) {
  3657. $sel = 'selected';
  3658. }
  3659. $groupOptions .= "<option value=\"$k\" $sel>$k</option>";
  3660. }
  3661. $groupOptions .= "</select>";
  3662. }
  3663. $form .= "
  3664. <tr $id1>
  3665. <td><img onclick='removeRow(\"$id0\",\"allroles\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3666. <td> <input $id2 type='text' class='admin' name='role[$roleID][role_name]' value='$roleObject[role_name]'/></td>
  3667. <td align='center'><input $id3 type='checkbox' name='role[$roleID][admin_role]' value='$adminRoleValue' $adminRoleChecked/></td>
  3668. <td align='center'><input $id4 type='checkbox' name='role[$roleID][delete_role]' value='$deleteRoleValue' $deleteRoleChecked/></td>
  3669. <td align='center'><input $id5 type='checkbox' name='role[$roleID][update_role]' value='$updateRoleValue' $updateRoleChecked/></td>
  3670. <td align='center'><input $id6 type='checkbox' name='role[$roleID][insert_role]' value='$insertRoleValue' $insertRoleChecked/></td>
  3671. <td align='center'><input $id7 type='checkbox' name='role[$roleID][search_role]' value='$searchRoleValue' $searchRoleChecked/></td>
  3672. <td align='center'>$groupOptions</td>
  3673. </tr>";
  3674. $i++;
  3675. }
  3676. }
  3677. if (!isset($_GET['edit'])) {
  3678. $selectAll = "
  3679. var elms = document.body.getElementsByTagName(\"select\");
  3680. for(var p = 0, maxI = elms.length; p < maxI; ++p) {
  3681. for(var i=0; i<elms[p].length; i++) {
  3682. elms[p].options[i].selected = true;
  3683. }
  3684. }";
  3685. }
  3686. echo
  3687. "
  3688. Step 5: Setup Roles
  3689. <form action='".$_SERVER['PHP_SELF']."?admin=1&select_roles=1&store_database=1' name='tableForm' id='tableForm' method='post'>
  3690. <input id=\"totalRoles\" type=\"hidden\" value=\"$i\"/>
  3691. ".$this->displayGenericObjects()."
  3692. <table id='allroles'>
  3693. <tr>
  3694. <td>Del:</td>
  3695. <td>Role Name: </td>
  3696. <td>CRUDDY Admin: </td>
  3697. <td>Delete Link: </td>
  3698. <td>Update Link: </td>
  3699. <td>Insert Link: </td>
  3700. <td>Search Link: </td>
  3701. <td>Group Access: </td>
  3702. </tr>
  3703. $form
  3704. </table>
  3705. <button type=\"button\" onclick=\"cloneRow('cloner');$('cloner_name').value='NewRoleName';changeClonerNames();\"><span style=\"font-size:1.4em;padding-bottom:10px;cursor:pointer;\" >Add Another Role</span> <img src=\"".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/db_add.png\"/></button>
  3706. <br/>
  3707. <br/>
  3708. <a class='button' onclick='{$selectAll}$(\"tableForm\").action= $(\"tableForm\").action + \"&conf=$this->current_config\";$(\"tableForm\").submit();'><span>Create Roles</span></a>
  3709. </form>
  3710. ";
  3711. }
  3712. function storeRolesSelectionForm() {
  3713. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  3714. $this->currentAdminDB['crud']['completed_step'] = 5;
  3715. }
  3716. ob_end_clean();
  3717. $this->currentAdminDB['crud']['roles'] = $_POST['role'];
  3718. $this->writeAdminDB();
  3719. if (!isset($_COOKIE['redirect']) || $this->currentAdminDB['crud']['completed_step'] != 'All') {
  3720. $this->redirect($_SERVER['PHP_SELF']."?admin=1&select_users");
  3721. } else {
  3722. $this->redirect($_COOKIE['redirect']);
  3723. }
  3724. exit;
  3725. }
  3726. #6 Step
  3727. function displayUserSelectionForm() {
  3728. $groupOptions = "<select class='admin' TOKN2 name=\"user[TOKEN][role]\">";
  3729. if (isset($this->currentAdminDB['crud']['roles'])) {
  3730. foreach ($this->currentAdminDB['crud']['roles'] as $k=>$v) {
  3731. $groupOptions .= "<option value=\"$k\">$v[role_name]</option>";
  3732. }
  3733. $groupOptions .= "</select>";
  3734. }
  3735. if (!isset($_GET['edit'])) {
  3736. if (isset($this->currentAdminDB['crud']['users'])) {
  3737. die('<script>document.location = "'.$_SERVER['PHP_SELF'].'?admin=1&select_users=1&edit=true";</script>');
  3738. }
  3739. $form = "
  3740. <tr id='cloner'>
  3741. <td><img onclick='removeRow(\"cloner\",\"allusers\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3742. <td> <input id='user_name' type='text' class='admin' name='user[1][user_name]' value=''/></td>
  3743. <td align='center'><input id='password' type='password' class='admin' name='user[1][password]' value=''/></td>
  3744. <td align='center'>".str_replace(array('TOKEN','TOKN2'),array('1','id="group_roles"'),$groupOptions)."</td>
  3745. </tr>";
  3746. $i=1;
  3747. } else {
  3748. $i=0;
  3749. foreach ($this->currentAdminDB['crud']['users'] as $roleID=>$roleObject) {
  3750. if ($i == sizeof($this->currentAdminDB['crud']['users'])-1) {
  3751. $id0="cloner";
  3752. $id1="id='cloner'";
  3753. $id2="id='user_name'";
  3754. $id3="id='password'";
  3755. } else {
  3756. $id1="id='$i'";
  3757. $id0=$i;
  3758. }
  3759. $groupOptions = "<select $id8 class='admin' TOKN2 name=\"user[TOKEN][role]\">";
  3760. if (isset($this->currentAdminDB['crud']['roles'])) {
  3761. foreach ($this->currentAdminDB['crud']['roles'] as $k=>$v) {
  3762. $sel = '';
  3763. if ($k == $roleObject['role']) {
  3764. $sel = 'selected';
  3765. }
  3766. $groupOptions .= "<option $sel value=\"$k\">$v[role_name]</option>";
  3767. }
  3768. $groupOptions .= "</select>";
  3769. }
  3770. $form .= "
  3771. <tr $id1>
  3772. <td><img onclick='removeRow(\"$id0\",\"allusers\");' src='".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/delete.png' style='cursor:pointer;'/></td>
  3773. <td> <input $id2 type='text' class='admin' name='user[$roleID][user_name]' value='$roleObject[user_name]'/></td>
  3774. <td align='center'><input $id3 type='password' type='password' class='admin' name='user[$roleID][password]' value='$roleObject[password]'/></td>
  3775. <td align='center'>".str_replace(array('TOKEN','TOKN2'),array($roleID,'id="group_roles"'),$groupOptions)."</td>
  3776. </tr>";
  3777. $i++;
  3778. }
  3779. }
  3780. echo
  3781. "
  3782. Step 6: Setup Users
  3783. <form action='$_SERVER[PHP_SELF]?admin=1&select_users=1&store_database=1' name='tableForm' id='tableForm' method='post'>
  3784. <input id=\"totalUsers\" type=\"hidden\" value=\"$i\"/>
  3785. ".$this->displayGenericObjects()."
  3786. <table id='allusers'>
  3787. <tr>
  3788. <td>Del:</td>
  3789. <td>User Name: </td>
  3790. <td>Password: </td>
  3791. <td>Role: </td>
  3792. </tr>
  3793. $form
  3794. </table>
  3795. <button type=\"button\" onclick=\"cloneRow('cloner');changeClonerUserNames();\"><span style=\"font-size:1.4em;padding-bottom:10px;cursor:pointer;\" >Add Another User</span> <img src=\"".ABS_PATH_TO_CRUDDY_MYSQL_FOLDER."images/db_add.png\"/></button>
  3796. <br/>
  3797. <br/>
  3798. <a class='button' onclick='if (finishUser()){ $(\"tableForm\").action= $(\"tableForm\").action + \"&conf=$this->current_config\"; $(\"tableForm\").submit();}'><span>Create Users</span></a>
  3799. </form>
  3800. ";
  3801. }
  3802. function storeUserSelectionForm() {
  3803. if ($this->currentAdminDB['crud']['completed_step'] != 'All') {
  3804. $this->currentAdminDB['crud']['completed_step'] = 6;
  3805. }
  3806. ob_end_clean();
  3807. $this->currentAdminDB['crud']['users'] = $_POST['user'];
  3808. $this->writeAdminDB();
  3809. if (!isset($_COOKIE['redirect']) || $this->currentAdminDB['crud']['completed_step'] != 'All') {
  3810. $this->redirect($_SERVER['PHP_SELF']."?admin=1&select_theme");
  3811. } else {
  3812. $this->redirect($_COOKIE['redirect']);
  3813. }
  3814. exit;
  3815. }
  3816. #8 Step
  3817. function displayThemeSelectionForm() {
  3818. echo $this->displayGenericObjects();
  3819. if ($_GET['edit']) {
  3820. $currentTheme = $_GET['edit'];
  3821. } elseif (isset($this->currentAdminDB['crud']['theme'])) {
  3822. $currentTheme = $this->currentAdminDB['crud']['theme'];
  3823. } else {
  3824. $currentTheme = 'Default Cruddy MySql';
  3825. }
  3826. echo
  3827. "
  3828. <div id='serverinfo'>
  3829. Final Step 7: Themes... Yum
  3830. <table>
  3831. <tr>
  3832. <td>Select A Theme: </td>
  3833. <td>".$this->displayThemeCSS($currentTheme)."</td>
  3834. </tr>
  3835. <tr>
  3836. <td><a class='button' onclick='storeThemeInfo()'><span>Finish Setup</span></a></td>
  3837. </tr>
  3838. </table>
  3839. </div>
  3840. ";
  3841. }
  3842. function storeThemeSelectionForm() {
  3843. /*if ($this->isPageInclude) {
  3844. if ($_GET['conf'] != $this->current_config) {
  3845. return;
  3846. }
  3847. }*/
  3848. $this->currentAdminDB['crud']['completed_step'] = 'All';
  3849. ob_end_clean();
  3850. $this->currentAdminDB['crud']['theme'] = $_GET['theme'];
  3851. $this->writeAdminDB();
  3852. exit;
  3853. }
  3854. function cleanTableNames($tableName) {
  3855. return preg_replace('/[^a-z0-9]/i', '',str_replace(" ","_",$tableName));
  3856. }
  3857. function displayGenericObjects() {
  3858. $ret = "<span id='results'></span>";
  3859. if (isset($_GET['edit'])) {
  3860. $ret .= "<input type=\"hidden\" id=\"editing\" value=\"true\"/>";
  3861. }
  3862. return $ret;
  3863. }
  3864. function adminDBExists() {
  3865. if (file_exists($this->adminFile)) {
  3866. return true;
  3867. } else {
  3868. return false;
  3869. }
  3870. }
  3871. function productionizeAdminDB() {
  3872. if (isset($_GET['conf']) && $_GET['conf'] != $this->current_config) {
  3873. return;
  3874. }
  3875. echo "<div class='success'>$this->adminFile has been productionized into a secure php array.<br/><a href=\"javascript:history.go(-1);\">(Click Here To Go Back)</a></div>";
  3876. $this->writeAdminDB("<?php\n\n\$cruddyMysqlConfiguration = ".var_export($this->currentAdminDB,true).";\n\n?>");
  3877. }
  3878. function readAdminDB() {
  3879. $array = file_get_contents($this->adminFile);
  3880. $newArray = unserialize($array);
  3881. if ($newArray === false) {
  3882. // -- assuming you have productionized your config array into a secure array configuration
  3883. include($this->adminFile);
  3884. $newArray = $cruddyMysqlConfiguration;
  3885. $this->isProductionized = true;
  3886. } else {
  3887. $this->isProductionized = false;
  3888. }
  3889. $newArray['crud']['console_name'] = stripslashes($newArray['crud']['console_name']);
  3890. //$this->processAssociativeArray($newArray[CRUD_FIELD_CONFIG],"\$assocArray[\$n] = stripslashes(\$v);");
  3891. return $newArray;
  3892. }
  3893. function processAssociativeArray(&$assocArray,$phpCode) {
  3894. if (is_array($assocArray)) {
  3895. foreach ($assocArray as $n => $v) {
  3896. if (is_array($v)) {
  3897. $this->processAssociativeArray($v,$phpCode);
  3898. } else {
  3899. eval($phpCode);
  3900. }
  3901. }
  3902. } else {
  3903. return $assocArray;
  3904. }
  3905. }
  3906. function writeAdminDB($stream='') {
  3907. if (get_magic_quotes_gpc()) {
  3908. $array = $this->processAssociativeArray($this->currentAdminDB,"\$assocArray[\$n] = stripslashes(\$v);");
  3909. }
  3910. if ($stream=='') {
  3911. $data = serialize($this->currentAdminDB);
  3912. } else {
  3913. $data = $stream;
  3914. }
  3915. if (!$handle = @fopen($this->adminFile, 'w')) {
  3916. @chmod(getcwd(),'755');
  3917. if (!$handle = @fopen($this->adminFile, 'w')) {
  3918. $this->handleErrors("Cannot open file ($this->adminFile)","fatal");
  3919. }
  3920. }
  3921. if (fwrite($handle, $data) === FALSE) {
  3922. $this->handleErrors("Could not write to file","fatal");
  3923. }
  3924. fclose($handle);
  3925. }
  3926. function writeFile($file,$data) {
  3927. if (!$handle = @fopen($file, 'w')) {
  3928. $this->handleErrors("Cannot open file ($this->adminFile)","fatal");
  3929. }
  3930. if (fwrite($handle, $data) === FALSE) {
  3931. $this->handleErrors("Could not write to file","fatal");
  3932. }
  3933. fclose($handle);
  3934. }
  3935. function handleErrors($message,$level='fatal') {
  3936. echo "<br/>".$message;
  3937. if ($level=='fatal'){exit;}
  3938. }
  3939. function displayGlobalCSS() {
  3940. return ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/cruddy_mysql.css';
  3941. }
  3942. function displayThemeCSS($returnCSS=true) {
  3943. $crudStyles['templates']['Default Cruddy MySql'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/default.css';
  3944. $crudStyles['templates']['Blue Gradient'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/blue_gradient.css';
  3945. $crudStyles['templates']['Casablanca'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/casablanca.css';
  3946. $crudStyles['templates']['Coffee with milk'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/coffee.css';
  3947. $crudStyles['templates']['Cusco Sky'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/cusco.css';
  3948. $crudStyles['templates']['Grey Scale'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/grey_scale.css';
  3949. $crudStyles['templates']['Minimalist Blue'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/grey_scale.css';
  3950. $crudStyles['templates']['Innocent'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/innocent.css';
  3951. $crudStyles['templates']['Oranges in the sky'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/oranges.css';
  3952. $crudStyles['templates']['Shades of Blue'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/shades_of_blue.css';
  3953. $crudStyles['templates']['Sky is no heaven'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/sky_is_no_heaven.css';
  3954. $crudStyles['templates']['Smooth Taste'] = ABS_PATH_TO_CRUDDY_MYSQL_FOLDER.'styles/smooth_taste.css';
  3955. if ($returnCSS===true) {
  3956. if (isset($crudStyles['templates'][$this->currentAdminDB['crud']['theme']])) {
  3957. return $crudStyles['templates'][$this->currentAdminDB['crud']['theme']];
  3958. } else {
  3959. return $crudStyles['templates']['Default Cruddy MySql'];
  3960. }
  3961. } else {
  3962. $selectBox = "
  3963. <select class='admin' name='theme' id='theme'>
  3964. <option value='None'>None</option>
  3965. ";
  3966. foreach ($crudStyles['templates'] as $key=>$nothing) {
  3967. $selected=""; if ($key == $returnCSS) {$selected="selected";}
  3968. $selectBox .="<option $selected value=\"$key\">$key</option>";
  3969. }
  3970. $selectBox .= "</select>";
  3971. return $selectBox;
  3972. }
  3973. unset($crudStyles);
  3974. }
  3975. }
  3976. // pager class
  3977. class cruddyMysqlPager {
  3978. var $total_records = NULL;
  3979. var $start = NULL;
  3980. var $scroll_page = NULL;
  3981. var $per_page = NULL;
  3982. var $total_pages = NULL;
  3983. var $current_page = NULL;
  3984. var $page_links = NULL;
  3985. // total pages and essential variables
  3986. function total_pages ($pager_url, $total_records, $scroll_page, $per_page, $current_page) {
  3987. $this->url = $pager_url;
  3988. $this->total_records = $total_records;
  3989. $this->scroll_page = $scroll_page;
  3990. $this->per_page = $per_page;
  3991. if (!is_numeric($current_page)) {
  3992. $this->current_page = 1;
  3993. }else{
  3994. $this->current_page = $current_page;
  3995. }
  3996. if ($this->current_page == 1)$this->start = 0; else$this->start = ($this->current_page - 1) *$this->per_page;
  3997. $this->total_pages = ceil($this->total_records /$this->per_page);
  3998. }
  3999. // page links
  4000. function page_links ($inactive_page_tag, $pager_url_last) {
  4001. if ($this->total_pages <= $this->scroll_page) {
  4002. if ($this->total_records <= $this->per_page) {
  4003. $loop_start = 1;
  4004. $loop_finish = $this->total_pages;
  4005. }else{
  4006. $loop_start = 1;
  4007. $loop_finish = $this->total_pages;
  4008. }
  4009. }else{
  4010. if($this->current_page < intval($this->scroll_page / 2) + 1) {
  4011. $loop_start = 1;
  4012. $loop_finish = $this->scroll_page;
  4013. }else{
  4014. $loop_start = $this->current_page - intval($this->scroll_page / 2);
  4015. $loop_finish = $this->current_page + intval($this->scroll_page / 2);
  4016. if ($loop_finish >$this->total_pages) $loop_finish = $this->total_pages;
  4017. }
  4018. }
  4019. for ($i = $loop_start; $i <= $loop_finish; $i++) {
  4020. if ($i == $this->current_page) {
  4021. $this->page_links .= '<span '.$inactive_page_tag.'>'.$i.'</span>';
  4022. }else{
  4023. $this->page_links .= '<span><a href="'.$this->url.$i.$pager_url_last.'">'.$i.'</a></span>';
  4024. }
  4025. }
  4026. }
  4027. // previous page
  4028. function previous_page ($previous_page_text, $pager_url_last) {
  4029. if ($this->current_page > 1) {
  4030. $this->previous_page = '<span><a href="'.$this->url.($this->current_page - 1).$pager_url_last.'">'.$previous_page_text.'</a></span>';
  4031. }
  4032. }
  4033. // next page
  4034. function next_page ($next_page_text, $pager_url_last) {
  4035. if ($this->current_page <$this->total_pages) {
  4036. $this->next_page = '<span><a href="'.$this->url.($this->current_page + 1).$pager_url_last.'">'.$next_page_text.'</a></span>';
  4037. }
  4038. }
  4039. // first page
  4040. function first_page ($first_page_text, $pager_url_last) {
  4041. if ($this->current_page > 1) {
  4042. $this->first_page = '<span><a href="'.$this->url.'1'.$pager_url_last.'">'.$first_page_text.'</a></span>'; // :)
  4043. }
  4044. }
  4045. // last page
  4046. function last_page ($last_page_text, $pager_url_last) {
  4047. if ($this->current_page < $this->total_pages) {
  4048. $this->last_page = '<span><a href="'.$this->url.$this->total_pages.$pager_url_last.'">'.$last_page_text.'</a></span>';
  4049. }
  4050. }
  4051. // pages functions set
  4052. function 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, $pager_url_last) {
  4053. $this->total_pages($pager_url, $total_records, $scroll_page, $per_page, $current_page);
  4054. $this->page_links($inactive_page_tag, $pager_url_last);
  4055. $this->previous_page($previous_page_text, $pager_url_last);
  4056. $this->next_page($next_page_text, $pager_url_last);
  4057. $this->first_page($first_page_text, $pager_url_last);
  4058. $this->last_page($last_page_text, $pager_url_last);
  4059. }
  4060. }
  4061. ?>