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