· 9 years ago · Nov 03, 2016, 06:38 PM
1<?
2if(!class_exists('Obj'))
3{
4 class Obj {}
5}
6
7ob_start();
8session_start();
9@ini_set('default_charset', 'UTF-8');
10header('Content-Type: text/html; charset=UTF-8');
11
12/*
13try to make the default connection to the bank, from the framework.
14If it doesn't work you should try to include your own connection...
15Or use the maker without connection.
16It also works, but with some few limitations.
17*/
18@include('../../lib/defines.php');
19@include('../../local-defines.php');
20@include('../../lib/connection.php');
21
22/* definindo o tipo de tabela do mysql */
23define(MYSQL_TABLE_TYPE, $_GET['table_engine'] == 'MyISAM' ? 'MyISAM' : 'InnoDB');
24define(CREATE_FKS, MYSQL_TABLE_TYPE == 'InnoDB' ? true : false);
25
26$sql = "SHOW TABLES";
27if(@dboQuery($sql))
28{
29 define (MYSQL_CONNECTION, TRUE);
30 $sql = "SELECT * FROM perfil"; /* checks if the perfil table exists. */
31 if(dboQuery($sql))
32 {
33 define(HAS_PROFILES, TRUE);
34 } else {
35 define(HAS_PROFILES, FALSE);
36 }
37} else {
38 define (MYSQL_CONNECTION, FALSE);
39 define(HAS_PROFILES, FALSE);
40}
41
42if(!function_exists('safeArrayKey'))
43{
44 function safeArrayKey($key, $array)
45 {
46 if(@array_key_exists($key, $array))
47 {
48 return safeArrayKey($key+100, $array);
49 }
50 return $key;
51 }
52}
53
54/* ---------------------------------------------------------------------------------------------------------- */
55
56function dboAbbr($string, $params = array())
57{
58 extract($params);
59 $size = $size ?: 3;
60 $separador = $separator ?: "_";
61
62 $vogais = array('a','e','i','o','u');
63
64 $string = str_replace('-', '_', $string);
65 $parts = explode('_', $string);
66 $parts = array_filter($parts);
67
68 $abbr = array();
69
70 foreach($parts as $part)
71 {
72 $i = 0;
73 $word = '';
74 $vogal = false;
75 while(strlen($word) < $size && $i < strlen($part))
76 {
77 $word .= $part[$i];
78 if(!$vogal && in_array($part[$i], $vogais))
79 {
80 $vogal = true;
81 $i++;
82 continue;
83 }
84 $i++;
85 }
86 $abbr[] = $word;
87 }
88
89 return implode($separador, $abbr);
90}
91
92/* ---------------------------------------------------------------------------------------------------------- */
93
94function renderSelectFkActions($input_name, $selected, $operation)
95{
96 $selected = $selected ? $selected : ($operation == 'update' ? 'CASCADE' : ($operation == 'delete' ? 'SET NULL' : ''));
97 ob_start();
98 ?>
99 <select name="<?= $input_name ?>">
100 <option <?= $selected == 'RESTRICT' ? 'selected' : '' ?>>RESTRICT</option>
101 <option <?= $selected == 'NO ACTION' ? 'selected' : '' ?>>NO ACTION</option>
102 <option <?= $selected == 'CASCADE' ? 'selected' : '' ?>>CASCADE</option>
103 <option <?= $selected == 'SET NULL' ? 'selected' : '' ?>>SET NULL</option>
104 <option <?= $selected == 'SET DEFAULT' ? 'selected' : '' ?>>SET DEFAULT</option>
105 </select>
106 <?php
107 return ob_get_clean();
108}
109
110/* ---------------------------------------------------------------------------------------------------------- */
111
112function createFksIfNotExists($foo = array())
113{
114 /* Foo:
115 - table
116 - column
117 - referenced_table
118 - referenced_column
119 */
120 //verificando se AS FKs estão ativas e o array de data tem conteudo
121 //criando as chaves estrangeiras
122 if(CREATE_FKS && sizeof((array)$foo))
123 {
124
125 foreach($foo as $data)
126 {
127 //extraindo as variaveis do array para melhor semântica
128 extract($data);
129
130 $update_action = $on_update ? $on_update : 'CASCADE';
131 $delete_action = $on_delete ? $on_delete : 'SET NULL';
132
133 //não criar para campos automaticos do dbo
134 if(in_array($column, array('created_by', 'updated_by', 'deleted_by'))) continue;
135
136 //verifica se a tabela em que a chave vai ser criada é do tipo InnoDB
137 $sql = "SHOW TABLE STATUS WHERE Name = '".$table."'";
138 $res = dboQuery($sql);
139 $lin = dboFetchObject($res);
140 //se a tabela é InnoDB, declaramos o nome da constraint
141 if($lin->Engine == 'InnoDB')
142 {
143 //primeiramente, dropamos a constraint antiga, pois havia casos em que o nome era muito longo para funcionar.
144 $const_name = "constr_t_".str_replace('.', '_', $table)."_c_".$column."_fk";
145
146 //verifica se a constraint já existe
147 $sql = "
148 SELECT *
149 FROM information_schema.REFERENTIAL_CONSTRAINTS
150 WHERE CONSTRAINT_SCHEMA = '".DB_BASE."'
151 AND REFERENCED_TABLE_NAME = '".$referenced_table."'
152 AND CONSTRAINT_NAME = '".$const_name."'
153 ";
154 $res = dboQuery($sql);
155 if(dboAffectedRows())
156 {
157 $sql = "ALTER TABLE ".$table." DROP FOREIGN KEY ".$const_name;
158 dboQuery($sql);
159 }
160
161 //agora construimos a constraint com um tamanho adequado...
162
163 //definindo o nome da constraint
164 $const_name = "t_".dboAbbr(str_replace('.', '_', $table)."_c_".$column)."_".substr(md5($const_name), 0, 8)."_fk";
165
166 //verifica se a constraint já existe
167 $sql = "
168 SELECT *
169 FROM information_schema.REFERENTIAL_CONSTRAINTS
170 WHERE CONSTRAINT_SCHEMA = '".DB_BASE."'
171 AND REFERENCED_TABLE_NAME = '".$referenced_table."'
172 AND CONSTRAINT_NAME = '".$const_name."'
173 ";
174 $res = dboQuery($sql);
175 $lin = dboFetchObject($res);
176
177 //agora, verificamos se as regras de updade ou delete são diferentes do desejado
178 //se for, dropamos a FK e recriamos (ou criamos pela primeira vez, se for o caso)
179 if($lin->UPDATE_RULE != $update_action || $lin->DELETE_RULE != $delete_action)
180 {
181 //dropa a constraint, se existe
182 if(dboAffectedRows())
183 {
184 $sql = "ALTER TABLE ".$table." DROP FOREIGN KEY ".$const_name;
185 dboQuery($sql);
186 }
187
188 //cria a constraint (ou recria, dependendo do caso)
189 $sql = "ALTER TABLE ".$table." ADD CONSTRAINT ".$const_name." FOREIGN KEY ".$column."_fk (".$column.") REFERENCES ".$referenced_table." (".$referenced_column.") ON DELETE ".$delete_action." ON UPDATE ".$update_action;
190 //echo "FK criada: ".$const_name.', ';
191 if(dboQuery($sql))
192 {
193 echo "FK criada: ".$const_name.', ';
194 };
195 }
196 }
197 }
198 }
199}
200
201/* ---------------------------------------------------------------------------------------------------------- */
202
203function unident($text)
204{
205 $text = trim($text);
206 $partes = explode("\n", $text);
207
208 $partes_trimmed = array();
209 $count = 1;
210 foreach($partes as $chave => $valor)
211 {
212 if($count != 1) {
213 $partes_trimmed[] = substr($valor, 1, strlen($valor)-1);
214 } else {
215 $partes_trimmed[] = $valor;
216 }
217 $count++;
218 }
219 return implode("\n", $partes_trimmed);
220}
221
222/* ---------------------------------------------------------------------------------------------------------- */
223
224function ident($code)
225{
226 $partes_final = array();
227 $code = stripslashes($code);
228 $partes = explode("\n", $code);
229 foreach($partes as $key => $value)
230 {
231 $partes_final[] = "\t".$value;
232 }
233 return implode("\n", $partes_final);
234}
235
236/* ---------------------------------------------------------------------------------------------------------- */
237
238function maxModuleOrderBy()
239{
240 $max = 0;
241 if(is_array($_SESSION['dbomaker_modulos']))
242 {
243 foreach($_SESSION['dbomaker_modulos'] as $modulo)
244 {
245 if($modulo->order_by > $max && $modulo->modulo != 'temporary_module_key_5658')
246 {
247 $max = $modulo->order_by;
248 }
249 }
250 }
251 return $max;
252}
253
254/* ---------------------------------------------------------------------------------------------------------- */
255
256function checkBackupDir()
257{
258 //first we'll see if the backup folder exists and is writable. If not, we'll try to create it.
259 $backup_folder = '../module_backups';
260 if(file_exists($backup_folder))
261 {
262 if(is_writable($backup_folder))
263 {
264 return true;
265 }
266 return false;
267 }
268 else
269 {
270 if(@mkdir($backup_folder))
271 {
272 return true;
273 }
274 return false;
275 }
276}
277
278/* ---------------------------------------------------------------------------------------------------------- */
279
280function unixEOL($string)
281{
282 //fix line breaks bugs
283 $search = array("\r\n", "\r");
284 $replace = array("\n", "\n");
285 return str_replace($search, $replace, $string);
286}
287
288/* ---------------------------------------------------------------------------------------------------------- */
289
290function singleScape($string)
291{
292 return str_replace("'", "\\'", $string);
293}
294
295/* ---------------------------------------------------------------------------------------------------------- */
296
297function encNameAjax($name)
298{
299 $name = str_replace("_", "~", $name);
300 $name = str_replace("-", "^", $name);
301 $name = str_replace("=", "§", $name);
302 return $name;
303}
304
305/* ---------------------------------------------------------------------------------------------------------- */
306
307function decNameAjax($name)
308{
309 $name = str_replace("~", "_", $name);
310 $name = str_replace("^", "-", $name);
311 $name = str_replace("§", "=", $name);
312 return $name;
313}
314
315/* ---------------------------------------------------------------------------------------------------------- */
316
317function checkSyntax($code)
318{
319 if(strlen(trim($code)))
320 {
321 return true;
322// return @eval($code);
323 }
324 return true;
325}
326
327/* ---------------------------------------------------------------------------------------------------------- */
328
329function flagUpdate($module)
330{
331 $_SESSION['dbomaker_updated'][$module] = $module;
332 unflagDelete($module);
333}
334
335/* ---------------------------------------------------------------------------------------------------------- */
336
337function flagDelete($module)
338{
339 $_SESSION['dbomaker_deleted'][$module] = $module;
340}
341
342/* ---------------------------------------------------------------------------------------------------------- */
343
344function unflagUpdate($module)
345{
346 unset($_SESSION['dbomaker_updated'][$module]);
347}
348
349/* ---------------------------------------------------------------------------------------------------------- */
350
351function unflagDelete($module)
352{
353 unset($_SESSION['dbomaker_deleted'][$module]);
354}
355
356/* ---------------------------------------------------------------------------------------------------------- */
357
358function diskDelete($mod)
359{
360 @unlink('../_dbo_'.$mod.'.php');
361}
362
363/* ---------------------------------------------------------------------------------------------------------- */
364
365function getModuleTable($module)
366{
367 return $_SESSION['dbomaker_modulos'][$module]->tabela;
368}
369
370/* ---------------------------------------------------------------------------------------------------------- */
371
372function dropModuleFks($module)
373{
374 foreach((array)$module->campo as $key => $campo)
375 {
376 if($campo->tipo == 'join')
377 {
378 //nao criar para campos automaticos do sistema.
379 if(in_array($campo->coluna, array('created_by', 'updated_by', 'deleted_by'))) continue;
380
381 $const_name = "constr_t_".str_replace('.', '_', $module->tabela)."_c_".$campo->coluna."_fk";
382 $sql = "ALTER TABLE ".$module->tabela." DROP FOREIGN KEY ".$const_name.";";
383 if(!dboQuery($sql))
384 {
385 echo dboQueryError()."<br />";
386 }
387 }
388 }
389}
390
391/* ---------------------------------------------------------------------------------------------------------- */
392
393function syncTable($module)
394{
395
396 //echo $module->modulo.", ";
397
398 //se for um modulo que não possui nenhum campo, já remove.
399 if(!sizeof((array)$module->campo)) return;
400
401 //trying to create the tables.
402 $sql = "CREATE TABLE IF NOT EXISTS ".$module->tabela." (\n";
403 if(is_array($module->campo))
404 {
405 $sql_parts = array();
406 $joinNN = array();
407
408 foreach($module->campo as $field)
409 {
410 if($field->tipo == 'pk')
411 {
412 $pk = $field->coluna;
413 $sql_parts[] = "\t".$field->coluna." int(11) NOT NULL auto_increment";
414 }
415 elseif($field->tipo == 'join')
416 {
417 //se o tipo da tabela for InnoDB, tenta criar as chaves
418 if($module->table_engine == 'InnoDB')
419 {
420 $fks[] = array(
421 'table' => $module->tabela,
422 'column' => $field->coluna,
423 'referenced_table' => getModuleTable($field->join->modulo),
424 'referenced_column' => $field->join->chave,
425 'on_update' => $field->join->on_update,
426 'on_delete' => $field->join->on_delete,
427 );
428 }
429 $sql_parts[] = "\t".$field->coluna." ".$field->type." ".(($field->isnull)?("NULL"):("NOT NULL"));
430 }
431 //para o caso de PKs não A.I.
432 elseif($field->tipo == 'joinNN')
433 {
434 //montando as configurações de chave estrangeira
435 $fks[] = array(
436 'table' => $field->join->tabela_ligacao,
437 'column' => $field->join->chave1,
438 'referenced_table' => $module->tabela,
439 'referenced_column' => $field->join->chave1_pk ? $field->join->chave1_pk : 'id',
440 'on_update' => $field->join->chave1_on_update,
441 'on_delete' => $field->join->chave1_on_delete,
442 );
443 $fks[] = array(
444 'table' => $field->join->tabela_ligacao,
445 'column' => $field->join->chave2,
446 'referenced_table' => getModuleTable($field->join->modulo),
447 'referenced_column' => $field->join->chave2_pk ? $field->join->chave2_pk : 'id',
448 'on_update' => $field->join->chave2_on_update,
449 'on_delete' => $field->join->chave2_on_delete,
450 );
451
452 $sql_join = "CREATE TABLE IF NOT EXISTS ".$field->join->tabela_ligacao." (\n";
453 $sql_join .= "\tid int(11) NOT NULL auto_increment,\n";
454 $sql_join .= "\t".$field->join->chave1." int(11) NULL,\n";
455 $sql_join .= "\t".$field->join->chave2." int(11) NULL,\n";
456 $sql_join .= "UNIQUE (".$field->join->chave1.", ".$field->join->chave2."),\n";
457 $sql_join .= "PRIMARY KEY (id)\n";
458 $sql_join .= ") ENGINE = InnoDB DEFAULT CHARSET=utf8mb4; ";
459 dboQuery($sql_join);
460
461 //salvando a definição dos joinNN para o alter table
462 $joinNN[] = $field->join;
463 }
464 elseif($field->coluna == 'inativo')
465 {
466 $sql_parts[] = "\t".$field->coluna." int(11) NOT NULL";
467 }
468 elseif($field->tipo == 'query') {}
469 else
470 {
471 if($field->pk == true) {
472 $pk = $field->coluna;
473 }
474 $sql_parts[] = "\t".$field->coluna." ".$field->type." ".(($field->isnull)?("NULL"):("NOT NULL")).($field->unique ? ' UNIQUE' : '');
475 }
476 }
477 }
478 if($pk)
479 {
480 $sql_parts[] .= "PRIMARY KEY ( ".$pk." )";
481 }
482 $sql .= @implode(",\n", $sql_parts);
483 $sql .= ") ENGINE = ".($module->table_engine ? $module->table_engine : MYSQL_TABLE_TYPE)." DEFAULT CHARSET=utf8mb4; ";
484
485 dboQuery($sql);
486
487 //agora, tenta verificar se a tabela em questão é do mesmo engine que está no modulo
488 $sql = "SHOW TABLE STATUS WHERE Name = '".$module->tabela."'";
489 $res = dboQuery($sql);
490 $lin = dboFetchObject($res);
491 if($module->table_engine && $module->table_engine != $lin->Engine)
492 {
493 //se o módulo for MyISAM, remove todas as constraints da tabela antes de fazer a alteração
494 if($module->table_engine == 'MyISAM') dropModuleFks($module);
495
496 //finalmente, altera o engine da tabela
497 $sql = "ALTER TABLE ".$module->tabela." ENGINE = ".$module->table_engine.";";
498 if(!dboQuery($sql))
499 {
500 echo dboQueryError();
501 };
502 }
503
504 //and now checking for the fields in the table. alter tables to create extra-fields.
505 $sql = "SHOW COLUMNS FROM ".$module->tabela;
506 $res = dboQuery($sql);
507
508 //saving all fields in the temp array
509 if(dboAffectedRows())
510 {
511 while($lin = @dboFetchObject($res))
512 {
513 $fields[] = $lin->Field;
514 }
515 }
516
517 $virtual_field_types = array('joinNN', 'query');
518
519 //check if the module field exists in the table
520 if(is_array($module->campo) && is_array($fields))
521 {
522 foreach($module->campo as $field)
523 {
524 //if not exists, create.
525 if(!in_array($field->coluna, $fields) && !in_array($field->tipo, $virtual_field_types) && $field->coluna != 'temporary_field_key_5658')
526 {
527
528 if($field->tipo == 'pk')
529 {
530 $sql = "ALTER TABLE ".$module->tabela." ADD ".$field->coluna." INT NOT NULL AUTO_INCREMENT PRIMARY KEY";
531 }
532 else
533 {
534 $sql = "ALTER TABLE ".$module->tabela." ADD ".$field->coluna." ".fieldType($field->type)." ".((checkTypeForCollate($field->type))?("CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"):(""))." ".(($field->isnull)?("NULL"):("NOT NULL"));
535 }
536 echo $sql;
537 dboQuery($sql);
538 }
539 }
540 }
541
542 //fazendo alter table nas tabelas de ligação
543 if(sizeof($joinNN))
544 {
545 $colunas = array(
546 'chave1',
547 'chave2',
548 'relacao_adicional_coluna',
549 );
550 foreach($joinNN as $join)
551 {
552 $sql = "SHOW COLUMNS FROM ".$join->tabela_ligacao;
553 $res = dboQuery($sql);
554
555 //saving all fields in the temp array
556 if(dboAffectedRows())
557 {
558 $fields = array();
559 while($lin = @dboFetchObject($res))
560 {
561 $fields[] = $lin->Field;
562 }
563 foreach($colunas as $coluna)
564 {
565 if(isset($join->$coluna) && !in_array($join->{$coluna}, $fields))
566 {
567 $sql = "ALTER TABLE ".$join->tabela_ligacao." ADD ".$join->{$coluna}." INT(11);";
568 echo $sql;
569 dboQuery($sql);
570 }
571 }
572 }
573 }
574 }
575
576 //cria as chaves estrangeiras no banco de dados, se for o caso.
577 createFksIfNotExists($fks);
578}
579
580/* ---------------------------------------------------------------------------------------------------------- */
581
582function fieldType($type)
583{
584 $no_size = array(
585 'text',
586 'tinytext',
587 'mediumtext',
588 'longtext',
589 );
590 if(in_array($type, $no_size))
591 {
592 list($type, $trash) = explode("(", $type);
593 }
594 return $type;
595}
596
597/* ---------------------------------------------------------------------------------------------------------- */
598
599function checkTypeForCollate($string)
600{
601 $need_collate = array(
602 'varchar',
603 'char',
604 'text',
605 'tinytext',
606 'mediumtext',
607 'longtext',
608 );
609 list($tipo, $lixo) = explode("(", $string);
610 return in_array(strtolower($tipo), $need_collate);
611}
612
613/* ---------------------------------------------------------------------------------------------------------- */
614
615function auth()
616{
617 include('../../lib/defines.php');
618 if(!in_array($_SESSION['user'], $SUPER_ADMINS))
619 {
620 ?><h1>Access Denied.</h1><p>You either is not a super-admin developer or is not logged in.<br>Shame on you.</p><?
621 exit();
622 }
623}
624
625/* ---------------------------------------------------------------------------------------------------------- */
626
627function checkCHMOD($path)
628{
629 if(file_exists($path))
630 {
631 return intval(substr(sprintf('%o', @fileperms($path)), -4));
632 }
633 else
634 {
635 return 1000;
636 }
637}
638
639
640?>