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