Added meta tag with charset specification to header
[mirrors/SokoMan.git] / index.php
CommitLineData
cdfce7c2
TM
1<?php
2/*
3 * SkladovySystem - Storage management system compatible with LMS
4 * Copyright (C) 2011 Thomas 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
20require_once('sklad.conf.php');
21require_once('Sklad_LMS-fake.class.php');
22require_once('HTTP_Auth.class.php');
23
24class Sklad_HTML {
25 function header_print($title='') {
26 $home = URL_HOME;
27 $script = $_SERVER['SCRIPT_NAME'];
28 $search = @trim($_GET['q']);
29 echo <<<EOF
10562613 30<head>
31 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
32</head>
cdfce7c2
TM
33<h1><a href="$script/">SystémSklad</a><small>$title</small></h1>
34<div>
35 <menu>
36 <li><a href="?logout">Logout</a></li>
37 <li><a href="$script/">Home</a></li>
38 </menu>
39 <form action="?" method="GET">
40 <input type="text" name="q" placeholder="regexp..." value="$search" />
41 <input type="submit" value="filter" />
42 </form>
43 <!-- form action="$script/" method="GET">
44 <input type="text" name="q" placeholder="regexp..." value="$search" />
45 <input type="submit" value="search items" />
46 </form -->
47</div>
48EOF;
49 }
50
51 function row_print($row) {
52 echo('<tr>');
53 foreach($row as $var) {
54 if(trim($var) == '') $var = '&nbsp;';
55 echo("<td>$var</td>");
56 }
57 echo('</tr>');
58 }
59
60 function table_print(&$table, $params='border=1') {
61 echo("<table $params>");
62 $header=true;
63 foreach($table as $row) {
64 if($header) {
65 $this->row_print(array_keys($row));
66 $header=false;
67 }
68 $this->row_print($row);
69 }
70 echo('</table>');
71 }
72
73 function link($title='n/a', $link='#void', $internal=true) {
74 if($internal) $link = $_SERVER['SCRIPT_NAME'].'/'.$link;
75 return "<a href='$link'>$title</a>";
76 }
77
78 function img($src='#void', $title='img') {
79 return "<img src='$src' alt='$title' title='$title' width=64 />";
80 }
81
82 function table_add_images(&$table) {
83 $image = array('model_id');
84 foreach($table as $id => $row) {
85 foreach($image as $column) if(isset($table[$id][$column])) {
86 $type = @array_shift(preg_split('/_/', $column));
87 $src=URL_IMAGES."/$type/".$table[$id][$column].'.jpg';
88 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
89 }
90 }
91 }
92
93 function table_collapse(&$table) {
94 $collapse = array(
95 'item_id' => 'item_id',
96 'model_id' => 'model_name',
97 'category_id' => 'category_name',
98 'producer_id' => 'producer_name',
99 'vendor_id' => 'vendor_name',
100 'room_id' => 'room_name',
101 'status_id' => 'status_name',
102 );
103 foreach($table as $id => $row) {
104 foreach($collapse as $link => $title)
105 if(isset($table[$id][$link])) {
106 $type = @array_shift(preg_split('/_/', $link));
107 if($link != $title) unset($table[$id][$link]);
108 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
109 }
110 }
111 }
112
113 function table_sort(&$table) {
114 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
115 $table_sorted = array();
116 foreach($table as $id => $row) {
117 $table_sorted[$id] = array();
118 foreach($precedence as $column) if(isset($table[$id][$column])) {
119 $table_sorted[$id][$column]=$table[$id][$column];
120 unset($table[$id][$column]);
121 }
122 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
123 }
124 $table = $table_sorted;
125 }
126
127 function print_item_table($table) {
128 $this->table_add_images($table);
129 $this->table_collapse($table);
130 $this->table_sort($table);
131 return $this->table_print($table);
132 }
133
134 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false) {
135 $html = "<input type='$type' ";
136 if($name) $html.= "name='$name' ";
137 if(!is_bool($value)) $html.= "value='$value' ";
138 if($options) $html.= "$options ";
139 if($placeholder) $html.= "placeholder='$placeholder' ";
140 $html .= '/>';
141 return $html;
142 }
143
144 function select($name, $selectbox, $default=false) {
145 //echo('<pre>'); print_r($selectbox);
146 $html = "<select name='$name'>";
147
148 if($default) {
149 $value=$default; $title=$selectbox[$value];
150 $html .= "<option value='$value'>$value :: $title</option>";
151 unset($selectbox[$value]);
152 }
153 foreach($selectbox as $value => $title) {
154 $html .= "<option value='$value'>$value :: $title</option>";
155 }
156 $html .= "</select>";
157 return $html;
158 }
159
160 function print_insert_form($class, $columns, $selectbox=array(), $current=false, $multi_insert=true) {
161 //echo('<pre>'); print_r($selectbox);
162 //echo('<pre>'); print_r($current);
163 $update = false;
164 if(is_array($current)) {
165 $update = true;
166 $current = array_shift($current);
167 }
168
169 echo('<form method="POST">');
170 if($multi_insert) echo('<div name="input_set" style="float:left; border:1px solid grey;">');
171 echo $this->input('table', $class, 'hidden');
172 foreach($columns as $column) {
173 echo($column['Field'].': ');
174 $name='value:'.$column['Field'].'[]';
175 switch(true) {
176 case preg_match('/auto_increment/', $column['Extra']):
177 $val = $update ? $current[$column['Field']] : ''; //opakuje se (skoro) zbytecne
178 echo $this->input($name, $val, 'hidden');
179 echo($val.'(AUTO)');
180 break;
181 case isset($selectbox[$column['Field']]):
182 $val = $update ? $current[$column['Field']] : false;
183 echo $this->select($name,$selectbox[$column['Field']],$val); //opakuje se
184 break;
185 default:
186 $val = $update ? $current[$column['Field']] : false; //opakuje se
187 echo $this->input($name, $val);
188 break;
189 }
190 echo('<br />');
191 }
192
193 if($multi_insert) {
194 //TODO, move to separate JS file
195 echo <<<EOF
196 </div>
197 <span name="input_set_next"></span><br style="clear:both" />
198 <script>
199 function duplicate_element(what, where) {
200 document.getElementsByName(where)[0].outerHTML =
201 document.getElementsByName(what)[0].outerHTML
202 + document.getElementsByName(where)[0].outerHTML;
203 }
204 </script>
205 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
206EOF;
207 }
208
209 $btn = is_array($current) ? 'UPDATE' : 'INSERT';
210 echo($this->input(false, $btn, 'submit'));
211 echo('</form>');
212 }
213}
214
215class Sklad_DB extends PDO {
216 function __construct() {
217 $this->lms = new Sklad_LMS();
218
219 parent::__construct(
220 DB_DSN, DB_USER, DB_PASS,
221 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
222 );
223 }
224
225 function escape($str) {
226 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
227 }
228
229 function build_query_select($class, $id=false, $limit=false, $offset=0, $search=false, $id_suffix='_id') {
230 $class = $this->escape($class);
231 $join = array(
232 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
233 'model' => array('category', 'producer')
234 );
235 $search_fields = array(
236 'item' => array('item_id','model_name','model_barcode','model_descript','producer_name','vendor_name')
237 );
238 $sql="SELECT * FROM $class\n";
239 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$id_suffix)\n";
240 if($search) {
241 $search = $this->quote($search);
242 if(!isset($search_fields[$class])) {
243 trigger_error("Ve tride $class zatim vyhledavat nemozno :-(");
244 die();
245 }
246 $sql .= 'WHERE FALSE ';
247 foreach($search_fields[$class] as $column) $sql .= "OR $column REGEXP $search ";
248 } elseif($id) $sql .= "WHERE $class$id_suffix = $id\n";
249 if($limit) {
250 $limit = $this->escape((int)$limit);
251 $offset = $this->escape((int)$offset);
252 $sql .= "LIMIT $offset,$limit\n";
253 }
254 return $sql;
255 }
256
257 function safe_query($sql) {
258 $result = $this->query($sql);
259 if(!$result) {
260 trigger_error('<font color=red><b>QUERY FAILED:</b><pre>'.$sql.'</pre></font>');
261 die();
262 }
263 return $result;
264 }
265
266 function get_listing($class, $id=false, $limit=false, $offset=0, $search=false, $indexed=array(), $suffix_id='_id') {
267 $sql = $this->build_query_select($class, $id, $limit, $offset, $search);
268 $result = $this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
269 if(!$result || !is_array($indexed)) return $result;
270
271 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
272 return $indexed;
273 }
274
275 function get_columns($class) {
276 $class = $this->escape($class);
277 $sql = "SHOW COLUMNS FROM $class;";
278 return $this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
279 }
280
281 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
282 $selectbox=array();
283 foreach($columns as $column) {
284 if($class && $column['Field'] == $class.$suffix_id) continue;
285 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
286 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
287 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table;";
288 $result=$this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
289 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
290 }
291 //echo('<pre>'); print_r($selectbox);
292 return $selectbox;
293 }
294
295 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
296 $table = $this->escape($table);
297
298 //Get list of POSTed columns
299 $columns = implode(',',array_map(array($this,'escape'), array_keys($values[0])));
300
301 //Insert into table (columns)
302 $sql = 'INSERT';
303 if($replace) $sql = 'REPLACE';
304 $sql .= " INTO $table ($columns) VALUES ";
305
306 //Values (a,b,c),(d,e,f)
307 $comma='';
308 foreach($values as $row) {
309 $sql .= $comma.'('.implode(',',array_map(array($this,'quote'), $row)).')';
310 $comma = ',';
311 }
312
313 //Terminate
314 $sql .= ';';
315 return $sql;
316 }
317
318 function insert_or_update($table, $values) {
319 $sql = $this->build_query_insert($table, $values);
320 $this->safe_query($sql);
321 return $this->lastInsertId();
322 }
323
324 function delete($table, $id, $suffix_id='_id') {
325 $key = $this->escape($table.$suffix_id);
326 $table = $this->escape($table);
327 $id = $this->quote($id);
328 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
329 }
330}
331
332class Sklad_UI {
333 function __construct() {
334 $this->db = new Sklad_DB();
335 $this->html = new Sklad_HTML();
336 }
337
338 function show_items($class, $id=false, $limit=false, $offset=0, $search=false) {
339 $this->html->print_item_table($this->db->get_listing($class, $id, $limit, $offset, $search));
340 }
341
342 function show_form_add($class) {
343 $columns = $this->db->get_columns($class);
344 $selectbox = $this->db->columns_get_selectbox($columns, $class);
345 $this->html->print_insert_form($class, $columns, $selectbox);
346 }
347
348 function show_form_edit($class, $id) {
349 $columns = $this->db->get_columns($class);
350 $selectbox = $this->db->columns_get_selectbox($columns, $class);
351 $current = $this->db->get_listing($class, $id);
352 $this->html->print_insert_form($class, $columns, $selectbox, $current);
353 }
354
355 function show_single_record_details($class, $id) {
356 $id_next = $id + 1;
357 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
358 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
359 echo $this->html->link('<<', "$class/$id_prev/");
360 echo '-';
361 echo $this->html->link('>>', "$class/$id_next/");
362 echo ('<br />');
363 echo $this->html->link('edit', "$class/$id/edit/");
364 }
365
366 function show_listing_navigation($class, $id, $limit, $offset) {
367 $offset_next = $offset + $limit;
368 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
369 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
370 echo $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
371 echo '-';
372 echo $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
373 echo ('<br />');
374 echo $this->html->link('new', "$class/new/$get");
375 }
376
377 function show_listing_extensions($class, $id, $limit, $offset, $edit=false) {
378 if(is_numeric($id)) {
379 $this->show_single_record_details($class, $id);
380 } else {
381 $this->show_listing_navigation($class, '*', $limit, $offset);
382 }
383 if($edit) {
384 echo('<br />TODO UPDATE FORM!<br />');
385 $this->show_form_edit($class, $id);
386 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
387 echo("<form action='$action' method='POST'>");
388 echo $this->html->input(false, 'DELETE', 'submit');
389 echo 'sure?'.$this->html->input('sure', false, 'checkbox');
390 echo('</form>');
391 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
392 echo("<form action='$action' method='POST' enctype='multipart/form-data'>");
393 echo $this->html->input('image', false, 'file', false, 'size="30"');
394 echo $this->html->input(false, 'IMAGE', 'submit');
395 echo('</form>');
396 }
397 }
398
399 function check_auth() {
400 new HTTP_Auth('SkladovejSystem', true, array($this->db->lms,'check_auth'));
401 }
402
403 function post_redirect_get($last, $next) { //TODO prepracovat, tohle je uplna picovina...
404 //header('Location: '.$_SERVER['REQUEST_URI']); //TODO redirect (need templating system or ob_start() first!!!)
405 echo 'Hotovo. Poslední vložený záznam naleznete '.$this->html->link('zde', $last).'.<br />'.
406 'Další záznam přidáte '.$this->html->link('zde', $next).'.';
407 die();
408 }
409
410 function process_http_request_post($action=false, $class=false, $id=false) {
411 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
412 echo('<pre>'); //DEBUG (maybe todo remove)
413
414 //SephirPOST:
415 $values=array();
416 foreach($_POST as $key => $value) {
417 $name = preg_split('/:/',$key);
418 if(isset($name[0])) switch($name[0]) {
419 case 'value':
420 foreach($value as $id => $val) $values[$id][$name[1]]=$value[$id];
421 break;
422 default:
423 break;
424 }
425 }
426
427 if($action) switch($action) {
428 case 'new':
429 case 'edit':
430 if(!isset($_POST['table'])) die(trigger_error("Jest nutno specifikovat tabulku voe!"));
431 $table=$_POST['table'];
432 //print_r($values); //debug
433 $last = $this->db->insert_or_update($table, $values);
434 $this->post_redirect_get("$table/$last/", "$table/new/");
435 break;
436 case 'delete':
437 if(!isset($_POST['sure']) || !$_POST['sure']) die(trigger_error('Sure user expected :-)'));
438 //$this->db->delete($class, $id);
439 die('Neco asi bylo smazano. Fnuk :\'-('); //TODO REDIRECT
440 break;
441 case 'image':
442 $image_classes = array('model'); //TODO, use this more widely across the code
443 if(!in_array($class, $image_classes)) die(trigger_error("Nekdo nechce k DB Tride '$class' prirazovat obrazky!"));
444 $image_destination = DIR_IMAGES."/$class/$id.jpg";
445 if($_FILES['image']['name'] == '') die(trigger_error('Kazde neco se musi nejak jmenovat!'));
446 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
447 chmod ($image_destination, 0664);
448 die('Obrazek se naladoval :)'); //TODO REDIRECT
449 } else die(trigger_error('Soubor se nenahral :('));
450 break;
451 default:
452 trigger_error('Nothin\' to do here my cutie :-*');
453 break;
454 }
455
456 die('POSTed pyčo!');
457 }
458
459 function process_http_request() {
460 $this->check_auth();
461
462 @ini_set('magic_quotes_gpc' , 'off');
463 if(get_magic_quotes_gpc()) {
464 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
465 }
466
467 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
468 $this->html->header_print($PATH_INFO);
469
470
471 //Sephirot:
472 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
473 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
474 switch($PATH_CHUNKS[1]) {
475 case 'test': //test
476 die('Tell me why you cry');
477 break;
478 default: //?
479 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
480 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
481 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
482 switch($PATH_CHUNKS[2]) {
483 case 'new': //?/new
484 $this->process_http_request_post($PATH_CHUNKS[2], $class);
485 $this->show_form_add($class);
486 break;
487 default: //?/?
488 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
489 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
490 $edit=false;
491 switch($PATH_CHUNKS[3]) {
492 case 'edit': //?/?/edit
493 case 'image': //?/image
494 case 'delete': //?/delete
495 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
496 $edit=true;
497 default: //?/?/?
498 $limit = (int) (isset($PATH_CHUNKS[3]) ? $PATH_CHUNKS[3] : '0');
499 $offset = (int) (isset($PATH_CHUNKS[4]) ? $PATH_CHUNKS[4] : '0');
500 $this->show_items($class, $id, $limit, $offset, $search);
501 $this->show_listing_extensions($class, $id, $limit, $offset, $edit);
502 //print_r(array("<pre>",$_SERVER));
503 break;
504 }
505 break;
506 }
507 break;
508 }
509 }
510}
511
512$sklad = new Sklad_UI();
513$sklad->process_http_request();
514
515echo("<hr/>");
This page took 0.43414 seconds and 4 git commands to generate.