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