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