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