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