Marius Cramer
2014-02-17 ebbe6374fc9c308daf729d2ad1b2f8007ed771ce
commit | author | age
5bff39 1 <?php
M 2
3 /*
4 Copyright (c) 2007, Till Brehm, projektfarm Gmbh
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without modification,
8 are permitted provided that the following conditions are met:
9
10     * Redistributions of source code must retain the above copyright notice,
11       this list of conditions and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright notice,
13       this list of conditions and the following disclaimer in the documentation
14       and/or other materials provided with the distribution.
15     * Neither the name of ISPConfig nor the names of its contributors
16       may be used to endorse or promote products derived from this software without
17       specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
26 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 /**
b1a6a5 32  * Formularbehandlung
MC 33  *
34  * Functions to validate, display and save form values
35  *
36  *        Database table field definitions
37  *
38  *        Datatypes:
39  *        - INTEGER (Converts data to int automatically)
40  *        - DOUBLE
41  *        - CURRENCY (Formats digits in currency notation)
42  *        - VARCHAR (No format check)
43  *        - DATE (Date format, converts from and to UNIX timestamps automatically)
44  *
45  *        Formtype:
46  *        - TEXT (Normal text field)
47  *        - PASSWORD (password field, the content will not be displayed again to the user)
48  *        - SELECT (Option fiield)
49  *        - MULTIPLE (Allows selection of multiple values)
50  *
51  *        VALUE:
52  *        - Value or array
53  *
54  *        SEPARATOR
55  *        - separator char used for fileds with multiple values
56  *
57  *        Hint: The auto increment (ID) filed of the table has not be be definied separately.
58  *
59  */
60
5bff39 61
M 62 class tform_base {
63
b1a6a5 64     /**
MC 65      * Definition of the database table (array)
66      * @var tableDef
67      */
68     var $tableDef;
5bff39 69
b1a6a5 70     /**
MC 71      * Private
72      * @var action
73      */
74     var $action;
5bff39 75
b1a6a5 76     /**
MC 77      * Table name (String)
78      * @var table_name
79      */
80     var $table_name;
5bff39 81
b1a6a5 82     /**
MC 83      * Debug Variable
84      * @var debug
85      */
86     var $debug = 0;
5bff39 87
b1a6a5 88     /**
MC 89      * name of the primary field of the database table (string)
90      * @var table_index
91      */
92     var $table_index;
5bff39 93
b1a6a5 94     /**
MC 95      * contains the error messages
96      * @var errorMessage
97      */
98     var $errorMessage = '';
5bff39 99
b1a6a5 100     var $dateformat = "d.m.Y";
MC 101     var $formDef = array();
102     var $wordbook;
103     var $module;
104     var $primary_id;
105     var $diffrec = array();
5bff39 106
b1a6a5 107     /**
MC 108      * Loading of the table definition
109      *
110      * @param file: path to the form definition file
111      * @return true
112      */
113     /*
5bff39 114         function loadTableDef($file) {
M 115                 global $app,$conf;
116
117                 include_once($file);
118                 $this->tableDef = $table;
119                 $this->table_name = $table_name;
120                 $this->table_index = $table_index;
121                 return true;
122         }
123         */
124
b1a6a5 125     function loadFormDef($file, $module = '') {
MC 126         global $app, $conf;
5bff39 127
b1a6a5 128         include $file;
MC 129         $this->formDef = $form;
5bff39 130
b1a6a5 131         $this->module = $module;
MC 132         $wb = array();
5bff39 133
b1a6a5 134         include_once ISPC_ROOT_PATH.'/lib/lang/'.$_SESSION['s']['language'].'.lng';
5bff39 135
b1a6a5 136         if(is_array($wb)) $wb_global = $wb;
5bff39 137
b1a6a5 138         if($module == '') {
MC 139             $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
140             if(!file_exists($lng_file)) $lng_file = "lib/lang/en_".$this->formDef["name"].".lng";
141             include $lng_file;
142         } else {
143             $lng_file = "../$module/lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
144             if(!file_exists($lng_file)) $lng_file = "../$module/lib/lang/en_".$this->formDef["name"].".lng";
145             include $lng_file;
5bff39 146         }
M 147
b1a6a5 148         if(is_array($wb_global)) {
MC 149             $wb = $app->functions->array_merge($wb_global, $wb);
150         }
151         if(isset($wb_global)) unset($wb_global);
152
153         $this->wordbook = $wb;
154
155         $this->dateformat = $app->lng('conf_format_dateshort');
156
157         return true;
158     }
159
160     /*
5bff39 161         * Converts the data in the array to human readable format
M 162         * Datatype conversion e.g. to show the data in lists
163         *
164         * @param record
165         * @param tab
166         * @param apply_filters
167         * @return record
168         */
b1a6a5 169     protected function _decode($record, $tab = '', $api = false) {
MC 170         global $app;
171         $new_record = '';
172         if($api == false) {
173             $table_idx = $this->formDef['db_table_idx'];
174             if(isset($record[$table_idx])) $new_record[$table_idx] = $app->functions->intval($record[$table_idx ]);
175             $fields = &$this->formDef['tabs'][$tab]['fields'];
176         } else {
177             $fields = &$this->formDef['fields'];
178         }
179
180         if(is_array($record)) {
181             foreach($fields as $key => $field) {
182
183                 //* Apply filter to record value.
184                 if($api == false && isset($field['filters']) && is_array($field['filters'])) {
185                     $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SHOW');
5bff39 186                 }
M 187
b1a6a5 188                 switch ($field['datatype']) {
MC 189                 case 'VARCHAR':
190                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
191                     break;
5bff39 192
b1a6a5 193                 case 'TEXT':
MC 194                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
195                     break;
5bff39 196
b1a6a5 197                 case 'DATETSTAMP':
MC 198                     if($record[$key] > 0) {
199                         $new_record[$key] = date($this->dateformat, $record[$key]);
200                     }
201                     break;
5bff39 202
b1a6a5 203                 case 'DATE':
MC 204                     if($record[$key] != '' && $record[$key] != '0000-00-00') {
205                         $tmp = explode('-', $record[$key]);
206                         $new_record[$key] = date($this->dateformat, mktime(0, 0, 0, $tmp[1]  , $tmp[2], $tmp[0]));
207                     }
208                     break;
5bff39 209
b1a6a5 210                 case 'INTEGER':
MC 211                     $new_record[$key] = $app->functions->intval($record[$key]);
212                     break;
5bff39 213
b1a6a5 214                 case 'DOUBLE':
MC 215                     $new_record[$key] = $record[$key];
216                     break;
5bff39 217
b1a6a5 218                 case 'CURRENCY':
MC 219                     $new_record[$key] = $app->functions->currency_format($record[$key]);
220                     break;
5bff39 221
b1a6a5 222                 default:
MC 223                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
5bff39 224                 }
b1a6a5 225             }
MC 226
227         }
5bff39 228
M 229         return $new_record;
b1a6a5 230     }
MC 231
232
233     /**
234      * Converts the data in the array to human readable format
235      * Datatype conversion e.g. to show the data in lists
236      *
237      * @param record
238      * @return record
239      */
240     function decode($record, $tab) {
241         global $conf, $app;
242         if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab does not exist or the tab is empty (TAB: $tab).");
243         return $this->_decode($record, $tab, false);
244     }
245
246     /**
247      * Get the key => value array of a form filled from a datasource definitiom
248      *
249      * @param field = array with field definition
250      * @param record = Dataset as array
251      * @return key => value array for the value field of a form
252      */
253     protected function _getDatasourceData($field, $record, $api = false) {
254         global $app;
255
256         $values = array();
257
258         if($field["datasource"]["type"] == 'SQL') {
259
260             // Preparing SQL string. We will replace some
261             // common placeholders
262             $querystring = $field["datasource"]["querystring"];
263             $querystring = str_replace("{USERID}", $_SESSION["s"]["user"]["userid"], $querystring);
264             $querystring = str_replace("{GROUPID}", $_SESSION["s"]["user"]["default_group"], $querystring);
265             $querystring = str_replace("{GROUPS}", $_SESSION["s"]["user"]["groups"], $querystring);
266             $table_idx = $this->formDef['db_table_idx'];
267
268             $tmp_recordid = (isset($record[$table_idx]))?$record[$table_idx]:0;
269             $querystring = str_replace("{RECORDID}", $tmp_recordid, $querystring);
270             unset($tmp_recordid);
271
272             $querystring = str_replace("{AUTHSQL}", $this->getAuthSQL('r'), $querystring);
b52e4f 273             $querystring = preg_replace_callback('@{AUTHSQL::(.+?)}@', "self::table_auth_sql", $querystring);
b1a6a5 274
MC 275             // Getting the records
276             $tmp_records = $app->db->queryAllRecords($querystring);
277             if($app->db->errorMessage != '') die($app->db->errorMessage);
278             if(is_array($tmp_records)) {
279                 $key_field = $field["datasource"]["keyfield"];
280                 $value_field = $field["datasource"]["valuefield"];
281                 foreach($tmp_records as $tmp_rec) {
282                     $tmp_id = $tmp_rec[$key_field];
283                     $values[$tmp_id] = $tmp_rec[$value_field];
284                 }
285             }
5bff39 286         }
M 287
b1a6a5 288         if($field["datasource"]["type"] == 'CUSTOM') {
MC 289             // Calls a custom class to validate this record
290             if($field["datasource"]['class'] != '' and $field["datasource"]['function'] != '') {
291                 $datasource_class = $field["datasource"]['class'];
292                 $datasource_function = $field["datasource"]['function'];
293                 $app->uses($datasource_class);
294                 $values = $app->$datasource_class->$datasource_function($field, $record);
295             } else {
296                 $this->errorMessage .= "Custom datasource class or function is empty<br />\r\n";
297             }
5bff39 298         }
M 299
b1a6a5 300         if($api == false && isset($field['filters']) && is_array($field['filters'])) {
MC 301             $new_values = array();
302             foreach($values as $index => $value) {
303                 $new_index = $this->filterField($index, $index, $field['filters'], 'SHOW');
304                 $new_values[$new_index] = $this->filterField($index, (isset($values[$index]))?$values[$index]:'', $field['filters'], 'SHOW');
305             }
306             $values = $new_values;
307             unset($new_values);
308             unset($new_index);
309         }
5bff39 310
b1a6a5 311         return $values;
5bff39 312
b1a6a5 313     }
5bff39 314
M 315
b1a6a5 316     /**
MC 317      * Get the key => value array of a form filled from a datasource definitiom
318      *
319      * @param field = array with field definition
320      * @param record = Dataset as array
321      * @return key => value array for the value field of a form
322      */
323     function getDatasourceData($field, $record) {
324         return $this->_getDatasourceData($field, $record, false);
325     }
5bff39 326
b1a6a5 327     //* If the parameter 'valuelimit' is set
MC 328     function applyValueLimit($limit, $values) {
5bff39 329
b1a6a5 330         global $app;
5bff39 331
b1a6a5 332         $limit_parts = explode(':', $limit);
5bff39 333
b1a6a5 334         //* values are limited to a comma separated list
MC 335         if($limit_parts[0] == 'list') {
336             $allowed = explode(',', $limit_parts[1]);
337         }
5bff39 338
b1a6a5 339         //* values are limited to a field in the client settings
MC 340         if($limit_parts[0] == 'client') {
341             if($_SESSION["s"]["user"]["typ"] == 'admin') {
5bff39 342                 return $values;
b1a6a5 343             } else {
MC 344                 $client_group_id = $_SESSION["s"]["user"]["default_group"];
345                 $client = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id");
346                 $allowed = explode(',', $client['lm']);
347             }
5bff39 348         }
M 349
b1a6a5 350         //* values are limited to a field in the reseller settings
MC 351         if($limit_parts[0] == 'reseller') {
352             if($_SESSION["s"]["user"]["typ"] == 'admin') {
353                 return $values;
354             } else {
355                 //* Get the limits of the client that is currently logged in
356                 $client_group_id = $_SESSION["s"]["user"]["default_group"];
357                 $client = $app->db->queryOneRecord("SELECT parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id");
358                 //echo "SELECT parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id";
359                 //* If the client belongs to a reseller, we will check against the reseller Limit too
360                 if($client['parent_client_id'] != 0) {
5bff39 361
b1a6a5 362                     //* first we need to know the groups of this reseller
MC 363                     $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ".$client['parent_client_id']);
364                     $reseller_groups = $tmp["groups"];
365                     $reseller_userid = $tmp["userid"];
5bff39 366
b1a6a5 367                     // Get the limits of the reseller of the logged in client
5bff39 368                     $client_group_id = $_SESSION["s"]["user"]["default_group"];
b1a6a5 369                     $reseller = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM client WHERE client_id = ".$client['parent_client_id']);
MC 370                     $allowed = explode(',', $reseller['lm']);
371                 } else {
372                     return $values;
5bff39 373                 }
b1a6a5 374             } // end if admin
MC 375         } // end if reseller
5bff39 376
b1a6a5 377         //* values are limited to a field in the system settings
MC 378         if($limit_parts[0] == 'system') {
379             $app->uses('getconf');
380             $tmp_conf = $app->getconf->get_global_config($limit_parts[1]);
381             $tmp_key = $limit_parts[2];
382             $allowed = $tmp_conf[$tmp_key];
383         }
5bff39 384
b1a6a5 385         $values_new = array();
MC 386         foreach($values as $key => $val) {
387             if(in_array($key, $allowed)) $values_new[$key] = $val;
388         }
5bff39 389
b1a6a5 390         return $values_new;
MC 391     }
392
393
394     /**
395      * Prepare the data record to show the data in a form.
396      *
397      * @param record = Datensatz als Array
398      * @param action = NEW oder EDIT
399      * @return record
400      */
401     function getHTML($record, $tab, $action = 'NEW') {
402
403         global $app;
404
405         $this->action = $action;
406
407         if(!is_array($this->formDef)) $app->error("No form definition found.");
408         if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
409
410         $new_record = array();
411         if($action == 'EDIT') {
412             $record = $this->decode($record, $tab);
413             if(is_array($record)) {
414                 foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
415
416                     if(isset($record[$key])) {
417                         $val = $record[$key];
5bff39 418                     } else {
b1a6a5 419                         $val = '';
5bff39 420                     }
M 421
b1a6a5 422                     // If Datasource is set, get the data from there
MC 423                     if(isset($field['datasource']) && is_array($field['datasource'])) {
424                         if(is_array($field["value"])) {
425                             //$field["value"] = array_merge($field["value"],$this->getDatasourceData($field, $record));
426                             $field["value"] = $app->functions->array_merge($field["value"], $this->getDatasourceData($field, $record));
427                         } else {
428                             $field["value"] = $this->getDatasourceData($field, $record);
5bff39 429                         }
M 430                     }
431
b1a6a5 432                     // If a limitation for the values is set
MC 433                     if(isset($field['valuelimit']) && is_array($field["value"])) {
434                         $field["value"] = $this->applyValueLimit($field['valuelimit'], $field["value"]);
435                     }
5bff39 436
b1a6a5 437                     switch ($field['formtype']) {
MC 438                     case 'SELECT':
439                         $out = '';
440                         if(is_array($field['value'])) {
441                             foreach($field['value'] as $k => $v) {
442                                 $selected = ($k == $val)?' SELECTED':'';
443                                 if(!empty($this->wordbook[$v]))
444                                     $v = $this->wordbook[$v];
445                                 $out .= "<option value='$k'$selected>".$this->lng($v)."</option>\r\n";
5bff39 446                             }
b1a6a5 447                         }
MC 448                         $new_record[$key] = $out;
449                         break;
450                     case 'MULTIPLE':
451                         if(is_array($field['value'])) {
452
453                             // Split
454                             $vals = explode($field['separator'], $val);
455
456                             // write HTML
457                             $out = '';
458                             foreach($field['value'] as $k => $v) {
459
460                                 $selected = '';
461                                 foreach($vals as $tvl) {
462                                     if(trim($tvl) == trim($k)) $selected = ' SELECTED';
463                                 }
464
465                                 $out .= "<option value='$k'$selected>$v</option>\r\n";
466                             }
467                         }
468                         $new_record[$key] = $out;
469                         break;
470
471                     case 'PASSWORD':
472                         $new_record[$key] = '';
473                         break;
474
475                     case 'CHECKBOX':
476                         $checked = ($val == $field['value'][1])?' CHECKED':'';
477                         $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n";
478                         break;
479
480                     case 'CHECKBOXARRAY':
481                         if(is_array($field['value'])) {
482
483                             // aufsplitten ergebnisse
484                             $vals = explode($field['separator'], $val);
485
486                             // HTML schreiben
487                             $out = '';
488                             $elementNo = 0;
489                             foreach($field['value'] as $k => $v) {
490
491                                 $checked = '';
492                                 foreach($vals as $tvl) {
493                                     if(trim($tvl) == trim($k)) $checked = ' CHECKED';
494                                 }
495                                 // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
496                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label><br/>\r\n";
497                                 $elementNo++;
498                             }
499                         }
500                         $new_record[$key] = $out;
501                         break;
502
503                     case 'RADIO':
504                         if(is_array($field['value'])) {
505
506                             // HTML schreiben
507                             $out = '';
508                             $elementNo = 0;
509                             foreach($field['value'] as $k => $v) {
510                                 $checked = ($k == $val)?' CHECKED':'';
511                                 //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
512                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v </label>\r\n";
513                                 $elementNo++;
514                             }
515                         }
516                         $new_record[$key] = $out;
517                         break;
518
519                     case 'DATETIME':
520                         if (strtotime($val) !== false) {
521                             $dt_value = $val;
522                         } elseif ( isset($field['default']) && (strtotime($field['default']) !== false) ) {
523                             $dt_value = $field['default'];
524                         } else {
525                             $dt_value = 0;
526                         }
527
528                         $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
529
530                         $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
531                         break;
532
533                     default:
534                         if(isset($record[$key])) {
535                             $new_record[$key] = htmlspecialchars($record[$key]);
536                         } else {
537                             $new_record[$key] = '';
538                         }
539                     }
540                 }
541             }
542         } else {
543             // Action: NEW
544             foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
545
546                 // If Datasource is set, get the data from there
547                 if(@is_array($field['datasource'])) {
548                     if(is_array($field["value"])) {
549                         $field["value"] = $app->functions->array_merge($field["value"], $this->getDatasourceData($field, $record));
5bff39 550                     } else {
b1a6a5 551                         $field["value"] = $this->getDatasourceData($field, $record);
5bff39 552                     }
b1a6a5 553                 }
MC 554
555                 // If a limitation for the values is set
556                 if(isset($field['valuelimit']) && is_array($field["value"])) {
557                     $field["value"] = $this->applyValueLimit($field['valuelimit'], $field["value"]);
558                 }
559
560                 switch ($field['formtype']) {
561                 case 'SELECT':
562                     if(is_array($field['value'])) {
563                         $out = '';
564                         foreach($field['value'] as $k => $v) {
565                             $selected = ($k == $field["default"])?' SELECTED':'';
566                             $out .= "<option value='$k'$selected>".$this->lng($v)."</option>\r\n";
567                         }
5bff39 568                     }
b1a6a5 569                     if(isset($out)) $new_record[$key] = $out;
MC 570                     break;
571                 case 'MULTIPLE':
572                     if(is_array($field['value'])) {
573
574                         // aufsplitten ergebnisse
575                         $vals = explode($field['separator'], $val);
576
577                         // HTML schreiben
578                         $out = '';
579                         foreach($field['value'] as $k => $v) {
580
581                             $out .= "<option value='$k'>$v</option>\r\n";
582                         }
5bff39 583                     }
b1a6a5 584                     $new_record[$key] = $out;
MC 585                     break;
586
587                 case 'PASSWORD':
588                     //$new_record[$key] = '';
589                     $new_record[$key] = htmlspecialchars($field['default']);
590                     break;
591
592                 case 'CHECKBOX':
593                     // $checked = (empty($field["default"]))?'':' CHECKED';
594                     $checked = ($field["default"] == $field['value'][1])?' CHECKED':'';
595                     $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n";
596                     break;
597
598                 case 'CHECKBOXARRAY':
599                     if(is_array($field['value'])) {
600
601                         // aufsplitten ergebnisse
602                         $vals = explode($field['separator'], $field["default"]);
603
604                         // HTML schreiben
605                         $out = '';
606                         $elementNo = 0;
607                         foreach($field['value'] as $k => $v) {
608
609                             $checked = '';
610                             foreach($vals as $tvl) {
611                                 if(trim($tvl) == trim($k)) $checked = ' CHECKED';
612                             }
613                             // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
614                             $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label> &nbsp;\r\n";
615                             $elementNo++;
616                         }
5bff39 617                     }
b1a6a5 618                     $new_record[$key] = $out;
MC 619                     break;
620
621                 case 'RADIO':
622                     if(is_array($field['value'])) {
623
624                         // HTML schreiben
625                         $out = '';
626                         $elementNo = 0;
627                         foreach($field['value'] as $k => $v) {
628                             $checked = ($k == $field["default"])?' CHECKED':'';
629                             //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
630                             $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
631                             $elementNo++;
632                         }
5bff39 633                     }
b1a6a5 634                     $new_record[$key] = $out;
MC 635                     break;
636
637                 case 'DATETIME':
638                     $dt_value = (isset($field['default'])) ? $field['default'] : 0;
639                     $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
640
641                     $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
642                     break;
643
644                 default:
645                     $new_record[$key] = htmlspecialchars($field['default']);
646                 }
647             }
648
649         }
650
651         if($this->debug == 1) $this->dbg($new_record);
652
653         return $new_record;
654     }
655
656     /**
657      * Rewrite the record data to be stored in the database
658      * and check values with regular expressions.
659      *
660      * @param record = Datensatz als Array
661      * @return record
662      */
663     protected function _encode($record, $tab, $dbencode = true, $api = false) {
664         global $app;
665         if($api == true) $fields = &$this->formDef['fields'];
666         else $fields = &$this->formDef['tabs'][$tab]['fields'];
667         if(is_array($record)) {
668             foreach($fields as $key => $field) {
669
670                 //* Apply filter to record value
671                 if(isset($field['filters']) && is_array($field['filters'])) {
672                     $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SAVE');
673                 }
674                 //* Validate record value
675                 if(isset($field['validators']) && is_array($field['validators'])) {
676                     $this->validateField($key, (isset($record[$key]))?$record[$key]:'', $field['validators']);
677                 }
678
679                 switch ($field['datatype']) {
680                 case 'VARCHAR':
681                     if(!@is_array($record[$key])) {
682                         $new_record[$key] = (isset($record[$key]))?$record[$key]:'';
683                     } else {
684                         $new_record[$key] = implode($field['separator'], $record[$key]);
685                     }
686                     break;
687                 case 'TEXT':
688                     if(!is_array($record[$key])) {
689                         $new_record[$key] = $record[$key];
690                     } else {
691                         $new_record[$key] = implode($field['separator'], $record[$key]);
692                     }
693                     break;
694                 case 'DATETSTAMP':
695                     if($record[$key] > 0) {
696                         list($tag, $monat, $jahr) = explode('.', $record[$key]);
697                         $new_record[$key] = mktime(0, 0, 0, $monat, $tag, $jahr);
698                     } else {
699                         $new_record[$key] = 0;
700                     }
701                     break;
702                 case 'DATE':
703                     if($record[$key] != '' && $record[$key] != '0000-00-00') {
704                         if(function_exists('date_parse_from_format')) {
705                             $date_parts = date_parse_from_format($this->dateformat, $record[$key]);
706                             //list($tag,$monat,$jahr) = explode('.',$record[$key]);
707                             $new_record[$key] = $date_parts['year'].'-'.$date_parts['month'].'-'.$date_parts['day'];
708                             //$tmp = strptime($record[$key],$this->dateformat);
709                             //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday'];
710                         } else {
711                             //$tmp = strptime($record[$key],$this->dateformat);
712                             //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday'];
713                             $tmp = strtotime($record[$key]);
714                             $new_record[$key] = date('Y-m-d', $tmp);
715                         }
716                     } else {
717                         $new_record[$key] = '0000-00-00';
718                     }
719                     break;
720                 case 'INTEGER':
721                     $new_record[$key] = (isset($record[$key]))?$app->functions->intval($record[$key]):0;
722                     //if($new_record[$key] != $record[$key]) $new_record[$key] = $field['default'];
723                     //if($key == 'refresh') die($record[$key]);
724                     break;
725                 case 'DOUBLE':
726                     $new_record[$key] = $record[$key];
727                     break;
728                 case 'CURRENCY':
729                     $new_record[$key] = str_replace(",", ".", $record[$key]);
730                     break;
731
732                 case 'DATETIME':
733                     if (is_array($record[$key]))
734                     {
735                         $filtered_values = array_map(create_function('$item', 'return (int)$item;'), $record[$key]);
736                         extract($filtered_values, EXTR_PREFIX_ALL, '_dt');
737
738                         if ($_dt_day != 0 && $_dt_month != 0 && $_dt_year != 0) {
739                             $new_record[$key] = date( 'Y-m-d H:i:s', mktime($_dt_hour, $_dt_minute, $_dt_second, $_dt_month, $_dt_day, $_dt_year) );
740                         }
741                     }
742                     break;
743                 }
744
745                 // The use of the field value is deprecated, use validators instead
746                 if(isset($field['regex']) && $field['regex'] != '') {
747                     // Enable that "." matches also newlines
748                     $field['regex'] .= 's';
749                     if(!preg_match($field['regex'], $record[$key])) {
750                         $errmsg = $field['errmsg'];
751                         $this->errorMessage .= ($api == true ? $errmsg : $this->wordbook[$errmsg]."<br />") . "\r\n";
752                     }
753                 }
754
755                 //* Add slashes to all records, when we encode data which shall be inserted into mysql.
756                 if($dbencode == true) $new_record[$key] = $app->db->quote($new_record[$key]);
757             }
758         }
759         return $new_record;
760     }
761
762
763     /**
764      * Rewrite the record data to be stored in the database
765      * and check values with regular expressions.
766      *
767      * @param record = Datensatz als Array
768      * @return record
769      */
770     function encode($record, $tab, $dbencode = true) {
771         global $app;
772
773         if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab is empty or does not exist (TAB: $tab).");
774         return $this->_encode($record, $tab, $dbencode, false);
775     }
776
777
778     /**
779      * process the filters for a given field.
780      *
781      * @param field_name = Name of the field
782      * @param field_value = value of the field
783      * @param filters = Array of filters
784      * @param filter_event = 'SAVE'or 'SHOW'
785      * @return record
786      */
787     function filterField($field_name, $field_value, $filters, $filter_event) {
788
789         global $app;
790         $returnval = $field_value;
791
792         //* Loop trough all filters
793         foreach($filters as $filter) {
794             if($filter['event'] == $filter_event) {
795                 switch ($filter['type']) {
796                 case 'TOLOWER':
797                     $returnval = strtolower($returnval);
798                     break;
799                 case 'TOUPPER':
800                     $returnval = strtoupper($returnval);
801                     break;
802                 case 'IDNTOASCII':
803                     $returnval = $app->functions->idn_encode($returnval);
804                     break;
805                 case 'IDNTOUTF8':
806                     $returnval = $app->functions->idn_decode($returnval);
807                     break;
808                 default:
809                     $this->errorMessage .= "Unknown Filter: ".$filter['type'];
810                     break;
811                 }
812             }
813         }
814         return $returnval;
815     }
816
817
818     /**
819      * process the validators for a given field.
820      *
821      * @param field_name = Name of the field
822      * @param field_value = value of the field
823      * @param validatoors = Array of validators
824      * @return record
825      */
826     function validateField($field_name, $field_value, $validators) {
827
828         global $app;
829
830         $escape = '`';
831
832         // loop trough the validators
833         foreach($validators as $validator) {
834
835             switch ($validator['type']) {
836             case 'REGEX':
837                 $validator['regex'] .= 's';
838                 if(!preg_match($validator['regex'], $field_value)) {
839                     $errmsg = $validator['errmsg'];
840                     if(isset($this->wordbook[$errmsg])) {
841                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
842                     } else {
5bff39 843                         $this->errorMessage .= $errmsg."<br />\r\n";
M 844                     }
b1a6a5 845                 }
5bff39 846                 break;
b1a6a5 847             case 'UNIQUE':
MC 848                 if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n';
849                 if($validator['allowempty'] == 'n' || ($validator['allowempty'] == 'y' && $field_value != '')){
850                     if($this->action == 'NEW') {
851                         $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."'");
852                         if($num_rec["number"] > 0) {
853                             $errmsg = $validator['errmsg'];
854                             if(isset($this->wordbook[$errmsg])) {
855                                 $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
856                             } else {
857                                 $this->errorMessage .= $errmsg."<br />\r\n";
858                             }
5bff39 859                         }
M 860                     } else {
b1a6a5 861                         $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."' AND ".$this->formDef['db_table_idx']." != ".$this->primary_id);
MC 862                         if($num_rec["number"] > 0) {
863                             $errmsg = $validator['errmsg'];
864                             if(isset($this->wordbook[$errmsg])) {
865                                 $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
866                             } else {
867                                 $this->errorMessage .= $errmsg."<br />\r\n";
868                             }
5bff39 869                         }
M 870                     }
871                 }
b1a6a5 872                 break;
MC 873             case 'NOTEMPTY':
874                 if(empty($field_value)) {
875                     $errmsg = $validator['errmsg'];
876                     if(isset($this->wordbook[$errmsg])) {
877                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
878                     } else {
879                         $this->errorMessage .= $errmsg."<br />\r\n";
880                     }
881                 }
882                 break;
bd8b72 883             case 'ISASCII':
MC 884                 if(preg_match("/[^\x20-\x7F]/", $field_value)) {
885                     $errmsg = $validator['errmsg'];
886                     if(isset($this->wordbook[$errmsg])) {
887                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
888                     } else {
889                         $this->errorMessage .= $errmsg."<br />\r\n";
890                     }
891                 }
b1a6a5 892             case 'ISEMAIL':
MC 893                 if(function_exists('filter_var')) {
894                     if(filter_var($field_value, FILTER_VALIDATE_EMAIL) === false) {
895                         $errmsg = $validator['errmsg'];
896                         if(isset($this->wordbook[$errmsg])) {
897                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
5bff39 898                         } else {
b1a6a5 899                             $this->errorMessage .= $errmsg."<br />\r\n";
5bff39 900                         }
b1a6a5 901                     }
MC 902                 } else {
903                     if(!preg_match("/^\w+[\w\.\-\+]*\w{0,}@\w+[\w.-]*\w+\.[a-zA-Z0-9\-]{2,30}$/i", $field_value)) {
904                         $errmsg = $validator['errmsg'];
905                         if(isset($this->wordbook[$errmsg])) {
906                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
907                         } else {
908                             $this->errorMessage .= $errmsg."<br />\r\n";
909                         }
910                     }
5bff39 911                 }
b1a6a5 912                 break;
MC 913             case 'ISINT':
914                 if(function_exists('filter_var') && $field_value < 2147483647) {
915                     if($field_value != '' && filter_var($field_value, FILTER_VALIDATE_INT) === false) {
916                         $errmsg = $validator['errmsg'];
917                         if(isset($this->wordbook[$errmsg])) {
918                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
919                         } else {
920                             $this->errorMessage .= $errmsg."<br />\r\n";
921                         }
922                     }
923                 } else {
924                     $tmpval = $app->functions->intval($field_value);
925                     if($tmpval === 0 and !empty($field_value)) {
926                         $errmsg = $validator['errmsg'];
927                         if(isset($this->wordbook[$errmsg])) {
928                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
929                         } else {
930                             $this->errorMessage .= $errmsg."<br />\r\n";
931                         }
932                     }
933                 }
934                 break;
935             case 'ISPOSITIVE':
936                 if(!is_numeric($field_value) || $field_value <= 0){
937                     $errmsg = $validator['errmsg'];
938                     if(isset($this->wordbook[$errmsg])) {
939                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
940                     } else {
941                         $this->errorMessage .= $errmsg."<br />\r\n";
942                     }
943                 }
944                 break;
fbeb11 945             case 'V6PREFIXEND':
FS 946                 $explode_field_value = explode(':',$field_value);
947 //                if ($explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]=='' ){ }
948                 if (!$explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]!='' ) {
949                     $errmsg = $validator['errmsg'];
950                     if(isset($this->wordbook[$errmsg])) {
951                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
952                     } else {
953                         $this->errorMessage .= $errmsg."<br />\r\n";
954                     }
955                 }
956                 break;
957             case 'V6PREFIXLENGTH':
958                 // find shortes ipv6 subnet can`t be longer
959                 $sql_v6 = $app->db->queryOneRecord("SELECT ip_address FROM server_ip WHERE ip_type = 'IPv6' AND virtualhost = 'y' ORDER BY CHAR_LENGTH(ip_address) ASC LIMIT 0,1;");
960                 $sql_v6_explode=explode(':',$sql_v6['ip_address']);
961                 $explode_field_value = explode(':',$field_value);
962                 if (count($sql_v6_explode) < count($explode_field_value) && isset($sql_v6['ip_address'])) {
963                     $errmsg = $validator['errmsg'];
964                     if(isset($this->wordbook[$errmsg])) {
965                         $this->errorMessage .= $this->wordbook[$errmsg].$sql_v6[ip_address]."<br />\r\n";
966                     } else {
967                         $this->errorMessage .= $errmsg."<br />\r\n";
968                     }
969                 }
970                 break;
b1a6a5 971             case 'ISV6PREFIX':
fbeb11 972                 $v6_prefix_ok=0;
FS 973                 $explode_field_value = explode(':',$field_value);
b1a6a5 974                 if ($explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]=='' ){
MC 975                     if ( count($explode_field_value) <= 9 ) {
fbeb11 976                         if (filter_var(substr($field_value,0,strlen($field_value)-2),FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) or filter_var(substr($field_value,0,strlen($field_value)-2).'::0',FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) or filter_var(substr($field_value,0,strlen($field_value)-2).':0',FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) ) {
b1a6a5 977                             $v6_prefix_ok = 1;
MC 978                         }
979                     }
980                 }
fbeb11 981                 if($v6_prefix_ok <> 1) {
b1a6a5 982                     $errmsg = $validator['errmsg'];
fbeb11 983                     if(isset($this->wordbook[$errmsg])) {
FS 984                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
985                     } else {
986                         $this->errorMessage .= $errmsg."<br />\r\n";
987                     }
b1a6a5 988                 }
MC 989                 break;
fbeb11 990
FS 991
992
b1a6a5 993             case 'ISIPV4':
MC 994                 $vip=1;
995                 if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
996                     $groups=explode(".", $field_value);
997                     foreach($groups as $group){
998                         if($group<0 or $group>255)
999                             $vip=0;
1000                     }
1001                 }else{$vip=0;}
1002                 if($vip==0) {
1003                     $errmsg = $validator['errmsg'];
1004                     if(isset($this->wordbook[$errmsg])) {
1005                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1006                     } else {
1007                         $this->errorMessage .= $errmsg."<br />\r\n";
1008                     }
1009                 }
1010                 break;
1011             case 'ISIP':
1012                 if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n';
1013                 if($validator['allowempty'] == 'y' && $field_value == '') {
1014                     //* Do nothing
1015                 } else {
1016                     //* Check if its a IPv4 or IPv6 address
1017                     if(isset($validator['separator']) && $validator['separator'] != '') {
1018                         //* When the field may contain several IP addresses, split them by the char defined as separator
1019                         $field_value_array = explode($validator['separator'], $field_value);
1020                     } else {
1021                         $field_value_array[] = $field_value;
1022                     }
1023                     foreach($field_value_array as $field_value) {
1024                         $field_value = trim($field_value);
1025                         if(function_exists('filter_var')) {
1026                             if(!filter_var($field_value, FILTER_VALIDATE_IP)) {
1027                                 $errmsg = $validator['errmsg'];
1028                                 if(isset($this->wordbook[$errmsg])) {
1029                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1030                                 } else {
1031                                     $this->errorMessage .= $errmsg."<br />\r\n";
1032                                 }
1033                             }
1034                         } else {
1035                             //* Check content with regex, if we use php < 5.2
1036                             $ip_ok = 0;
1037                             if(preg_match("/^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i", $field_value)){
1038                                 $ip_ok = 1;
1039                             }
1040                             if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
1041                                 $ip_ok = 1;
1042                             }
1043                             if($ip_ok == 0) {
1044                                 $errmsg = $validator['errmsg'];
1045                                 if(isset($this->wordbook[$errmsg])) {
1046                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1047                                 } else {
1048                                     $this->errorMessage .= $errmsg."<br />\r\n";
1049                                 }
1050                             }
1051                         }
1052                     }
1053                 }
1054                 break;
1055             case 'RANGE':
1056                 //* Checks if the value is within the given range or above / below a value
1057                 //* Range examples: < 10 = ":10", between 2 and 10 = "2:10", above 5 = "5:".
1058                 $range_parts = explode(':', trim($validator['range']));
1059                 $ok = true;
1060                 if($range_parts[0] != '' && $field_value < $range_parts[0]) {
1061                     $ok = false;
1062                 }
1063                 if($range_parts[1] != '' && $field_value > $range_parts[1]) {
1064                     $ok = false;
1065                 }
1066                 if($ok != true) {
1067                     $errmsg = $validator['errmsg'];
1068                     if(isset($this->wordbook[$errmsg])) {
1069                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1070                     } else {
1071                         $this->errorMessage .= $errmsg."<br />\r\n";
1072                     }
1073                 }
1074                 unset($range_parts);
1075                 break;
1076             case 'CUSTOM':
1077                 // Calls a custom class to validate this record
1078                 if($validator['class'] != '' and $validator['function'] != '') {
1079                     $validator_class = $validator['class'];
1080                     $validator_function = $validator['function'];
1081                     $app->uses($validator_class);
1082                     $this->errorMessage .= $app->$validator_class->$validator_function($field_name, $field_value, $validator);
1083                 } else {
1084                     $this->errorMessage .= "Custom validator class or function is empty<br />\r\n";
1085                 }
1086                 break;
1087             default:
1088                 $this->errorMessage .= "Unknown Validator: ".$validator['type'];
1089                 break;
1090             }
5bff39 1091
M 1092
1093         }
b1a6a5 1094
MC 1095         return true;
1096     }
1097
1098     /**
1099      * Create SQL statement
1100      *
1101      * @param record = Datensatz als Array
1102      * @param action = INSERT oder UPDATE
1103      * @param primary_id
1104      * @return record
1105      */
1106     protected function _getSQL($record, $tab, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '', $api = false) {
1107
1108         global $app;
1109
1110         $this->action = $action;
1111         $this->primary_id = $primary_id;
1112
1113
1114         $record = $this->encode($record, $tab, true);
1115         $sql_insert_key = '';
1116         $sql_insert_val = '';
1117         $sql_update = '';
1118
1119         if($api == true) $fields = &$this->formDef['fields'];
1120         else $fields = &$this->formDef['tabs'][$tab]['fields'];
1121
1122         // go trough all fields of the tab
1123         if(is_array($record)) {
1124             foreach($fields as $key => $field) {
1125                 // Wenn es kein leeres Passwortfeld ist
1126                 if (!($field['formtype'] == 'PASSWORD' and $record[$key] == '')) {
1127                     // Erzeuge Insert oder Update Quelltext
1128                     if($action == "INSERT") {
1129                         if($field['formtype'] == 'PASSWORD') {
1130                             $sql_insert_key .= "`$key`, ";
1131                             if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) {
1132                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1133                             } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') {
1134                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
1135                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1136                             } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
1137                                 $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`");
1138                                 $record[$key] = $tmp['crypted'];
1139                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1140                             } else {
1141                                 $record[$key] = md5(stripslashes($record[$key]));
1142                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1143                             }
1144                         } elseif ($field['formtype'] == 'CHECKBOX') {
1145                             $sql_insert_key .= "`$key`, ";
1146                             if($record[$key] == '') {
1147                                 // if a checkbox is not set, we set it to the unchecked value
1148                                 $sql_insert_val .= "'".$field['value'][0]."', ";
1149                                 $record[$key] = $field['value'][0];
1150                             } else {
1151                                 $sql_insert_val .= "'".$record[$key]."', ";
1152                             }
1153                         } else {
1154                             $sql_insert_key .= "`$key`, ";
1155                             $sql_insert_val .= "'".$record[$key]."', ";
1156                         }
1157                     } else {
1158                         if($field['formtype'] == 'PASSWORD') {
1159                             if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) {
1160                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1161                             } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') {
1162                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
1163                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1164                             } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
1165                                 $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`");
1166                                 $record[$key] = $tmp['crypted'];
1167                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1168                             } else {
1169                                 $record[$key] = md5(stripslashes($record[$key]));
1170                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1171                             }
1172
1173                         } elseif ($field['formtype'] == 'CHECKBOX') {
1174                             if($record[$key] == '') {
1175                                 // if a checkbox is not set, we set it to the unchecked value
1176                                 $sql_update .= "`$key` = '".$field['value'][0]."', ";
1177                                 $record[$key] = $field['value'][0];
1178                             } else {
1179                                 $sql_update .= "`$key` = '".$record[$key]."', ";
1180                             }
1181                         } else {
1182                             $sql_update .= "`$key` = '".$record[$key]."', ";
1183                         }
1184                     }
1185                 } else {
1186                     // we unset the password filed, if empty to tell the datalog function
1187                     // that the password has not been changed
1188                     unset($record[$key]);
1189                 }
1190             }
1191         }
1192
1193
1194         // Add backticks for incomplete table names
1195         if(stristr($this->formDef['db_table'], '.')) {
1196             $escape = '';
1197         } else {
1198             $escape = '`';
1199         }
1200
1201
1202         if($action == "INSERT") {
1203             if($this->formDef['auth'] == 'yes') {
1204                 // Set user and group
1205                 $sql_insert_key .= "`sys_userid`, ";
1206                 $sql_insert_val .= ($this->formDef["auth_preset"]["userid"] > 0)?"'".$this->formDef["auth_preset"]["userid"]."', ":"'".$_SESSION["s"]["user"]["userid"]."', ";
1207                 $sql_insert_key .= "`sys_groupid`, ";
1208                 $sql_insert_val .= ($this->formDef["auth_preset"]["groupid"] > 0)?"'".$this->formDef["auth_preset"]["groupid"]."', ":"'".$_SESSION["s"]["user"]["default_group"]."', ";
1209                 $sql_insert_key .= "`sys_perm_user`, ";
1210                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_user"]."', ";
1211                 $sql_insert_key .= "`sys_perm_group`, ";
1212                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_group"]."', ";
1213                 $sql_insert_key .= "`sys_perm_other`, ";
1214                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_other"]."', ";
1215             }
1216             $sql_insert_key = substr($sql_insert_key, 0, -2);
1217             $sql_insert_val = substr($sql_insert_val, 0, -2);
1218             $sql = "INSERT INTO ".$escape.$this->formDef['db_table'].$escape." ($sql_insert_key) VALUES ($sql_insert_val)";
1219         } else {
1220             if($this->formDef['auth'] == 'yes') {
1221                 if($primary_id != 0) {
1222                     if($api == true && $_SESSION["s"]["user"]["client_id"] > 0 && $_SESSION["s"]["user"]["iserid"] > 0 && $_SESSION["s"]["user"]["default_group"] > 0) {
1223                         $sql_update .= '`sys_userid` = '.$this->sys_userid.', ';
1224                         $sql_update .= '`sys_groupid` = '.$this->sys_default_group.', ';
1225                     }
1226
1227                     $sql_update = substr($sql_update, 0, -2);
1228                     $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->getAuthSQL('u')." AND ".$this->formDef['db_table_idx']." = ".$primary_id;
1229                     if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1230                 } else {
1231                     $app->error("Primary ID fehlt!");
1232                 }
1233             } else {
1234                 if($primary_id != 0) {
1235                     $sql_update = substr($sql_update, 0, -2);
1236                     $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
1237                     if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1238                 } else {
1239                     $app->error("Primary ID fehlt!");
1240                 }
1241             }
1242             //* return a empty string if there is nothing to update
1243             if(trim($sql_update) == '') $sql = '';
1244         }
1245
1246         return $sql;
1247     }
1248
1249
1250     /**
1251      * Create SQL statement
1252      *
1253      * @param record = Datensatz als Array
1254      * @param action = INSERT oder UPDATE
1255      * @param primary_id
1256      * @return record
1257      */
1258     function getSQL($record, $tab, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '') {
1259
1260         global $app;
1261
1262         // If there are no data records on the tab, return empty sql string
1263         if(count($this->formDef['tabs'][$tab]['fields']) == 0) return '';
1264
1265         // checking permissions
1266         if($this->formDef['auth'] == 'yes' && $_SESSION["s"]["user"]["typ"] != 'admin') {
1267             if($action == "INSERT") {
1268                 if(!$this->checkPerm($primary_id, 'i')) $this->errorMessage .= "Insert denied.<br />\r\n";
1269             } else {
1270                 if(!$this->checkPerm($primary_id, 'u')) $this->errorMessage .= "Update denied.<br />\r\n";
1271             }
1272         }
1273
1274         if(!is_array($this->formDef)) $app->error("Form definition not found.");
1275         if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
1276
1277         return $this->_getSQL($record, $tab, $action, $primary_id, $sql_ext_where, false);
1278     }
1279
1280
1281     /**
1282      * Debugging arrays.
1283      *
1284      * @param array_data
1285      */
1286     function dbg($array_data) {
1287
1288         echo "<pre>";
1289         print_r($array_data);
1290         echo "</pre>";
1291
1292     }
5bff39 1293
M 1294
1295     function showForm() {
b1a6a5 1296         global $app, $conf;
5bff39 1297
M 1298         if(!is_array($this->formDef)) die("Form Definition wurde nicht geladen.");
1299
b1a6a5 1300         $active_tab = $this->getNextTab();
5bff39 1301
M 1302         // go trough the tabs
1303         foreach( $this->formDef["tabs"] as $key => $tab) {
1304
1305             $tab['name'] = $key;
1306             // Translate the title of the tab
1307             $tab['title'] = $this->lng($tab['title']);
1308
1309             if($tab['name'] == $active_tab) {
1310
1311                 // If module is set, then set the template path relative to the module..
1312                 if($this->module != '') $tab["template"] = "../".$this->module."/".$tab["template"];
1313
1314                 // Generate the template if it does not exist yet.
1315
1316
1317
1318                 if(!is_file($tab["template"])) {
b1a6a5 1319                     $app->uses('tform_tpl_generator');
MC 1320                     $app->tform_tpl_generator->buildHTML($this->formDef, $tab['name']);
5bff39 1321                 }
M 1322                 $app->tpl->setVar('readonly_tab', (isset($tab['readonly']) && $tab['readonly'] == true));
b1a6a5 1323                 $app->tpl->setInclude('content_tpl', $tab["template"]);
5bff39 1324                 $tab["active"] = 1;
M 1325                 $_SESSION["s"]["form"]["tab"] = $tab['name'];
1326             } else {
b1a6a5 1327                 $tab["active"] = 0;
5bff39 1328             }
M 1329
b1a6a5 1330             // Unset unused variables.
MC 1331             unset($tab["fields"]);
1332             unset($tab["plugins"]);
5bff39 1333
M 1334             $frmTab[] = $tab;
1335         }
1336
1337         // setting form tabs
1338         $app->tpl->setLoop("formTab", $frmTab);
1339
b1a6a5 1340         // Set form action
MC 1341         $app->tpl->setVar('form_action', $this->formDef["action"]);
1342         $app->tpl->setVar('form_active_tab', $active_tab);
5bff39 1343
b1a6a5 1344         // Set form title
MC 1345         $form_hint = $this->lng($this->formDef["title"]);
1346         if($this->formDef["description"] != '') $form_hint .= '<div class="pageForm_description">'.$this->lng($this->formDef["description"]).'</div>';
1347         $app->tpl->setVar('form_hint', $form_hint);
5bff39 1348
b1a6a5 1349         // Set Wordbook for this form
5bff39 1350
b1a6a5 1351         $app->tpl->setVar($this->wordbook);
MC 1352     }
1353
1354     function getDataRecord($primary_id) {
1355         global $app;
1356         $escape = '`';
1357         $sql = "SELECT * FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id." AND ".$this->getAuthSQL('r', $this->formDef['db_table']);
1358         return $app->db->queryOneRecord($sql);
1359     }
1360
1361
1362     function datalogSave($action, $primary_id, $record_old, $record_new) {
1363         global $app, $conf;
1364
1365         $app->db->datalogSave($this->formDef['db_table'], $action, $this->formDef['db_table_idx'], $primary_id, $record_old, $record_new);
1366         return true;
1367     }
1368
1369     function getAuthSQL($perm, $table = '') {
ebbe63 1370         if($_SESSION["s"]["user"]["typ"] == 'admin' || $_SESSION['s']['user']['mailuser_id'] > 0) {
b1a6a5 1371             return '1';
MC 1372         } else {
1373             if ($table != ''){
1374                 $table = ' ' . $table . '.';
1375             }
1376             $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
1377             $sql = '(';
1378             $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR  ";
1379             $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
1380             $sql .= $table . "sys_perm_other like '%$perm%'";
1381             $sql .= ')';
1382
1383             return $sql;
5bff39 1384         }
b1a6a5 1385     }
5bff39 1386
M 1387 }
1388
1389 ?>