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