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