Cisla zakazniku predelany na linky s parametrem where
[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),array('edit','model/%v/edit/')),
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]) && isset($relations_conditions[$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 'item_author' => 'item_author_backend',
379 'item_customer' => 'item_customer',
380 );
381
382 foreach($table as $id => $row) {
383 foreach($collapse as $link => $title)
384 if(isset($table[$id][$link]) && isset($row[$title])) {
385 $type = @array_shift(preg_split('/_/', $link));
386 if($link != $title) unset($table[$id][$link]);
387 switch($link) { //TODO: Move to array for easy configuration
388 case 'item_author':
389 case 'item_customer':
390 $table[$id][$title]=$this->link($row[$title], "?where[$link]==".$row[$link], false);
391 break;
392 default:
393 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
394 break;
395 }
396 }
397 }
398 }
399
400 function table_sort(&$table) {
401 $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');
402 $table_sorted = array();
403 foreach($table as $id => $row) {
404 $table_sorted[$id] = array();
405 foreach($precedence as $column) if(isset($table[$id][$column])) {
406 $table_sorted[$id][T($column)]=$table[$id][$column];
407 unset($table[$id][$column]);
408 }
409 //$table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
410 foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
411 }
412 $table = $table_sorted;
413 }
414
415 function table_hide_columns(&$table, $class) { //TODO: Move to build_query_select() !!! :-)))
416 $fields_hide = array(
417 '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')
418 );
419 //print_r($table); die();
420 if(isset($fields_hide[$class])) foreach($table as $id => $row) {
421 foreach($fields_hide[$class] as $field) unset($table[$id][$field]);
422 }
423 }
424
425 function render_item_table($table,$class=false) {
426 if(empty($table)) return '<h3>'.T('holy primordial emptiness is all you can find here...').'</h3><br />';
427 $this->table_add_images($table);
428 if($class) $this->table_add_relations($table,$class);
429 $this->table_add_barcodes($table);
430 $this->table_collapse($table);
431 if($class) $this->table_hide_columns($table,$class);
432 $this->table_sort($table);
433 return $this->table($table);
434 }
435
436 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
437 $textarea = array(
438 'item' => array('item_note'),
439 'model' => array('model_descript')
440 );
441 $html = '';
442 foreach($columns as $column) {
443 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
444 $name="values[$class][".$column['Field'].'][]';
445 $val = $update && isset($current[$column['Field']]) ? $current[$column['Field']] : false;
446 switch(true) {
447 case (preg_match('/auto_increment/', $column['Extra']) || in_array($column['Field'], $hidecols)):
448 if(!$val) $val = '';
449 $html.=$this->input($name, $val, 'hidden');
450 $html.=$val.'(AUTO)';
451 break;
452 case isset($selectbox[$column['Field']]):
453 $html.=$this->select($name,$selectbox[$column['Field']],$val);
454 break;
455 case isset($textarea[$class]) && in_array($column['Field'],$textarea[$class]):
456 $html.=$this->input($name, $val, 'textarea');
457 break;
458 default:
459 $html.=$this->input($name, $val);
460 break;
461 }
462 $html.='<br />';
463 }
464 return $html;
465 }
466
467 function render_insert_form_multi($array) {
468 $html = '';
469 $head=false;
470
471 foreach($array as $key => $args) {
472 $parts=array('inputs');
473 if(!$head) { $head = true;
474 $parts[]='head';
475 }
476 if(!isset($array[$key+1])) {
477 $parts[]='foot';
478 $hr = '';
479 } else $hr = '<hr />';
480 //$args[] = false;
481 $args[] = $parts;
482
483 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
484 $html .= $hr;
485 }
486 return $html;
487 }
488
489 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
490 $html = '';
491 //print_r($parts);
492 //echo('<pre>'); print_r($selectbox);
493 //echo('<pre>'); print_r($current);
494 $update = false;
495 if(is_array($current)) {
496 $update = true;
497 $current = array_shift($current);
498 }
499
500 if(!is_array($hidecols)) $hidecols = array();
501 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
502
503 if(!is_array($parts) || in_array('head', $parts)) {
504 $action = $action ? " action='$action'" : false;
505 $html.="<form$action method='POST'>"; //TODO: use $this->form()
506 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
507 }
508
509 if(!is_array($parts) || in_array('inputs', $parts))
510 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
511
512 if(!is_array($parts) || in_array('foot', $parts)) {
513 $html .= '</div></span><br style="clear:both" />';
514 if($multi_insert) { //TODO, move to separate JS file
515 $html.=<<<EOF
516 <script>
517 function duplicate_element(what, where) {
518 var node = document.getElementsByName(what)[0];
519 node.parentNode.appendChild(node.cloneNode(true));
520 }
521 </script>
522 <a href='#' onClick="duplicate_element('input_set')">+</a>
523 EOF;
524 }
525
526 $btn = is_array($current) ? 'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
527 $html.=$this->input(false, $btn, 'submit');
528 $html.='</form>';
529 }
530 return $html;
531 }
532 }
533
534 /**
535 * Trida poskytuje rozhrani k databazi skladu
536 *
537 * @package Sklad_DB
538 * @author Tomas Mudrunka
539 */
540 class Sklad_DB extends PDO {
541 function __construct() {
542 $this->auth = new Sklad_Auth();
543
544 parent::__construct(
545 DB_DSN, DB_USER, DB_PASS,
546 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
547 );
548 }
549
550 function escape($str) {
551 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
552 }
553
554 function quote_identifier($str) {
555 return '`'.$this->escape($str).'`'; //TODO HACK
556 }
557
558 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
559 //Configuration
560 $join = array(
561 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
562 'model' => array('category', 'producer')
563 ); //TODO Autodetect using foreign keys?
564 $fields_search = array(
565 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name'),
566 'model' => array('model_id','model_name','model_barcode','model_descript','producer_name')
567 ); //TODO Autodetect
568
569 //Init
570 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
571
572 //Escaping
573 $class = $this->escape($class);
574
575 //SELECT
576 $sql="SELECT * FROM `$class`\n";
577 //JOIN
578 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN `$j` USING($j$suffix_id)\n";
579 //WHERE/REGEXP
580 if($search) {
581 $search = $this->quote($search);
582 if(!isset($fields_search[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
583 $sql_search = '';
584 foreach($fields_search[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
585 $where[] = "FALSE $sql_search";
586 } elseif($id) $where[] = "$class$suffix_id = $id";
587 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
588
589 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
590 //ORDER
591 if(!$order) $order = $class.$suffix_id.' DESC';
592 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
593 $sql .= "ORDER BY $order\n";
594 //LIMIT/OFFSET
595 if($limit) {
596 $limit = $this->escape((int)$limit);
597 $offset = $this->escape((int)$offset);
598 $sql .= "LIMIT $offset,$limit\n";
599 }
600
601 return $sql;
602 }
603
604 function safe_query($sql, $fatal=true) {
605 $result = $this->query($sql);
606 if(!$result) {
607 $error = $this->errorInfo();
608 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>");
609 if($fatal) die();
610 }
611 return $result;
612 }
613
614 function translate_query_results(&$result) {
615 $translate_cols = array('status_name', 'item_valid_till'); //TODO: Hardcoded
616 foreach($result as $key => $row) {
617 foreach($translate_cols as $col) if(isset($result[$key][$col])){
618 $result[$key][$col] = T($result[$key][$col]);
619 }
620 }
621 }
622
623 function load_backend_data_to_query_results(&$result,$suffix_backend='_backend') {
624 $translate_cols = array(
625 'item_author' => 'return($this->auth->get_username_by_id($result[$key][$col]));'
626 ); //TODO: Hardcoded
627 foreach($result as $key => $row) {
628 foreach($translate_cols as $col => $backend) if(isset($result[$key][$col])){
629 $result[$key][$col.$suffix_backend] = eval($backend);
630 }
631 }
632 }
633
634 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO::FETCH_ASSOC, $translate=true) {
635 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
636 $this->load_backend_data_to_query_results($result);
637 if($translate) $this->translate_query_results($result);
638 return $result;
639 }
640
641
642 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
643 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
644 $result = $this->safe_query_fetch($sql);
645 if(!$result || !is_array($indexed)) return $result;
646
647 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
648 return $indexed;
649 }
650
651 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
652 $class = $this->escape($class);
653 $sql = "SHOW COLUMNS FROM $class;";
654 $columns = $this->safe_query_fetch($sql);
655 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
656 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
657 }*/
658 return $columns;
659 }
660
661 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
662 $selectbox=array( //TODO: Hardcoded...
663 'model_countable' => array(0 => 'no', 1 => 'yes'),
664 'model_eshop_hide' => array(0 => 'no', 1 => 'yes'),
665 'vendor_id' => array('COMPULSORY' => 'select...')
666 );
667 foreach($columns as $column) {
668 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)!
669 if($class && $column['Field'] == $class.$suffix_id) continue;
670 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
671 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
672
673 $history = $this->contains_history($table) ? " WHERE ${table}_valid_till=0" : '';
674 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
675 $result = $this->safe_query_fetch($sql, false);
676 if(!$result) continue;
677 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
678 }
679 //echo('<pre>'); print_r($selectbox);
680 return array_filter($selectbox, 'ksort');
681 }
682
683 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
684 $history = $this->contains_history($table) ? " AND ${table}_valid_till=0" : '';
685 $value=$this->quote($value);
686 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
687 $result = $this->safe_query_fetch($sql);
688 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
689 }
690
691 function contains_history($table) {
692 $history_tables = array('item'); //TODO Autodetect
693 return in_array($table, $history_tables);
694 }
695
696 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
697 //Init
698 $history = $this->contains_history($table);
699
700 //Escaping
701 $table = $this->escape($table);
702
703 //Get list of POSTed columns
704 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
705 $columns = implode(',',$columns_array);
706
707 //Build query
708 $sql = '';
709 //echo('<pre>'); die(print_r($values));
710
711 if($history) {
712 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
713 if($history_update) {
714 $sql .= "UPDATE $table";
715 $sql .= " SET ${table}_valid_till=NOW()";
716 $sql .= " WHERE ${table}_valid_till=0 AND (";
717 $or = '';
718 foreach($values as $row) {
719 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
720 $or = ' OR';
721 }
722 $sql .= " );\n\n";
723 $replace = false;
724 }
725 }
726
727 //Insert into table (columns)
728 $sql .= "INSERT INTO $table ($columns) VALUES ";
729
730 //Values (a,b,c),(d,e,f)
731 $comma='';
732 foreach($values as $row) {
733 $row_quoted = array_map(array($this,'quote'), $row); //Check
734 if($history) {
735 foreach($row as $column => $value) {
736 switch($column) {
737 case $table.'_valid_from':
738 $row_quoted[$column] = 'NOW()';
739 break;
740 case $table.'_valid_till':
741 $row_quoted[$column] = '0';
742 break;
743 case $table.'_author':
744 $row_quoted[$column] = $this->auth->get_user_id();
745 //die($this->auth->get_user_id().'=USER');
746 break;
747 }
748 }
749 }
750 $sql .= $comma.'('.implode(',',$row_quoted).')';
751 $comma = ',';
752 }
753
754 //On duplicate key
755 if($replace) {
756 foreach($columns_array as $col) {
757 if($col == $table.'_id' || $col == $table.'_valid_till') continue;
758 $on_duplicate[] = "$col=VALUES($col)";
759 }
760 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
761 }
762
763 //Terminate
764 $sql .= ';';
765 return $sql;
766 }
767
768 function insert_or_update($table, $values, $replace=true) {
769 $sql = $this->build_query_insert($table, $values, $replace);
770 $this->safe_query($sql);
771 return $this->lastInsertId();
772 }
773
774 function insert_or_update_multitab($values, $replace=true) {
775 $last=false;
776 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
777 return $last;
778 }
779
780 function delete($table, $id, $suffix_id='_id') {
781 if($this->contains_history($table)) return false;
782 $key = $this->escape($table.$suffix_id);
783 $table = $this->escape($table);
784 $id = $this->quote($id);
785 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
786 }
787 }
788
789 /**
790 * Trida poskytuje high-level rozhrani k databazi skladu
791 *
792 * @package Sklad_DB_Abstract
793 * @author Tomas Mudrunka
794 */
795 class Sklad_DB_Abstract extends Sklad_DB {
796 //TODO Code
797 }
798
799 /**
800 * Trida implementuje uzivatelske rozhrani skladu
801 *
802 * Example usage:
803 * $sklad = new Sklad_UI();
804 * $sklad->process_http_request();
805 *
806 * @package Sklad_UI
807 * @author Tomas Mudrunka
808 */
809 class Sklad_UI {
810 function __construct() {
811 $this->db = new Sklad_DB();
812 $this->html = new Sklad_HTML();
813 }
814
815 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
816 return $this->html->render_item_table($this->db->get_listing($class, $id, $limit, $offset, $where, $search, $history, false),$class);
817 }
818
819 function render_form_add($class) {
820 $columns = $this->db->get_columns($class);
821 $selectbox = $this->db->columns_get_selectbox($columns, $class);
822 return $this->html->render_insert_form($class, $columns, $selectbox);
823 }
824
825 function render_form_edit($class, $id, $multi_insert) {
826 $columns = $this->db->get_columns($class);
827 $selectbox = $this->db->columns_get_selectbox($columns, $class);
828 $current = $this->db->get_listing($class, $id, 1);
829 return $this->html->render_insert_form($class, $columns, $selectbox, $current, false, false, $multi_insert);
830 }
831
832 function render_single_record_details($class, $id) {
833 $id_next = $id + 1;
834 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
835 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
836 $html='';
837 $html.= $this->html->link('<<', "$class/$id_prev/");
838 $html.= '-';
839 $html.= $this->html->link('>>', "$class/$id_next/");
840 $html.= '<br />';
841 $html.='<span style="float:right;">'.$this->html->render_barcode(BARCODE_PREFIX.strtoupper("$class/$id")).'</span>';
842 $html.= $this->html->link('edit', "$class/$id/edit/");
843 if($this->db->contains_history($class)) $html.= ' ][ '.$this->html->link('history', "$class/$id/history/");
844 return $html;
845 }
846
847 function render_listing_navigation($class, $id, $limit, $offset) {
848 $offset_next = $offset + $limit;
849 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
850 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
851 $html='';
852 $html.= $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
853 $html.= '-';
854 $html.= $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
855 $html.= '<br />';
856 $html.= $this->html->link('new', "$class/new/$get");
857 return $html;
858 }
859
860 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
861 $html='';
862 if(is_numeric($id)) {
863 $html.=$this->render_single_record_details($class, $id);
864 } else {
865 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
866 }
867 if($edit) {
868 $html.= $this->render_form_edit($class, $id, false);
869 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
870 $html.=$this->html->form($action,'POST',array(
871 array(false,'DELETE','submit'),
872 array('sure', false, 'checkbox', false, false, 'sure?')
873 ));
874 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
875 $html.=$this->html->form($action,'POST',array(
876 array('image', false, 'file', false, 'size="30"'),
877 array(false, 'IMAGE', 'submit')
878 ), "enctype='multipart/form-data'");
879 }
880 return $html;
881 }
882
883 function check_auth() {
884 new HTTP_Auth('WareHouse ['.BACKEND_AUTH.']', true, array($this->db->auth,'check_auth'));
885 }
886
887 function post_redirect_get($location, $message='', $error=false, $translate=true) {
888 $messaget = $translate ? T($message) : $message;
889 $url_args = $messaget != '' ? '?message='.urlencode($messaget) : '';
890 $location = $this->html->internal_url($location).$url_args;
891 header('Location: '.$location);
892 if($error) trigger_error($message);
893 $location=htmlspecialchars($location);
894 die(
895 "<meta http-equiv='refresh' content='0; url=$location'>".
896 $messaget."<br />Location: <a href='$location'>$location</a>"
897 );
898 }
899
900 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
901 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
902 $filename="$dir/$name$ext";
903 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
904 foreach($vars as $var => $val) $$var=$val;
905 ob_start();
906 include($filename);
907 $out=ob_get_contents();
908 ob_end_clean();
909 return $out;
910 }
911
912 function check_input_validity($field, $value='', $ruleset=0) {
913 $rules = array(0 => array(
914 'model_barcode' => '/./',
915 'item_serial' => '/./',
916 'vendor_id' => '/^[0-9]*$/'
917 ));
918 if(isset($rules[$ruleset][$field]) && !preg_match($rules[$ruleset][$field], trim($value))) return false;
919 return true;
920 }
921
922 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
923 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
924 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
925
926 //SephirPOST:
927
928 /* Tenhle foreach() prekopiruje promenne
929 * z: $_POST['values'][$table][$column][$id];
930 * do: $values[$table][$id][$column]
931 */
932 if(isset($_POST['values'])) {
933 $values=array();
934 foreach($_POST['values'] as $table => $columns) {
935 foreach($columns as $column => $ids) {
936 foreach($ids as $id => $val) {
937 $values[$table][$id][$column] = trim($val);
938 if(!$this->check_input_validity($column,$val)) {
939 $message = "Spatny vstup: $column [$id] = \"$val\"; ". //XSS
940 $this->html->link('GO BACK', 'javascript:history.back()', false, false);
941 $this->post_redirect_get('', $message, false, false);
942 }
943 }
944 }
945 }
946 //die(print_r($values));
947 }
948
949 if($action) switch($action) {
950 case 'new':
951 $replace = false;
952 case 'edit':
953 if(!isset($replace)) $replace = true;
954 $table = $class ? $class : 'item';
955 //print_r($values); //debug
956 $last = $this->db->insert_or_update_multitab($values, $replace);
957 $last = $force_redirect ? $force_redirect."?last=$last" : "$table/$last/";
958 $next = "$table/new/";
959 $message = $force_redirect ? '' : 'Hotovo. Další záznam přidáte '.$this->html->link('zde', $next).'.';
960 $this->post_redirect_get($last, $message);
961 break;
962 case 'delete':
963 if(!isset($_POST['sure']) || !$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
964 $this->db->delete($class, $id) || $this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
965 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
966 break;
967 case 'image':
968 $image_classes = array('model'); //TODO, use this more widely across the code
969 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
970 $image_destination = DIR_IMAGES."/$class/$id.jpg";
971 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
972 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
973 chmod ($image_destination, 0664);
974 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
975 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
976 break;
977 default:
978 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
979 break;
980 }
981
982 die('POSTed pyčo!');
983 }
984
985 function process_http_request() {
986 $this->check_auth();
987
988 @ini_set('magic_quotes_gpc' , 'off');
989 if(get_magic_quotes_gpc()) {
990 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
991 }
992
993 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
994 if($PATH_INFO == '' || $PATH_INFO == '/') $PATH_INFO = FRONTEND_PAGE_WELCOME;
995 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
996 //Sephirot:
997 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
998 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcode' && $PATH_CHUNKS[1]!='api') //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
999 echo $this->html->header($PATH_INFO,$this->db->auth->get_user());
1000 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
1001 case 'test': //test
1002 die('Tell me why you cry');
1003 break;
1004 case 'assistant': case 'api': //assistant|api
1005 $incdirs = array(
1006 'assistant' => DIR_ASSISTANTS,
1007 'api' => DIR_APIS
1008 );
1009 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ? trim($PATH_CHUNKS[3]) : false;
1010 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
1011 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
1012 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
1013 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
1014 echo $this->safe_include($incdirs[$PATH_CHUNKS[1]],$PATH_CHUNKS[2],$assistant_vars);
1015 break;
1016 case 'barcode': //barcode
1017 Barcode::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
1018 break;
1019 default: //?
1020 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
1021 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
1022 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
1023 switch($PATH_CHUNKS[2]) {
1024 case 'new': //?/new
1025 $this->process_http_request_post($PATH_CHUNKS[2], $class);
1026 echo $this->render_form_add($class);
1027 break;
1028 default: //?/?
1029 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
1030 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
1031 $edit=false;
1032 switch($PATH_CHUNKS[3]) {
1033 case 'edit': //?/?/edit
1034 case 'image': //?/?/image
1035 case 'delete': //?/?/delete
1036 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
1037 $edit=true;
1038 default: //?/?/?
1039 $history = $PATH_CHUNKS[3] == 'history' ? true : false;
1040 $limit = is_numeric($PATH_CHUNKS[3]) ? (int) $PATH_CHUNKS[3] : FRONTEND_LISTING_LIMIT;
1041 $offset = isset($PATH_CHUNKS[4]) ? (int) $PATH_CHUNKS[4] : 0;
1042 $where = @is_array($_GET['where']) ? $_GET['where'] : false;
1043 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
1044 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
1045 //print_r(array("<pre>",$_SERVER));
1046 break;
1047 }
1048 break;
1049 }
1050 break;
1051 }
1052 }
1053 }
1054
1055 $sklad = new Sklad_UI();
1056 $sklad->process_http_request();
1057
1058 echo('<br style="clear:both;" /><hr />');
This page took 1.225428 seconds and 5 git commands to generate.