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