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