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