Komplet prepsano (a prelozeno) menu, Prohloubena abstrakce generovani HTML kodu
[mirrors/SokoMan.git] / index.php
CommitLineData
cdfce7c2
TM
1<?php
2/*
3 * SkladovySystem - Storage management system compatible with LMS
78bf26a5 4 * Copyright (C) 2011 Tomas Mudrunka
cdfce7c2
TM
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20require_once('sklad.conf.php');
5f093236
TM
21set_include_path(DIR_LIB.PATH_SEPARATOR.get_include_path());
22
cdfce7c2
TM
23require_once('Sklad_LMS-fake.class.php');
24require_once('HTTP_Auth.class.php');
326a9fc9 25require_once('Locale.class.php');
cdfce7c2 26
0a027cc7
TM
27/**
28* Trida poskytuje vseobecne funkce pro generovani HTML kodu
29*
30* Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
31*
32* @package HTML
33* @author Tomas Mudrunka
34*/
35class HTML {
36 function row($row) {
37 $html='<tr>';
38 foreach($row as $var) {
39 if(trim($var) == '') $var = '&nbsp;';
40 $html.="<td>$var</td>";
41 }
42 $html.='</tr>';
43 return $html;
44 }
45
46 function table(&$table, $params='border=1') {
47 $html="<table $params>";
48 $header=true;
49 foreach($table as $row) {
50 if($header) {
51 $html.=$this->row(array_keys($row));
52 $header=false;
53 }
54 $html.=$this->row($row);
55 }
56 $html.='</table>';
57 return $html;
58 }
59
60 function link($title='n/a', $link='#void', $internal=true) {
35916247 61 if($internal && (!isset($link[0]) || $link[0] != '#')) $link = $this->internal_url($link);
326a9fc9 62 return "<a href='$link'>".T($title)."</a>";
0a027cc7
TM
63 }
64
65 function img($src='#void', $title='img') {
66 return "<img src='$src' alt='$title' title='$title' width=64 />";
67 }
68
35916247
TM
69 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
70 $html = T($prefix)."<input type='$type' ";
0a027cc7 71 if($name) $html.= "name='$name' ";
326a9fc9
TM
72 if(!is_bool($value)) {
73 if($type == 'submit') $value = T($value);
74 $html.= "value='$value' ";
75 }
0a027cc7
TM
76 if($options) $html.= "$options ";
77 if($placeholder) $html.= "placeholder='$placeholder' ";
78 $html .= '/>';
79 return $html;
80 }
81
35916247
TM
82 function form($action=false, $method=false, $inputs, $options=false) {
83 $action = $action ? " action='$action'" : '';
84 $method = $method ? " method='$method'" : '';
85 $options = $options ? " $options" : '';
86 $html = "<form$action$method$options>";
87 foreach($inputs as $input) $html .= call_user_func_array(array($this,'input'), $input);
88 $html .= "</form>";
89 return $html;
90 }
91
0a027cc7
TM
92 function select($name, $selectbox, $default=false) {
93 //echo('<pre>'); print_r($selectbox);
94 $html = "<select name='$name'>";
95
96 if($default) {
97 $value=$default; $title=$selectbox[$value];
98 $html .= "<option value='$value'>$value :: $title</option>";
99 unset($selectbox[$value]);
100 }
101 foreach($selectbox as $value => $title) {
102 $html .= "<option value='$value'>$value :: $title</option>";
103 }
104 $html .= "</select>";
105 return $html;
106 }
35916247
TM
107
108 function ul($items,$tag=ul,$head='',$class=false) {
109 $class = $class ? " class='$class'" : '';
110 $html = "$head<$tag$class>";
111 foreach($items as $key => $value) {
112 $html .= '<li>';
113 if(is_numeric($key)) {
114 $html .= $value;
115 } else {
116 $html .= $this->link($key,$value);
117 }
118 $html .= '</li>';
119 }
120 $html .= "</$tag>";
121 return $html;
122 }
123
124 function div($html, $options) {
125 $options = $options ? " $options" : '';
126 return "<div$options>$html</div>";
127 }
0a027cc7
TM
128}
129
78bf26a5
TM
130/**
131* Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
132*
fc5c5b8b
TM
133* Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
134*
78bf26a5
TM
135* @package Sklad_HTML
136* @author Tomas Mudrunka
137*/
35916247 138class Sklad_HTML extends HTML { //TODO: Split into few more methods
fc5c5b8b 139 function header($title='') {
cdfce7c2
TM
140 $home = URL_HOME;
141 $script = $_SERVER['SCRIPT_NAME'];
d9384cb5 142 $search = htmlspecialchars(@trim($_GET['q']));
64f31c54 143 $message = strip_tags(@trim($_GET['message']),'<a><b><u><i>');
ac2ed3a1 144 $instance = INSTANCE_ID != '' ? '/'.INSTANCE_ID : '';
35916247
TM
145 //$title = T($title); //TODO
146 $html = <<<EOF
10562613 147<head>
148 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
ac2ed3a1 149 <title>SōkoMan$title</title>
10562613 150</head>
ac2ed3a1 151<h1><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
c9759229
TM
152
153<style type="text/css">
ac2ed3a1
TM
154* { font-family: arial; }
155
7bcd6b42 156.menu li {
c9759229 157 float: left;
7bcd6b42
TM
158 padding: 0.2em;
159}
160
161.menu * li {
162 float: none;
c9759229
TM
163}
164
165.menu * menu {
166 position: absolute;
7bcd6b42 167 padding: 0.2em;
c9759229
TM
168}
169
170.menu, .menu * menu {
171 list-style: none;
172}
173
174.menu * menu {
7bcd6b42 175 border: 1px solid orange;
c9759229
TM
176 display: none;
177 margin: 0;
178}
179
7bcd6b42 180.menu li:hover menu, .menu li:hover {
c9759229 181 display: block;
7bcd6b42 182 background-color: yellow;
c9759229 183}
7bcd6b42 184
c9759229
TM
185</style>
186
cdfce7c2 187<div>
35916247
TM
188EOF;
189
190 $assistants=array();
191 foreach(scandir(DIR_ASSISTANTS) as $item) {
192 if($item == '.' || $item == '..') continue;
193 $item = preg_replace('/\.inc\.php$/','',$item);
194 $assistants[$item] = "assistant/$item";
195 }
196
197 $tables=array('item','model','category','producer','vendor','room','status');
198
199 foreach($tables as $table) {
200 $listable[$table] = $table;
201 $insertable[$table] = "$table/new";
202 }
203
204 $html .= $this->ul(array(
205 'Logout' => '?logout',
206 'Home' => '',
207 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
208 1 => $this->ul($listable,'menu',$this->link('List','#')),
209 2 => $this->ul($insertable,'menu',$this->link('New','#'))
210 ),'menu', '', 'menu');
211
212 $html .= '<div style="float: right;">';
213
214 $html .= $this->form("$script/assistant/go", 'GET', array(
215 array('q','','text','smart id...'),
216 array(false,'go','submit')
217 ), 'style="float: left;"');
218
219 $html .= $this->form('?', 'GET', array(
220 array('q',$search,'text','regexp...'),
221 array(false,'filter','submit')
222 ), 'style="float: left;"');
223
224 $html .= '</div>';
225
226 $html .= <<<EOF
cdfce7c2 227</div>
c9759229 228<hr style="clear: both;" />
d9384cb5
TM
229<div style="background-color:#FFDDDD;">
230 <font color="red">$message</font>
231</div>
cdfce7c2 232EOF;
35916247
TM
233
234 return $html;
cdfce7c2
TM
235 }
236
d9384cb5
TM
237 function internal_url($link) {
238 return $_SERVER['SCRIPT_NAME'].'/'.$link;
239 }
240
cdfce7c2
TM
241 function table_add_images(&$table) {
242 $image = array('model_id');
243 foreach($table as $id => $row) {
244 foreach($image as $column) if(isset($table[$id][$column])) {
245 $type = @array_shift(preg_split('/_/', $column));
246 $src=URL_IMAGES."/$type/".$table[$id][$column].'.jpg';
247 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
248 }
249 }
250 }
251
252 function table_collapse(&$table) {
253 $collapse = array(
254 'item_id' => 'item_id',
255 'model_id' => 'model_name',
256 'category_id' => 'category_name',
257 'producer_id' => 'producer_name',
258 'vendor_id' => 'vendor_name',
259 'room_id' => 'room_name',
260 'status_id' => 'status_name',
261 );
262 foreach($table as $id => $row) {
263 foreach($collapse as $link => $title)
fff6ce40 264 if(isset($table[$id][$link]) && isset($row[$title])) {
cdfce7c2
TM
265 $type = @array_shift(preg_split('/_/', $link));
266 if($link != $title) unset($table[$id][$link]);
267 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
268 }
269 }
270 }
271
272 function table_sort(&$table) {
273 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
274 $table_sorted = array();
275 foreach($table as $id => $row) {
276 $table_sorted[$id] = array();
277 foreach($precedence as $column) if(isset($table[$id][$column])) {
326a9fc9 278 $table_sorted[$id][T($column)]=$table[$id][$column];
cdfce7c2
TM
279 unset($table[$id][$column]);
280 }
326a9fc9
TM
281 //$table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
282 foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
cdfce7c2
TM
283 }
284 $table = $table_sorted;
285 }
286
fc5c5b8b 287 function render_item_table($table) {
cdfce7c2
TM
288 $this->table_add_images($table);
289 $this->table_collapse($table);
290 $this->table_sort($table);
fc5c5b8b 291 return $this->table($table);
cdfce7c2
TM
292 }
293
16261142 294 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true) {
cdfce7c2
TM
295 //echo('<pre>'); print_r($selectbox);
296 //echo('<pre>'); print_r($current);
297 $update = false;
298 if(is_array($current)) {
299 $update = true;
300 $current = array_shift($current);
301 }
302
a084118b
TM
303 if(!is_array($hidecols)) $hidecols = array('item_author', 'item_valid_from', 'item_valid_till'); //TODO Autodetect
304
16261142 305 $action = $action ? " action='$action'" : false;
35916247 306 $html="<form$action method='POST'>"; //TODO: use $this->form()
fc5c5b8b 307 if($multi_insert) $html.='<div name="input_set" style="float:left; border:1px solid grey;">';
371a86f4 308 //$html.=$this->input('table', $class, 'hidden');
cdfce7c2 309 foreach($columns as $column) {
326a9fc9 310 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
7d20381f 311 $name="values[$class][".$column['Field'].'][]';
16261142 312 $val = $update && isset($current[$column['Field']]) ? $current[$column['Field']] : false;
cdfce7c2 313 switch(true) {
a084118b 314 case (preg_match('/auto_increment/', $column['Extra']) || in_array($column['Field'], $hidecols)):
e9cb8cea 315 if(!$val) $val = '';
fc5c5b8b
TM
316 $html.=$this->input($name, $val, 'hidden');
317 $html.=$val.'(AUTO)';
cdfce7c2
TM
318 break;
319 case isset($selectbox[$column['Field']]):
e9cb8cea 320 $html.=$this->select($name,$selectbox[$column['Field']],$val);
cdfce7c2
TM
321 break;
322 default:
fc5c5b8b 323 $html.=$this->input($name, $val);
cdfce7c2
TM
324 break;
325 }
fc5c5b8b 326 $html.='<br />';
cdfce7c2
TM
327 }
328
329 if($multi_insert) {
330 //TODO, move to separate JS file
fc5c5b8b 331 $html.=<<<EOF
cdfce7c2
TM
332 </div>
333 <span name="input_set_next"></span><br style="clear:both" />
334 <script>
335 function duplicate_element(what, where) {
336 document.getElementsByName(where)[0].outerHTML =
337 document.getElementsByName(what)[0].outerHTML
338 + document.getElementsByName(where)[0].outerHTML;
339 }
340 </script>
341 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
342EOF;
343 }
344
bda4a4be 345 $btn = is_array($current) ? 'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
fc5c5b8b
TM
346 $html.=$this->input(false, $btn, 'submit');
347 $html.='</form>';
348 return $html;
cdfce7c2
TM
349 }
350}
351
78bf26a5
TM
352/**
353* Trida poskytuje rozhrani k databazi skladu
354*
355* @package Sklad_DB
356* @author Tomas Mudrunka
357*/
cdfce7c2
TM
358class Sklad_DB extends PDO {
359 function __construct() {
360 $this->lms = new Sklad_LMS();
361
362 parent::__construct(
363 DB_DSN, DB_USER, DB_PASS,
364 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
365 );
366 }
367
368 function escape($str) {
369 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
370 }
371
cb8a6861 372 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
2bedfdac 373 //Configuration
cdfce7c2
TM
374 $join = array(
375 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
376 'model' => array('category', 'producer')
9ea191cb 377 ); //TODO Autodetect using foreign keys?
cdfce7c2 378 $search_fields = array(
df4079a6 379 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name')
9ea191cb 380 ); //TODO Autodetect
2bedfdac
TM
381
382 //Escaping
383 $class = $this->escape($class);
384
385 //SELECT
cdfce7c2 386 $sql="SELECT * FROM $class\n";
2bedfdac 387 //JOIN
8fd613d6 388 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
2bedfdac 389 //WHERE/REGEXP
cdfce7c2
TM
390 if($search) {
391 $search = $this->quote($search);
326a9fc9 392 if(!isset($search_fields[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
5895162b
TM
393 $sql_search = '';
394 foreach($search_fields[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
395 $where[] = "FALSE $sql_search";
cb8a6861
TM
396 } elseif($id) $where[] = "$class$suffix_id = $id";
397 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
398
5895162b 399 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
117817be
TM
400 //ORDER
401 if(!$order) $order = $class.$suffix_id;
402 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
403 $sql .= "ORDER BY $order\n";
2bedfdac 404 //LIMIT/OFFSET
cdfce7c2
TM
405 if($limit) {
406 $limit = $this->escape((int)$limit);
407 $offset = $this->escape((int)$offset);
408 $sql .= "LIMIT $offset,$limit\n";
409 }
2bedfdac 410
cdfce7c2
TM
411 return $sql;
412 }
413
66b6f4d6 414 function safe_query($sql, $fatal=true) {
cdfce7c2
TM
415 $result = $this->query($sql);
416 if(!$result) {
2bedfdac 417 $error = $this->errorInfo();
66b6f4d6
TM
418 trigger_error("<font color=red><b>QUERY FAILED ($error[0],$error[1]): </b>$error[2]<br /><br /><b>QUERY:</b>\n<pre>$sql</pre></font>");
419 if($fatal) die();
cdfce7c2
TM
420 }
421 return $result;
422 }
423
326a9fc9
TM
424 function translate_query_results($result) {
425 $translate_cols = array('status_name', 'item_valid_till'); //TODO: Hardcoded
426 foreach($result as $key => $row) {
427 foreach($translate_cols as $col) if(isset($result[$key][$col])){
428 $result[$key][$col] = T($result[$key][$col]);
429 }
430 }
431 return $result;
432 }
433
434 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO::FETCH_ASSOC, $translate=true) {
435 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
436 if($translate) $result = $this->translate_query_results($result);
437 return $result;
438 }
439
440
cb8a6861
TM
441 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
442 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
326a9fc9 443 $result = $this->safe_query_fetch($sql);
cdfce7c2
TM
444 if(!$result || !is_array($indexed)) return $result;
445
446 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
447 return $indexed;
448 }
449
450 function get_columns($class) {
451 $class = $this->escape($class);
452 $sql = "SHOW COLUMNS FROM $class;";
326a9fc9 453 return $this->safe_query_fetch($sql);
cdfce7c2
TM
454 }
455
456 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
457 $selectbox=array();
458 foreach($columns as $column) {
66b6f4d6 459 if($column['Field'] == 'user_id') continue; //TODO HACK Blacklist: tabulka nemusi obsahovat *_name!!! momentalne se to tyka jen tabulky user (a item - u ty to nevadi)!
cdfce7c2
TM
460 if($class && $column['Field'] == $class.$suffix_id) continue;
461 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
462 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
66b6f4d6 463
117817be 464 $history = $this->contains_history($table) ? " WHERE ${table}_valid_till=0" : '';
b4dcae05 465 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
326a9fc9 466 $result = $this->safe_query_fetch($sql, false);
66b6f4d6 467 if(!$result) continue;
cdfce7c2
TM
468 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
469 }
470 //echo('<pre>'); print_r($selectbox);
66b6f4d6 471 return array_filter($selectbox, 'ksort');
9ea191cb
TM
472 }
473
16261142
TM
474 function map_unique($key, $value, $select, $table) { //TODO: Guess $select and $table if not passed
475 $history = $this->contains_history($table) ? " AND ${table}_valid_till=0" : '';
476 $value=$this->quote($value);
477 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
326a9fc9
TM
478 $result = $this->safe_query_fetch($sql);
479 if(isset($result[0][$select])) return $result[0][$select]; else die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
16261142
TM
480 }
481
9ea191cb
TM
482 function contains_history($table) {
483 $history_tables = array('item'); //TODO Autodetect
484 return in_array($table, $history_tables);
cdfce7c2
TM
485 }
486
487 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
b66fadbb
TM
488 //Init
489 $history = $this->contains_history($table);
490
9ea191cb 491 //Escaping
cdfce7c2
TM
492 $table = $this->escape($table);
493
494 //Get list of POSTed columns
aa3fd0a8
TM
495 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
496 $columns = implode(',',$columns_array);
cdfce7c2 497
9fb856ba 498 //Build query
b66fadbb 499 $sql = '';
b66fadbb
TM
500 //echo('<pre>'); die(print_r($values));
501
502 if($history) {
503 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
504 if($history_update) {
505 $sql .= "UPDATE $table";
117817be
TM
506 $sql .= " SET ${table}_valid_till=NOW()";
507 $sql .= " WHERE ${table}_valid_till=0 AND (";
b66fadbb
TM
508 $or = '';
509 foreach($values as $row) {
510 $sql .= $or.' '.$table.'_id='.$row[$table.'_id'];
511 $or = ' OR';
512 }
513 $sql .= " );\n\n";
514 $replace = false;
515 }
516 }
517
cdfce7c2 518 //Insert into table (columns)
aa3fd0a8 519 $sql .= "INSERT INTO $table ($columns) VALUES ";
cdfce7c2
TM
520
521 //Values (a,b,c),(d,e,f)
522 $comma='';
523 foreach($values as $row) {
9fb856ba
TM
524 $row_quoted = array_map(array($this,'quote'), $row); //Check
525 if($history) {
b66fadbb
TM
526 foreach($row as $column => $value) {
527 switch($column) {
528 case $table.'_valid_from':
529 $row_quoted[$column] = 'NOW()';
530 break;
531 case $table.'_valid_till':
532 $row_quoted[$column] = '0';
533 break;
9fb856ba
TM
534 case $table.'_author':
535 $row_quoted[$column] = $this->lms->get_authorized_user_id();
b66fadbb
TM
536 //die($this->lms->get_authorized_user_id().'=USER');
537 break;
b66fadbb
TM
538 }
539 }
540 }
541 $sql .= $comma.'('.implode(',',$row_quoted).')';
cdfce7c2
TM
542 $comma = ',';
543 }
544
aa3fd0a8
TM
545 //On duplicate key
546 if($replace) {
547 foreach($columns_array as $col) {
548 if($col == $table.'_id' || $col == $table.'_valid_till') continue;
549 $on_duplicate[] = "$col=VALUES($col)";
550 }
551 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
552 }
553
cdfce7c2
TM
554 //Terminate
555 $sql .= ';';
556 return $sql;
557 }
558
b4dcae05
TM
559 function insert_or_update($table, $values, $replace=true) {
560 $sql = $this->build_query_insert($table, $values, $replace);
cdfce7c2
TM
561 $this->safe_query($sql);
562 return $this->lastInsertId();
563 }
564
b4dcae05 565 function insert_or_update_multitab($values, $replace=true) {
371a86f4 566 $last=false;
b4dcae05 567 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
371a86f4
TM
568 return $last;
569 }
570
cdfce7c2 571 function delete($table, $id, $suffix_id='_id') {
64f31c54 572 if($this->contains_history($table)) return false;
cdfce7c2
TM
573 $key = $this->escape($table.$suffix_id);
574 $table = $this->escape($table);
575 $id = $this->quote($id);
576 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
577 }
578}
579
0a027cc7
TM
580/**
581* Trida poskytuje high-level rozhrani k databazi skladu
582*
583* @package Sklad_DB_Abstract
584* @author Tomas Mudrunka
585*/
586class Sklad_DB_Abstract extends Sklad_DB {
587 //TODO Code
588}
589
78bf26a5
TM
590/**
591* Trida implementuje uzivatelske rozhrani skladu
592*
593* Example usage:
594* $sklad = new Sklad_UI();
595* $sklad->process_http_request();
596*
597* @package Sklad_UI
598* @author Tomas Mudrunka
599*/
cdfce7c2
TM
600class Sklad_UI {
601 function __construct() {
602 $this->db = new Sklad_DB();
603 $this->html = new Sklad_HTML();
604 }
605
cb8a6861
TM
606 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
607 return $this->html->render_item_table($this->db->get_listing($class, $id, $limit, $offset, $where, $search, $history, false));
cdfce7c2
TM
608 }
609
a25f85f8 610 function render_form_add($class) {
cdfce7c2
TM
611 $columns = $this->db->get_columns($class);
612 $selectbox = $this->db->columns_get_selectbox($columns, $class);
a25f85f8 613 return $this->html->render_insert_form($class, $columns, $selectbox);
cdfce7c2
TM
614 }
615
a25f85f8 616 function render_form_edit($class, $id) {
cdfce7c2
TM
617 $columns = $this->db->get_columns($class);
618 $selectbox = $this->db->columns_get_selectbox($columns, $class);
117817be 619 $current = $this->db->get_listing($class, $id, 1);
a25f85f8 620 return $this->html->render_insert_form($class, $columns, $selectbox, $current);
cdfce7c2
TM
621 }
622
a25f85f8 623 function render_single_record_details($class, $id) {
cdfce7c2
TM
624 $id_next = $id + 1;
625 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
626 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
a25f85f8
TM
627 $html='';
628 $html.= $this->html->link('<<', "$class/$id_prev/");
629 $html.= '-';
630 $html.= $this->html->link('>>', "$class/$id_next/");
631 $html.= '<br />';
632 $html.= $this->html->link('edit', "$class/$id/edit/");
9fb856ba 633 if($this->db->contains_history($class)) $html.= ' ][ '.$this->html->link('history', "$class/$id/history/");
a25f85f8 634 return $html;
cdfce7c2
TM
635 }
636
a25f85f8 637 function render_listing_navigation($class, $id, $limit, $offset) {
cdfce7c2
TM
638 $offset_next = $offset + $limit;
639 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
640 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
a25f85f8
TM
641 $html='';
642 $html.= $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
643 $html.= '-';
644 $html.= $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
645 $html.= '<br />';
646 $html.= $this->html->link('new', "$class/new/$get");
647 return $html;
cdfce7c2
TM
648 }
649
a25f85f8
TM
650 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
651 $html='';
cdfce7c2 652 if(is_numeric($id)) {
a25f85f8 653 $html.=$this->render_single_record_details($class, $id);
cdfce7c2 654 } else {
a25f85f8 655 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
cdfce7c2
TM
656 }
657 if($edit) {
a25f85f8 658 $html.= $this->render_form_edit($class, $id);
cdfce7c2 659 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
35916247
TM
660 $html.=$this->html->form($action,'POST',array(
661 array(false,'DELETE','submit'),
662 array('sure', false, 'checkbox', false, false, 'sure?')
663 ));
cdfce7c2 664 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
35916247
TM
665 $html.=$this->html->form($action,'POST',array(
666 array('image', false, 'file', false, 'size="30"'),
667 array(false, 'IMAGE', 'submit')
668 ), "enctype='multipart/form-data'");
cdfce7c2 669 }
a25f85f8 670 return $html;
cdfce7c2
TM
671 }
672
673 function check_auth() {
674 new HTTP_Auth('SkladovejSystem', true, array($this->db->lms,'check_auth'));
675 }
676
64f31c54 677 function post_redirect_get($location, $message='', $error=false) {
326a9fc9 678 $url_args = $message != '' ? '?message='.urlencode(T($message)) : '';
8acef003 679 $location = $this->html->internal_url($location).$url_args;
1f74892d 680 header('Location: '.$location);
64f31c54 681 if($error) trigger_error($message);
7efdf72a
TM
682 $location=htmlspecialchars($location);
683 die(
684 "<meta http-equiv='refresh' content='0; url=$location'>".
326a9fc9 685 T($message)."<br />Location: <a href='$location'>$location</a>"
7efdf72a 686 );
cdfce7c2
TM
687 }
688
623c65e2 689 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
64f31c54 690 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
3e6c412e 691 $filename="$dir/$name$ext";
64f31c54 692 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
623c65e2 693 foreach($vars as $var => $val) $$var=$val;
3e6c412e
TM
694 ob_start();
695 include($filename);
696 $out=ob_get_contents();
697 ob_end_clean();
698 return $out;
699 }
700
bda4a4be 701 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
cdfce7c2 702 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
1f74892d 703 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
cdfce7c2
TM
704
705 //SephirPOST:
371a86f4
TM
706
707 /* Tenhle foreach() prekopiruje promenne
7d20381f 708 * z: $_POST['values'][$table][$column][$id];
371a86f4
TM
709 * do: $values[$table][$id][$column]
710 */
7d20381f
TM
711 if(isset($_POST['values'])) {
712 $values=array();
713 foreach($_POST['values'] as $table => $columns) {
714 foreach($columns as $column => $ids) {
715 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
716 }
cdfce7c2 717 }
7d20381f 718 //die(print_r($values));
cdfce7c2
TM
719 }
720
721 if($action) switch($action) {
722 case 'new':
b4dcae05 723 $replace = false;
cdfce7c2 724 case 'edit':
b4dcae05 725 if(!isset($replace)) $replace = true;
64f31c54 726 $table = $class ? $class : 'item';
cdfce7c2 727 //print_r($values); //debug
b4dcae05 728 $last = $this->db->insert_or_update_multitab($values, $replace);
bda4a4be 729 $last = $force_redirect ? $force_redirect."?last=$last" : "$table/$last/";
d9384cb5 730 $next = "$table/new/";
bda4a4be
TM
731 $message = $force_redirect ? '' : 'Hotovo. Další záznam přidáte '.$this->html->link('zde', $next).'.';
732 $this->post_redirect_get($last, $message);
cdfce7c2
TM
733 break;
734 case 'delete':
64f31c54
TM
735 if(!isset($_POST['sure']) || !$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
736 $this->db->delete($class, $id) || $this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
1f74892d 737 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
cdfce7c2
TM
738 break;
739 case 'image':
740 $image_classes = array('model'); //TODO, use this more widely across the code
64f31c54 741 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
cdfce7c2 742 $image_destination = DIR_IMAGES."/$class/$id.jpg";
326a9fc9 743 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
cdfce7c2 744 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
1f74892d 745 chmod ($image_destination, 0664);
326a9fc9
TM
746 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
747 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
cdfce7c2
TM
748 break;
749 default:
326a9fc9 750 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
cdfce7c2
TM
751 break;
752 }
753
754 die('POSTed pyčo!');
755 }
756
757 function process_http_request() {
758 $this->check_auth();
759
760 @ini_set('magic_quotes_gpc' , 'off');
761 if(get_magic_quotes_gpc()) {
762 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
763 }
764
765 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
8fd613d6 766 if($_SERVER['REQUEST_METHOD'] != 'POST') echo $this->html->header($PATH_INFO); //TODO tahle podminka naznacuje ze je v navrhu nejaka drobna nedomyslenost...
cdfce7c2
TM
767
768
769 //Sephirot:
770 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
771 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
772 switch($PATH_CHUNKS[1]) {
773 case 'test': //test
774 die('Tell me why you cry');
775 break;
3e6c412e 776 case 'assistant': //assistant
de77377e
TM
777 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ? trim($PATH_CHUNKS[3]) : false;
778 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
779 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
780 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
623c65e2 781 echo $this->safe_include(DIR_ASSISTANTS,$PATH_CHUNKS[2],$assistant_vars);
3e6c412e 782 break;
cdfce7c2
TM
783 default: //?
784 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
785 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
786 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
787 switch($PATH_CHUNKS[2]) {
788 case 'new': //?/new
789 $this->process_http_request_post($PATH_CHUNKS[2], $class);
a25f85f8 790 echo $this->render_form_add($class);
cdfce7c2
TM
791 break;
792 default: //?/?
793 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
794 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
795 $edit=false;
796 switch($PATH_CHUNKS[3]) {
797 case 'edit': //?/?/edit
9fb856ba
TM
798 case 'image': //?/?/image
799 case 'delete': //?/?/delete
cdfce7c2
TM
800 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
801 $edit=true;
802 default: //?/?/?
9fb856ba 803 $history = $PATH_CHUNKS[3] == 'history' ? true : false;
cdfce7c2
TM
804 $limit = (int) (isset($PATH_CHUNKS[3]) ? $PATH_CHUNKS[3] : '0');
805 $offset = (int) (isset($PATH_CHUNKS[4]) ? $PATH_CHUNKS[4] : '0');
cb8a6861
TM
806 $where = false; //TODO get from URL
807 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
a25f85f8 808 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
cdfce7c2
TM
809 //print_r(array("<pre>",$_SERVER));
810 break;
811 }
812 break;
813 }
814 break;
815 }
816 }
817}
818
819$sklad = new Sklad_UI();
820$sklad->process_http_request();
821
822echo("<hr/>");
This page took 0.845765 seconds and 4 git commands to generate.