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