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