diff --git a/www/admin/class_test.php b/www/admin/class_test.php index 0dc1b4a4..b42094d3 100644 --- a/www/admin/class_test.php +++ b/www/admin/class_test.php @@ -1,194 +1,195 @@ db_info(1); +$basic = new AdminBackend($DB_CONFIG[MAIN_DB], $lang); +$basic->db_info(1); - // set + check edit access id - $edit_access_id = 3; - print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."
"; - print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."
"; - if ($login->login_check_edit_access($edit_access_id)) - $basic->edit_access_id = $edit_access_id; - else - $basic->edit_access_id = $login->acl['unit_id']; +// set + check edit access id +$edit_access_id = 3; +print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."
"; +print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."
"; +if ($login->login_check_edit_access($edit_access_id)) { + $basic->edit_access_id = $edit_access_id; +} else { + $basic->edit_access_id = $login->acl['unit_id']; +} // $basic->debug('SESSION', $basic->print_ar($_SESSION)); - print "TEST CLASS"; - print ""; - print '
'; - print 'Logout'; - print ''; - print '
'; +print "TEST CLASS"; +print ""; +print '
'; +print 'Logout'; +print ''; +print '
'; - // print the debug core vars - print "DEBUG OUT: ".$basic->debug_output."
"; - print "ECHO OUT: ".$basic->echo_output."
"; - print "PRINT OUT: ".$basic->print_output."
"; - print "NOT DEBUG OUT: ".$basic->debug_output_not."
"; - print "NOT ECHO OUT: ".$basic->echo_output_not."
"; - print "NOT PRINT OUT: ".$basic->print_output_not."
"; - print "DEBUG OUT ALL: ".$basic->debug_output_all."
"; - print "ECHO OUT ALL: ".$basic->echo_output_all."
"; - print "PRINT OUT ALL: ".$basic->print_output_all."
"; +// print the debug core vars +print "DEBUG OUT: ".$basic->debug_output."
"; +print "ECHO OUT: ".$basic->echo_output."
"; +print "PRINT OUT: ".$basic->print_output."
"; +print "NOT DEBUG OUT: ".$basic->debug_output_not."
"; +print "NOT ECHO OUT: ".$basic->echo_output_not."
"; +print "NOT PRINT OUT: ".$basic->print_output_not."
"; +print "DEBUG OUT ALL: ".$basic->debug_output_all."
"; +print "ECHO OUT ALL: ".$basic->echo_output_all."
"; +print "PRINT OUT ALL: ".$basic->print_output_all."
"; - print "CALLER BACKTRACE: ".$basic->get_caller_method()."
"; - $basic->debug('SOME MARK', 'Some error output'); +print "CALLER BACKTRACE: ".$basic->get_caller_method()."
"; +$basic->debug('SOME MARK', 'Some error output'); - print "EDIT ACCESS ID: ".$basic->edit_access_id."
"; +print "EDIT ACCESS ID: ".$basic->edit_access_id."
"; // print "ACL:
".$basic->print_ar($login->acl)."
"; - $basic->debug('ACL', "ACL: ".$basic->print_ar($login->acl)); +$basic->debug('ACL', "ACL: ".$basic->print_ar($login->acl)); // print "DEFAULT ACL:
".$basic->print_ar($login->default_acl_list)."
"; // print "DEFAULT ACL:
".$basic->print_ar($login->default_acl_list)."
"; // $result = array_flip(array_filter(array_flip($login->default_acl_list), function ($key) { if (is_numeric($key)) return $key; })); // print "DEFAULT ACL:
".$basic->print_ar($result)."
"; - // DEPRICATED CALL +// DEPRICATED CALL // $basic->adbSetACL($login->acl); - while ($res = $basic->db_return("SELECT * FROM max_test")) - { - print "TIME: ".$res['time']."
"; - } +while ($res = $basic->db_return("SELECT * FROM max_test")) { + print "TIME: ".$res['time']."
"; +} - $status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO TEST ".time()."') RETURNING test"); - print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; - print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; - $basic->db_prepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)"); - $status = $basic->db_execute("ins_foo", array('BAR TEST '.time())); - print "PREPARE INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; - print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; - // returning test with multiple entries +$status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO TEST ".time()."') RETURNING test"); +print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; +print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; +$basic->db_prepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)"); +$status = $basic->db_execute("ins_foo", array('BAR TEST '.time())); +print "PREPARE INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; +print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; +// returning test with multiple entries // $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id"); - $status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test"); - print "DIRECT MULTIPLE INSERT STATUS: $status | PRIMARY KEYS: ".print_r($basic->insert_id, 1)." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; - // no returning, but not needed ; - $status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO; TEST ".time()."');"); - print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; +$status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test"); +print "DIRECT MULTIPLE INSERT STATUS: $status | PRIMARY KEYS: ".print_r($basic->insert_id, 1)." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; +// no returning, but not needed ; +$status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO; TEST ".time()."');"); +print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."
"; - # db write class test - $table = 'foo'; - print "TABLE META DATA: ".$basic->print_ar($basic->db_show_table_meta_data($table))."
"; - $primary_key = ''; # unset - $db_write_table = array ('test', 'string_a', 'number_a', 'some_bool'); +# db write class test +$table = 'foo'; +print "TABLE META DATA: ".$basic->print_ar($basic->db_show_table_meta_data($table))."
"; +$primary_key = ''; # unset +$db_write_table = array ('test', 'string_a', 'number_a', 'some_bool'); // $db_write_table = array ('test'); - $object_fields_not_touch = array (); - $object_fields_not_update = array (); - $data = array ('test' => 'BOOL TEST SOMETHING '.time(), 'string_a' => 'SOME TEXT', 'number_a' => 5); - $primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); - print "Wrote to DB tabel $table and got primary key $primary_key
"; - $data = array ('test' => 'BOOL TEST ON '.time(), 'string_a' => '', 'number_a' => 0, 'some_bool' => 1); - $primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); - print "Wrote to DB tabel $table and got primary key $primary_key
"; - $data = array ('test' => 'BOOL TEST OFF '.time(), 'string_a' => null, 'number_a' => null, 'some_bool' => 0); - $primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); - print "Wrote to DB tabel $table and got primary key $primary_key
"; - $data = array ('test' => 'BOOL TEST UNSET '.time()); - $primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); - print "Wrote to DB tabel $table and got primary key $primary_key
"; +$object_fields_not_touch = array (); +$object_fields_not_update = array (); +$data = array ('test' => 'BOOL TEST SOMETHING '.time(), 'string_a' => 'SOME TEXT', 'number_a' => 5); +$primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); +print "Wrote to DB tabel $table and got primary key $primary_key
"; +$data = array ('test' => 'BOOL TEST ON '.time(), 'string_a' => '', 'number_a' => 0, 'some_bool' => 1); +$primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); +print "Wrote to DB tabel $table and got primary key $primary_key
"; +$data = array ('test' => 'BOOL TEST OFF '.time(), 'string_a' => null, 'number_a' => null, 'some_bool' => 0); +$primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); +print "Wrote to DB tabel $table and got primary key $primary_key
"; +$data = array ('test' => 'BOOL TEST UNSET '.time()); +$primary_key = $basic->db_write_data_ext($db_write_table, $primary_key, $table, $object_fields_not_touch, $object_fields_not_update, $data); +print "Wrote to DB tabel $table and got primary key $primary_key
"; - # async test queries +# async test queries /* $basic->db_exec_async("SELECT test FROM foo, (SELECT pg_sleep(10)) as sub WHERE foo_id IN (27, 50, 67, 44, 10)"); - echo "WAITING FOR ASYNC: "; - $chars = array('|', '/', '-', '\\'); - while (($ret = $basic->db_check_async()) === true) +echo "WAITING FOR ASYNC: "; +$chars = array('|', '/', '-', '\\'); +while (($ret = $basic->db_check_async()) === true) +{ + if ((list($_, $char) = each($chars)) === FALSE) { - if ((list($_, $char) = each($chars)) === FALSE) - { - reset($chars); - list($_, $char) = each($chars); - } - print $char; - sleep(1); - flush(); + reset($chars); + list($_, $char) = each($chars); } - print "
END STATUS: ".$ret."
"; + print $char; + sleep(1); + flush(); +} +print "
END STATUS: ".$ret."
"; // while ($res = $basic->db_fetch_array($ret)) - while ($res = $basic->db_fetch_array()) - { - echo "RES: ".$res['test']."
"; - } - # test async insert - $basic->db_exec_async("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')"); - echo "WAITING FOR ASYNC INSERT: "; - while (($ret = $basic->db_check_async()) === true) - { - print "."; - sleep(1); - flush(); - } - print "
END STATUS: ".$ret." | PK: ".$basic->insert_id."
"; - print "ASYNC PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; */ +while ($res = $basic->db_fetch_array()) +{ + echo "RES: ".$res['test']."
"; +} +# test async insert +$basic->db_exec_async("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')"); +echo "WAITING FOR ASYNC INSERT: "; +while (($ret = $basic->db_check_async()) === true) +{ + print "."; + sleep(1); + flush(); +} +print "
END STATUS: ".$ret." | PK: ".$basic->insert_id."
"; +print "ASYNC PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."
"; */ - $to_db_version = '9.1.9'; - print "VERSION DB: ".$basic->db_version()."
"; - print "DB Version smaller $to_db_version: ".$basic->db_compare_version('<'.$to_db_version)."
"; - print "DB Version smaller than $to_db_version: ".$basic->db_compare_version('<='.$to_db_version)."
"; - print "DB Version equal $to_db_version: ".$basic->db_compare_version('='.$to_db_version)."
"; - print "DB Version bigger than $to_db_version: ".$basic->db_compare_version('>='.$to_db_version)."
"; - print "DB Version bigger $to_db_version: ".$basic->db_compare_version('>'.$to_db_version)."
"; +$to_db_version = '9.1.9'; +print "VERSION DB: ".$basic->db_version()."
"; +print "DB Version smaller $to_db_version: ".$basic->db_compare_version('<'.$to_db_version)."
"; +print "DB Version smaller than $to_db_version: ".$basic->db_compare_version('<='.$to_db_version)."
"; +print "DB Version equal $to_db_version: ".$basic->db_compare_version('='.$to_db_version)."
"; +print "DB Version bigger than $to_db_version: ".$basic->db_compare_version('>='.$to_db_version)."
"; +print "DB Version bigger $to_db_version: ".$basic->db_compare_version('>'.$to_db_version)."
"; /* $q = "SELECT FOO FRO BAR"; // $q = "Select * from foo"; - $foo = $basic->db_exec_async($q); - print "[ERR] Query: ".$q."
"; - print "[ERR] RESOURCE: $foo
"; - while (($ret = $basic->db_check_async()) === true) - { - print "[ERR]: $ret
"; +$foo = $basic->db_exec_async($q); +print "[ERR] Query: ".$q."
"; +print "[ERR] RESOURCE: $foo
"; +while (($ret = $basic->db_check_async()) === true) +{ + print "[ERR]: $ret
"; // sleep(5); - } */ +} */ - // search path check - $q = "SHOW search_path"; - $cursor = $basic->db_exec($q); - $data = $basic->db_fetch_array($cursor)['search_path']; - print "RETURN DATA FOR search_path: ".$data."
"; +// search path check +$q = "SHOW search_path"; +$cursor = $basic->db_exec($q); +$data = $basic->db_fetch_array($cursor)['search_path']; +print "RETURN DATA FOR search_path: ".$data."
"; // print "RETURN DATA FOR search_path: ".$basic->print_ar($data)."
"; - // insert something into test.schema_test and see if we get the PK back - $status = $basic->db_exec("INSERT INTO test.schema_test (contents, id) VALUES ('TIME: ".time()."', ".rand(1, 10).")"); - print "OTHER SCHEMA INSERT STATUS: ".$status." | PK NAME: ".$basic->pk_name.", PRIMARY KEY: ".$basic->insert_id."
"; +// insert something into test.schema_test and see if we get the PK back +$status = $basic->db_exec("INSERT INTO test.schema_test (contents, id) VALUES ('TIME: ".time()."', ".rand(1, 10).")"); +print "OTHER SCHEMA INSERT STATUS: ".$status." | PK NAME: ".$basic->pk_name.", PRIMARY KEY: ".$basic->insert_id."
"; - // time string thest - $timestamp = 5887998.33445; - $time_string = $basic->TimeStringFormat($timestamp); - print "TIME STRING TEST: ".$time_string."
"; - print "REVERSE TIME STRING: ".$basic->StringToTime($time_string); +// time string thest +$timestamp = 5887998.33445; +$time_string = $basic->TimeStringFormat($timestamp); +print "TIME STRING TEST: ".$time_string."
"; +print "REVERSE TIME STRING: ".$basic->StringToTime($time_string); - // magic links test - print $basic->magic_links('user@bubu.at').'
'; - print $basic->magic_links('http://test.com/foo/bar.php?foo=1').'
'; +// magic links test +print $basic->magic_links('user@bubu.at').'
'; +print $basic->magic_links('http://test.com/foo/bar.php?foo=1').'
'; - // compare date - $date_1 = '2017/1/5'; - $date_2 = '2017-01-05'; - print "COMPARE DATE: ".$basic->CompareDate($date_1, $date_2)."
"; +// compare date +$date_1 = '2017/1/5'; +$date_2 = '2017-01-05'; +print "COMPARE DATE: ".$basic->CompareDate($date_1, $date_2)."
"; - // print error messages - print $basic->print_error_msg(); +// print error messages +print $basic->print_error_msg(); - print ""; -?> +print ""; diff --git a/www/admin/edit_base.inc b/www/admin/edit_base.inc index 0562c4d8..62ee3d32 100644 --- a/www/admin/edit_base.inc +++ b/www/admin/edit_base.inc @@ -1,345 +1,324 @@ db_exec("SET search_path TO ".LOGIN_DB_SCHEMA); - if ($form->mobile_phone) - { - echo "I am sorry, but this page cannot be viewed by a mobile phone"; - exit; - } - // smarty template engine (extended Translation version) - $smarty = new SmartyML($lang); +// create form class +$form = new form($DB_CONFIG[MAIN_DB], $lang); +$form->db_exec("SET search_path TO ".LOGIN_DB_SCHEMA); +if ($form->mobile_phone) { + echo "I am sorry, but this page cannot be viewed by a mobile phone"; + exit; +} +// smarty template engine (extended Translation version) +$smarty = new SmartyML($lang); - if (TARGET == 'live' || TARGET == 'remote') - { - // login - $login->debug_output_all = DEBUG ? 1 : 0; - $login->echo_output_all = 0; - $login->print_output_all = DEBUG ? 1 : 0; - // form - $form->debug_output_all = DEBUG ? 1 : 0; - $form->echo_output_all = 0; - $form->print_output_all = DEBUG ? 1 : 0; - } - // set the template dir - // WARNING: this has a special check for the mailing tool layout (old layout) - if (defined('LAYOUT')) - { - $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); - $DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS; - $DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS; - } - else - { - $smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE); - $DATA['css'] = CSS.DEFAULT_TEMPLATE; - $DATA['js'] = JS.DEFAULT_TEMPLATE; - } +if (TARGET == 'live' || TARGET == 'remote') { + // login + $login->debug_output_all = DEBUG ? 1 : 0; + $login->echo_output_all = 0; + $login->print_output_all = DEBUG ? 1 : 0; + // form + $form->debug_output_all = DEBUG ? 1 : 0; + $form->echo_output_all = 0; + $form->print_output_all = DEBUG ? 1 : 0; +} +// set the template dir +// WARNING: this has a special check for the mailing tool layout (old layout) +if (defined('LAYOUT')) { + $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); + $DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS; + $DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS; +} else { + $smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE); + $DATA['css'] = CSS.DEFAULT_TEMPLATE; + $DATA['js'] = JS.DEFAULT_TEMPLATE; +} - // space for setting special debug flags - $login->debug_output_all = 1; +// space for setting special debug flags +$login->debug_output_all = 1; - // define edit logging function. should be in a special edit interface class later - // METHOD: EditLog() - // PARAMS: event -> any kind of event description, data -> any kind of data related to that event - // RETURN: none - // DESC: writes all action vars plus other info into edit_log table - function EditLog($event = '', $data = '') - { - $q = "INSERT INTO edit_log "; - $q .= "(euid, event_date, ip, event, data, page) "; - $q .= "VALUES (".$_SESSION['EUID'].", NOW(), '".$_SERVER["REMOTE_ADDR"]."', '".$GLOBALS['form']->db_escape_string($event)."', '".$GLOBALS['form']->db_escape_string($data)."', '".$GLOBALS['form']->get_page_name()."')"; - } +// define edit logging function. should be in a special edit interface class later +// METHOD: EditLog() +// PARAMS: event -> any kind of event description, data -> any kind of data related to that event +// RETURN: none +// DESC: writes all action vars plus other info into edit_log table +function EditLog($event = '', $data = '') +{ + $q = "INSERT INTO edit_log "; + $q .= "(euid, event_date, ip, event, data, page) "; + $q .= "VALUES (".$_SESSION['EUID'].", NOW(), '".$_SERVER["REMOTE_ADDR"]."', '".$GLOBALS['form']->db_escape_string($event)."', '".$GLOBALS['form']->db_escape_string($data)."', '".$GLOBALS['form']->get_page_name()."')"; +} - // log backend data - // data part creation - $data = array ( - '_SESSION' => $_SESSION, - '_GET' => $_GET, - '_POST' => $_POST, - '_FILES' => $_FILES - ); - // log action - EditLog('Edit Submit', serialize($data)); +// log backend data +// data part creation +$data = array ( + '_SESSION' => $_SESSION, + '_GET' => $_GET, + '_POST' => $_POST, + '_FILES' => $_FILES +); +// log action +EditLog('Edit Submit', serialize($data)); - $form->form_procedure_load(${$form->archive_pk_name}); - $form->form_procedure_new(); - $form->form_procedure_save(); - $form->form_procedure_delete(); - $form->form_procedure_delete_from_element_list($element_list, $remove_name); +$form->form_procedure_load(${$form->archive_pk_name}); +$form->form_procedure_new(); +$form->form_procedure_save(); +$form->form_procedure_delete(); +$form->form_procedure_delete_from_element_list($element_list, $remove_name); - // define all needed smarty stuff for the general HTML/page building - $HEADER['CSS'] = CSS; - $HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; - $HEADER['JS'] = JS; - $HEADER['STYLESHEET'] = $EDIT_STYLESHEET; - $HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; +// define all needed smarty stuff for the general HTML/page building +$HEADER['CSS'] = CSS; +$HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; +$HEADER['JS'] = JS; +$HEADER['STYLESHEET'] = $EDIT_STYLESHEET; +$HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; - $DATA['table_width'] = $table_width; +$DATA['table_width'] = $table_width; - // write out error / status messages - $messages[] = $form->form_error_msg(); - $DATA['form_error_msg'] = $messages; +// write out error / status messages +$messages[] = $form->form_error_msg(); +$DATA['form_error_msg'] = $messages; - // MENU START - // request some session vars - if (!$HEADER_COLOR) - $DATA['HEADER_COLOR'] = "#E0E2FF"; - else - $DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR']; - $DATA['USER_NAME'] = $_SESSION["USER_NAME"]; - $DATA['EUID'] = $_SESSION["EUID"]; - $DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"]; - $DATA['GROUP_LEVEL'] = $_SESSION["GROUP_LEVEL"]; - $PAGES = $_SESSION["PAGES"]; +// MENU START +// request some session vars +if (!$HEADER_COLOR) { + $DATA['HEADER_COLOR'] = "#E0E2FF"; +} else { + $DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR']; +} +$DATA['USER_NAME'] = $_SESSION["USER_NAME"]; +$DATA['EUID'] = $_SESSION["EUID"]; +$DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"]; +$DATA['GROUP_LEVEL'] = $_SESSION["GROUP_LEVEL"]; +$PAGES = $_SESSION["PAGES"]; //$form->debug('menu', $form->print_ar($PAGES)); - // baue nav aus $PAGES ... - for ($i = 0; $i < count($PAGES); $i ++) - { - if ($PAGES[$i]["menu"] && $PAGES[$i]["online"]) - { - $menuarray[] = $PAGES[$i]; - } +// baue nav aus $PAGES ... +for ($i = 0; $i < count($PAGES); $i ++) { + if ($PAGES[$i]["menu"] && $PAGES[$i]["online"]) { + $menuarray[] = $PAGES[$i]; } +} - // split point for nav points - $COUNT_NAV_POINTS = count($menuarray); - $SPLIT_FACTOR = 3; - $START_SPLIT_COUNT = 3; - // WTF ?? I dunno what I am doing here ... - for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) - { - if ($COUNT_NAV_POINTS > $i) - $SPLIT_FACTOR += 1; +// split point for nav points +$COUNT_NAV_POINTS = count($menuarray); +$SPLIT_FACTOR = 3; +$START_SPLIT_COUNT = 3; +// WTF ?? I dunno what I am doing here ... +for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) { + if ($COUNT_NAV_POINTS > $i) { + $SPLIT_FACTOR += 1; } +} - for ($i = 1; $i <= count($menuarray); $i ++) - { - // do that for new array - $j = $i - 1; - $menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]); - $menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"]; - if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) - { - $menu_data[$j]['splitfactor_in'] = 1; - } - if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) - { - $position = $i - 1; - $menu_data[$j]['position'] = 1; - } - else - { - // add query stuff - // HAS TO DONE LATER ... set urlencode, etc ... - // check if popup needed - if ($menuarray[($i - 1)]["popup"]) - { - $menu_data[$j]['popup'] = 1; - $menu_data[$j]['rand'] = uniqid(rand()); - $menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"]; - $menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"]; - } // popup or not - } // highlight or not - if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) - { - $menu_data[$j]['splitfactor_out'] = 1; - } // split - } // for - $DATA['menu_data'] = $menu_data; - $DATA['page_name'] = $menuarray[$position]["page_name"]; - $L_TITLE = $DATA['page_name']; - // html title - $HEADER['HTML_TITLE'] = ((!$L_TITLE) ? $form->l->__($G_TITLE) : $form->l->__($L_TITLE)); - // END MENU - // LOAD AND NEW - $DATA['load'] = $form->form_create_load(); - $DATA['new'] = $form->form_create_new(); - // SHOW DATA PART - if ($form->yes) - { - $DATA['form_yes'] = $form->yes; - $DATA['form_my_page_name'] = $form->my_page_name; +for ($i = 1; $i <= count($menuarray); $i ++) { + // do that for new array + $j = $i - 1; + $menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]); + $menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"]; + if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) { + $menu_data[$j]['splitfactor_in'] = 1; + } + if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) { + $position = $i - 1; + $menu_data[$j]['position'] = 1; + } else { + // add query stuff + // HAS TO DONE LATER ... set urlencode, etc ... + // check if popup needed + if ($menuarray[($i - 1)]["popup"]) { + $menu_data[$j]['popup'] = 1; + $menu_data[$j]['rand'] = uniqid(rand()); + $menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"]; + $menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"]; + } // popup or not + } // highlight or not + if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) { + $menu_data[$j]['splitfactor_out'] = 1; + } // split +} // for +$DATA['menu_data'] = $menu_data; +$DATA['page_name'] = $menuarray[$position]["page_name"]; +$L_TITLE = $DATA['page_name']; +// html title +$HEADER['HTML_TITLE'] = ((!$L_TITLE) ? $form->l->__($G_TITLE) : $form->l->__($L_TITLE)); +// END MENU +// LOAD AND NEW +$DATA['load'] = $form->form_create_load(); +$DATA['new'] = $form->form_create_new(); +// SHOW DATA PART +if ($form->yes) { + $DATA['form_yes'] = $form->yes; + $DATA['form_my_page_name'] = $form->my_page_name; - // depending on the "get_page_name()" I show different stuff - switch ($form->my_page_name) - { - case "edit_users": - $elements[] = $form->form_create_element("login_error_count"); - $elements[] = $form->form_create_element("login_error_date_last"); - $elements[] = $form->form_create_element("login_error_date_first"); - $elements[] = $form->form_create_element("enabled"); - $elements[] = $form->form_create_element("username"); - $elements[] = $form->form_create_element("password"); - $elements[] = $form->form_create_element("password_change_interval"); - $elements[] = $form->form_create_element("email"); - $elements[] = $form->form_create_element("last_name"); - $elements[] = $form->form_create_element("first_name"); - $elements[] = $form->form_create_element("edit_group_id"); - $elements[] = $form->form_create_element("edit_access_right_id"); - $elements[] = $form->form_create_element("strict"); - $elements[] = $form->form_create_element("locked"); - $elements[] = $form->form_create_element("admin"); - $elements[] = $form->form_create_element("debug"); - $elements[] = $form->form_create_element("db_debug"); - $elements[] = $form->form_create_element("edit_language_id"); - $elements[] = $form->form_create_element("edit_scheme_id"); - $elements[] = $form->form_show_list_table("edit_access_user"); + // depending on the "get_page_name()" I show different stuff + switch ($form->my_page_name) { + case "edit_users": + $elements[] = $form->form_create_element("login_error_count"); + $elements[] = $form->form_create_element("login_error_date_last"); + $elements[] = $form->form_create_element("login_error_date_first"); + $elements[] = $form->form_create_element("enabled"); + $elements[] = $form->form_create_element("username"); + $elements[] = $form->form_create_element("password"); + $elements[] = $form->form_create_element("password_change_interval"); + $elements[] = $form->form_create_element("email"); + $elements[] = $form->form_create_element("last_name"); + $elements[] = $form->form_create_element("first_name"); + $elements[] = $form->form_create_element("edit_group_id"); + $elements[] = $form->form_create_element("edit_access_right_id"); + $elements[] = $form->form_create_element("strict"); + $elements[] = $form->form_create_element("locked"); + $elements[] = $form->form_create_element("admin"); + $elements[] = $form->form_create_element("debug"); + $elements[] = $form->form_create_element("db_debug"); + $elements[] = $form->form_create_element("edit_language_id"); + $elements[] = $form->form_create_element("edit_scheme_id"); + $elements[] = $form->form_show_list_table("edit_access_user"); break; - case "edit_schemes": - $elements[] = $form->form_create_element("enabled"); - $elements[] = $form->form_create_element("name"); - $elements[] = $form->form_create_element("header_color"); - $elements[] = $form->form_create_element("template"); + case "edit_schemes": + $elements[] = $form->form_create_element("enabled"); + $elements[] = $form->form_create_element("name"); + $elements[] = $form->form_create_element("header_color"); + $elements[] = $form->form_create_element("template"); break; - case "edit_pages": - if (!$form->table_array["edit_page_id"]["value"]) - { - $q = "DELETE FROM temp_files"; - $form->db_exec($q); - // gets all files in the current dir ending with .php - $crap = exec("ls *.php", $output, $status); - // now get all that are NOT in de DB - $q = "INSERT INTO temp_files VALUES "; - for ($i = 0; $i < count($output); $i ++) - { - $t_q = "('".$form->db_escape_string($output[$i])."')"; - $form->db_exec($q.$t_q, 'NULL'); - } - $elements[] = $form->form_create_element("filename"); + case "edit_pages": + if (!$form->table_array["edit_page_id"]["value"]) { + $q = "DELETE FROM temp_files"; + $form->db_exec($q); + // gets all files in the current dir ending with .php + $crap = exec("ls *.php", $output, $status); + // now get all that are NOT in de DB + $q = "INSERT INTO temp_files VALUES "; + for ($i = 0; $i < count($output); $i ++) { + $t_q = "('".$form->db_escape_string($output[$i])."')"; + $form->db_exec($q.$t_q, 'NULL'); } - else // show file menu - { - // just show name of file ... - $DATA['filename_exist'] = 1; - $DATA['filename'] = $form->table_array["filename"]["value"]; - } // File Name View IF - $elements[] = $form->form_create_element("name"); -// $elements[] = $form->form_create_element("tag"); -// $elements[] = $form->form_create_element("min_acl"); - $elements[] = $form->form_create_element("order_number"); - $elements[] = $form->form_create_element("online"); - $elements[] = $form->form_create_element("menu"); - $elements[] = $form->form_show_list_table("edit_query_string"); - $elements[] = $form->form_create_element("popup"); - $elements[] = $form->form_create_element("popup_x"); - $elements[] = $form->form_create_element("popup_y"); - $elements[] = $form->form_show_reference_table("edit_visible_group"); - $elements[] = $form->form_show_reference_table("edit_menu_group"); + $elements[] = $form->form_create_element("filename"); + } else { + // show file menu + // just show name of file ... + $DATA['filename_exist'] = 1; + $DATA['filename'] = $form->table_array["filename"]["value"]; + } // File Name View IF + $elements[] = $form->form_create_element("name"); + // $elements[] = $form->form_create_element("tag"); + // $elements[] = $form->form_create_element("min_acl"); + $elements[] = $form->form_create_element("order_number"); + $elements[] = $form->form_create_element("online"); + $elements[] = $form->form_create_element("menu"); + $elements[] = $form->form_show_list_table("edit_query_string"); + $elements[] = $form->form_create_element("popup"); + $elements[] = $form->form_create_element("popup_x"); + $elements[] = $form->form_create_element("popup_y"); + $elements[] = $form->form_show_reference_table("edit_visible_group"); + $elements[] = $form->form_show_reference_table("edit_menu_group"); break; - case "edit_languages": - $elements[] = $form->form_create_element("enabled"); - $elements[] = $form->form_create_element("short_name"); - $elements[] = $form->form_create_element("long_name"); - $elements[] = $form->form_create_element("iso_name"); + case "edit_languages": + $elements[] = $form->form_create_element("enabled"); + $elements[] = $form->form_create_element("short_name"); + $elements[] = $form->form_create_element("long_name"); + $elements[] = $form->form_create_element("iso_name"); break; - case "edit_groups": - $elements[] = $form->form_create_element("enabled"); - $elements[] = $form->form_create_element("name"); - $elements[] = $form->form_create_element("edit_access_right_id"); - $elements[] = $form->form_create_element("edit_scheme_id"); - $elements[] = $form->form_show_list_table("edit_page_access"); + case "edit_groups": + $elements[] = $form->form_create_element("enabled"); + $elements[] = $form->form_create_element("name"); + $elements[] = $form->form_create_element("edit_access_right_id"); + $elements[] = $form->form_create_element("edit_scheme_id"); + $elements[] = $form->form_show_list_table("edit_page_access"); break; - case "edit_visible_group": - $elements[] = $form->form_create_element("name"); - $elements[] = $form->form_create_element("flag"); + case "edit_visible_group": + $elements[] = $form->form_create_element("name"); + $elements[] = $form->form_create_element("flag"); break; - case "edit_menu_group": - $elements[] = $form->form_create_element("name"); - $elements[] = $form->form_create_element("flag"); - $elements[] = $form->form_create_element("order_number"); + case "edit_menu_group": + $elements[] = $form->form_create_element("name"); + $elements[] = $form->form_create_element("flag"); + $elements[] = $form->form_create_element("order_number"); break; - case "edit_access": - $elements[] = $form->form_create_element("name"); - $elements[] = $form->form_create_element("color"); - $elements[] = $form->form_create_element("description"); - // add name/value list here - $elements[] = $form->form_show_list_table("edit_access_data"); + case "edit_access": + $elements[] = $form->form_create_element("name"); + $elements[] = $form->form_create_element("color"); + $elements[] = $form->form_create_element("description"); + // add name/value list here + $elements[] = $form->form_show_list_table("edit_access_data"); break; + default: + print "[No valid page definition given]"; break; - default: - print "NO NO NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO!"; - break; - } + } // $form->debug('edit', "Elements:
".$form->print_ar($elements));
-		$DATA['elements'] = $elements;
-		$DATA['hidden'] = $form->form_create_hidden_fields();
-		$DATA['save_delete'] = $form->form_create_save_delete();
-	}
+	$DATA['elements'] = $elements;
+	$DATA['hidden'] = $form->form_create_hidden_fields();
+	$DATA['save_delete'] = $form->form_create_save_delete();
+}
 
-	// debug data, if DEBUG flag is on, this data is print out
-	$DEBUG_DATA['DEBUG'] = $DEBUG_TMPL;
+// debug data, if DEBUG flag is on, this data is print out
+$DEBUG_DATA['DEBUG'] = $DEBUG_TMPL;
 
-	// create main data array
-	$CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA);
-	// data is 1:1 mapping (all vars, values, etc)
-	while (list($key, $value) = each($CONTENT_DATA))
-	{
-		$smarty->assign($key, $value);
-	}
+// create main data array
+$CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA);
+// data is 1:1 mapping (all vars, values, etc)
+while (list($key, $value) = each($CONTENT_DATA)) {
+	$smarty->assign($key, $value);
+}
 
 //	$smarty->assign('popup_page', 'mt_popup_'.$body_part.'.tpl');
 
-	$smarty->display('edit_body.tpl');
+$smarty->display('edit_body.tpl');
 
-	// debug output
-	echo $login->print_error_msg();
-	echo $form->print_error_msg();
-?>
+// debug output
+echo $login->print_error_msg();
+echo $form->print_error_msg();
diff --git a/www/admin/error_test.php b/www/admin/error_test.php
index fda7ad5f..f9e1aa50 100644
--- a/www/admin/error_test.php
+++ b/www/admin/error_test.php
@@ -1,18 +1,18 @@
 ";
-	}
-?>
+if ($var) {
+	echo "OUT
"; +} diff --git a/www/admin/files.php b/www/admin/files.php index 955c1ce1..0966d070 100644 --- a/www/admin/files.php +++ b/www/admin/files.php @@ -1,486 +1,456 @@ action == 'new' && $cms->action_yes == 'true') - { - unset($file_uid); - unset($file_id); - unset($file_type); - $new_okay = 1; +// create 0 entries for: templates, menu, data_group? +if ($cms->action == 'new' && $cms->action_yes == 'true') { + unset($file_uid); + unset($file_id); + unset($file_type); + $new_okay = 1; +} +// file type: P picture, M mouse over picutre, F flash, V video, B binary +if ($cms->action == 'save') { + if (!$file_type) { + $file_type = 'B'; } - // file type: P picture, M mouse over picutre, F flash, V video, B binary - if ($cms->action == 'save') - { - if (!$file_type) - $file_type = 'B'; - $file_ok = false; - if (!$_FILES['file_up']['name'] && !$file_uid) - { - $cms->messages[] = array('msg' => 'No file name given', 'class' => 'error'); + $file_ok = false; + if (!$_FILES['file_up']['name'] && !$file_uid) { + $cms->messages[] = array('msg' => 'No file name given', 'class' => 'error'); + $error = 1; + } + if (!$_FILES['file_up']['name'] && $file_uid) { + $file_ok = true; + } + // echo "FILE TYPE: ".$_FILES['file_up']['type']."
"; + foreach (split(',', $show_type) as $_show_type) { + // check if the uploaded filename matches to the given type + if ($_FILES['file_up']['name'] && preg_match("/jpeg|png|gif/", $_FILES['file_up']['type']) && preg_match("/P/", $show_type)) { + $file_ok = true; + } + if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) { + $file_ok = true; + } + if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) { + $file_ok = true; + } + if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) { + $file_ok = true; + } + if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) { + $file_ok = true; + } + if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) { + $file_ok = true; + } + } + // write out error messages according to show type + if (!$file_ok) { + if (preg_match("/P/", $show_type)) { + $cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error'); $error = 1; } - if (!$_FILES['file_up']['name'] && $file_uid) - $file_ok = true; -// echo "FILE TYPE: ".$_FILES['file_up']['type']."
"; - foreach (split(',', $show_type) as $_show_type) - { - // check if the uploaded filename matches to the given type - if ($_FILES['file_up']['name'] && preg_match("/jpeg|png|gif/", $_FILES['file_up']['type']) && preg_match("/P/", $show_type)) - { - $file_ok = true; - } - if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) - { - $file_ok = true; - } - if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) - { - $file_ok = true; - } - if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) - { - $file_ok = true; - } - if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) - { - $file_ok = true; - } - if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) - $file_ok = true; + if (preg_match("/F/", $show_type)) { + $cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error'); + $error = 1; } - // write out error messages according to show type - if (!$file_ok) - { - if (preg_match("/P/", $show_type)) - { - $cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error'); - $error = 1; - } - if (preg_match("/F/", $show_type)) - { - $cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error'); - $error = 1; - } - if (preg_match("/V/", $show_type)) - { - $cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error'); - $error = 1; - } - if (preg_match("/D/", $show_type)) - { - $cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error'); - $error = 1; - } - if (preg_match("/A/", $show_type)) - { - $cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error'); - $error = 1; - } - if (preg_match("/B/", $show_type)) - { - $cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error'); - $error = 1; - } + if (preg_match("/V/", $show_type)) { + $cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error'); + $error = 1; + } + if (preg_match("/D/", $show_type)) { + $cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error'); + $error = 1; + } + if (preg_match("/A/", $show_type)) { + $cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error'); + $error = 1; + } + if (preg_match("/B/", $show_type)) { + $cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error'); + $error = 1; } - // binary: all okay - // if no error, save data - if (!$error) - { - if ($_FILES['file_up']['name']) - { - $mime_type = $_FILES['file_up']['type']; - $file_size = $_FILES['file_up']['size']; - $file_name = $_FILES['file_up']['name']; - // get picture size - list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']); -$cms->debug('upload', "Width: $width X Height: $height"); - // set the file type and the target folder - if (preg_match("/jpeg|png|gif/", $mime_type)) - $file_type = 'P'; - elseif (preg_match("/swf/", $mime_type)) - $file_type = 'F'; - elseif (preg_match("/video/", $mime_type)) - $file_type = 'V'; - elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) - $file_type = 'D'; - elseif (preg_match("/pdf/", $mime_type)) - $file_type = 'A'; - elseif ($mime_type) - $file_type = 'B'; - } - // if we have an id -> updated - if ($file_uid) - { - $q = "UPDATE file SET"; - $q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' "; - if ($_FILES['file_up']['name']) - { - $q_set .= ", type = '".$file_type."', mime_type = '$mime_type', file_size = $file_size, size_x = $width, size_y = $height "; - } - $q .= $q_set."WHERE file_uid = '".$file_uid."'"; - $cms->db_exec($q); - if (QUEUE == 'live_queue') - { - $sql_action = 'UPDATE'; - $sql_data = $q_set; - } - } - // insert new data - else - { - $file_uid = md5(uniqid(rand(), true)); - $q = "INSERT INTO file (name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type) VALUES ('".addslashes($name_en)."', '".addslashes($name_ja)."', '".addslashes($file_name)."', '".$online."', '".$mime_type."', $file_size, ".(($width) ? $width : 'NULL').", ".(($height) ? $height : 'NULL').", '".$file_uid."', '".$file_type."')"; - $cms->db_exec($q); - $file_id = $cms->insert_id; - // if queue - if (QUEUE == 'live_queue') - { - $sql_data = $q; - $sql_action = 'INSERT'; - } - } - $size_x = $width; - $size_y = $height; - $file = DEV_SCHEMA."_".$file_uid; - // now upload the file - if ($_FILES['file_up']['name']) - { - $upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file; - // wipe out any old tmp data for this new upload - if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) - { - foreach (glob(ROOT.TMP."thumb_".$file."*") AS $filename) - @unlink($filename); - } - # copy file to correct path - $error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file); - -$cms->debug('file_upload', "UP: $upload_file"); -$cms->debug('file_upload', "Orig: ".$cms->print_ar($_FILES['file_up'])); - - // because I get bogus error info from move_uploaded_file ... - $error = 0; - if ($error) - { -$cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize")); - $cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error'); - $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; - $cms->db_exec($q); - unset($file_id); - unset($file_uid); - $view = 'list'; - } - else - { - $cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning'); -// $vew = 'list'; - } - } // if file upload - // create thumbs + file size - $picture = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 400, 280, $file_type, '', $cms->cache_pictures_root); - $picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $file_type, '', $cms->cache_pictures_root); - $file_size = $cms->adbByteStringFormat($file_size); - // for live queue this is here needed - if (QUEUE == 'live_queue') - { - $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action"; - if ($_FILES['file_up']['name']) - $q .= ", file"; - $q .= ") VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', '".$sql_action."', 'file', '".$cms->db_escape_string($sql_data)."', '".$cms->queue_key."', '".$cms->action."'"; - if ($_FILES['file_up']['name']) - $q .= ", '".ROOT.MEDIA.$cms->data_path[$file_type].$file."#".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."'"; - $q .= ")"; - $cms->db_exec($q); - } - } // if not error } - if ($cms->action == 'delete' && $cms->action_yes == 'true') - { - $file_uid = $cms->action_id; - $q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'"; - list ($file_type) = $cms->db_return_row($q); - // get the file type for the file path - $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; - $cms->db_exec($q); - if (QUEUE == 'set_live') - { - $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')"; + // binary: all okay + // if no error, save data + if (!$error) { + if ($_FILES['file_up']['name']) { + $mime_type = $_FILES['file_up']['type']; + $file_size = $_FILES['file_up']['size']; + $file_name = $_FILES['file_up']['name']; + // get picture size + list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']); + $cms->debug('upload', "Width: $width X Height: $height"); + // set the file type and the target folder + if (preg_match("/jpeg|png|gif/", $mime_type)) { + $file_type = 'P'; + } elseif (preg_match("/swf/", $mime_type)) { + $file_type = 'F'; + } elseif (preg_match("/video/", $mime_type)) { + $file_type = 'V'; + } elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) { + $file_type = 'D'; + } elseif (preg_match("/pdf/", $mime_type)) { + $file_type = 'A'; + } elseif ($mime_type) { + $file_type = 'B'; + } + } + // if we have an id -> updated + if ($file_uid) { + $q = "UPDATE file SET"; + $q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' "; + if ($_FILES['file_up']['name']) { + $q_set .= ", type = '".$file_type."', mime_type = '$mime_type', file_size = $file_size, size_x = $width, size_y = $height "; + } + $q .= $q_set."WHERE file_uid = '".$file_uid."'"; $cms->db_exec($q); + if (QUEUE == 'live_queue') { + $sql_action = 'UPDATE'; + $sql_data = $q_set; + } + } else { + // insert new data + $file_uid = md5(uniqid(rand(), true)); + $q = "INSERT INTO file (name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type) VALUES ("; + $q .= "'".addslashes($name_en)."', '".addslashes($name_ja)."', '".addslashes($file_name)."', '".$online."', '".$mime_type."', "; + $q .= "$file_size, ".(($width) ? $width : 'NULL').", ".(($height) ? $height : 'NULL').", '".$file_uid."', '".$file_type."')"; + $cms->db_exec($q); + $file_id = $cms->insert_id; + // if queue + if (QUEUE == 'live_queue') { + $sql_data = $q; + $sql_action = 'INSERT'; + } } - if (QUEUE == 'live_queue') - { - $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action, file) VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', 'DELETE', 'file', '', '".$cms->queue_key."', '".$cms->action."', '".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."')"; - } - @unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid); - unset($file_uid); - unset($file_id); - $delete_done = 1; - $view = 'list'; - } - if ($cms->action == 'load') - { - $file_uid = $cms->action_id; - // load the data - $q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, type FROM file WHERE file_uid = '".$file_uid."'"; - list($file_id, $name_en, $name_ja, $file_name, $online, $mime_type, $file_size, $size_x, $size_y, $file_type) = $cms->db_return_row($q); - // create thumbnail for edit view + $size_x = $width; + $size_y = $height; $file = DEV_SCHEMA."_".$file_uid; - // thumbnails are only valid for pictures + // now upload the file + if ($_FILES['file_up']['name']) { + $upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file; + // wipe out any old tmp data for this new upload + if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) { + foreach (glob(ROOT.TMP."thumb_".$file."*") as $filename) { + @unlink($filename); + } + } + # copy file to correct path + $error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file); + + $cms->debug('file_upload', "UP: $upload_file"); + $cms->debug('file_upload', "Orig: ".$cms->print_ar($_FILES['file_up'])); + + // because I get bogus error info from move_uploaded_file ... + $error = 0; + if ($error) { + $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize")); + $cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error'); + $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; + $cms->db_exec($q); + unset($file_id); + unset($file_uid); + $view = 'list'; + } else { + $cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning'); + // $view = 'list'; + } + } // if file upload + // create thumbs + file size $picture = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 400, 280, $file_type, '', $cms->cache_pictures_root); $picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $file_type, '', $cms->cache_pictures_root); $file_size = $cms->adbByteStringFormat($file_size); - // view to edit - $view = 'edit'; - } - if ($cms->action == 'add_new') - { - $view = 'edit'; - } - if ($cms->action == 'view_files' && $cms->action_yes == 'true') - { - $view = 'list'; - } - // set delete live - if ($cms->action_flag == 'set_live' && $cms->action = 'set_delete') - { - $q = "SELECT file_uid, pkid, type FROM ".LOGIN_DB_SCHEMA.".set_live sl, file f WHERE sl.pkid = f.file_uid table_name = '".$cms->page_name."' AND delete_flag = 't'"; - while ($res = $cms->db_return($q)) - { - $q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"'; - $cms->db_exec($q_del); - @unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']); + // for live queue this is here needed + if (QUEUE == 'live_queue') { + $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action"; + if ($_FILES['file_up']['name']) { + $q .= ", file"; + } + $q .= ") VALUES ('".$cms->queue_name."', '".$file_uid."', 'file_uid', '".$sql_action."', 'file', '".$cms->db_escape_string($sql_data)."', '".$cms->queue_key."', '".$cms->action."'"; + if ($_FILES['file_up']['name']) { + $q .= ", '".ROOT.MEDIA.$cms->data_path[$file_type].$file."#".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."'"; + } + $q .= ")"; + $cms->db_exec($q); } - $q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; + } // if not error +} +if ($cms->action == 'delete' && $cms->action_yes == 'true') { + $file_uid = $cms->action_id; + $q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'"; + list ($file_type) = $cms->db_return_row($q); + // get the file type for the file path + $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; + $cms->db_exec($q); + if (QUEUE == 'set_live') { + $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')"; $cms->db_exec($q); } - if (DEV_SCHEMA != PUBLIC_SCHEMA) - { - // read out possible deleted, to add "delete from live" - $q = "SELECT pkid FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; - while ($res = $cms->db_return($q, 3)) - { - $cms->DATA['set_delete'][]['pkid'] = $res['pkid']; - } + if (QUEUE == 'live_queue') { + $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action, file) VALUES ("; + $q .= "'".$cms->queue_name."', '".$file_uid."', 'file_uid', 'DELETE', 'file', '', '".$cms->queue_key."', '".$cms->action."', '".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."')"; } - // get th max entries - $q = "SELECT COUNT(file_uid) FROM file "; - $q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') "; - if ($search_what) - { - $q_search_where .= "AND LOWER(name_en) LIKE '%".addslashes(strtolower($search_what))."%' OR name_ja LIKE '%".addslashes($search_what)."%' OR LOWER(file_name) LIKE '%".addslashes(strtolower($search_what))."%' "; + @unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid); + unset($file_uid); + unset($file_id); + $delete_done = 1; + $view = 'list'; +} +if ($cms->action == 'load') { + $file_uid = $cms->action_id; + // load the data + $q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, type FROM file WHERE file_uid = '".$file_uid."'"; + list($file_id, $name_en, $name_ja, $file_name, $online, $mime_type, $file_size, $size_x, $size_y, $file_type) = $cms->db_return_row($q); + // create thumbnail for edit view + $file = DEV_SCHEMA."_".$file_uid; + // thumbnails are only valid for pictures + $picture = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 400, 280, $file_type, '', $cms->cache_pictures_root); + $picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $file_type, '', $cms->cache_pictures_root); + $file_size = $cms->adbByteStringFormat($file_size); + // view to edit + $view = 'edit'; +} +if ($cms->action == 'add_new') { + $view = 'edit'; +} +if ($cms->action == 'view_files' && $cms->action_yes == 'true') { + $view = 'list'; +} +// set delete live +if ($cms->action_flag == 'set_live' && $cms->action = 'set_delete') { + $q = "SELECT file_uid, pkid, type FROM ".LOGIN_DB_SCHEMA.".set_live sl, file f WHERE sl.pkid = f.file_uid table_name = '".$cms->page_name."' AND delete_flag = 't'"; + while ($res = $cms->db_return($q)) { + $q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"'; + $cms->db_exec($q_del); + @unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']); } - $q .= $q_search_where; - // get selection from show_type - list ($file_count) = $cms->db_return_row($q); + $q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; + $cms->db_exec($q); +} +if (DEV_SCHEMA != PUBLIC_SCHEMA) { + // read out possible deleted, to add "delete from live" + $q = "SELECT pkid FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; + while ($res = $cms->db_return($q, 3)) { + $cms->DATA['set_delete'][]['pkid'] = $res['pkid']; + } +} +// get th max entries +$q = "SELECT COUNT(file_uid) FROM file "; +$q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') "; +if ($search_what) { + $q_search_where .= "AND LOWER(name_en) LIKE '%".addslashes(strtolower($search_what))."%' OR name_ja LIKE '%".addslashes($search_what)."%' OR LOWER(file_name) LIKE '%".addslashes(strtolower($search_what))."%' "; +} +$q .= $q_search_where; +// get selection from show_type +list ($file_count) = $cms->db_return_row($q); - if ($cms->action == 'browse') - { - // browse in the list of data - switch ($cms->action_id) - { - case "<<<<": - $start_row = 0; - break; - case "<": - $start_row -= $show_amount; - break; - case ">": - $start_row += $show_amount; - break; - case ">>>>": - $start_row = $file_count - $show_amount; - break; - case "gopage": - // for page is page -1, so page 1 start from 0, etc - $start_row = ((($cms->action_value - 1) > 0) ? ($cms->action_value - 1) * $show_amount : 0); - $current_page = $cms->action_value; - break; - } +if ($cms->action == 'browse') { + // browse in the list of data + switch ($cms->action_id) { + case "<<<<": + $start_row = 0; + break; + case "<": + $start_row -= $show_amount; + break; + case ">": + $start_row += $show_amount; + break; + case ">>>>": + $start_row = $file_count - $show_amount; + break; + case "gopage": + // for page is page -1, so page 1 start from 0, etc + $start_row = ((($cms->action_value - 1) > 0) ? ($cms->action_value - 1) * $show_amount : 0); + $current_page = $cms->action_value; + break; } +} - // check overflow - if ($start_row < 0) - $start_row = 0; - if ($start_row > $file_count) - $start_row = $file_count - $show_amount; +// check overflow +if ($start_row < 0) { + $start_row = 0; +} +if ($start_row > $file_count) { + $start_row = $file_count - $show_amount; +} - // if we have a "fresh_load" - if ($fresh_load) - { - $count = 1; - $q = "SELECT file_uid FROM file "; - if ($q_search_where) - $q .= $q_search_where; - $q .= "ORDER BY ".$sort_order." ".$sort_direction." "; - while ($res = $cms->db_return($q)) - { - // if data_id is set and not file_id, go to the page where the current highlight is, but only if this is a "virgin" load of the page - if ($data_id && ($data_id == $res['file_uid'])) - { - $current_page = floor(($count / $show_amount)); - $start_row = $current_page * $show_amount; - $current_page ++; - } - $count ++; - } - } - - // page forward/back buttons settings - if ($start_row > 0) - { - $cms->DATA['show_back'] = 1; - } - $cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1; - $cms->DATA['page_count'] = ceil($file_count / $show_amount); - if ($cms->DATA['page_count'] > 2 && !$current_page) - { - $current_page = 1; - } - if (($start_row + $show_amount) < $file_count) - { - $cms->DATA['show_forward'] = 1; - } - - $q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type FROM file "; - // if search what, search in name_en, name_ja, file_name for the string - if ($q_search_where) +// if we have a "fresh_load" +if ($fresh_load) { + $count = 1; + $q = "SELECT file_uid FROM file "; + if ($q_search_where) { $q .= $q_search_where; + } $q .= "ORDER BY ".$sort_order." ".$sort_direction." "; - $q .= "LIMIT ".$show_amount." OFFSET ".$start_row; - while ($res = $cms->db_return($q)) - { - $data_files[] = array ( - 'id' => $res['file_id'], - 'name_en' => $res['name_en'], - 'name_ja' => $res['name_ja'], - 'file_name' => $res['file_name'], - 'online' => $res['online'], - 'mime_type' => $res['mime_type'], - 'file_size' => $cms->adbByteStringFormat($res['file_size']), - 'size_x' => $res['size_x'], - 'size_y' => $res['size_y'], - 'file_uid' => $res['file_uid'], - 'file_type' => $res['type'], - 'picture' => $cms->cache_pictures.$cms->adbCreateThumbnail(DEV_SCHEMA.'_'.$res['file_uid'], 80, 60, $res['type'], '', $cms->cache_pictures_root) - ); + while ($res = $cms->db_return($q)) { + // if data_id is set and not file_id, go to the page where the current highlight is, but only if this is a "virgin" load of the page + if ($data_id && ($data_id == $res['file_uid'])) { + $current_page = floor(($count / $show_amount)); + $start_row = $current_page * $show_amount; + $current_page ++; + } + $count ++; } +} - $cms->DATA['show_type'] = $show_type; - $cms->DATA['data_files'] = $data_files; - $cms->DATA['view'] = $view; - $cms->DATA['images_path'] = MEDIA.$cms->data_path[$file_type]; - // get vars for position (only when) - $cms->DATA['form_name'] = $form_name; - $cms->DATA['value_name'] = $value_name; - $cms->DATA['file_id'] = $file_id; - $cms->DATA['file_uid'] = $file_uid; +// page forward/back buttons settings +if ($start_row > 0) { + $cms->DATA['show_back'] = 1; +} +$cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1; +$cms->DATA['page_count'] = ceil($file_count / $show_amount); +if ($cms->DATA['page_count'] > 2 && !$current_page) { + $current_page = 1; +} +if (($start_row + $show_amount) < $file_count) { + $cms->DATA['show_forward'] = 1; +} - // write back all the other vars - if (!($delete_done || $new_okay)) - { - // data name - $cms->DATA['file_name'] = $file_name; - $cms->DATA['name_en'] = $name_en; - $cms->DATA['name_ja'] = $name_ja; - $cms->DATA['mime_type'] = $mime_type; - $cms->DATA['file_size'] = $file_size; - $cms->DATA['size_x'] = $size_x; - $cms->DATA['size_y'] = $size_y; - $cms->DATA['online'] = $online; - $cms->DATA['picture'] = $picture; - $cms->DATA['picture_small'] = $picture_small; - $cms->DATA['file_type'] = $file_type; - } - $cms->DATA['sort_order_list'] = $sort_order_list; - $cms->DATA['sort_order'] = $sort_order; - $cms->DATA['sort_direction_list'] = $sort_direction_list; - $cms->DATA['sort_direction'] = $sort_direction; - $cms->DATA['search_what'] = $search_what; - $cms->DATA['current_page'] = $current_page; - $cms->DATA['yesno_list'] = $yesno_list; - $cms->DATA['start_row'] = $start_row; - $cms->DATA['show_amount'] = $show_amount; - if ($data_id) - $cms->DATA['data_id'] = $data_id; - $cms->DATA['top'] = 0; - $cms->DATA['left'] = 0; +$q = "SELECT file_id, name_en, name_ja, file_name, online, mime_type, file_size, size_x, size_y, file_uid, type FROM file "; +// if search what, search in name_en, name_ja, file_name for the string +if ($q_search_where) { + $q .= $q_search_where; +} +$q .= "ORDER BY ".$sort_order." ".$sort_direction." "; +$q .= "LIMIT ".$show_amount." OFFSET ".$start_row; +while ($res = $cms->db_return($q)) { + $data_files[] = array ( + 'id' => $res['file_id'], + 'name_en' => $res['name_en'], + 'name_ja' => $res['name_ja'], + 'file_name' => $res['file_name'], + 'online' => $res['online'], + 'mime_type' => $res['mime_type'], + 'file_size' => $cms->adbByteStringFormat($res['file_size']), + 'size_x' => $res['size_x'], + 'size_y' => $res['size_y'], + 'file_uid' => $res['file_uid'], + 'file_type' => $res['type'], + 'picture' => $cms->cache_pictures.$cms->adbCreateThumbnail(DEV_SCHEMA.'_'.$res['file_uid'], 80, 60, $res['type'], '', $cms->cache_pictures_root) + ); +} - //------------------------------ processing data end +$cms->DATA['show_type'] = $show_type; +$cms->DATA['data_files'] = $data_files; +$cms->DATA['view'] = $view; +$cms->DATA['images_path'] = MEDIA.$cms->data_path[$file_type]; +// get vars for position (only when) +$cms->DATA['form_name'] = $form_name; +$cms->DATA['value_name'] = $value_name; +$cms->DATA['file_id'] = $file_id; +$cms->DATA['file_uid'] = $file_uid; - //------------------------------ smarty start - require("smarty.inc"); - //------------------------------ smarty end +// write back all the other vars +if (!($delete_done || $new_okay)) { + // data name + $cms->DATA['file_name'] = $file_name; + $cms->DATA['name_en'] = $name_en; + $cms->DATA['name_ja'] = $name_ja; + $cms->DATA['mime_type'] = $mime_type; + $cms->DATA['file_size'] = $file_size; + $cms->DATA['size_x'] = $size_x; + $cms->DATA['size_y'] = $size_y; + $cms->DATA['online'] = $online; + $cms->DATA['picture'] = $picture; + $cms->DATA['picture_small'] = $picture_small; + $cms->DATA['file_type'] = $file_type; +} +$cms->DATA['sort_order_list'] = $sort_order_list; +$cms->DATA['sort_order'] = $sort_order; +$cms->DATA['sort_direction_list'] = $sort_direction_list; +$cms->DATA['sort_direction'] = $sort_direction; +$cms->DATA['search_what'] = $search_what; +$cms->DATA['current_page'] = $current_page; +$cms->DATA['yesno_list'] = $yesno_list; +$cms->DATA['start_row'] = $start_row; +$cms->DATA['show_amount'] = $show_amount; +if ($data_id) { + $cms->DATA['data_id'] = $data_id; +} +$cms->DATA['top'] = 0; +$cms->DATA['left'] = 0; - //------------------------------ footer - require("footer.inc"); - //------------------------------ footer +//------------------------------ processing data end -?> +//------------------------------ smarty start +require("smarty.inc"); +//------------------------------ smarty end + +//------------------------------ footer +require("footer.inc"); +//------------------------------ footer diff --git a/www/admin/footer.inc b/www/admin/footer.inc index c40fb05c..058db58c 100644 --- a/www/admin/footer.inc +++ b/www/admin/footer.inc @@ -1,13 +1,12 @@ print_error_msg(); - echo $cms->print_error_msg(); -?> +// print debug messages +echo $login->print_error_msg(); +echo $cms->print_error_msg(); diff --git a/www/admin/header.inc b/www/admin/header.inc index f0898e11..3c2e5fb6 100644 --- a/www/admin/header.inc +++ b/www/admin/header.inc @@ -1,102 +1,104 @@ .log - if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) - include("libs/Error.Handling.inc"); - // predefine vars - $lang = ''; - $messages = array (); - // import all POST vars - extract($_POST, EXTR_SKIP); - //------------------------------ variable init end +//------------------------------ variable init start +// for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-.log +if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) { + include("libs/Error.Handling.inc"); +} +// predefine vars +$lang = ''; +$messages = array (); +// import all POST vars +extract($_POST, EXTR_SKIP); +//------------------------------ variable init end - //------------------------------ library include start - // set output to quiet for load of classes & session settings - ob_start(); - require("config.inc"); - // set the session name - define('SET_SESSION_NAME', EDIT_SESSION_NAME); - // login class, DB connections & Admin class, Smarty extension - foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class) - _spl_autoload('Class.'.$class.'.inc'); - //------------------------------ library include end +//------------------------------ library include start +// set output to quiet for load of classes & session settings +ob_start(); +require("config.inc"); - //------------------------------ basic variable settings start - // set encoding - if (!isset($encoding)) - $encoding = DEFAULT_ENCODING; - // set the default lang, if not given - if (session_id() && $_SESSION['DEFAULT_LANG']) - $lang = $_SESSION['DEFAULT_LANG']; - elseif (!$lang) - $lang = DEFAULT_LANG; - // end the stop of the output flow, but only if we didn't request a csv file download - if (array_key_exists('action', $_POST) && $_POST['action'] != 'download_csv') - { - header("Content-type: text/html; charset=".$encoding); - ob_end_flush(); - } - //------------------------------ basic variable settings start +// login class, DB connections & Admin class, Smarty extension +foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class) { + _spl_autoload('Class.'.$class.'.inc'); +} +//------------------------------ library include end - //------------------------------ class init start - // login & page access check - $login = new login($DB_CONFIG[LOGIN_DB], $lang); - // post login lang check - if ($_SESSION['DEFAULT_LANG']) - $lang = $_SESSION['DEFAULT_LANG']; - // create smarty object - $smarty = new SmartyML($lang); - // create new DB class - $cms = new AdminBackend($DB_CONFIG[MAIN_DB], $lang); - // set search path to the default DB schema - $cms->db_exec("SET search_path TO ".DB_SCHEMA); - // the menu show flag (what menu to show) - $cms->menu_show_flag = 'main'; - // db nfo - $cms->db_info(); - // set acl - $cms->acl = $login->acl; - //------------------------------ class init end +//------------------------------ basic variable settings start +// set encoding +if (!isset($encoding)) { + $encoding = DEFAULT_ENCODING; +} +// set the default lang, if not given +if (session_id() && $_SESSION['DEFAULT_LANG']) { + $lang = $_SESSION['DEFAULT_LANG']; +} elseif (!$lang) { + $lang = DEFAULT_LANG; +} +// end the stop of the output flow, but only if we didn't request a csv file download +if (array_key_exists('action', $_POST) && $_POST['action'] != 'download_csv') { + header("Content-type: text/html; charset=".$encoding); + ob_end_flush(); +} +//------------------------------ basic variable settings start - //------------------------------ logging start - // log backend data - // data part creation - $data = array ( - '_SESSION' => $_SESSION, - '_GET' => $_GET, - '_POST' => $_POST, - '_FILES' => $_FILES - ); - // log action - // no log if login - if (!$login->login) - $cms->adbEditLog('Submit', $data, 'BINARY'); - //------------------------------ logging end +//------------------------------ class init start +// login & page access check +$login = new login($DB_CONFIG[LOGIN_DB], $lang); +// post login lang check +if ($_SESSION['DEFAULT_LANG']) { + $lang = $_SESSION['DEFAULT_LANG']; +} +// create smarty object +$smarty = new SmartyML($lang); +// create new DB class +$cms = new AdminBackend($DB_CONFIG[MAIN_DB], $lang); +// set search path to the default DB schema +$cms->db_exec("SET search_path TO ".DB_SCHEMA); +// the menu show flag (what menu to show) +$cms->menu_show_flag = 'main'; +// db nfo +$cms->db_info(); +// set acl +$cms->acl = $login->acl; +//------------------------------ class init end - //------------------------------ page rights start - // flag if to show the edit access id drop down list - // check if we have more than one EA ID - $cms->DATA['show_ea_extra'] = $login->acl['acl']['show_ea_extra']; - //------------------------------ page rights ned +//------------------------------ logging start +// log backend data +// data part creation +$data = array ( + '_SESSION' => $_SESSION, + '_GET' => $_GET, + '_POST' => $_POST, + '_FILES' => $_FILES +); +// log action +// no log if login +if (!$login->login) { + $cms->adbEditLog('Submit', $data, 'BINARY'); +} +//------------------------------ logging end - // automatic hide for DEBUG messages on live server - // can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script (for emergency debugging of one page only) - if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) - { - $login->debug_output_all = 0; - $login->echo_output_all = 0; - $login->print_output_all = 0; - $cms->debug_output_all = 0; - $cms->echo_output_all = 0; - $cms->print_output_all = 0; - } - $cms->DATA['JS_DEBUG'] = DEBUG; -?> +//------------------------------ page rights start +// flag if to show the edit access id drop down list +// check if we have more than one EA ID +$cms->DATA['show_ea_extra'] = $login->acl['acl']['show_ea_extra']; +//------------------------------ page rights ned + +// automatic hide for DEBUG messages on live server +// can be overridden when setting DEBUG_ALL_OVERRIDE on top of the script (for emergency debugging of one page only) +if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) { + $login->debug_output_all = 0; + $login->echo_output_all = 0; + $login->print_output_all = 0; + $cms->debug_output_all = 0; + $cms->echo_output_all = 0; + $cms->print_output_all = 0; +} +$cms->DATA['JS_DEBUG'] = DEBUG; diff --git a/www/admin/includes/Date.Vars.inc b/www/admin/includes/Date.Vars.inc index a6c9f6bc..1ccc03b1 100644 --- a/www/admin/includes/Date.Vars.inc +++ b/www/admin/includes/Date.Vars.inc @@ -1,53 +1,51 @@ +$month_short[1] = "Jan"; +$month_short[2] = "Feb"; +$month_short[3] = "Mar"; +$month_short[4] = "Apr"; +$month_short[5] = "May"; +$month_short[6] = "Jun"; +$month_short[7] = "Jul"; +$month_short[8] = "Aug"; +$month_short[9] = "Sep"; +$month_short[10] = "Oct"; +$month_short[11] = "Nov"; +$month_short[12] = "Dec"; diff --git a/www/admin/set_paths.inc b/www/admin/set_paths.inc index 41272903..263bc3e7 100644 --- a/www/admin/set_paths.inc +++ b/www/admin/set_paths.inc @@ -1,113 +1,119 @@ page_name); - $FORM_NAME = !isset($FORM_NAME) || !$FORM_NAME ? str_replace(".php", "", $cms->page_name) : $FORM_NAME; - // set local page title - $L_TITLE = ucfirst(str_replace('_', ' ', $cms->get_page_name(1))).' - '.$G_TITLE; - // strip tpl and replace it with inc - // php include file per page - $cms->INC_TEMPLATE_NAME = str_replace(".tpl", ".inc", $CONTENT_INCLUDE); - // javascript include per page - $cms->JS_TEMPLATE_NAME = str_replace(".tpl", ".js", $CONTENT_INCLUDE); - // css per page - $cms->CSS_TEMPLATE_NAME = str_replace(".tpl", ".css", $CONTENT_INCLUDE); - // special CSS file - $cms->CSS_SPECIAL_TEMPLATE_NAME = @$CSS_NAME; - // special JS file - $cms->JS_SPECIAL_TEMPLATE_NAME = @$JS_NAME; +// set include & template names +$CONTENT_INCLUDE = str_replace(".php", ".tpl", $cms->page_name); +$FORM_NAME = !isset($FORM_NAME) || !$FORM_NAME ? str_replace(".php", "", $cms->page_name) : $FORM_NAME; +// set local page title +$L_TITLE = ucfirst(str_replace('_', ' ', $cms->get_page_name(1))).' - '.$G_TITLE; +// strip tpl and replace it with inc +// php include file per page +$cms->INC_TEMPLATE_NAME = str_replace(".tpl", ".inc", $CONTENT_INCLUDE); +// javascript include per page +$cms->JS_TEMPLATE_NAME = str_replace(".tpl", ".js", $CONTENT_INCLUDE); +// css per page +$cms->CSS_TEMPLATE_NAME = str_replace(".tpl", ".css", $CONTENT_INCLUDE); +// special CSS file +$cms->CSS_SPECIAL_TEMPLATE_NAME = @$CSS_NAME; +// special JS file +$cms->JS_SPECIAL_TEMPLATE_NAME = @$JS_NAME; - // set basic template path (tmp) - $smarty->setTemplateDir(LAYOUT.$TEMPLATE_DIR.TEMPLATES.'/'); - $cms->lang_dir = LAYOUT.$TEMPLATE_DIR.LANG."/"; - $cms->includes = LAYOUT.$TEMPLATE_DIR.INCLUDES."/"; - $cms->javascript = LAYOUT.$TEMPLATE_DIR.JS."/"; - $cms->css = LAYOUT.$TEMPLATE_DIR.CSS."/"; - $cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/"; - $cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/'; - $cms->cache_pictures_root = ROOT.$cms->cache_pictures; - if (!is_dir($cms->cache_pictures_root)) - mkdir($cms->cache_pictures_root); - $template_set = $TEMPLATE; +// set basic template path (tmp) +$smarty->setTemplateDir(LAYOUT.$TEMPLATE_DIR.TEMPLATES.'/'); +$cms->lang_dir = LAYOUT.$TEMPLATE_DIR.LANG."/"; +$cms->includes = LAYOUT.$TEMPLATE_DIR.INCLUDES."/"; +$cms->javascript = LAYOUT.$TEMPLATE_DIR.JS."/"; +$cms->css = LAYOUT.$TEMPLATE_DIR.CSS."/"; +$cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/"; +$cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/'; +$cms->cache_pictures_root = ROOT.$cms->cache_pictures; +if (!is_dir($cms->cache_pictures_root)) { + mkdir($cms->cache_pictures_root); +} +$template_set = $TEMPLATE; - // if we don't find the master template, set the template path back AND set the insert template as absolute path - if (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".MASTER_TEMPLATE_NAME)) - { - if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) - $TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME; - $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); - $template_set = DEFAULT_TEMPLATE; +// if we don't find the master template, set the template path back AND set the insert template as absolute path +if (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".MASTER_TEMPLATE_NAME)) { + if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) { + $TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME; } + $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); + $template_set = DEFAULT_TEMPLATE; +} elseif (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) { // check if the template exists in the template path, if not, set path to to default - elseif (!file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) - { - $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); - $template_set = DEFAULT_TEMPLATE; - } - // loop to check if dir exists - // check if file exists, if not reset to default path + $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); + $template_set = DEFAULT_TEMPLATE; +} +// loop to check if dir exists +// check if file exists, if not reset to default path - // check if the javascript folder exists in the template path, if not fall back to default - if (!is_dir($cms->javascript)) - $cms->javascript = LAYOUT.DEFAULT_TEMPLATE.JS."/"; - // check if lang_dir folder exists in the template path, if not fall back to default - if (!is_dir($cms->lang_dir)) - $cms->lang_dir = LAYOUT.DEFAULT_TEMPLATE.LANG."/"; - // check if include folder exists in the template path, if not fall back to default - if (!is_dir($cms->includes)) - $cms->includes = LAYOUT.DEFAULT_TEMPLATE.INCLUDES."/"; - // check if css folder exists in the template path, if not fall back to default - if (!is_dir($cms->css)) - $cms->css = LAYOUT.DEFAULT_TEMPLATE.CSS."/"; - if (!is_dir($cms->pictures)) - $cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/'; - if (!is_dir($cms->cache_pictures)) - $cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/'; +// check if the javascript folder exists in the template path, if not fall back to default +if (!is_dir($cms->javascript)) { + $cms->javascript = LAYOUT.DEFAULT_TEMPLATE.JS."/"; +} +// check if lang_dir folder exists in the template path, if not fall back to default +if (!is_dir($cms->lang_dir)) { + $cms->lang_dir = LAYOUT.DEFAULT_TEMPLATE.LANG."/"; +} +// check if include folder exists in the template path, if not fall back to default +if (!is_dir($cms->includes)) { + $cms->includes = LAYOUT.DEFAULT_TEMPLATE.INCLUDES."/"; +} +// check if css folder exists in the template path, if not fall back to default +if (!is_dir($cms->css)) { + $cms->css = LAYOUT.DEFAULT_TEMPLATE.CSS."/"; +} +if (!is_dir($cms->pictures)) { + $cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/'; +} +if (!is_dir($cms->cache_pictures)) { + $cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/'; +} - // if the template_dir is != DEFAULT_TEMPLATE, then try to make a lang switch - // if the default lang is not like the lang given, switch lang - if (false === strstr(LAYOUT.DEFAULT_TEMPLATE.LANG, $cms->lang_dir) || strcasecmp(DEFAULT_LANG, $lang)) - { - $cms->debug('LANG', 'Orig: '.LAYOUT.DEFAULT_TEMPLATE.LANG.', New: '.$cms->lang_dir.' | Orig Lang: '.DEFAULT_LANG.', New Lang: '.$lang); - $cms->l->l10nReloadMOfile($lang, $cms->lang_dir); - $smarty->l10n->l10nReloadMOfile($lang, $cms->lang_dir); - } +// if the template_dir is != DEFAULT_TEMPLATE, then try to make a lang switch +// if the default lang is not like the lang given, switch lang +if (false === strstr(LAYOUT.DEFAULT_TEMPLATE.LANG, $cms->lang_dir) || strcasecmp(DEFAULT_LANG, $lang)) { + $cms->debug('LANG', 'Orig: '.LAYOUT.DEFAULT_TEMPLATE.LANG.', New: '.$cms->lang_dir.' | Orig Lang: '.DEFAULT_LANG.', New Lang: '.$lang); + $cms->l->l10nReloadMOfile($lang, $cms->lang_dir); + $smarty->l10n->l10nReloadMOfile($lang, $cms->lang_dir); +} // $cms->debug("LANGUAGE", "L: $lang | ".$cms->lang_dir." | MO File: ".$cms->l->mofile); - $cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']); - $cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]); - -?> +$cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']); +$cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]); diff --git a/www/admin/smarty.inc b/www/admin/smarty.inc index 1a500a42..2cb730f3 100644 --- a/www/admin/smarty.inc +++ b/www/admin/smarty.inc @@ -1,103 +1,96 @@ HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE; - // scriptacolous, can only be used with prototype - if (USE_PROTOTYPE) - $cms->HEADER['USE_SCRIPTACULOUS'] = USE_SCRIPTACULOUS; - // jquery and prototype should not be used together - $cms->HEADER['USE_JQUERY'] = USE_JQUERY; // don't use either of those two toger +// trigger flags +$cms->HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE; +// scriptacolous, can only be used with prototype +if (USE_PROTOTYPE) { + $cms->HEADER['USE_SCRIPTACULOUS'] = USE_SCRIPTACULOUS; +} +// jquery and prototype should not be used together +$cms->HEADER['USE_JQUERY'] = USE_JQUERY; // don't use either of those two toger - // set basic template path (tmp) - // paths are set in the 'set_paths.inc' file +// set basic template path (tmp) +// paths are set in the 'set_paths.inc' file - // check if we have an external file with the template name - if (file_exists($cms->includes.$cms->INC_TEMPLATE_NAME) && is_file($cms->includes.$cms->INC_TEMPLATE_NAME)) - { - include($cms->includes.$cms->INC_TEMPLATE_NAME); - } - // additional per page Javascript include - $cms->JS_INCLUDE = ''; - if (file_exists($cms->javascript.$cms->JS_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_TEMPLATE_NAME)) - { - $cms->JS_INCLUDE = $cms->javascript.$cms->JS_TEMPLATE_NAME; - } - // per page css file - $cms->CSS_INCLUDE = ''; - if (file_exists($cms->css.$cms->CSS_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_TEMPLATE_NAME)) - { - $cms->CSS_INCLUDE = $cms->css.$cms->CSS_TEMPLATE_NAME; - } - // optional CSS file - $cms->CSS_SPECIAL_INCLUDE = ''; - if (file_exists($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME)) - { - $cms->CSS_SPECIAL_INCLUDE = $cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME; - } - // optional JS file - $cms->JS_SPECIAL_INCLUDE = ''; - if (file_exists($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME)) - { - $cms->JS_SPECIAL_INCLUDE = $cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME; - } +// check if we have an external file with the template name +if (file_exists($cms->includes.$cms->INC_TEMPLATE_NAME) && is_file($cms->includes.$cms->INC_TEMPLATE_NAME)) { + include($cms->includes.$cms->INC_TEMPLATE_NAME); +} +// additional per page Javascript include +$cms->JS_INCLUDE = ''; +if (file_exists($cms->javascript.$cms->JS_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_TEMPLATE_NAME)) { + $cms->JS_INCLUDE = $cms->javascript.$cms->JS_TEMPLATE_NAME; +} +// per page css file +$cms->CSS_INCLUDE = ''; +if (file_exists($cms->css.$cms->CSS_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_TEMPLATE_NAME)) { + $cms->CSS_INCLUDE = $cms->css.$cms->CSS_TEMPLATE_NAME; +} +// optional CSS file +$cms->CSS_SPECIAL_INCLUDE = ''; +if (file_exists($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME)) { + $cms->CSS_SPECIAL_INCLUDE = $cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME; +} +// optional JS file +$cms->JS_SPECIAL_INCLUDE = ''; +if (file_exists($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME)) { + $cms->JS_SPECIAL_INCLUDE = $cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME; +} - // the actual include files for javascript (per page) - $cms->HEADER['JS_INCLUDE'] = $cms->JS_INCLUDE; - $cms->HEADER['CSS_INCLUDE'] = $cms->CSS_INCLUDE; - $cms->HEADER['CSS_SPECIAL_INCLUDE'] = $cms->CSS_SPECIAL_INCLUDE; - $cms->HEADER['JS_SPECIAL_INCLUDE'] = $cms->JS_SPECIAL_INCLUDE; - // paths to the files - $cms->DATA['includes'] = $cms->includes; - $cms->DATA['js'] = $cms->javascript; - $cms->DATA['css'] = $cms->css; - $cms->DATA['pictures'] = $cms->pictures; +// the actual include files for javascript (per page) +$cms->HEADER['JS_INCLUDE'] = $cms->JS_INCLUDE; +$cms->HEADER['CSS_INCLUDE'] = $cms->CSS_INCLUDE; +$cms->HEADER['CSS_SPECIAL_INCLUDE'] = $cms->CSS_SPECIAL_INCLUDE; +$cms->HEADER['JS_SPECIAL_INCLUDE'] = $cms->JS_SPECIAL_INCLUDE; +// paths to the files +$cms->DATA['includes'] = $cms->includes; +$cms->DATA['js'] = $cms->javascript; +$cms->DATA['css'] = $cms->css; +$cms->DATA['pictures'] = $cms->pictures; - // default CMS settings - // define all needed smarty stuff for the general HTML/page building - $cms->HEADER['CSS'] = CSS; - $cms->HEADER['JS'] = JS; - $cms->HEADER['ENCODING'] = $encoding; - $cms->HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; - $cms->HEADER['STYLESHEET'] = $EDIT_STYLESHEET; - $cms->HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; - // html title - $cms->HEADER['HTML_TITLE'] = (!isset($L_TITLE) || !$L_TITLE) ? $cms->l->__($G_TITLE) : $cms->l->__($L_TITLE); - $cms->DATA['table_width'] = $PAGE_WIDTH ? $PAGE_WIDTH : PAGE_WIDTH; +// default CMS settings +// define all needed smarty stuff for the general HTML/page building +$cms->HEADER['CSS'] = CSS; +$cms->HEADER['JS'] = JS; +$cms->HEADER['ENCODING'] = $encoding; +$cms->HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; +$cms->HEADER['STYLESHEET'] = $EDIT_STYLESHEET; +$cms->HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; +// html title +$cms->HEADER['HTML_TITLE'] = (!isset($L_TITLE) || !$L_TITLE) ? $cms->l->__($G_TITLE) : $cms->l->__($L_TITLE); +$cms->DATA['table_width'] = $PAGE_WIDTH ? $PAGE_WIDTH : PAGE_WIDTH; - // messages = array('msg' =>, 'class' => 'error/warning/...') - $cms->DATA['messages'] = $cms->messages; +// messages = array('msg' =>, 'class' => 'error/warning/...') +$cms->DATA['messages'] = $cms->messages; - // top menu - $cms->DATA['nav_menu'] = $cms->adbTopMenu(); - // the page name - $cms->DATA['page_name'] = $cms->page_name; - // user name - $cms->DATA['USER_NAME'] = $_SESSION['USER_NAME']; - // the template part to include into the body - $cms->DATA['TEMPLATE_NAME'] = $TEMPLATE_NAME; - $cms->DATA['CONTENT_INCLUDE'] = $CONTENT_INCLUDE; - // LANG - $cms->DATA['LANG'] = $lang; - $cms->DATA['TINYMCE_LANG'] = $lang_short; +// top menu +$cms->DATA['nav_menu'] = $cms->adbTopMenu(); +// the page name +$cms->DATA['page_name'] = $cms->page_name; +// user name +$cms->DATA['USER_NAME'] = $_SESSION['USER_NAME']; +// the template part to include into the body +$cms->DATA['TEMPLATE_NAME'] = $TEMPLATE_NAME; +$cms->DATA['CONTENT_INCLUDE'] = $CONTENT_INCLUDE; +// LANG +$cms->DATA['LANG'] = $lang; +$cms->DATA['TINYMCE_LANG'] = $lang_short; - // debug data, if DEBUG flag is on, this data is print out - $cms->DEBUG_DATA['debug_error_msg'] = $cms->running_time(); - $cms->DEBUG_DATA['DEBUG'] = @$DEBUG_TMPL; +// debug data, if DEBUG flag is on, this data is print out +$cms->DEBUG_DATA['debug_error_msg'] = $cms->running_time(); +$cms->DEBUG_DATA['DEBUG'] = @$DEBUG_TMPL; - // create main data array - $cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA); - // data is 1:1 mapping (all vars, values, etc) - while (list($key, $value) = each($cms->CONTENT_DATA)) - { - $smarty->assign($key, $value); - } - $smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang); - -?> +// create main data array +$cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA); +// data is 1:1 mapping (all vars, values, etc) +while (list($key, $value) = each($cms->CONTENT_DATA)) { + $smarty->assign($key, $value); +} +$smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang); diff --git a/www/admin/smarty_test.php b/www/admin/smarty_test.php index 702dbbdd..f79455b5 100644 --- a/www/admin/smarty_test.php +++ b/www/admin/smarty_test.php @@ -1,21 +1,20 @@ DATA['SMARTY_TEST'] = 'Test Data'; +// smarty test +$cms->DATA['SMARTY_TEST'] = 'Test Data'; - require("smarty.inc"); - require("footer.inc"); -?> +require("smarty.inc"); +require("footer.inc"); diff --git a/www/admin/table_arrays/array_edit_access.inc b/www/admin/table_arrays/array_edit_access.inc index 0aa9acde..e5e81e46 100644 --- a/www/admin/table_arrays/array_edit_access.inc +++ b/www/admin/table_arrays/array_edit_access.inc @@ -1,77 +1,76 @@ array ( - "edit_access_id" => array ( - "value" => $GLOBALS["edit_access_id"], - "type" => "hidden", - "pk" => 1 - ), - "name" => array ( - "value" => $GLOBALS["name"], - "output_name" => $this->l->__("Access Group Name"), - "mandatory" => 1, - "type" => "text", - "error_check" => "alphanumericspace|unique" - ), - "description" => array ( - "value" => $GLOBALS["description"], - "output_name" => $this->l->__("Description"), - "type" => "textarea" - ), - "color" => array ( - "value" => $GLOBALS["color"], - "output_name" => $this->l->__("Color"), - "mandatory" => 0, - "type" => "text", - "size" => 6, - "length" => 6, - "error_check" => "custom", - "error_regex" => "/[\dA-Fa-f]{6}/", - "error_example" => "F6A544" - ) +$edit_access = array ( + "table_array" => array ( + "edit_access_id" => array ( + "value" => $GLOBALS["edit_access_id"], + "type" => "hidden", + "pk" => 1 ), - "table_name" => "edit_access", - "load_query" => "SELECT edit_access_id, name FROM edit_access ORDER BY name", - "show_fields" => array ( - array ( - "name" => "name" - ) + "name" => array ( + "value" => $GLOBALS["name"], + "output_name" => $this->l->__("Access Group Name"), + "mandatory" => 1, + "type" => "text", + "error_check" => "alphanumericspace|unique" ), - "element_list" => array ( - "edit_access_data" => array ( - "output_name" => "Edit Access Data", - "type" => "reference_data", # is not a sub table read and connect, but only a sub table with data - "max_empty" => 5, # maxium visible if no data is set, if filled add this number to visible - "prefix" => "ead", - "elements" => array ( - "edit_access_data_id" => array ( - "output_name" => "Activate", - "type" => "hidden", - "int" => 1, - "pk_id" => 1 - ), - "name" => array ( - "type" => "text", - "error_check" => "alphanumeric|unique", - "output_name" => "Name" - ), - "value" => array ( - "type" => "text", - "output_name" => "Value" - ), - "enabled" => array ( - "type" => "checkbox", - "output_name" => "Activate", - "int" => 1, - "element_list" => array(1) - ), - "edit_access_id" => array ( - "int" => 1, - "type" => "hidden", - "fk_id" => 1 # reference main key from master table above - ) + "description" => array ( + "value" => $GLOBALS["description"], + "output_name" => $this->l->__("Description"), + "type" => "textarea" + ), + "color" => array ( + "value" => $GLOBALS["color"], + "output_name" => $this->l->__("Color"), + "mandatory" => 0, + "type" => "text", + "size" => 6, + "length" => 6, + "error_check" => "custom", + "error_regex" => "/[\dA-Fa-f]{6}/", + "error_example" => "F6A544" + ) + ), + "table_name" => "edit_access", + "load_query" => "SELECT edit_access_id, name FROM edit_access ORDER BY name", + "show_fields" => array ( + array ( + "name" => "name" + ) + ), + "element_list" => array ( + "edit_access_data" => array ( + "output_name" => "Edit Access Data", + "type" => "reference_data", # is not a sub table read and connect, but only a sub table with data + "max_empty" => 5, # maxium visible if no data is set, if filled add this number to visible + "prefix" => "ead", + "elements" => array ( + "edit_access_data_id" => array ( + "output_name" => "Activate", + "type" => "hidden", + "int" => 1, + "pk_id" => 1 + ), + "name" => array ( + "type" => "text", + "error_check" => "alphanumeric|unique", + "output_name" => "Name" + ), + "value" => array ( + "type" => "text", + "output_name" => "Value" + ), + "enabled" => array ( + "type" => "checkbox", + "output_name" => "Activate", + "int" => 1, + "element_list" => array(1) + ), + "edit_access_id" => array ( + "int" => 1, + "type" => "hidden", + "fk_id" => 1 # reference main key from master table above ) ) ) - ); -?> + ) +); diff --git a/www/admin/table_arrays/array_edit_groups.inc b/www/admin/table_arrays/array_edit_groups.inc index 9814adc4..4f479618 100644 --- a/www/admin/table_arrays/array_edit_groups.inc +++ b/www/admin/table_arrays/array_edit_groups.inc @@ -1,100 +1,99 @@ array ( - "edit_group_id" => array ( - "value" => $GLOBALS["edit_group_id"], - "pk" => 1, - "type" => "hidden" - ), - "enabled" => array ( - "value" => $GLOBALS["enabled"], - "output_name" => "Enabled", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "name" => array ( - "value" => $GLOBALS["name"], - "output_name" => "Group Name", - "type" => "text", - "mandatory" => 1 - ), - "edit_access_right_id" => array ( - "value" => $GLOBALS["edit_access_right_id"], - "output_name" => "Group Level", - "mandatory" => 1, - "int" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" - ), - "edit_scheme_id" => array ( - "value" => $GLOBALS["edit_scheme_id"], - "output_name" => "Group Scheme", - "int_null" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name" +$edit_groups = array ( + "table_array" => array ( + "edit_group_id" => array ( + "value" => $GLOBALS["edit_group_id"], + "pk" => 1, + "type" => "hidden" + ), + "enabled" => array ( + "value" => $GLOBALS["enabled"], + "output_name" => "Enabled", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) ), - "load_query" => "SELECT edit_group_id, name, enabled FROM edit_group ORDER BY name", - "table_name" => "edit_group", - "show_fields" => array ( - array ( - "name" => "name" - ), - array ( - "name" => "enabled", - "binary" => array ("Yes", "No"), - "before_value" => "Enabled: " - ) + "name" => array ( + "value" => $GLOBALS["name"], + "output_name" => "Group Name", + "type" => "text", + "mandatory" => 1 ), - "element_list" => array ( - "edit_page_access" => array ( - "output_name" => "Pages", - "mandatory" => 1, - "delete" => 0, // set then reference entries are deleted, else the "enable" flag is only set - "enable_name" => "enable_page_access", - "prefix" => "epa", - "read_data" => array ( - "table_name" => "edit_page", - "pk_id" => "edit_page_id", - "name" => "name", - "order" => "order_number" - ), - "elements" => array ( - "edit_page_access_id" => array ( - "output_name" => "Activate", - "type" => "hidden", - "int" => 1, - "pk_id" => 1 - ), - "enabled" => array ( - "type" => "checkbox", - "output_name" => "Activate", - "int" => 1, - "element_list" => array(1) - ), - "edit_access_right_id" => array ( - "type" => "drop_down_db", - "output_name" => "Access Level", - "int" => 1, - "preset" => 1, // first of the select - "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" - ), - "edit_page_id" => array ( - "int" => 1, - "type" => "hidden" - ) - /*, - "edit_default" => array ( - "output_name" => "Default", - "type" => "radio", - "mandatory" => 1 - )*/ - ) - ) // edit pages ggroup + "edit_access_right_id" => array ( + "value" => $GLOBALS["edit_access_right_id"], + "output_name" => "Group Level", + "mandatory" => 1, + "int" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" + ), + "edit_scheme_id" => array ( + "value" => $GLOBALS["edit_scheme_id"], + "output_name" => "Group Scheme", + "int_null" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name" ) - ); -?> + ), + "load_query" => "SELECT edit_group_id, name, enabled FROM edit_group ORDER BY name", + "table_name" => "edit_group", + "show_fields" => array ( + array ( + "name" => "name" + ), + array ( + "name" => "enabled", + "binary" => array ("Yes", "No"), + "before_value" => "Enabled: " + ) + ), + "element_list" => array ( + "edit_page_access" => array ( + "output_name" => "Pages", + "mandatory" => 1, + "delete" => 0, // set then reference entries are deleted, else the "enable" flag is only set + "enable_name" => "enable_page_access", + "prefix" => "epa", + "read_data" => array ( + "table_name" => "edit_page", + "pk_id" => "edit_page_id", + "name" => "name", + "order" => "order_number" + ), + "elements" => array ( + "edit_page_access_id" => array ( + "output_name" => "Activate", + "type" => "hidden", + "int" => 1, + "pk_id" => 1 + ), + "enabled" => array ( + "type" => "checkbox", + "output_name" => "Activate", + "int" => 1, + "element_list" => array(1) + ), + "edit_access_right_id" => array ( + "type" => "drop_down_db", + "output_name" => "Access Level", + "int" => 1, + "preset" => 1, // first of the select + "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" + ), + "edit_page_id" => array ( + "int" => 1, + "type" => "hidden" + ) + /*, + "edit_default" => array ( + "output_name" => "Default", + "type" => "radio", + "mandatory" => 1 + )*/ + ) + ) // edit pages ggroup + ) +); diff --git a/www/admin/table_arrays/array_edit_languages.inc b/www/admin/table_arrays/array_edit_languages.inc index f5196d03..b20c8c45 100644 --- a/www/admin/table_arrays/array_edit_languages.inc +++ b/www/admin/table_arrays/array_edit_languages.inc @@ -1,73 +1,72 @@ array ( - "edit_language_id" => array ( - "value" => $GLOBALS["edit_language_id"], - "type" => "hidden", - "pk" => 1 - ), - "short_name" => array ( - "value" => $GLOBALS["short_name"], - "output_name" => "Language (short)", - "mandatory" => 1, - "type" => "text", - "size" => 2, - "length" => 2 - ), - "long_name" => array ( - "value" => $GLOBALS["long_name"], - "output_name" => "Language (long)", - "mandatory" => 1, - "type" => "text", - "size" => 40 - ), - "iso_name" => array ( - "value" => $GLOBALS["iso_name"], - "output_name" => "ISO Code", - "mandatory" => 1, - "type" => "text" - ), - "order_number" => array ( - "value" => $GLOBALS["order_number"], - "int" => 1, - "order" => 1 - ), - "enabled" => array ( - "value" => $GLOBALS["enabled"], - "output_name" => "Enabled", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "lang_default" => array ( - "value" => $GLOBALS["lang_default"], - "output_name" => "Default Language", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) +$edit_languages=array ( + "table_array" => array ( + "edit_language_id" => array ( + "value" => $GLOBALS["edit_language_id"], + "type" => "hidden", + "pk" => 1 + ), + "short_name" => array ( + "value" => $GLOBALS["short_name"], + "output_name" => "Language (short)", + "mandatory" => 1, + "type" => "text", + "size" => 2, + "length" => 2 + ), + "long_name" => array ( + "value" => $GLOBALS["long_name"], + "output_name" => "Language (long)", + "mandatory" => 1, + "type" => "text", + "size" => 40 + ), + "iso_name" => array ( + "value" => $GLOBALS["iso_name"], + "output_name" => "ISO Code", + "mandatory" => 1, + "type" => "text" + ), + "order_number" => array ( + "value" => $GLOBALS["order_number"], + "int" => 1, + "order" => 1 + ), + "enabled" => array ( + "value" => $GLOBALS["enabled"], + "output_name" => "Enabled", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) ), - "load_query" => "SELECT edit_language_id, long_name, iso_name, enabled FROM edit_language ORDER BY long_name", - "show_fields" => array ( - array ( - "name" => "long_name" - ), - array ( - "name" => "iso_name", - "before_value" => "ISO: " - ), - array ( - "name" => "enabled", - "before_value" => "Enabled: ", - "binary" => array ("Yes","No") + "lang_default" => array ( + "value" => $GLOBALS["lang_default"], + "output_name" => "Default Language", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) + ) + ), + "load_query" => "SELECT edit_language_id, long_name, iso_name, enabled FROM edit_language ORDER BY long_name", + "show_fields" => array ( + array ( + "name" => "long_name" ), - "table_name" => "edit_language" - ); -?> + array ( + "name" => "iso_name", + "before_value" => "ISO: " + ), + array ( + "name" => "enabled", + "before_value" => "Enabled: ", + "binary" => array ("Yes","No") + ) + ), + "table_name" => "edit_language" +); diff --git a/www/admin/table_arrays/array_edit_menu_group.inc b/www/admin/table_arrays/array_edit_menu_group.inc index f40c2ec5..6851ed6a 100644 --- a/www/admin/table_arrays/array_edit_menu_group.inc +++ b/www/admin/table_arrays/array_edit_menu_group.inc @@ -1,38 +1,37 @@ array ( - "edit_menu_group_id" => array ( - "value" => $GLOBALS["edit_menu_group_id"], - "type" => "hidden", - "pk" => 1 - ), - "name" => array ( - "value" => $GLOBALS["name"], - "output_name" => $this->l->__("Group name"), - "mandatory" => 1, - "type" => "text" - ), - "flag" => array ( - "value" => $GLOBALS["flag"], - "output_name" => $this->l->__("Flag"), - "mandatory" => 1, - "type" => "text", - "error_check" => "alphanumeric|unique" - ), - "order_number" => array ( - "value" => $GLOBALS["order_number"], - "output_name" => "Group order", - "type" => "order", - "int" => 1, - "order" => 1 - ) +$edit_menu_group = array ( + "table_array" => array ( + "edit_menu_group_id" => array ( + "value" => $GLOBALS["edit_menu_group_id"], + "type" => "hidden", + "pk" => 1 ), - "table_name" => "edit_menu_group", - "load_query" => "SELECT edit_menu_group_id, name FROM edit_menu_group ORDER BY name", - "show_fields" => array ( - array ( - "name" => "name" - ) + "name" => array ( + "value" => $GLOBALS["name"], + "output_name" => $this->l->__("Group name"), + "mandatory" => 1, + "type" => "text" + ), + "flag" => array ( + "value" => $GLOBALS["flag"], + "output_name" => $this->l->__("Flag"), + "mandatory" => 1, + "type" => "text", + "error_check" => "alphanumeric|unique" + ), + "order_number" => array ( + "value" => $GLOBALS["order_number"], + "output_name" => "Group order", + "type" => "order", + "int" => 1, + "order" => 1 ) - ); -?> + ), + "table_name" => "edit_menu_group", + "load_query" => "SELECT edit_menu_group_id, name FROM edit_menu_group ORDER BY name", + "show_fields" => array ( + array ( + "name" => "name" + ) + ) +); diff --git a/www/admin/table_arrays/array_edit_pages.inc b/www/admin/table_arrays/array_edit_pages.inc index 61c8444e..70bee23c 100644 --- a/www/admin/table_arrays/array_edit_pages.inc +++ b/www/admin/table_arrays/array_edit_pages.inc @@ -1,178 +1,177 @@ array ( - "edit_page_id" => array ( - "value" => $GLOBALS["edit_page_id"], - "type" => "hidden", - "pk" => 1 - ), - "filename" => array ( - "value" => $GLOBALS["filename"], - "output_name" => "Add File ...", - "mandatory" => 1, - "type" => "drop_down_db", - "query" => "SELECT DISTINCT temp_files.filename AS id, temp_files.filename AS name FROM temp_files LEFT JOIN edit_page ep ON temp_files.filename = ep.filename WHERE ep.filename IS NULL" - ), - "name" => array ( - "value" => $GLOBALS["name"], - "output_name" => "Page name", - "mandatory" => 1, - "type" => "text" - ), - "order_number" => array ( - "value" => $GLOBALS["order_number"], - "output_name" => "Page order", - "type" => "order", - "int" => 1, - "order" => 1 - ), +$edit_pages = array ( + "table_array" => array ( + "edit_page_id" => array ( + "value" => $GLOBALS["edit_page_id"], + "type" => "hidden", + "pk" => 1 + ), + "filename" => array ( + "value" => $GLOBALS["filename"], + "output_name" => "Add File ...", + "mandatory" => 1, + "type" => "drop_down_db", + "query" => "SELECT DISTINCT temp_files.filename AS id, temp_files.filename AS name FROM temp_files LEFT JOIN edit_page ep ON temp_files.filename = ep.filename WHERE ep.filename IS NULL" + ), + "name" => array ( + "value" => $GLOBALS["name"], + "output_name" => "Page name", + "mandatory" => 1, + "type" => "text" + ), + "order_number" => array ( + "value" => $GLOBALS["order_number"], + "output_name" => "Page order", + "type" => "order", + "int" => 1, + "order" => 1 + ), /* "flag" => array ( - "value" => $GLOBALS["flag"], - "output_name" => "Page Flag", - "type" => "drop_down_array", - "query" => array ( - "0" => "0", - "1" => "1", - "2" => "2", - "3" => "3", - "4" => "4", - "5" => "5" - ) - ),*/ - "online" => array ( - "value" => $GLOBALS["online"], - "output_name" => "Online", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "menu" => array ( - "value" => $GLOBALS["menu"], - "output_name" => "Menu", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "popup" => array ( - "value" => $GLOBALS["popup"], - "output_name" => "Popup", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "popup_x" => array ( - "value" => $GLOBALS["popup_x"], - "output_name" => "Popup Width", - "int_null" => 1, - "type" => "text", - "size" => 4, - "length" => 4 - ), - "popup_y" => array ( - "value" => $GLOBALS["popup_y"], - "output_name" => "Popup Height", - "int_null" => 1, - "type" => "text", - "size" => 4, - "length" => 4 - )/*, - "query_string" => array ( - "value" => $GLOBALS["query_string"], - "output_name" => "Query String for Link", - "type" => "text", - "size" => "50" - )*/ - ), - "load_query" => "SELECT edit_page_id, filename, name, online, menu, popup FROM edit_page ORDER BY order_number", - "table_name" => "edit_page", - "show_fields" => array ( - array ( - "name" => "name" - ), - array ( - "name" => "filename", - "before_value" => "Filename: " - ), - array( - "name" => "online", - "binary" => array("Yes","No"), - "before_value" => "Online: " - ), - array( - "name" => "menu", - "binary" => array("Yes","No"), - "before_value" => "Menu: " - ), - array( - "name" => "popup", - "binary" => array("Yes","No"), - "before_value" => "Popup: " + "value" => $GLOBALS["flag"], + "output_name" => "Page Flag", + "type" => "drop_down_array", + "query" => array ( + "0" => "0", + "1" => "1", + "2" => "2", + "3" => "3", + "4" => "4", + "5" => "5" + ) + ),*/ + "online" => array ( + "value" => $GLOBALS["online"], + "output_name" => "Online", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) ), - "reference_arrays" => array ( - "edit_visible_group" => array ( - "table_name" => "edit_page_visible_group", - "other_table_pk" => "edit_visible_group_id", - "output_name" => "Visible Groups (access)", - "mandatory" => 1, - "select_size" => 10, - "selected" => $GLOBALS["edit_visible_group_id"], - "query" => 'SELECT edit_visible_group_id, \'Name: \' || name || \', \' || \'Flag: \' || flag FROM edit_visible_group ORDER BY name' - ), - "edit_menu_group" => array ( - "table_name" => "edit_page_menu_group", - "other_table_pk" => "edit_menu_group_id", - "output_name" => "Menu Groups (grouping)", - "mandatory" => 1, - "select_size" => 10, - "selected" => $GLOBALS["edit_menu_group_id"], - "query" => 'SELECT edit_menu_group_id, \'Name: \' || name || \', \' || \'Flag: \' || flag FROM edit_menu_group ORDER BY order_number' + "menu" => array ( + "value" => $GLOBALS["menu"], + "output_name" => "Menu", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) + ), + "popup" => array ( + "value" => $GLOBALS["popup"], + "output_name" => "Popup", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "popup_x" => array ( + "value" => $GLOBALS["popup_x"], + "output_name" => "Popup Width", + "int_null" => 1, + "type" => "text", + "size" => 4, + "length" => 4 + ), + "popup_y" => array ( + "value" => $GLOBALS["popup_y"], + "output_name" => "Popup Height", + "int_null" => 1, + "type" => "text", + "size" => 4, + "length" => 4 + )/*, + "query_string" => array ( + "value" => $GLOBALS["query_string"], + "output_name" => "Query String for Link", + "type" => "text", + "size" => "50" + )*/ + ), + "load_query" => "SELECT edit_page_id, filename, name, online, menu, popup FROM edit_page ORDER BY order_number", + "table_name" => "edit_page", + "show_fields" => array ( + array ( + "name" => "name" + ), + array ( + "name" => "filename", + "before_value" => "Filename: " + ), + array ( + "name" => "online", + "binary" => array ("Yes","No"), + "before_value" => "Online: " + ), + array ( + "name" => "menu", + "binary" => array ("Yes","No"), + "before_value" => "Menu: " + ), + array ( + "name" => "popup", + "binary" => array ("Yes","No"), + "before_value" => "Popup: " + ) + ), + "reference_arrays" => array ( + "edit_visible_group" => array ( + "table_name" => "edit_page_visible_group", + "other_table_pk" => "edit_visible_group_id", + "output_name" => "Visible Groups (access)", + "mandatory" => 1, + "select_size" => 10, + "selected" => $GLOBALS["edit_visible_group_id"], + "query" => 'SELECT edit_visible_group_id, \'Name: \' || name || \', \' || \'Flag: \' || flag FROM edit_visible_group ORDER BY name' + ), + "edit_menu_group" => array ( + "table_name" => "edit_page_menu_group", + "other_table_pk" => "edit_menu_group_id", + "output_name" => "Menu Groups (grouping)", + "mandatory" => 1, + "select_size" => 10, + "selected" => $GLOBALS["edit_menu_group_id"], + "query" => 'SELECT edit_menu_group_id, \'Name: \' || name || \', \' || \'Flag: \' || flag FROM edit_menu_group ORDER BY order_number' + ) - ), - "element_list" => array ( - "edit_query_string" => array ( - "output_name" => "Query Strings", - "delete_name" => "remove_query_string", - "prefix" => "eqs", - "elements" => array ( - "name" => array ( - "output_name" => "Name", - "type" => "text", - "error_check" => "unique|alphanumeric", - "mandatory" => 1 - ), - "value" => array ( - "output_name" => "Value", - "type" => "text" - ), - "enabled" => array ( - "output_name" => "Enabled", - "int" => 1, - "type" => "checkbox", - "element_list" => array(1) - ), - "dynamic" => array ( - "output_name" => "Dynamic", - "int" => 1, - "type" => "checkbox", - "element_list" => array(1) - ), - "edit_query_string_id" => array ( - "type" => "hidden", - "pk_id" => 1 - ) - ) // elements - ) // query_string element list - ) // element list - ); -?> + ), + "element_list" => array ( + "edit_query_string" => array ( + "output_name" => "Query Strings", + "delete_name" => "remove_query_string", + "prefix" => "eqs", + "elements" => array ( + "name" => array ( + "output_name" => "Name", + "type" => "text", + "error_check" => "unique|alphanumeric", + "mandatory" => 1 + ), + "value" => array ( + "output_name" => "Value", + "type" => "text" + ), + "enabled" => array ( + "output_name" => "Enabled", + "int" => 1, + "type" => "checkbox", + "element_list" => array (1) + ), + "dynamic" => array ( + "output_name" => "Dynamic", + "int" => 1, + "type" => "checkbox", + "element_list" => array (1) + ), + "edit_query_string_id" => array ( + "type" => "hidden", + "pk_id" => 1 + ) + ) // elements + ) // query_string element list + ) // element list +); diff --git a/www/admin/table_arrays/array_edit_schemes.inc b/www/admin/table_arrays/array_edit_schemes.inc index 967feb0d..668d69a5 100644 --- a/www/admin/table_arrays/array_edit_schemes.inc +++ b/www/admin/table_arrays/array_edit_schemes.inc @@ -1,55 +1,55 @@ array ( - "edit_scheme_id" => array ( - "value" => $GLOBALS["edit_scheme_id"], - "type" => "hidden", - "pk" => 1 - ), - "name" => array ( - "value" => $GLOBALS["name"], - "output_name" => "Scheme Name", - "mandatory" => 1, - "type" => "text" - ), - "header_color" => array ( - "value" => $GLOBALS["header_color"], - "output_name" => "Header Color", - "mandatory" => 1, - "type" => "text", - "size" => 6, - "length" => 6, - "error_check" => "custom", - "error_regex" => "/[\dA-Fa-f]{6}/", - "error_example" => "F6A544" - ), - "enabled" => array ( - "value" => $GLOBALS["enabled"], - "output_name" => "Enabled", - "int" => 1, - "type" => "binary", - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "template" => array ( - "value" => $GLOBALS["template"], - "output_name" => "Template", - "type" => "text" +$edit_schemes = array ( + "table_array" => array ( + "edit_scheme_id" => array ( + "value" => $GLOBALS["edit_scheme_id"], + "type" => "hidden", + "pk" => 1 + ), + "name" => array ( + "value" => $GLOBALS["name"], + "output_name" => "Scheme Name", + "mandatory" => 1, + "type" => "text" + ), + "header_color" => array ( + "value" => $GLOBALS["header_color"], + "output_name" => "Header Color", + "mandatory" => 1, + "type" => "text", + "size" => 6, + "length" => 6, + "error_check" => "custom", + "error_regex" => "/[\dA-Fa-f]{6}/", + "error_example" => "F6A544" + ), + "enabled" => array ( + "value" => $GLOBALS["enabled"], + "output_name" => "Enabled", + "int" => 1, + "type" => "binary", + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) ), - "table_name" => "edit_scheme", - "load_query" => "SELECT edit_scheme_id, name, enabled FROM edit_scheme ORDER BY name", - "show_fields" => array ( - array ( - "name" => "name" - ), - array ( - "name" => "enabled", - "binary" => array ("Yes", "No"), - "before_value" => "Enabled: " - ) + "template" => array ( + "value" => $GLOBALS["template"], + "output_name" => "Template", + "type" => "text" ) - ); // main array - ?> + ), + "table_name" => "edit_scheme", + "load_query" => "SELECT edit_scheme_id, name, enabled FROM edit_scheme ORDER BY name", + "show_fields" => array ( + array ( + "name" => "name" + ), + array ( + "name" => "enabled", + "binary" => array ("Yes", "No"), + "before_value" => "Enabled: " + ) + ) +); // main array + diff --git a/www/admin/table_arrays/array_edit_users.inc b/www/admin/table_arrays/array_edit_users.inc index 8013de61..9cbe7711 100644 --- a/www/admin/table_arrays/array_edit_users.inc +++ b/www/admin/table_arrays/array_edit_users.inc @@ -1,254 +1,253 @@ array ( - "edit_user_id" => array ( - "value" => $GLOBALS["edit_user_id"], - "type" => "hidden", - "pk" => 1, - "int" => 1 - ), - "username" => array ( - "value" => $GLOBALS["username"], - "output_name" => "Username", - "mandatory" => 1, - "error_check" => "unique|alphanumericextended", - "type" => "text" - ), - "password" => array ( - "value" => $GLOBALS["password"], - "HIDDEN_value" => $GLOBALS["HIDDEN_password"], - "CONFIRM_value" => $GLOBALS["CONFIRM_password"], - "output_name" => "Password", - "mandatory" => 1, - "type" => "password", // later has to be password for encryption in database - 'update' => array ( // connected field updates, and update data - 'password_change_date' => array ( // db row to update - 'type' => 'date', // type of field (int/text/date/etc) - 'value' => 'NOW()' // value [todo: complex reference - ) +$edit_users = array ( + "table_array" => array ( + "edit_user_id" => array ( + "value" => $GLOBALS["edit_user_id"], + "type" => "hidden", + "pk" => 1, + "int" => 1 + ), + "username" => array ( + "value" => $GLOBALS["username"], + "output_name" => "Username", + "mandatory" => 1, + "error_check" => "unique|alphanumericextended", + "type" => "text" + ), + "password" => array ( + "value" => $GLOBALS["password"], + "HIDDEN_value" => $GLOBALS["HIDDEN_password"], + "CONFIRM_value" => $GLOBALS["CONFIRM_password"], + "output_name" => "Password", + "mandatory" => 1, + "type" => "password", // later has to be password for encryption in database + 'update' => array ( // connected field updates, and update data + 'password_change_date' => array ( // db row to update + 'type' => 'date', // type of field (int/text/date/etc) + 'value' => 'NOW()' // value [todo: complex reference ) - ), - // password date when first insert and password is set, needs special field with connection to password - 'password_change_interval' => array ( - 'value' => $GLOBALS['password_change_interval'], - 'output_name' => 'Password change interval', - 'error_check' => 'intervalshort', // can be any date length format. n Y/M/D [not H/M/S], only one set, no combination - 'type' => 'text', - 'interval' => 1, // interval needs NULL write for empty - 'size' => 5, // make it 5 chars long - 'length' => 5 - ), - // password reset force interval, if set, user needs to reset password after X time period - "enabled" => array ( - "value" => $GLOBALS["enabled"], - "output_name" => "Enabled", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "strict" => array ( - "value" => $GLOBALS["strict"], - "output_name" => "Strict (Lock after errors)", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "locked" => array ( - "value" => $GLOBALS["locked"], - "output_name" => "Locked (auto set if strict with errors)", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "admin" => array ( - "value" => $GLOBALS["admin"], - "output_name" => "Admin", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "debug" => array ( - "value" => $GLOBALS["debug"], - "output_name" => "Debug", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "db_debug" => array ( - "value" => $GLOBALS["db_debug"], - "output_name" => "DB Debug", - "type" => "binary", - "int" => 1, - "element_list" => array ( - "1" => "Yes", - "0" => "No" - ) - ), - "email" => array ( - "value" => $GLOBALS["email"], - "output_name" => "E-Mail", - "type" => "text" - ), - "last_name" => array ( - "value" => $GLOBALS["last_name"], - "output_name" => "Last Name", - "type" => "text" - ), - "first_name" => array ( - "value" => $GLOBALS["first_name"], - "output_name" => "First Name", - "type" => "text" - ), - "edit_language_id" => array ( - "value" => $GLOBALS["edit_language_id"], - "output_name" => "Language", - "mandatory" => 1, - "int" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_language_id, long_name FROM edit_language WHERE enabled = 1 ORDER BY order_number" - ), - "edit_scheme_id" => array ( - "value" => $GLOBALS["edit_scheme_id"], - "output_name" => "Scheme", - "int_null" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name" - ), - "edit_group_id" => array ( - "value" => $GLOBALS["edit_group_id"], - "output_name" => "Group", - "int" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_group_id, name FROM edit_group WHERE enabled = 1 ORDER BY name", - "mandatory" => 1 - ), - "edit_access_right_id" => array ( - "value" => $GLOBALS["edit_access_right_id"], - "output_name" => "User Level", - "mandatory" => 1, - "int" => 1, - "type" => "drop_down_db", - "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" - ), - "login_error_count" => array ( - "output_name" => "Login error count", - "value" => $GLOBALS['login_error_count'], - "type" => "view", - "empty" => "0" - ), - "login_error_date_last" => array ( - "output_name" => "Last login error", - "value" => $GLOBALS['login_error_date_liast'], - "type" => "view", - "empty" => "-" - ), - "login_error_date_first" => array ( - "output_name" => "First login error", - "value" => $GLOBALS['login_error_date_first'], - "type" => "view", - "empty" => "-" - ), - // planned delete lock flag - "protected" => array ( - "value" => $GLOBALS["protected"], - "int" => 1 ) ), - "load_query" => "SELECT edit_user_id, username, enabled, debug, db_debug, strict, locked, login_error_count FROM edit_user ORDER BY username", - "table_name" => "edit_user", - "show_fields" => array ( - array ( - "name" => "username" - ), - array ( - "name" => "enabled", - "binary" => array("Yes", "No"), - "before_value" => "Enabled: " - ), - array ( - "name" => "debug", - "binary" => array("Yes", "No"), - "before_value" => "Debug: " - ), - array ( - "name" => "db_debug", - "binary" => array("Yes", "No"), - "before_value" => "DB Debug: " - ), - array ( - "name" => "strict", - "binary" => array("Yes", "No"), - "before_value" => "Strict: " - ), - array ( - "name" => "locked", - "binary" => array("Yes", "No"), - "before_value" => "Locked: " - ), - array ( - "name" => "login_error_count", - "before_value" => "Errors: " + // password date when first insert and password is set, needs special field with connection to password + 'password_change_interval' => array ( + 'value' => $GLOBALS['password_change_interval'], + 'output_name' => 'Password change interval', + 'error_check' => 'intervalshort', // can be any date length format. n Y/M/D [not H/M/S], only one set, no combination + 'type' => 'text', + 'interval' => 1, // interval needs NULL write for empty + 'size' => 5, // make it 5 chars long + 'length' => 5 + ), + // password reset force interval, if set, user needs to reset password after X time period + "enabled" => array ( + "value" => $GLOBALS["enabled"], + "output_name" => "Enabled", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" ) ), - "element_list" => array ( - "edit_access_user" => array ( - "output_name" => "Accounts", - "mandatory" => 1, - "delete" => 0, // set then reference entries are deleted, else the "enable" flag is only set - "prefix" => "ecu", - "read_data" => array ( - "table_name" => "edit_access", - "pk_id" => "edit_access_id", - "name" => "name", - "order" => "name" - ), - "elements" => array ( - "edit_access_user_id" => array ( - "output_name" => "Activate", - "type" => "hidden", - "int" => 1, - "pk_id" => 1 - ), - "enabled" => array ( - "type" => "checkbox", - "output_name" => "Activate", - "int" => 1, - "element_list" => array(1) - ), - "edit_access_right_id" => array ( - "type" => "drop_down_db", - "output_name" => "Access Level", - "preset" => 1, // first of the select - "int" => 1, - "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" - ), - "edit_default" => array ( - "type" => "radio_group", - "output_name" => "Default", - "int" => 1, - "element_list" => "radio_group" - ), - "edit_access_id" => array ( - "type" => "hidden", - "int" => 1 - ) - ) - ) // edit pages ggroup + "strict" => array ( + "value" => $GLOBALS["strict"], + "output_name" => "Strict (Lock after errors)", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "locked" => array ( + "value" => $GLOBALS["locked"], + "output_name" => "Locked (auto set if strict with errors)", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "admin" => array ( + "value" => $GLOBALS["admin"], + "output_name" => "Admin", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "debug" => array ( + "value" => $GLOBALS["debug"], + "output_name" => "Debug", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "db_debug" => array ( + "value" => $GLOBALS["db_debug"], + "output_name" => "DB Debug", + "type" => "binary", + "int" => 1, + "element_list" => array ( + "1" => "Yes", + "0" => "No" + ) + ), + "email" => array ( + "value" => $GLOBALS["email"], + "output_name" => "E-Mail", + "type" => "text" + ), + "last_name" => array ( + "value" => $GLOBALS["last_name"], + "output_name" => "Last Name", + "type" => "text" + ), + "first_name" => array ( + "value" => $GLOBALS["first_name"], + "output_name" => "First Name", + "type" => "text" + ), + "edit_language_id" => array ( + "value" => $GLOBALS["edit_language_id"], + "output_name" => "Language", + "mandatory" => 1, + "int" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_language_id, long_name FROM edit_language WHERE enabled = 1 ORDER BY order_number" + ), + "edit_scheme_id" => array ( + "value" => $GLOBALS["edit_scheme_id"], + "output_name" => "Scheme", + "int_null" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_scheme_id, name FROM edit_scheme WHERE enabled = 1 ORDER BY name" + ), + "edit_group_id" => array ( + "value" => $GLOBALS["edit_group_id"], + "output_name" => "Group", + "int" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_group_id, name FROM edit_group WHERE enabled = 1 ORDER BY name", + "mandatory" => 1 + ), + "edit_access_right_id" => array ( + "value" => $GLOBALS["edit_access_right_id"], + "output_name" => "User Level", + "mandatory" => 1, + "int" => 1, + "type" => "drop_down_db", + "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" + ), + "login_error_count" => array ( + "output_name" => "Login error count", + "value" => $GLOBALS['login_error_count'], + "type" => "view", + "empty" => "0" + ), + "login_error_date_last" => array ( + "output_name" => "Last login error", + "value" => $GLOBALS['login_error_date_liast'], + "type" => "view", + "empty" => "-" + ), + "login_error_date_first" => array ( + "output_name" => "First login error", + "value" => $GLOBALS['login_error_date_first'], + "type" => "view", + "empty" => "-" + ), + // planned delete lock flag + "protected" => array ( + "value" => $GLOBALS["protected"], + "int" => 1 ) - ); -?> + ), + "load_query" => "SELECT edit_user_id, username, enabled, debug, db_debug, strict, locked, login_error_count FROM edit_user ORDER BY username", + "table_name" => "edit_user", + "show_fields" => array ( + array ( + "name" => "username" + ), + array ( + "name" => "enabled", + "binary" => array ("Yes", "No"), + "before_value" => "Enabled: " + ), + array ( + "name" => "debug", + "binary" => array ("Yes", "No"), + "before_value" => "Debug: " + ), + array ( + "name" => "db_debug", + "binary" => array ("Yes", "No"), + "before_value" => "DB Debug: " + ), + array ( + "name" => "strict", + "binary" => array ("Yes", "No"), + "before_value" => "Strict: " + ), + array ( + "name" => "locked", + "binary" => array ("Yes", "No"), + "before_value" => "Locked: " + ), + array ( + "name" => "login_error_count", + "before_value" => "Errors: " + ) + ), + "element_list" => array ( + "edit_access_user" => array ( + "output_name" => "Accounts", + "mandatory" => 1, + "delete" => 0, // set then reference entries are deleted, else the "enable" flag is only set + "prefix" => "ecu", + "read_data" => array ( + "table_name" => "edit_access", + "pk_id" => "edit_access_id", + "name" => "name", + "order" => "name" + ), + "elements" => array ( + "edit_access_user_id" => array ( + "output_name" => "Activate", + "type" => "hidden", + "int" => 1, + "pk_id" => 1 + ), + "enabled" => array ( + "type" => "checkbox", + "output_name" => "Activate", + "int" => 1, + "element_list" => array (1) + ), + "edit_access_right_id" => array ( + "type" => "drop_down_db", + "output_name" => "Access Level", + "preset" => 1, // first of the select + "int" => 1, + "query" => "SELECT edit_access_right_id, name FROM edit_access_right ORDER BY level" + ), + "edit_default" => array ( + "type" => "radio_group", + "output_name" => "Default", + "int" => 1, + "element_list" => "radio_group" + ), + "edit_access_id" => array ( + "type" => "hidden", + "int" => 1 + ) + ) + ) // edit pages ggroup + ) +); diff --git a/www/admin/table_arrays/array_edit_visible_group.inc b/www/admin/table_arrays/array_edit_visible_group.inc index b3fd7ae6..752b5ca2 100644 --- a/www/admin/table_arrays/array_edit_visible_group.inc +++ b/www/admin/table_arrays/array_edit_visible_group.inc @@ -28,4 +28,3 @@ ) ) ); -?> diff --git a/www/configs/config.inc b/www/configs/config.inc index 328ad76e..0283e86d 100644 --- a/www/configs/config.inc +++ b/www/configs/config.inc @@ -1,280 +1,275 @@ "); - // frontend - DEFINE('SESSION_NAME', ""); +/************* SESSION NAMES *************/ +// backend +DEFINE('EDIT_SESSION_NAME', ""); +// frontend +DEFINE('SESSION_NAME', ""); +// set the session name +define('SET_SESSION_NAME', EDIT_SESSION_NAME); - /************* LANGUAGE / ENCODING *******/ - DEFINE('DEFAULT_LANG', "en_utf8"); - // default web page encoding setting - DEFINE('DEFAULT_ENCODING', "UTF-8"); +/************* LANGUAGE / ENCODING *******/ +DEFINE('DEFAULT_LANG', "en_utf8"); +// default web page encoding setting +DEFINE('DEFAULT_ENCODING', "UTF-8"); - /************* PATHS *********************/ - // ** NEW/BETTER DIR DECLARATIONS ** - // path to original file (if symlink) - DEFINE('DIR', __DIR__."/"); - // libs base path based on DIR - DEFINE('LIBDIR', DIR.'libs/'); - // SMARTY path based on DIR - DEFINE('SMARTYDIR', DIR.'Smarty/'); - // table arrays for Class Form - DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); +/************* PATHS *********************/ +// ** NEW/BETTER DIR DECLARATIONS ** +// path to original file (if symlink) +DEFINE('DIR', __DIR__."/"); +// libs base path based on DIR +DEFINE('LIBDIR', DIR.'libs/'); +// SMARTY path based on DIR +DEFINE('SMARTYDIR', DIR.'Smarty/'); +// table arrays for Class Form +DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); - // ** OLD DIR DECLARATIONS ** - // path to document root of file called - DEFINE('ROOT', getcwd()."/"); - // libs path - DEFINE('LIBS', "libs/"); - // includes (strings, arrays for static, etc) - DEFINE('INCLUDES', "includes/"); - // layout base path - DEFINE('LAYOUT', 'layout/'); - // pic-root (compatible to CMS) - DEFINE('PICTURES', "images/"); - // images - DEFINE('IMAGES', "images/"); - // icons (below the images/ folder) - DEFINE('ICONS', 'icons/'); - // media - DEFINE('MEDIA', "media/"); - // flash-root (below media) - DEFINE('FLASH', "flash/"); - // uploads (anything to keep) - DEFINE('UPLOADS', "uploads/"); - // files (binaries) (below media) - DEFINE('BINARIES', "binaries/"); - // files (videos) (below media) - DEFINE('VIDEOS', "videos/"); - // files (documents) (below media) - DEFINE('DOCUMENTS', "documents/"); - // files (pdfs) (below media) - DEFINE('PDFS', "documents/"); - // css - DEFINE('CSS', "css/"); - // js - DEFINE('JS', "javascript/"); - // table arrays - DEFINE('TABLE_ARRAYS', "table_arrays/"); - // smarty libs path - DEFINE('SMARTY', "Smarty/"); - // po langs - DEFINE('LANG', "lang/"); - // cache path - DEFINE('CACHE', "cache/"); - // temp path - DEFINE('TMP', "tmp/"); - // log files - DEFINE('LOG', 'log/'); - // template base - DEFINE('TEMPLATES', "templates/"); - // frontend template dir', only for admin - DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); - // default template - DEFINE('DEFAULT_TEMPLATE', "default/"); - // default template file - DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); +// ** OLD DIR DECLARATIONS ** +// path to document root of file called +DEFINE('ROOT', getcwd()."/"); +// libs path +DEFINE('LIBS', "libs/"); +// includes (strings, arrays for static, etc) +DEFINE('INCLUDES', "includes/"); +// layout base path +DEFINE('LAYOUT', 'layout/'); +// pic-root (compatible to CMS) +DEFINE('PICTURES', "images/"); +// images +DEFINE('IMAGES', "images/"); +// icons (below the images/ folder) +DEFINE('ICONS', 'icons/'); +// media +DEFINE('MEDIA', "media/"); +// flash-root (below media) +DEFINE('FLASH', "flash/"); +// uploads (anything to keep) +DEFINE('UPLOADS', "uploads/"); +// files (binaries) (below media) +DEFINE('BINARIES', "binaries/"); +// files (videos) (below media) +DEFINE('VIDEOS', "videos/"); +// files (documents) (below media) +DEFINE('DOCUMENTS', "documents/"); +// files (pdfs) (below media) +DEFINE('PDFS', "documents/"); +// css +DEFINE('CSS', "css/"); +// js +DEFINE('JS', "javascript/"); +// table arrays +DEFINE('TABLE_ARRAYS', "table_arrays/"); +// smarty libs path +DEFINE('SMARTY', "Smarty/"); +// po langs +DEFINE('LANG', "lang/"); +// cache path +DEFINE('CACHE', "cache/"); +// temp path +DEFINE('TMP', "tmp/"); +// log files +DEFINE('LOG', 'log/'); +// template base +DEFINE('TEMPLATES', "templates/"); +// frontend template dir', only for admin +DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); +// default template +DEFINE('DEFAULT_TEMPLATE', "default/"); +// default template file +DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); - /************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ - // default hash type - DEFINE('DEFAULT_HASH', 'sha256'); - // default acl level - DEFINE('DEFAULT_ACL_LEVEL', 80); - // default levels for certain actions +/************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ +// default hash type +DEFINE('DEFAULT_HASH', 'sha256'); +// default acl level +DEFINE('DEFAULT_ACL_LEVEL', 80); +// default levels for certain actions /* DEFINE('DEFAULT_ACL_READ', 20); - DEFINE('DEFAULT_ACL_CONFIRM', 35); - DEFINE('DEFAULT_ACL_MOD', 40); - DEFINE('DEFAULT_ACL_WRITE', 60); - DEFINE('DEFAULT_ACL_SEND', 70); - DEFINE('DEFAULT_ACL_DEL', 80); - DEFINE('DEFAULT_ACL_ADMIN', 100); */ - // SSL host name +DEFINE('DEFAULT_ACL_CONFIRM', 35); +DEFINE('DEFAULT_ACL_MOD', 40); +DEFINE('DEFAULT_ACL_WRITE', 60); +DEFINE('DEFAULT_ACL_SEND', 70); +DEFINE('DEFAULT_ACL_DEL', 80); +DEFINE('DEFAULT_ACL_ADMIN', 100); */ +// SSL host name // DEFINE('SSL_HOST', "ssl.host.name"); - // error page strictness, Default is 3 - // 1: only show error page as the last mesure if really no mid & aid can be loaded and found at all - // 2: if template not found, do not search, show error template - // 3: if default template is not found, show error template, do not fall back to default tree - // 4: very strict, even on normal fixable errors through error +// error page strictness, Default is 3 +// 1: only show error page as the last mesure if really no mid & aid can be loaded and found at all +// 2: if template not found, do not search, show error template +// 3: if default template is not found, show error template, do not fall back to default tree +// 4: very strict, even on normal fixable errors through error // DEFINE('ERROR_STRICT', 3); - // allow page caching in general, set to "FALSE" if you do debugging or development! +// allow page caching in general, set to "FALSE" if you do debugging or development! // DEFINE('ALLOW_SMARTY_CACHE', FALSE); - // cache life time, in seconds, default here is 2 days (172800s) - // -1 is never expire cache +// cache life time, in seconds, default here is 2 days (172800s) +// -1 is never expire cache // DEFINE('SMARTY_CACHE_LIFETIME', -1); - /************* LOGOUT ********************/ - // logout target - DEFINE('LOGOUT_TARGET', ''); - // password change allowed - DEFINE('PASSWORD_CHANGE', false); +/************* LOGOUT ********************/ +// logout target +DEFINE('LOGOUT_TARGET', ''); +// password change allowed +DEFINE('PASSWORD_CHANGE', false); - /************* AJAX / ACCESS *************/ - // ajax request type - DEFINE('AJAX_REQUEST_TYPE', 'POST'); - // what AJAX type to use - DEFINE('USE_PROTOTYPE', true); - DEFINE('USE_SCRIPTACULOUS', false); - DEFINE('USE_JQUERY', false); +/************* AJAX / ACCESS *************/ +// ajax request type +DEFINE('AJAX_REQUEST_TYPE', 'POST'); +// what AJAX type to use +DEFINE('USE_PROTOTYPE', true); +DEFINE('USE_SCRIPTACULOUS', false); +DEFINE('USE_JQUERY', false); - /************* LAYOUT WIDTHS *************/ - DEFINE('PAGE_WIDTH', 800); - // the default template name - DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); +/************* LAYOUT WIDTHS *************/ +DEFINE('PAGE_WIDTH', 800); +// the default template name +DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); - /************* QUEUE TABLE *************/ - // if we have a dev/live system - // set_live is a per page/per item - // live_queue is a global queue system +/************* QUEUE TABLE *************/ +// if we have a dev/live system +// set_live is a per page/per item +// live_queue is a global queue system // DEFINE('QUEUE', 'live_queue'); - /************* DB PATHS (PostgreSQL) *****************/ - // schema names, can also be defined per - DEFINE('PUBLIC_SCHEMA', 'public'); - DEFINE('DEV_SCHEMA', 'public'); - DEFINE('TEST_SCHEMA', 'public'); +/************* DB PATHS (PostgreSQL) *****************/ +// schema names, can also be defined per +DEFINE('PUBLIC_SCHEMA', 'public'); +DEFINE('DEV_SCHEMA', 'public'); +DEFINE('TEST_SCHEMA', 'public'); - // non constant part - /************* DB ACCESS *****************/ - // please be VERY carefull only to change the right side - $DB_CONFIG = array( - "" => array ( - "db_name" => "", - "db_user" => "", - "db_pass" => "", - "db_host" => "", - "db_port" => "5432", - "db_schema" => "public", // if not set, uses public - "db_type" => "pgsql", - "db_encoding" => '', - "db_ssl" => 'disable' // allow, disable, require, prefer - ) - ); +// non constant part +/************* DB ACCESS *****************/ +// please be VERY carefull only to change the right side +$DB_CONFIG = array ( + "" => array ( + "db_name" => "", + "db_user" => "", + "db_pass" => "", + "db_host" => "", + "db_port" => "5432", + "db_schema" => "public", // if not set, uses public + "db_type" => "pgsql", + "db_encoding" => '', + "db_ssl" => 'disable' // allow, disable, require, prefer + ) +); - // File and Folder paths - // ID is TARGET (first array element) +// File and Folder paths +// ID is TARGET (first array element) // $PATHS["test"]["csv_path"] = ""; // $PATHS["test"]["perl_bin"] = ""; // $PATHS["test"]["redirect_url"] = ""; - // each host has a different db_host - // development host - $DB_HOST[''] = ""; - // target host (live) +// each host has a different db_host +// development host +$DB_HOST[''] = ""; +// target host (live) // $DB_TARGET_HOST[''] = ""; - // url redirect database +// url redirect database // $DB_URL_REDIRECT_HOST[''] = ""; - // location flagging - // test/dev/live - $LOCATION[''] = ''; - // show DEBUG override - // true/false - $DEBUG_FLAG[''] = true; - // set postgresql paths (schemas) - $DB_PATH[''] = PUBLIC_SCHEMA; +// location flagging +// test/dev/live +$LOCATION[''] = ''; +// show DEBUG override +// true/false +$DEBUG_FLAG[''] = true; +// set postgresql paths (schemas) +$DB_PATH[''] = PUBLIC_SCHEMA; - // set the USE_DATABASE var, if there is nothing set, we assume TRUE - $USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; +// set the USE_DATABASE var, if there is nothing set, we assume TRUE +$USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; - // live frontend pages - // ** missing live domains ** - // get the name without the port - list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); - if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) - { - echo "No matching DB config found. Contact Admin
"; - exit -1; - } +// live frontend pages +// ** missing live domains ** +// get the name without the port +list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null); +if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) { + echo "No matching DB config found. Contact Admin
"; + exit -1; +} - // define the static names - DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); - DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); - DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); +// define the static names +DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); +DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); +DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); // DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]); // DEFINE('URL_REDIRECT_DB', $DB_URL_REDIRECT_HOST[$HOST_NAME]); - // next three if top is not set +// next three if top is not set // DEFINE('DEV_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']); // DEFINE('TEST_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']); // DEFINE('PUBLIC_SCHEMA', $DB_CONFIG[TARGET_DB]['db_schema']); - DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are - DEFINE('GLOBAL_DB_SCHEMA', 'public'); // where global tables are that are used by all schemas (eg queue tables for online, etc) - DEFINE('TARGET', $LOCATION[$HOST_NAME]); +DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are +DEFINE('GLOBAL_DB_SCHEMA', 'public'); // where global tables are that are used by all schemas (eg queue tables for online, etc) +DEFINE('TARGET', $LOCATION[$HOST_NAME]); // DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']); // DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']); // DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']); - DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); - DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled +DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); +DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled - /************* GENERAL PAGE TITLE ********/ - $G_TITLE = ''; +/************* GENERAL PAGE TITLE ********/ +$G_TITLE = ''; - /************ STYLE SHEETS / JS **********/ - $EDIT_STYLESHEET = "edit.css"; - $EDIT_JAVASCRIPT = "edit.js"; +/************ STYLE SHEETS / JS **********/ +$EDIT_STYLESHEET = "edit.css"; +$EDIT_JAVASCRIPT = "edit.js"; - $STYLESHEET = "frontend.css"; - $JAVASCRIPT = "frontend.js"; +$STYLESHEET = "frontend.css"; +$JAVASCRIPT = "frontend.js"; - /************* CONVERT *******************/ - $paths = array ( - '/bin', - '/usr/bin', - '/usr/local/bin' - ); - // find convert - foreach ($paths as $path) - { - if (file_exists($path."/convert") && is_file($path."/convert")) - { - // image magick convert location - DEFINE('CONVERT', $path."/convert"); - } +/************* CONVERT *******************/ +$paths = array ( + '/bin', + '/usr/bin', + '/usr/local/bin' +); +// find convert +foreach ($paths as $path) { + if (file_exists($path."/convert") && is_file($path."/convert")) { + // image magick convert location + DEFINE('CONVERT', $path."/convert"); } +} - // turn off debug if debug flag is OFF - if (DEBUG == false) - { - $ECHO_ALL = 0; - $DEBUG_ALL = 0; - $PRINT_ALL = 0; - $DB_DEBUG = 0; - $ENABLE_ERROR_HANDLING = 0; - } +// turn off debug if debug flag is OFF +if (DEBUG == false) { + $ECHO_ALL = 0; + $DEBUG_ALL = 0; + $PRINT_ALL = 0; + $DB_DEBUG = 0; + $ENABLE_ERROR_HANDLING = 0; +} - // any other global definitons here +// any other global definitons here // DEFINE('SOME_ID', ); - // function that will be called on top of each class include to load the class - function _spl_autoload($include_file) - { - // where to search for the files to include - $dirs = array ( - LIBDIR, - SMARTYDIR, - TABLEARRAYDIR, - '', - LIBS, - SMARTY, - TABLE_ARRAYS, - __DIR__.'/'.LIBS, - __DIR__.'/'.SMARTY - ); - // try to find and load the class ifle - foreach ($dirs as $folder) - { - if (file_exists($folder.$include_file)) - { - require_once($folder.$include_file); - return true; - } +// function that will be called on top of each class include to load the class +function _spl_autoload($include_file) +{ + // where to search for the files to include + $dirs = array ( + LIBDIR, + SMARTYDIR, + TABLEARRAYDIR, + '', + LIBS, + SMARTY, + TABLE_ARRAYS, + __DIR__.'/'.LIBS, + __DIR__.'/'.SMARTY + ); + // try to find and load the class ifle + foreach ($dirs as $folder) { + if (file_exists($folder.$include_file)) { + require_once($folder.$include_file); + return true; } - return false; } -?> + return false; +} diff --git a/www/configs/config.template.inc b/www/configs/config.template.inc index 73e104f1..6f5e3422 100644 --- a/www/configs/config.template.inc +++ b/www/configs/config.template.inc @@ -1,280 +1,275 @@ "); - // frontend - DEFINE('SESSION_NAME', ""); +/************* SESSION NAMES *************/ +// backend +DEFINE('EDIT_SESSION_NAME', ""); +// frontend +DEFINE('SESSION_NAME', ""); +// set the session name +define('SET_SESSION_NAME', EDIT_SESSION_NAME); - /************* LANGUAGE / ENCODING *******/ - DEFINE('DEFAULT_LANG', "en_utf8"); - // default web page encoding setting - DEFINE('DEFAULT_ENCODING', "UTF-8"); +/************* LANGUAGE / ENCODING *******/ +DEFINE('DEFAULT_LANG', "en_utf8"); +// default web page encoding setting +DEFINE('DEFAULT_ENCODING', "UTF-8"); - /************* PATHS *********************/ - // ** NEW/BETTER DIR DECLARATIONS ** - // path to original file (if symlink) - DEFINE('DIR', __DIR__."/"); - // libs base path based on DIR - DEFINE('LIBDIR', DIR.'libs/'); - // SMARTY path based on DIR - DEFINE('SMARTYDIR', DIR.'Smarty/'); - // table arrays for Class Form - DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); +/************* PATHS *********************/ +// ** NEW/BETTER DIR DECLARATIONS ** +// path to original file (if symlink) +DEFINE('DIR', __DIR__."/"); +// libs base path based on DIR +DEFINE('LIBDIR', DIR.'libs/'); +// SMARTY path based on DIR +DEFINE('SMARTYDIR', DIR.'Smarty/'); +// table arrays for Class Form +DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); - // ** OLD DIR DECLARATIONS ** - // path to document root of file called - DEFINE('ROOT', getcwd()."/"); - // libs path - DEFINE('LIBS', "libs/"); - // includes (strings, arrays for static, etc) - DEFINE('INCLUDES', "includes/"); - // layout base path - DEFINE('LAYOUT', 'layout/'); - // pic-root (compatible to CMS) - DEFINE('PICTURES', "images/"); - // images - DEFINE('IMAGES', "images/"); - // icons (below the images/ folder) - DEFINE('ICONS', 'icons/'); - // media - DEFINE('MEDIA', "media/"); - // flash-root (below media) - DEFINE('FLASH', "flash/"); - // uploads (anything to keep) - DEFINE('UPLOADS', "uploads/"); - // files (binaries) (below media) - DEFINE('BINARIES', "binaries/"); - // files (videos) (below media) - DEFINE('VIDEOS', "videos/"); - // files (documents) (below media) - DEFINE('DOCUMENTS', "documents/"); - // files (pdfs) (below media) - DEFINE('PDFS', "documents/"); - // css - DEFINE('CSS', "css/"); - // js - DEFINE('JS', "javascript/"); - // table arrays - DEFINE('TABLE_ARRAYS', "table_arrays/"); - // smarty libs path - DEFINE('SMARTY', "Smarty/"); - // po langs - DEFINE('LANG', "lang/"); - // cache path - DEFINE('CACHE', "cache/"); - // temp path - DEFINE('TMP', "tmp/"); - // log files - DEFINE('LOG', 'log/'); - // template base - DEFINE('TEMPLATES', "templates/"); - // frontend template dir', only for admin - DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); - // default template - DEFINE('DEFAULT_TEMPLATE', "default/"); - // default template file - DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); +// ** OLD DIR DECLARATIONS ** +// path to document root of file called +DEFINE('ROOT', getcwd()."/"); +// libs path +DEFINE('LIBS', "libs/"); +// includes (strings, arrays for static, etc) +DEFINE('INCLUDES', "includes/"); +// layout base path +DEFINE('LAYOUT', 'layout/'); +// pic-root (compatible to CMS) +DEFINE('PICTURES', "images/"); +// images +DEFINE('IMAGES', "images/"); +// icons (below the images/ folder) +DEFINE('ICONS', 'icons/'); +// media +DEFINE('MEDIA', "media/"); +// flash-root (below media) +DEFINE('FLASH', "flash/"); +// uploads (anything to keep) +DEFINE('UPLOADS', "uploads/"); +// files (binaries) (below media) +DEFINE('BINARIES', "binaries/"); +// files (videos) (below media) +DEFINE('VIDEOS', "videos/"); +// files (documents) (below media) +DEFINE('DOCUMENTS', "documents/"); +// files (pdfs) (below media) +DEFINE('PDFS', "documents/"); +// css +DEFINE('CSS', "css/"); +// js +DEFINE('JS', "javascript/"); +// table arrays +DEFINE('TABLE_ARRAYS', "table_arrays/"); +// smarty libs path +DEFINE('SMARTY', "Smarty/"); +// po langs +DEFINE('LANG', "lang/"); +// cache path +DEFINE('CACHE', "cache/"); +// temp path +DEFINE('TMP', "tmp/"); +// log files +DEFINE('LOG', 'log/'); +// template base +DEFINE('TEMPLATES', "templates/"); +// frontend template dir', only for admin +DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); +// default template +DEFINE('DEFAULT_TEMPLATE', "default/"); +// default template file +DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); - /************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ - // default hash type - DEFINE('DEFAULT_HASH', 'sha256'); - // default acl level - DEFINE('DEFAULT_ACL_LEVEL', 80); - // default levels for certain actions +/************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ +// default hash type +DEFINE('DEFAULT_HASH', 'sha256'); +// default acl level +DEFINE('DEFAULT_ACL_LEVEL', 80); +// default levels for certain actions /* DEFINE('DEFAULT_ACL_READ', 20); - DEFINE('DEFAULT_ACL_CONFIRM', 35); - DEFINE('DEFAULT_ACL_MOD', 40); - DEFINE('DEFAULT_ACL_WRITE', 60); - DEFINE('DEFAULT_ACL_SEND', 70); - DEFINE('DEFAULT_ACL_DEL', 80); - DEFINE('DEFAULT_ACL_ADMIN', 100); */ - // SSL host name +DEFINE('DEFAULT_ACL_CONFIRM', 35); +DEFINE('DEFAULT_ACL_MOD', 40); +DEFINE('DEFAULT_ACL_WRITE', 60); +DEFINE('DEFAULT_ACL_SEND', 70); +DEFINE('DEFAULT_ACL_DEL', 80); +DEFINE('DEFAULT_ACL_ADMIN', 100); */ +// SSL host name // DEFINE('SSL_HOST', "ssl.host.name"); - // error page strictness, Default is 3 - // 1: only show error page as the last mesure if really no mid & aid can be loaded and found at all - // 2: if template not found, do not search, show error template - // 3: if default template is not found, show error template, do not fall back to default tree - // 4: very strict, even on normal fixable errors through error +// error page strictness, Default is 3 +// 1: only show error page as the last mesure if really no mid & aid can be loaded and found at all +// 2: if template not found, do not search, show error template +// 3: if default template is not found, show error template, do not fall back to default tree +// 4: very strict, even on normal fixable errors through error // DEFINE('ERROR_STRICT', 3); - // allow page caching in general, set to "FALSE" if you do debugging or development! +// allow page caching in general, set to "FALSE" if you do debugging or development! // DEFINE('ALLOW_SMARTY_CACHE', FALSE); - // cache life time, in seconds, default here is 2 days (172800s) - // -1 is never expire cache +// cache life time, in seconds, default here is 2 days (172800s) +// -1 is never expire cache // DEFINE('SMARTY_CACHE_LIFETIME', -1); - /************* LOGOUT ********************/ - // logout target - DEFINE('LOGOUT_TARGET', ''); - // password change allowed - DEFINE('PASSWORD_CHANGE', false); +/************* LOGOUT ********************/ +// logout target +DEFINE('LOGOUT_TARGET', ''); +// password change allowed +DEFINE('PASSWORD_CHANGE', false); - /************* AJAX / ACCESS *************/ - // ajax request type - DEFINE('AJAX_REQUEST_TYPE', 'POST'); - // what AJAX type to use - DEFINE('USE_PROTOTYPE', true); - DEFINE('USE_SCRIPTACULOUS', false); - DEFINE('USE_JQUERY', false); +/************* AJAX / ACCESS *************/ +// ajax request type +DEFINE('AJAX_REQUEST_TYPE', 'POST'); +// what AJAX type to use +DEFINE('USE_PROTOTYPE', true); +DEFINE('USE_SCRIPTACULOUS', false); +DEFINE('USE_JQUERY', false); - /************* LAYOUT WIDTHS *************/ - DEFINE('PAGE_WIDTH', 800); - // the default template name - DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); +/************* LAYOUT WIDTHS *************/ +DEFINE('PAGE_WIDTH', 800); +// the default template name +DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); - /************* QUEUE TABLE *************/ - // if we have a dev/live system - // set_live is a per page/per item - // live_queue is a global queue system +/************* QUEUE TABLE *************/ +// if we have a dev/live system +// set_live is a per page/per item +// live_queue is a global queue system // DEFINE('QUEUE', 'live_queue'); - /************* DB PATHS (PostgreSQL) *****************/ - // schema names, can also be defined per - DEFINE('PUBLIC_SCHEMA', 'public'); - DEFINE('DEV_SCHEMA', 'public'); - DEFINE('TEST_SCHEMA', 'public'); +/************* DB PATHS (PostgreSQL) *****************/ +// schema names, can also be defined per +DEFINE('PUBLIC_SCHEMA', 'public'); +DEFINE('DEV_SCHEMA', 'public'); +DEFINE('TEST_SCHEMA', 'public'); - // non constant part - /************* DB ACCESS *****************/ - // please be VERY carefull only to change the right side - $DB_CONFIG = array( - "" => array ( - "db_name" => "", - "db_user" => "", - "db_pass" => "", - "db_host" => "", - "db_port" => "5432", - "db_schema" => "", // if not set, uses public - "db_type" => "pgsql", - "db_encoding" => '', - "db_ssl" => 'disable' // allow, disable, require, prefer - ) - ); +// non constant part +/************* DB ACCESS *****************/ +// please be VERY carefull only to change the right side +$DB_CONFIG = array ( + "" => array ( + "db_name" => "", + "db_user" => "", + "db_pass" => "", + "db_host" => "", + "db_port" => "5432", + "db_schema" => "", // if not set, uses public + "db_type" => "pgsql", + "db_encoding" => '', + "db_ssl" => 'disable' // allow, disable, require, prefer + ) +); - // File and Folder paths - // ID is TARGET (first array element) +// File and Folder paths +// ID is TARGET (first array element) // $PATHS["test"]["csv_path"] = ""; // $PATHS["test"]["perl_bin"] = ""; // $PATHS["test"]["redirect_url"] = ""; - // each host has a different db_host - // development host - $DB_HOST[''] = ""; - // target host (live) +// each host has a different db_host +// development host +$DB_HOST[''] = ""; +// target host (live) // $DB_TARGET_HOST[''] = ""; - // url redirect database +// url redirect database // $DB_URL_REDIRECT_HOST[''] = ""; - // location flagging - // test/dev/live - $LOCATION[''] = ''; - // show DEBUG override - // true/false - $DEBUG_FLAG[''] = true; - // set postgresql paths (schemas) - $DB_PATH[''] = PUBLIC_SCHEMA; +// location flagging +// test/dev/live +$LOCATION[''] = ''; +// show DEBUG override +// true/false +$DEBUG_FLAG[''] = true; +// set postgresql paths (schemas) +$DB_PATH[''] = PUBLIC_SCHEMA; - // set the USE_DATABASE var, if there is nothing set, we assume TRUE - $USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; +// set the USE_DATABASE var, if there is nothing set, we assume TRUE +$USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; - // live frontend pages - // ** missing live domains ** - // get the name without the port - list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); - if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) - { - echo "No matching DB config found. Contact Admin
"; - exit -1; - } +// live frontend pages +// ** missing live domains ** +// get the name without the port +list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null); +if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) { + echo "No matching DB config found. Contact Admin
"; + exit -1; +} - // define the static names - DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); - DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); - DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); +// define the static names +DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); +DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); +DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); // DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]); // DEFINE('URL_REDIRECT_DB', $DB_URL_REDIRECT_HOST[$HOST_NAME]); - // next three if top is not set +// next three if top is not set // DEFINE('DEV_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']); // DEFINE('TEST_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']); // DEFINE('PUBLIC_SCHEMA', $DB_CONFIG[TARGET_DB]['db_schema']); - DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are - DEFINE('GLOBAL_DB_SCHEMA', 'public'); // where global tables are that are used by all schemas (eg queue tables for online, etc) - DEFINE('TARGET', $LOCATION[$HOST_NAME]); +DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are +DEFINE('GLOBAL_DB_SCHEMA', 'public'); // where global tables are that are used by all schemas (eg queue tables for online, etc) +DEFINE('TARGET', $LOCATION[$HOST_NAME]); // DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']); // DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']); // DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']); - DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); - DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled +DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); +DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled - /************* GENERAL PAGE TITLE ********/ - $G_TITLE = ''; +/************* GENERAL PAGE TITLE ********/ +$G_TITLE = ''; - /************ STYLE SHEETS / JS **********/ - $EDIT_STYLESHEET = "edit.css"; - $EDIT_JAVASCRIPT = "edit.js"; +/************ STYLE SHEETS / JS **********/ +$EDIT_STYLESHEET = "edit.css"; +$EDIT_JAVASCRIPT = "edit.js"; - $STYLESHEET = "frontend.css"; - $JAVASCRIPT = "frontend.js"; +$STYLESHEET = "frontend.css"; +$JAVASCRIPT = "frontend.js"; - /************* CONVERT *******************/ - $paths = array ( - '/bin', - '/usr/bin', - '/usr/local/bin' - ); - // find convert - foreach ($paths as $path) - { - if (file_exists($path."/convert") && is_file($path."/convert")) - { - // image magick convert location - DEFINE('CONVERT', $path."/convert"); - } +/************* CONVERT *******************/ +$paths = array ( + '/bin', + '/usr/bin', + '/usr/local/bin' +); +// find convert +foreach ($paths as $path) { + if (file_exists($path."/convert") && is_file($path."/convert")) { + // image magick convert location + DEFINE('CONVERT', $path."/convert"); } +} - // turn off debug if debug flag is OFF - if (DEBUG == false) - { - $ECHO_ALL = 0; - $DEBUG_ALL = 0; - $PRINT_ALL = 0; - $DB_DEBUG = 0; - $ENABLE_ERROR_HANDLING = 0; - } +// turn off debug if debug flag is OFF +if (DEBUG == false) { + $ECHO_ALL = 0; + $DEBUG_ALL = 0; + $PRINT_ALL = 0; + $DB_DEBUG = 0; + $ENABLE_ERROR_HANDLING = 0; +} - // any other global definitons here +// any other global definitons here // DEFINE('SOME_ID', ); - // function that will be called on top of each class include to load the class - function _spl_autoload($include_file) - { - // where to search for the files to include - $dirs = array ( - LIBDIR, - SMARTYDIR, - TABLEARRAYDIR, - '', - LIBS, - SMARTY, - TABLE_ARRAYS, - __DIR__.'/'.LIBS, - __DIR__.'/'.SMARTY - ); - // try to find and load the class ifle - foreach ($dirs as $folder) - { - if (file_exists($folder.$include_file)) - { - require_once($folder.$include_file); - return true; - } +// function that will be called on top of each class include to load the class +function _spl_autoload($include_file) +{ + // where to search for the files to include + $dirs = array ( + LIBDIR, + SMARTYDIR, + TABLEARRAYDIR, + '', + LIBS, + SMARTY, + TABLE_ARRAYS, + __DIR__.'/'.LIBS, + __DIR__.'/'.SMARTY + ); + // try to find and load the class ifle + foreach ($dirs as $folder) { + if (file_exists($folder.$include_file)) { + require_once($folder.$include_file); + return true; } - return false; } -?> + return false; +} diff --git a/www/layout/admin/default/css/edit.css b/www/layout/admin/default/css/edit.css index 2c44db13..695b93bb 100644 --- a/www/layout/admin/default/css/edit.css +++ b/www/layout/admin/default/css/edit.css @@ -15,416 +15,353 @@ padding: 0; } */ -body -{ +body { background-color: white; color: black; - font-size : 8pt; font-family: Verdana,Arial,Helvetica,sans-serif; + font-size : 8pt; } -.large -{ +.large { + font-family: Verdana,Arial,Helvetica,sans-serif; font-size : 16pt; - font-family: Verdana,Arial,Helvetica,sans-serif; } -.big -{ +.big { + font-family: Verdana,Arial,Helvetica,sans-serif; font-size : 12pt; - font-family: Verdana,Arial,Helvetica,sans-serif; } -.normal -{ +.normal { + font-family: Verdana,Arial,Helvetica,sans-serif; font-size : 9pt; - font-family: Verdana,Arial,Helvetica,sans-serif; } -.small -{ - font-size : 8pt; +.small { font-family: Verdana,Arial,Helvetica,sans-serif; + font-size : 8pt; } -.smallbold -{ - font-size : 8pt; +.smallbold { font-family: Verdana,Arial,Helvetica,sans-serif; + font-size : 8pt; font-weight: bold; } -a:link -{ +a:link { color: #FF0000; text-decoration: none; } -a:active -{ +a:active { color: #FFFF00; text-decoration: none; } -a:visited -{ +a:visited { color: #550000; text-decoration: none; } -a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover -{ - color: #FF0000; +a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover { background-color: #e5e5e5; border-bottom: 1px dotted red; + color: #FF0000; } -a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover -{ - color: #ff0000; +a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover { background-color: #b3b3b3; - border-top: 1px dotted red; border-bottom: 1px dotted red; + border-top: 1px dotted red; + color: #ff0000; } /* link highlight */ -a.item_loaded -{ - font-weight: bold; - color: #451010; +a.item_loaded { background-color: #d5d6d6; + color: #451010; + font-weight: bold; } -a.item_deleted -{ +a.item_deleted { text-decoration: line-through; } -a.item_loaded_deleted -{ - text-decoration: line-through; - font-weight: bold; - color: #451010; +a.item_loaded_deleted { background-color: #d5d6d6; + color: #451010; + font-weight: bold; + text-decoration: line-through; } /* experimental */ -input[type="text"] -{ - border: 1px solid #999999; +input[type="text"] { background-color: #efefef; -} - -input[type="password"] -{ border: 1px solid #999999; } -input[type="submit"] -{ +input[type="password"] { + border: 1px solid #999999; +} + +input[type="submit"] { border: 1px solid #666666; } -input[type="checkbox"] -{ +input[type="checkbox"] { border: 1px solid #999999; } -input[type="radio"] -{ +input[type="radio"] { border: 1px solid #999999; } -input[type="file"] -{ +input[type="file"] { border: 1px solid #999999; } -input[type="button"] -{ +input[type="button"] { border: 1px solid #999999; } -textarea -{ - border: 1px solid #999999; +textarea { background-color: #efefef; + border: 1px solid #999999; } -select -{ - border: 1px solid #999999; +select { background-color: #efefef; + border: 1px solid #999999; } /* mouse over */ -input[type=submit]:hover, input[type=button]:hover, input[type="text"]:hover, input[type="password"]:hover, input[type="checkbox"]:hover, input[type="radio"]:hover, input[type="file"]:hover, textarea:hover, select:hover -{ +input[type=submit]:hover, input[type=button]:hover, input[type="text"]:hover, input[type="password"]:hover, input[type="checkbox"]:hover, input[type="radio"]:hover, input[type="file"]:hover, textarea:hover, select:hover { border: 1px dashed red; } /* selected */ -input[type=submit]:focus, input[type=button]:focus, input[type="password"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, input[type="file"]:focus -{ - border: 1px solid red; +input[type=submit]:focus, input[type=button]:focus, input[type="password"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, input[type="file"]:focus { background-color: #ffffff; + border: 1px solid red; } -input[type="text"]:focus, textarea:focus, select:focus -{ - border: 1px solid red; +input[type="text"]:focus, textarea:focus, select:focus { background-color: #ffffff; + border: 1px solid red; } /* error & status layouts for messges */ -.error -{ +.error { border: 1px solid red; - margin: 5px; - padding: 2px; color: red; + margin: 5px; + padding: 2px; text-align: center; } -.warning -{ +.warning { border: 1px solid #df7700; - margin: 5px; - padding: 2px; color: #d57200; - text-align: center; -} - -.info -{ - border: 1px solid #72C47E; margin: 5px; padding: 2px; - color: #1D731A; text-align: center; } -.div_error -{ - border: 1px solid red; - margin-top: 1px; - margin-bottom: 1px; +.info { + border: 1px solid #72C47E; + color: #1D731A; + margin: 5px; + padding: 2px; + text-align: center; } -.div_warning -{ +.div_error { + border: 1px solid red; + margin-bottom: 1px; + margin-top: 1px; +} + +.div_warning { border: 1px solid #df7700; } /* borders */ -.border_all -{ +.border_all { border: 1px solid black; } -.border_bottom_title -{ - font-weight: bold; +.border_bottom_title { border-bottom: 1px solid black; + font-weight: bold; } -.border_top -{ +.border_top { border-top: 1px solid #DCDCCC; } -.border_all_error -{ +.border_all_error { border: 1px solid red; } -.border_group -{ +.border_group { border: 1px solid #a89c5a; } -.border_master -{ +.border_master { border: 1px solid white; } -.border_sub -{ +.border_sub { border: 1px solid gray; } -.border_sub_sub -{ +.border_sub_sub { border: 1px solid #e5ddba; } /* employee hardware/software borders */ -.border_hardware -{ +.border_hardware { + background-color: #e9e9e9; border: 2px solid black; - background-color: #e9e9e9; } -.border_hardware_usage_end -{ +.border_hardware_usage_end { + background-color: #e9e9e9; border: 2px solid red; - background-color: #e9e9e9; } -.border_hardware_line -{ - border-left: 2px solid black; +.border_hardware_line { border-bottom: 2px solid black; + border-left: 2px solid black; } -.border_software -{ - border: 2px solid #a89c5a; +.border_software { background-color: #d5d4c8; + border: 2px solid #a89c5a; } -.border_software_line -{ - border-left: 2px solid #a89c5a; +.border_software_line { border-bottom: 2px solid #a89c5a; + border-left: 2px solid #a89c5a; } -.border_software_line_left -{ +.border_software_line_left { border-left: 2px solid #a89c5a; padding-bottom: 10px; } -.border_software_line_bottom -{ +.border_software_line_bottom { border-bottom: 2px solid #a89c5a; padding-left: 2px; } /* highlight */ -.highlight -{ +.highlight { background-color: #e7e7e7; font-weight: bold; } /* hide & show */ -.visible -{ +.visible { visibility: visible; } -.hidden -{ - visibility: hidden; +.hidden { display: none; + visibility: hidden; } /* spacer for line break in float elements */ -div.spacer -{ +.spacer { clear: both; } /* unique definitions */ /* main body */ /* menu on top */ -.menu -{ +.menu { border-bottom: 1px solid #a4a4a4; font-size: 10px; } -.pagename -{ - text-align: center; font-size: 15px; +.pagename { background-color: #e7e7e7; + font-size: 15px; font-weight: bold; padding: 5px; + text-align: center; } /* overlay side menu */ -.sidemenu -{ - border: 1px solid black; +.sidemenu { background-color: white; + border: 1px solid black; } -.buttongroup -{ +.buttongroup { border: 1px solid #e5ddba; } /* input group field */ /* normal */ -.input_group -{ +.input_group { border: 1px solid #e5ddba; } /* loaded with id */ -.input_group_id -{ +.input_group_id { border: 1px solid #8a7d3a; } /* deleted */ -.input_group_deleted -{ - border: 1px solid #8a7d3a; +.input_group_deleted { background-color: #d5d4c8; + border: 1px solid #8a7d3a; } /* header part */ /* normal */ -.input_group_header -{ +.input_group_header { background-color: #e9e9e9; } /* loaded with id */ -.input_group_header_id -{ +.input_group_header_id { background-color: #d5d5d5; } /* deleted */ -.input_group_header_deleted -{ +.input_group_header_deleted { background-color: #bfb59d; } /* error & warning messages */ -.top_error_message -{ +.top_error_message { + border: 2px solid red; + color: red; + font-size: 18px; margin: 5px; padding: 10px; - border: 2px solid red; - font-size: 18px; text-align: center; - color: red; } -.top_inventory_number -{ - margin: 5px; - padding: 10px; +.top_inventory_number { border: 2px solid orange; font-size: 18px; - text-align: center; -} - -.top_info_message -{ - border: 2px solid green; margin: 5px; padding: 10px; text-align: center; - font-size: 12px; } -.debug_message -{ +.top_info_message { + border: 2px solid green; + font-size: 12px; + margin: 5px; + padding: 10px; + text-align: center; +} + +.debug_message { border-top: 1px solid #a4a4a4; color: #a4a4a4; font-size: 8px; @@ -434,78 +371,63 @@ div.spacer /* set all colors here and not in the config file */ /* for edit interface */ -.menu_bgcolor -{ +.menu_bgcolor { background-color: #666666; } -.menu_fgcolor -{ +.menu_fgcolor { background-color: #DDDDDD; } -.menu_fgcolor_na -{ +.menu_fgcolor_na { background-color: #CCCCCC; } -.menu_fgcolor_a -{ +.menu_fgcolor_a { background-color: #EEEEEE; } -.edit_bgcolor -{ +.edit_bgcolor { background-color: #666666; } -.edit_fgcolor -{ +.edit_fgcolor { background-color: #FFFFDF; } -.edit_fgcolor_mod_a -{ +.edit_fgcolor_mod_a { background-color: #CECEB5; } -.edit_fgcolor_mod_b -{ +.edit_fgcolor_mod_b { background-color: #DEDEC3; } -.edit_fgcolor_2 -{ +.edit_fgcolor_2 { background-color: #AADAA2; } -.edit_fgcolor_no -{ +.edit_fgcolor_no { background-color: #CECEB5; } -.edit_fgcolor_alt -{ +.edit_fgcolor_alt { background-color: #CCCCCC; } -.edit_fgcolor_delete -{ +.edit_fgcolor_delete { background-color: red; } -.font_error -{ +.font_error { color: red; } -.edit_fgcolor_special -{ +.edit_fgcolor_special { background-color: #EEEEEE; } -.edit_temp -{ +.edit_temp { background-color: #FFDF6F; } diff --git a/www/layout/admin/default/javascript/debug.js b/www/layout/admin/default/javascript/debug.js index 58ebae1c..c8d70071 100644 --- a/www/layout/admin/default/javascript/debug.js +++ b/www/layout/admin/default/javascript/debug.js @@ -9,9 +9,8 @@ */ // if debug is set to true, console log messages are printed -if (!DEBUG) -{ +if (!DEBUG) { $($H(window.console)).each(function(w) { - window.console[w.key] = function() {} + window.console[w.key] = function() {}; }); } diff --git a/www/layout/admin/default/javascript/edit.js b/www/layout/admin/default/javascript/edit.js index 7dcd576c..f12f23fd 100644 --- a/www/layout/admin/default/javascript/edit.js +++ b/www/layout/admin/default/javascript/edit.js @@ -6,50 +6,43 @@ * Some browser detection */ var clientPC = navigator.userAgent.toLowerCase(); // Get client info -var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) - && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1)); +var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) && + (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1)); var is_safari = ((clientPC.indexOf('AppleWebKit') != -1) && (clientPC.indexOf('spoofer') == -1)); var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled )); -if (clientPC.indexOf('opera') != -1) -{ +if (clientPC.indexOf('opera') != -1) { var is_opera = true; var is_opera_preseven = (window.opera && !document.childNodes); var is_opera_seven = (window.opera && document.childNodes); } -function pop(theURL, winName, features) -{ +function pop(theURL, winName, features) { winName = window.open(theURL, winName, features); winName.focus(); } -function emd_check_checkbox() -{ - for (i = 0; i < document.manage_emails.length; i ++) - { - if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox') - { +function emd_check_checkbox() { + for (i = 0; i < document.manage_emails.length; i ++) { + if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox') { document.manage_emails.elements[i].checked = true; } } } -function expandTA(ta_id) -{ +function expandTA(ta_id) { var ta; // if a string comes, its a get by id, else use it as an element pass on - if (!ta_id.length) + if (!ta_id.length) { ta = ta_id; - else + } else { ta = document.getElementById(ta_id); + } var maxChars = ta.cols; var theRows = ta.value.split("\n"); var numNewRows = 0; - for ( var i = 0; i < theRows.length; i++ ) - { - if ((theRows[i].length+2) > maxChars) - { + for ( var i = 0; i < theRows.length; i++ ) { + if ((theRows[i].length+2) > maxChars) { numNewRows += Math.ceil( (theRows[i].length+2) / maxChars ) ; } } @@ -62,27 +55,27 @@ function expandTA(ta_id) // DESC: shows or hides the menu function ShowHideMenu(status, id) { - if (status == 'show') - { + if (status == 'show') { document.getElementById(id).style.visibility = 'visible'; - if (document.getElementById('search_results').innerHTML) + if (document.getElementById('search_results').innerHTML) { document.getElementById('search_results').style.visibility = 'visible'; - } - else if (status == 'hide') - { + } + } else if (status == 'hide') { document.getElementById(id).style.visibility = 'hidden'; - if (document.getElementById('search_results').style.visibility == 'visible') + if (document.getElementById('search_results').style.visibility == 'visible') { document.getElementById('search_results').style.visibility = 'hidden'; + } } } function ShowHideDiv(id) { element = document.getElementById(id); - if (element.className == 'visible' || !element.className) + if (element.className == 'visible' || !element.className) { element.className = 'hidden'; - else + } else { element.className = 'visible'; + } // alert('E: ' + element.className + ' -- ' + element.style.visibility); } @@ -100,14 +93,16 @@ function mv(id, direction) function le(id) { document.forms[form_name].action.value = 'load'; - if (load_id) + if (load_id) { document.forms[form_name].action_yes.value = confirm('Do you want to load this data?'); - else + } else { document.forms[form_name].action_yes.value = 'true'; + } document.forms[form_name].action_id.value = id; document.forms[form_name].action_menu.value = id; - if (document.forms[form_name].action_yes.value == 'true') + if (document.forms[form_name].action_yes.value == 'true') { document.forms[form_name].submit(); + } } // METHOD: getWindowSize @@ -119,7 +114,10 @@ function getWindowSize() var width, height; width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth); height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight); - return {width: width, height: height}; + return { + width: width, + height: height + }; } // METHOD: getScrollOffset @@ -131,7 +129,10 @@ function getScrollOffset() var left, top; left = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft); top = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop); - return {left: left, top: top}; + return { + left: left, + top: top + }; } // METHOD: setCenter @@ -149,14 +150,12 @@ function setCenter(id, left, top) // console.log('Id %s, type: %s, dimensions %s x %s, viewport %s x %s', id, $(id).getStyle('position'), dimensions.width, dimensions.height, viewport.width, viewport.height); // console.log('Scrolloffset left: %s, top: %s', offset.left, offset.top); // console.log('Left: %s, Top: %s (%s)', parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left), parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top), parseInt((viewport.height / 2) - (dimensions.height / 2))); - if (left) - { + if (left) { $(id).setStyle ({ left: parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left) + 'px' }); } - if (top) - { + if (top) { // if we have fixed, we do not add the offset, else it moves out of the screen var top_pos = type == 'fixed' ? parseInt((viewport.height / 2) - (dimensions.height / 2)) : parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top); $(id).setStyle ({ @@ -178,15 +177,12 @@ function sh(id, showText, hideText) // get status from element (hidden or visible) divStatus = $(id).visible(); //console.log('Set flag %s for element %s', divStatus, id); - if (divStatus) - { + if (divStatus) { // hide the element Effect.BlindUp(id, {duration:0.3}); $(flag).value = 0; $(btn).innerHTML = showText; - } - else if (!divStatus) - { + } else if (!divStatus) { // show the element Effect.BlindDown(id, {duration:0.3}); $(flag).value = 1; diff --git a/www/layout/admin/default/javascript/firebug.js b/www/layout/admin/default/javascript/firebug.js index 0d54b957..9c975f19 100644 --- a/www/layout/admin/default/javascript/firebug.js +++ b/www/layout/admin/default/javascript/firebug.js @@ -10,7 +10,7 @@ var ConsoleSetup = function() { for (var i = 0; i < names.length; ++i) { if (!window.console[names[i]]) { - window.console[names[i]] = function() {} + window.console[names[i]] = function() {}; } } }(); diff --git a/www/layout/frontend/default/css/frontend.css b/www/layout/frontend/default/css/frontend.css index 199f5a5e..382cd316 100644 --- a/www/layout/frontend/default/css/frontend.css +++ b/www/layout/frontend/default/css/frontend.css @@ -1,5 +1,4 @@ -.debug_message -{ +.debug_message { border-top: 1px solid #a4a4a4; color: #a4a4a4; font-size: 8px; diff --git a/www/layout/frontend/default/javascript/frontend.js b/www/layout/frontend/default/javascript/frontend.js index 5f4d11a0..10cb195f 100644 --- a/www/layout/frontend/default/javascript/frontend.js +++ b/www/layout/frontend/default/javascript/frontend.js @@ -8,10 +8,10 @@ // PARAMS: front/back -> what image to show // RETURN: none // DESC: ajax call to switch the main image in the detail view -function SwitchImage(image) -{ - if (image != 'front' || image != 'back') +function SwitchImage(image) { + if (image != 'front' || image != 'back') { image = 'front'; + } // disable / enable the href for the other side x_ajax_afSwitchImage(image, OutputSwitchImage); } @@ -20,7 +20,6 @@ function SwitchImage(image) // PARAMS: data -> the image full path for the new image // RETURN: none // DESC: replace the image in the product detail with the back image -function OutputSwitchImage(data) -{ +function OutputSwitchImage(data) { } diff --git a/www/libs/Class.Admin.Backend.inc b/www/libs/Class.Admin.Backend.inc index 05c6960f..1e7b5680 100644 --- a/www/libs/Class.Admin.Backend.inc +++ b/www/libs/Class.Admin.Backend.inc @@ -1,400 +1,410 @@ + public function __construct($db_config, $lang, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) { - // page name - public $page_name; // the name of the current page - public $menu = array(); - public $menu_show_flag = 0; // top menu flag (mostly string) - // action ids - public $action_list = array ('action', 'action_id', 'action_sub_id', 'action_yes', 'action_flag', 'action_menu', 'action_value', 'action_error', 'action_loaded'); - public $action; - public $action_id; - public $action_sub_id; - public $action_yes; - public $action_flag; - public $action_menu; - public $action_loaded; - public $action_value; - public $action_error; - // ACL array variable if we want to set acl data from outisde - public $acl = array (); - // the current active edit access id - public $edit_access_id; - // error/warning/info messages - public $messages = array (); - public $error = 0; - public $warning = 0; - public $info = 0; - // smarty publics - public $DATA; - public $HEADER; - public $DEBUG_DATA; - public $CONTENT_DATA; + // get the language sub class & init it + _spl_autoload('Class.l10n.inc'); - // CONSTRUCTOR / DECONSTRUCTOR |====================================> - public function __construct($db_config, $lang, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) - { - // get the language sub class & init it - _spl_autoload('Class.l10n.inc'); + $this->l = new l10n($lang); - $this->l = new l10n($lang); - - // init the database class + // init the database class // $this->db_io($db_config, $debug, $db_debug, $echo, $print); - parent::__construct($db_config, $debug, $db_debug, $echo, $print); + parent::__construct($db_config, $debug, $db_debug, $echo, $print); - // internal - $this->class_info["adbBackend"] = array( - "class_name" => "Admin Interface Backend", - "class_version" => "0.1.0", - "class_created" => "2006/08/15", - "class_author" => "cs/gullevek/jp" + // internal + $this->class_info["adbBackend"] = array( + "class_name" => "Admin Interface Backend", + "class_version" => "0.1.0", + "class_created" => "2006/08/15", + "class_author" => "cs/gullevek/jp" + ); + + // set page name + $this->page_name = $this->get_page_name(); + + // set the action ids + foreach ($this->action_list as $_action) { + $this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : ''; + } + + $this->default_acl = DEFAULT_ACL_LEVEL; + + // random key generation + $this->key_range = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9')); + $GLOBALS["_KEY_RANGE"] = $this->key_range; + $this->one_key_length = count($this->key_range); + $this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62) + + // queue key + if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) { + $this->queue_key = join( + '', + array_map( + function () { + $range = $GLOBALS['_KEY_RANGE']; + return $range[rand(0, (count($range) - 1))]; + }, + range(1, 3) + ) ); + } + } - // set page name - $this->page_name = $this->get_page_name(); + // deconstructor + public function __destruct() + { + parent::__destruct(); + } - // set the action ids - foreach ($this->action_list as $_action) - { - $this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : ''; - } + // INTERNAL METHODS |===============================================> - $this->default_acl = DEFAULT_ACL_LEVEL; - // random key generation - $this->key_range = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9')); - $GLOBALS["_KEY_RANGE"] = $this->key_range; - $this->one_key_length = count($this->key_range); - $this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62) + // PUBLIC METHODS |=================================================> - // queue key - if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) - { - $this->queue_key = join('', array_map(function () { $range = $GLOBALS['_KEY_RANGE']; return $range[rand(0, (count($range) - 1))]; }, range(1, 3))); - } + // METHOD: adbEditLog() + // PARAMS: event -> any kind of event description, data -> any kind of data related to that event + // RETURN: none + // DESC: writes all action vars plus other info into edit_log table + public function adbEditLog($event = '', $data = '', $write_type = 'STRING') + { + if ($write_type == 'BINARY') { + $data_binary = $this->db_escape_bytea(bzcompress(serialize($data))); + $data = 'see bzip compressed data_binary field'; + } + if ($write_type == 'STRING') { + $data = $this->db_escape_string(serialize($data)); } - // deconstructor - public function __destruct() - { - parent::__destruct(); + $q = "INSERT INTO ".LOGIN_DB_SCHEMA.".edit_log "; + $q .= "(euid, event_date, event, data, data_binary, page, "; + $q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, "; + $q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; + $q .= "VALUES "; + $q .= "(".@$_SESSION['EUID'].", NOW(), '".$this->db_escape_string($event)."', '".$data."', '".$data_binary."', '".$this->page_name."', "; + $q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->db_escape_string(@$_SERVER['HTTP_USER_AGENT'])."', "; + $q .= "'".$this->db_escape_string(@$_SERVER['HTTP_REFERER'])."', '".$this->db_escape_string(@$_SERVER['SCRIPT_FILENAME'])."', "; + $q .= "'".$this->db_escape_string(@$_SERVER['QUERY_STRING'])."', '".$this->db_escape_string(@$_SERVER['SERVER_NAME'])."', "; + $q .= "'".$this->db_escape_string(@$_SERVER['HTTP_HOST'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT'])."', "; + $q .= "'".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_CHARSET'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_ENCODING'])."', "; + $q .= "'".session_id()."', "; + $q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->action_id)."', "; + $q .= "'".$this->db_escape_string($this->action_yes)."', '".$this->db_escape_string($this->action_flag)."', "; + $q .= "'".$this->db_escape_string($this->action_menu)."', '".$this->db_escape_string($this->action_loaded)."', "; + $q .= "'".$this->db_escape_string($this->action_value)."', '".$this->db_escape_string($this->action_error)."')"; + $this->db_exec($q, 'NULL'); + } + + + // ================================== + // ALL THE PAGE RIGHTS/USER RIGHTS/ETC need to fixed and put into one + // proper settings have to be done with the defined top down rights flow + // ================================== + // all ACLs are set in the login class + + // METHOD: adbTopMenu + // PARAMS: level + // RETURN: returns an array for the top menu with all correct settings + // DESC: menu creater + public function adbTopMenu($flag = 0) + { + if ($this->menu_show_flag) { + $flag = $this->menu_show_flag; } - // INTERNAL METHODS |===============================================> - - - // PUBLIC METHODS |=================================================> - - // METHOD: adbEditLog() - // PARAMS: event -> any kind of event description, data -> any kind of data related to that event - // RETURN: none - // DESC: writes all action vars plus other info into edit_log table - public function adbEditLog($event = '', $data = '', $write_type = 'STRING') - { - if ($write_type == 'BINARY') - { - $data_binary = $this->db_escape_bytea(bzcompress(serialize($data))); - $data = 'see bzip compressed data_binary field'; - } - if ($write_type == 'STRING') - { - $data = $this->db_escape_string(serialize($data)); - } - - $q = "INSERT INTO ".LOGIN_DB_SCHEMA.".edit_log "; - $q .= "(euid, event_date, event, data, data_binary, page, "; - $q .= "ip, user_agent, referer, script_name, query_string, server_name, http_host, http_accept, http_accept_charset, http_accept_encoding, session_id, "; - $q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; - $q .= "VALUES "; - $q .= "(".@$_SESSION['EUID'].", NOW(), '".$this->db_escape_string($event)."', '".$data."', '".$data_binary."', '".$this->page_name."', "; - $q .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->db_escape_string(@$_SERVER['HTTP_USER_AGENT'])."', '".$this->db_escape_string(@$_SERVER['HTTP_REFERER'])."', '".$this->db_escape_string(@$_SERVER['SCRIPT_FILENAME'])."', '".$this->db_escape_string(@$_SERVER['QUERY_STRING'])."', '".$this->db_escape_string(@$_SERVER['SERVER_NAME'])."', '".$this->db_escape_string(@$_SERVER['HTTP_HOST'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_CHARSET'])."', '".$this->db_escape_string(@$_SERVER['HTTP_ACCEPT_ENCODING'])."', '".session_id()."', "; - $q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->action_id)."', '".$this->db_escape_string($this->action_yes)."', '".$this->db_escape_string($this->action_flag)."', '".$this->db_escape_string($this->action_menu)."', '".$this->db_escape_string($this->action_loaded)."', '".$this->db_escape_string($this->action_value)."', '".$this->db_escape_string($this->action_error)."')"; - $this->db_exec($q, 'NULL'); + // get the session pages array + $pages = $_SESSION["PAGES"]; + if (!is_array($pages)) { + $pages = array (); } - - // ================================== - // ALL THE PAGE RIGHTS/USER RIGHTS/ETC need to fixed and put into one - // proper settings have to be done with the defined top down rights flow - // ================================== - // all ACLs are set in the login class - - // METHOD: adbTopMenu - // PARAMS: level - // RETURN: returns an array for the top menu with all correct settings - // DESC: menu creater - public function adbTopMenu($flag = 0) - { - if ($this->menu_show_flag) - $flag = $this->menu_show_flag; - - // get the session pages array - $pages = $_SESSION["PAGES"]; - if (!is_array($pages)) - $pages = array (); - //$this->debug('pages', $this->print_ar($pages)); - // if flag is 0, then we show all, else, we show only the matching flagges array points - // array is already sorted after correct order - reset($pages); - for ($i = 0; $i < count($pages); $i ++) - { - $show = 0; - // is it visible in the menu & is it online - if ($pages[$i]["menu"] && $pages[$i]["online"]) - { - // check if it falls into our flag if we have a flag - if ($flag) - { - foreach ($pages[$i]["visible"] AS $name => $key) - { - if ($key == $flag) - $show = 1; + // if flag is 0, then we show all, else, we show only the matching flagges array points + // array is already sorted after correct order + reset($pages); + for ($i = 0; $i < count($pages); $i ++) { + $show = 0; + // is it visible in the menu & is it online + if ($pages[$i]["menu"] && $pages[$i]["online"]) { + // check if it falls into our flag if we have a flag + if ($flag) { + foreach ($pages[$i]["visible"] as $name => $key) { + if ($key == $flag) { + $show = 1; } } - else - { - // if no flag given, show all menu points - $show = 1; - } + } else { + // if no flag given, show all menu points + $show = 1; + } - if ($show) - { - // if it is popup, write popup arrayound - if ($pages[$i]["popup"]) - { - $type = "popup"; - } - else - { - $type = "normal"; - } - $query_string = ''; - if (count($pages[$i]["query"])) - { - for ($j = 0; $j < count($pages[$i]["query"]); $j ++) - { - if (strlen($query_string)) - $query_string .= "&"; - $query_string .= $pages[$i]["query"][$j]["name"]."="; - if (!$pages[$i]["query"][$j]["dynamic"]) - $query_string .= urlencode($pages[$i]["query"][$j]["value"]); - else - $query_string .= (($_GET[$pages[$i]["query"][$j]["value"]]) ? urlencode($_GET[$pages[$i]["query"][$j]["value"]]) : urlencode($_POST[$pages[$i]["query"][$j]["value"]])); + if ($show) { + // if it is popup, write popup arrayound + if ($pages[$i]["popup"]) { + $type = "popup"; + } else { + $type = "normal"; + } + $query_string = ''; + if (count($pages[$i]["query"])) { + for ($j = 0; $j < count($pages[$i]["query"]); $j ++) { + if (strlen($query_string)) { + $query_string .= "&"; + } + $query_string .= $pages[$i]["query"][$j]["name"]."="; + if (!$pages[$i]["query"][$j]["dynamic"]) { + $query_string .= urlencode($pages[$i]["query"][$j]["value"]); + } else { + $query_string .= $_GET[$pages[$i]["query"][$j]["value"]] ? urlencode($_GET[$pages[$i]["query"][$j]["value"]]) : urlencode($_POST[$pages[$i]["query"][$j]["value"]]); } } - $url = $pages[$i]["filename"]; - if (strlen($query_string)) - $url .= "?".$query_string; - $name = $pages[$i]["page_name"]; - // if page name matchs -> set selected flag - $selected = 0; - if ($this->get_page_name() == $pages[$i]["filename"]) - { - $selected = 1; - $this->page_name = $name; - } - // last check, is this menu point okay to show - $enabled = 0; - if ($this->adbShowMenuPoint($pages[$i]["filename"])) - { - $enabled = 1; - } - // write in to view menu array - array_push($this->menu, array("name" => $this->l->__($name), "url" => $url, "selected" => $selected, "enabled" => $enabled, "type" => $type)); - } // show page - } // online and in menu - } // for each page - return $this->menu; - } + } + $url = $pages[$i]["filename"]; + if (strlen($query_string)) { + $url .= "?".$query_string; + } + $name = $pages[$i]["page_name"]; + // if page name matchs -> set selected flag + $selected = 0; + if ($this->get_page_name() == $pages[$i]["filename"]) { + $selected = 1; + $this->page_name = $name; + } + // last check, is this menu point okay to show + $enabled = 0; + if ($this->adbShowMenuPoint($pages[$i]["filename"])) { + $enabled = 1; + } + // write in to view menu array + array_push($this->menu, array("name" => $this->l->__($name), "url" => $url, "selected" => $selected, "enabled" => $enabled, "type" => $type)); + } // show page + } // online and in menu + } // for each page + return $this->menu; + } - // METHOD: adbShowMenuPoint - // PARAMS: filename - // RETURN: returns boolean true/false - // DESC: checks if this filename is in the current situation (user id, etc) available - public function adbShowMenuPoint($filename) - { - $enabled = 0; - switch ($filename) - { - default: - $enabled = 1; + // METHOD: adbShowMenuPoint + // PARAMS: filename + // RETURN: returns boolean true/false + // DESC: checks if this filename is in the current situation (user id, etc) available + public function adbShowMenuPoint($filename) + { + $enabled = 0; + switch ($filename) { + default: + $enabled = 1; break; - }; - return $enabled; + }; + return $enabled; + } + + // REMARK: below function has moved to "Class.Basic" + // METHOD: adbAssocArray + // PARAMS: db array, key, value part + // RETURN: returns and associative array + // DESC: creates out of a normal db_return array an assoc array + public function adbAssocArray($db_array, $key, $value) + { + return $this->GenAssocArray($db_array, $key, $value); + } + + // REMARK: below function has moved to "Class.Basic" + // METHOD: adbByteStringFormat + // PARAMS: int + // RETURN: string + // DESC: converts bytes into formated string with KB, MB, etc + public function adbByteStringFormat($number) + { + return $this->ByteStringFormat($number); + } + + // REMARK: below function has moved to "Class.Basic" + // METHOD: adbCreateThumbnail + // PARAMS: id from picture where from we create a thumbnail + // x -> max x size of thumbnail + // y -> max y size of thumbnail + // dummy -> if set to true, then if no images was found we show a dummy image + // path -> if source start is not ROOT path, if empty ROOT is choosen + // cache -> cache path, if not given TMP is used + // RETURN: thumbnail name + // DESC: converts picture to a thumbnail with max x and max y size + public function adbCreateThumbnail($pic, $size_x, $size_y, $dummy = false, $path = "", $cache = "") + { + return $this->CreateThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache); + } + + // METHOD: adbMsg + // PARAMS: level -> info/warning/error + // msg -> string, can be printf formated + // var array -> optional data for a possible printf formated msg + // RETURN: none + // DESC: wrapper function to fill up the mssages array + public function adbMsg($level, $msg, $vars = array ()) + { + if (!preg_match("/^info|warning|error$/", $level)) { + $level = "info"; } - - // REMARK: below function has moved to "Class.Basic" - // METHOD: adbAssocArray - // PARAMS: db array, key, value part - // RETURN: returns and associative array - // DESC: creates out of a normal db_return array an assoc array - public function adbAssocArray($db_array, $key, $value) - { - return $this->GenAssocArray($db_array, $key, $value); - } - - // REMARK: below function has moved to "Class.Basic" - // METHOD: adbByteStringFormat - // PARAMS: int - // RETURN: string - // DESC: converts bytes into formated string with KB, MB, etc - public function adbByteStringFormat($number) - { - return $this->ByteStringFormat($number); - } - - // REMARK: below function has moved to "Class.Basic" - // METHOD: adbCreateThumbnail - // PARAMS: id from picture where from we create a thumbnail - // x -> max x size of thumbnail - // y -> max y size of thumbnail - // dummy -> if set to true, then if no images was found we show a dummy image - // path -> if source start is not ROOT path, if empty ROOT is choosen - // cache -> cache path, if not given TMP is used - // RETURN: thumbnail name - // DESC: converts picture to a thumbnail with max x and max y size - public function adbCreateThumbnail($pic, $size_x, $size_y, $dummy = false, $path = "", $cache = "") - { - return $this->CreateThumbnail($pic, $size_x, $size_y, $dummy, $path, $cache); - } - - // METHOD: adbMsg - // PARAMS: level -> info/warning/error - // msg -> string, can be printf formated - // var array -> optional data for a possible printf formated msg - // RETURN: none - // DESC: wrapper function to fill up the mssages array - public function adbMsg($level, $msg, $vars = array ()) - { - if (!preg_match("/^info|warning|error$/", $level)) - $level = "info"; - $this->messages[] = array ( - 'msg' => sprintf($this->l->__($msg), $vars), - 'class' => $level - ); - switch ($level) - { - case 'info': $this->info = 1; break; - case 'warning': $this->warning = 1; break; - case 'error': $this->error = 1; break; - } - } - - // METHOD: adbLiveQueue - // PARAMS: queue_key -> string to identfy the queue - // type -> INSERT/UPDATE/DELETE - // target -> target table to write to - // data -> SQL part to write, this can include #KEY_VALUE#, #KEY_NAME# for delete sub queries - // key_name -> key name, mostly used for update search - // key_value -> data for the key - // associate -> NULL for free, LOCK for first insert, group key for reference to first entry - // file -> string for special file copy actions; mostyle "test#live;..." - // RETURN: none - // DESC: writes live queue - public function adbLiveQueue($queue_key, $type, $target, $data, $key_name, $key_value, $associate = NULL, $file = NULL) - { - $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue ("; - $q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"; - $q .= ") VALUES ("; - $q .= "'".$this->db_escape_string($queue_key)."', '".$this->db_escape_string($key_value)."', '".$this->db_escape_string($key_name)."', '".$this->db_escape_string($type)."', '".$this->db_escape_string($target)."', '".$this->db_escape_string($data)."', '".$this->queue_key."', '".$this->action."', '".$this->db_escape_string($associate)."', '".$this->db_escape_string($file)."')"; - $this->db_exec($q); - } - - // METHOD: adbPrintDateTime - // PARAMS: year, month, day, hour, min: the date and time values - // suffix: additional info printed after the date time variable in the drop down, also used for ID in the on change JS call - // minute steps, can be 1 (default), 5, 10, etc, if invalid (outside 1h range, it falls back to 1min) - // RETURN: HTML formated strings for drop down lists of date and time - // DESC: print the date/time drop downs, used in any queue/send/insert at date/time place - public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) - { - // if suffix given, add _ before - if ($suffix) - $suffix = '_'.$suffix; - if ($min_steps < 1 || $min_steps > 59) - $min_steps = 1; - - $on_change_call = 'dt_list(\''.$suffix.'\');'; - - // always be 1h ahead (for safety) - $timestamp = time() + 3600; // in seconds - - // the max year is this year + 1; - $max_year = date("Y", $timestamp) + 1; - - // preset year, month, ... - $year = (!$year) ? date("Y", $timestamp) : $year; - $month = (!$month) ? date("m", $timestamp) : $month; - $day = (!$day) ? date("d", $timestamp) : $day; - $hour = (!$hour) ? date("H", $timestamp) : $hour; - $min = (!$min) ? date("i", $timestamp) : $min; // add to five min? - // max days in selected month - $days_in_month = date("t", strtotime($year."-".$month."-".$day." ".$hour.":".$min.":0")); - - // from now to ? - $string = $this->l->__('Year').' '; - $string .= ' '.$this->l->__('Month').' '; - $string .= ' '.$this->l->__('Day').' '; - $string .= ' '.$this->l->__('Hour').' '; - $string .= ' '.$this->l->__('Minute').' '; - $string .= ''; - // return the datetime select string - return $string; + $this->messages[] = array ( + 'msg' => sprintf($this->l->__($msg), $vars), + 'class' => $level + ); + switch ($level) { + case 'info': + $this->info = 1; + break; + case 'warning': + $this->warning = 1; + break; + case 'error': + $this->error = 1; + break; } } -?> + + // METHOD: adbLiveQueue + // PARAMS: queue_key -> string to identfy the queue + // type -> INSERT/UPDATE/DELETE + // target -> target table to write to + // data -> SQL part to write, this can include #KEY_VALUE#, #KEY_NAME# for delete sub queries + // key_name -> key name, mostly used for update search + // key_value -> data for the key + // associate -> NULL for free, LOCK for first insert, group key for reference to first entry + // file -> string for special file copy actions; mostyle "test#live;..." + // RETURN: none + // DESC: writes live queue + public function adbLiveQueue($queue_key, $type, $target, $data, $key_name, $key_value, $associate = null, $file = null) + { + $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue ("; + $q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"; + $q .= ") VALUES ("; + $q .= "'".$this->db_escape_string($queue_key)."', '".$this->db_escape_string($key_value)."', "; + $q .= "'".$this->db_escape_string($key_name)."', '".$this->db_escape_string($type)."', "; + $q .= "'".$this->db_escape_string($target)."', '".$this->db_escape_string($data)."', "; + $q .= "'".$this->queue_key."', '".$this->action."', '".$this->db_escape_string($associate)."', "; + $q .= "'".$this->db_escape_string($file)."')"; + $this->db_exec($q); + } + + // METHOD: adbPrintDateTime + // PARAMS: year, month, day, hour, min: the date and time values + // suffix: additional info printed after the date time variable in the drop down, also used for ID in the on change JS call + // minute steps, can be 1 (default), 5, 10, etc, if invalid (outside 1h range, it falls back to 1min) + // RETURN: HTML formated strings for drop down lists of date and time + // DESC: print the date/time drop downs, used in any queue/send/insert at date/time place + public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) + { + // if suffix given, add _ before + if ($suffix) { + $suffix = '_'.$suffix; + } + if ($min_steps < 1 || $min_steps > 59) { + $min_steps = 1; + } + + $on_change_call = 'dt_list(\''.$suffix.'\');'; + + // always be 1h ahead (for safety) + $timestamp = time() + 3600; // in seconds + + // the max year is this year + 1; + $max_year = date("Y", $timestamp) + 1; + + // preset year, month, ... + $year = (!$year) ? date("Y", $timestamp) : $year; + $month = (!$month) ? date("m", $timestamp) : $month; + $day = (!$day) ? date("d", $timestamp) : $day; + $hour = (!$hour) ? date("H", $timestamp) : $hour; + $min = (!$min) ? date("i", $timestamp) : $min; // add to five min? + // max days in selected month + $days_in_month = date("t", strtotime($year."-".$month."-".$day." ".$hour.":".$min.":0")); + + // from now to ? + $string = $this->l->__('Year').' '; + $string .= ' '.$this->l->__('Month').' '; + $string .= ' '.$this->l->__('Day').' '; + $string .= ' '.$this->l->__('Hour').' '; + $string .= ' '.$this->l->__('Minute').' '; + $string .= ''; + // return the datetime select string + return $string; + } +} diff --git a/www/libs/Class.Basic.inc b/www/libs/Class.Basic.inc index beaa0cb0..d73c7d6e 100644 --- a/www/libs/Class.Basic.inc +++ b/www/libs/Class.Basic.inc @@ -1,2071 +1,2070 @@ array that holds all the error messages, should not be written from outside, use debug method - * error_id - * error_string - * - * PUBLIC METHODS - * debug -> calls with "level", "string" and flag to turn off (0) the newline at the end - * debug_for -> sets debug on/off for a type (error, echo, print) for a certain level - * print_error_msg -> prints out the error message, optional parameter is a header prefix - * fdebug -> prints line directly to debug_file.log in tmp - * - * print_time -> prints time + microtime, optional flag to turn off (0) microtime printout - * basic -> constructor - * _basic -> desconstructor - * info -> info about that class - * running_time -> prints out the time of start/end (automatically called on created and error printout - * checked -> returnes checked or selected for var & array - * magic_links -> parses text and makes out of links - * get_page_name -> get the filename of the current page - * array_search_recursive -> search for a value/key combination in an array of arrays - * ByteStringFormat -> format bytes into KB, MB, GB, ... - * TimeStringFormat -> format a timestamp (seconds) into days, months, ... also with ms - * StringToTime -> reverste a TimeStringFormat to a timestamp - * GenAssocArray -> generactes a new associativ array from an existing array - * CheckDate -> checks if a date is valid - * CompareDate -> compares two dates. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger - * CompareDateTime -> compares two dates with time. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger - * _crc32b -> behaves like the hash("crc32b") in php < 5.2.8. this function will flip the hash like it was (wrong) - * before if a new php version is found - * crypt* -> encrypt and decrypt login string data, used by Login class - * setFormToken/validateFormToken -> form protection with token - * - * PRIVATE METHODS - * fdebug_fp -> opens and closes file, called from fdebug method - * write_error_msg -> writes error msg to file if requested - * - * HISTORY: - * 2010/12/24 (cs) add crypt classes with auto detect what crypt we can use, add php version check class - * 2008/08/07 (cs) fixed strange DEBUG_ALL on off behavour. data was written even thought DBEUG_ALL was off. now no debug logging is done at all if DEBUG_ALL is off - * 2007/11/13 (cs) add Comparedate function - * 2007/11/05 (cs) added GenAssocArray and CheckDate functions - * 2007/10/10 (cs) magic links function can use http:///path as a local prefix. blank target is removed & http:// also - * 2006/03/09 (cs) added Byte/TimeStringFormat functions - * 2006/02/21 (cs) fix various problems with the mime magic function: || not always working, fix prefix replacement, etc - * 2006/02/09 (cs) added _mb_mime_encode function, replacement for php internal one - * 2005/07/12 (cs) added some small stylesheet defs to debug output - * 2005/06/24 (cs) made the check selected/checked function way easier - * 2005/06/24 (cs) added a function to wrap around print_r for html formatted array print - * 2005/06/21 (cs) made the error_msg file writing immediatly after something is written with debug method - * 2005/06/20 (cs) added a quick to file write function, removed the mobile detect code - * 2005/06/20 (cs) test debug method, add surpress of
in debug output - * 2005/06/17 (cs) error_msg is an array, to put in various levels of error reporting - * 2005/04/06 (cs) added filename for error page when print to file - * 2005/05/31 (cs) added file printout of errors - * 2005/03/01 (cs) set a global regex for checking the email - * 2005/01/27 (cs) updated checked, haystack can be valur or array - * 2004/11/16 (cs) removed mobile detection here - * 2004/11/15 (cs) error_msg is no longer echoed, but returned - * 2004/11/15 (cs) added new functions: checked, magic_links, get_page_name - * 2004/08/06 (cs) bug with $_GLOBALS, should be $GLOBALS - * 2004/07/15 (cs) added print_error_msg method, updated to new schema - * 2003-06-09: added "detect_mobile" class for japanese mobile phone - * detection - * 2003-03-24: start of stub/basic class - *********************************************************************/ +/********************************************************************* +* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) +* CREATED: 2003/03/24 +* VERSION: 0.9.0 +* RELEASED LICENSE: GNU GPL 3 +* SHORT DESCRIPTION: +* basic class start class for ALL clases, holds basic vars, infos, methods, etc +* +* PUBLIC VARIABLES +* class_info +* +* These are if there is any debug to print out at all at the end +* debug_output_all - general yes no +* It's recommended to use the method "debug_for" to turn on of the array vars +* debug_output - turn on for one level (Array) +* debug_output_not - turn off for one level (array) +* +* Print out the debug at thend of the html +* echo_output_all +* echo_output +* echo_output_not +* +* Write debug to file +* print_output_all +* print_output +* print_output_not +* +* PRIVATE VARIABLES +* error_msg -> array that holds all the error messages, should not be written from outside, use debug method +* error_id +* error_string +* +* PUBLIC METHODS +* debug -> calls with "level", "string" and flag to turn off (0) the newline at the end +* debug_for -> sets debug on/off for a type (error, echo, print) for a certain level +* print_error_msg -> prints out the error message, optional parameter is a header prefix +* fdebug -> prints line directly to debug_file.log in tmp +* +* print_time -> prints time + microtime, optional flag to turn off (0) microtime printout +* basic -> constructor +* _basic -> desconstructor +* info -> info about that class +* running_time -> prints out the time of start/end (automatically called on created and error printout +* checked -> returnes checked or selected for var & array +* magic_links -> parses text and makes
out of links +* get_page_name -> get the filename of the current page +* array_search_recursive -> search for a value/key combination in an array of arrays +* ByteStringFormat -> format bytes into KB, MB, GB, ... +* TimeStringFormat -> format a timestamp (seconds) into days, months, ... also with ms +* StringToTime -> reverste a TimeStringFormat to a timestamp +* GenAssocArray -> generactes a new associativ array from an existing array +* CheckDate -> checks if a date is valid +* CompareDate -> compares two dates. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger +* CompareDateTime -> compares two dates with time. -1 if the first is smaller, 0 if they are equal, 1 if the first is bigger +* _crc32b -> behaves like the hash("crc32b") in php < 5.2.8. this function will flip the hash like it was (wrong) +* before if a new php version is found +* crypt* -> encrypt and decrypt login string data, used by Login class +* setFormToken/validateFormToken -> form protection with token +* +* PRIVATE METHODS +* fdebug_fp -> opens and closes file, called from fdebug method +* write_error_msg -> writes error msg to file if requested +* +* HISTORY: +* 2010/12/24 (cs) add crypt classes with auto detect what crypt we can use, add php version check class +* 2008/08/07 (cs) fixed strange DEBUG_ALL on off behavour. data was written even thought DBEUG_ALL was off. now no debug logging is done at all if DEBUG_ALL is off +* 2007/11/13 (cs) add Comparedate function +* 2007/11/05 (cs) added GenAssocArray and CheckDate functions +* 2007/10/10 (cs) magic links function can use http:///path as a local prefix. blank target is removed & http:// also +* 2006/03/09 (cs) added Byte/TimeStringFormat functions +* 2006/02/21 (cs) fix various problems with the mime magic function: || not always working, fix prefix replacement, etc +* 2006/02/09 (cs) added _mb_mime_encode function, replacement for php internal one +* 2005/07/12 (cs) added some small stylesheet defs to debug output +* 2005/06/24 (cs) made the check selected/checked function way easier +* 2005/06/24 (cs) added a function to wrap around print_r for html formatted array print +* 2005/06/21 (cs) made the error_msg file writing immediatly after something is written with debug method +* 2005/06/20 (cs) added a quick to file write function, removed the mobile detect code +* 2005/06/20 (cs) test debug method, add surpress of
in debug output +* 2005/06/17 (cs) error_msg is an array, to put in various levels of error reporting +* 2005/04/06 (cs) added filename for error page when print to file +* 2005/05/31 (cs) added file printout of errors +* 2005/03/01 (cs) set a global regex for checking the email +* 2005/01/27 (cs) updated checked, haystack can be valur or array +* 2004/11/16 (cs) removed mobile detection here +* 2004/11/15 (cs) error_msg is no longer echoed, but returned +* 2004/11/15 (cs) added new functions: checked, magic_links, get_page_name +* 2004/08/06 (cs) bug with $_GLOBALS, should be $GLOBALS +* 2004/07/15 (cs) added print_error_msg method, updated to new schema +* 2003-06-09: added "detect_mobile" class for japanese mobile phone +* detection +* 2003-03-24: start of stub/basic class +*********************************************************************/ - class basic +class basic +{ + public $class_info; // class info var + + public $page_name; + public $host_name; + public $host_port; + + private $error_id; // error ID for errors in classes + private $error_string; // error strings in classes (for error_id) + private $error_msg = array (); // the "connection" to the outside errors + + public $debug_output; // if this is true, show debug on desconstructor + public $debug_output_not; + public $debug_output_all; + public $echo_output; // errors: echo out, default is 1 + public $echo_output_not; + public $echo_output_all; + public $print_output; // errors: print to file, default is 0 + public $print_output_not; + public $print_output_all; + + // log file name + private $log_file_name_ext = 'log'; // use this for date rotate + public $log_max_filesize = 0; // set in kilobytes + private $log_print_file = 'error_msg##LOGID####LEVEL####CLASS####PAGENAME####DATE##'; + private $log_file_unique_id; // a unique ID set only once for call derived from this class + public $log_print_file_date = 1; // if set add Y-m-d and do automatic daily rotation + private $log_file_id = LOG_FILE_ID ? LOG_FILE_ID : ''; // a alphanumeric name that has to be set as global definition + public $log_per_level = 0; // set, it will split per level (first parameter in debug call) + public $log_per_class = 0; // set, will split log per class + public $log_per_page = 0; // set, will split log per called file + public $log_per_run = 0; // create a new log file per run (time stamp + unique ID) + + public $starttime; // start time if time debug is used + public $endtime; // end time if time debug is used + + public $email_regex; // regex var for email check + public $keitai_email_regex; // regex var for email check + + public $error_msg_prefix = ''; // prefix to the error string (the class name) + + public $debug_fp = ''; // filepointer for writing to file + public $debug_filename = 'debug_file.log'; // where to write output + public $hash_algo = 'crc32b'; // the hash algo used for the internal debug uid + public $running_uid = ''; // unique ID set on class init and used in logging as prefix + + // data path for files + public $data_path = array (); + + // error char for the char conver + public $mbErrorChar; + + // crypt saslt prefix + public $cryptSaltPrefix = ''; + public $cryptSaltSuffix = ''; + public $cryptIterationCost = 7; // this is for staying backwards compatible with the old ones + public $cryptSaltSize = 22; // default 22 chars for blowfish, 2 for STD DES, 8 for MD5, + + // session name + private $session_name = ''; + private $session_id = ''; + + // form token (used for form validation) + private $form_token = ''; + + // METHOD __construct + // PARAMS debug_all (0)/1, echo_all (1)/0, print_all (0)/1 + // RETURN none + // DESC constructor + public function __construct($debug_all = 0, $echo_all = 1, $print_all = 0) { - public $class_info; // class info var + // set per run UID for logging + $this->running_uid = hash($this->hash_algo, uniqid(rand(), true)); - public $page_name; - public $host_name; - public $host_port; + // internal info var + $this->class_info["basic"] = array ( + "class_name" => "Basic", + "class_version" => "0.9.0", + "class_created" => "2003-03-24", + "class_author" => 'Clemens "Gullevek" Schwaighofer (.at)' + ); - private $error_id; // error ID for errors in classes - private $error_string; // error strings in classes (for error_id) - private $error_msg = array (); // the "connection" to the outside errors + // set the page name + $this->page_name = $this->get_page_name(); + $this->host_name = $this->get_host_name(); - public $debug_output; // if this is true, show debug on desconstructor - public $debug_output_not; - public $debug_output_all; - public $echo_output; // errors: echo out, default is 1 - public $echo_output_not; - public $echo_output_all; - public $print_output; // errors: print to file, default is 0 - public $print_output_not; - public $print_output_all; + // set the paths matching to the valid file types + $this->data_path = array ( + 'P' => PICTURES, + 'F' => FLASH, + 'V' => VIDEOS, + 'D' => DOCUMENTS, + 'A' => PDFS, + 'B' => BINARIES + ); - // log file name - private $log_file_name_ext = 'log'; // use this for date rotate - public $log_max_filesize = 0; // set in kilobytes - private $log_print_file = 'error_msg##LOGID####LEVEL####CLASS####PAGENAME####DATE##'; - private $log_file_unique_id; // a unique ID set only once for call derived from this class - public $log_print_file_date = 1; // if set add Y-m-d and do automatic daily rotation - private $log_file_id = LOG_FILE_ID ? LOG_FILE_ID : ''; // a alphanumeric name that has to be set as global definition - public $log_per_level = 0; // set, it will split per level (first parameter in debug call) - public $log_per_class = 0; // set, will split log per class - public $log_per_page = 0; // set, will split log per called file - public $log_per_run = 0; // create a new log file per run (time stamp + unique ID) - - public $starttime; // start time if time debug is used - public $endtime; // end time if time debug is used - - public $email_regex; // regex var for email check - public $keitai_email_regex; // regex var for email check - - public $error_msg_prefix = ''; // prefix to the error string (the class name) - - public $debug_fp = ''; // filepointer for writing to file - public $debug_filename = 'debug_file.log'; // where to write output - public $hash_algo = 'crc32b'; // the hash algo used for the internal debug uid - public $running_uid = ''; // unique ID set on class init and used in logging as prefix - - // data path for files - public $data_path = array (); - - // error char for the char conver - public $mbErrorChar; - - // crypt saslt prefix - public $cryptSaltPrefix = ''; - public $cryptSaltSuffix = ''; - public $cryptIterationCost = 7; // this is for staying backwards compatible with the old ones - public $cryptSaltSize = 22; // default 22 chars for blowfish, 2 for STD DES, 8 for MD5, - - // session name - private $session_name = ''; - private $session_id = ''; - - // form token (used for form validation) - private $form_token = ''; - - // METHOD __construct - // PARAMS debug_all (0)/1, echo_all (1)/0, print_all (0)/1 - // RETURN none - // DESC constructor - public function __construct($debug_all = 0, $echo_all = 1, $print_all = 0) - { - // set per run UID for logging - $this->running_uid = hash($this->hash_algo, uniqid(rand(), true)); - - // internal info var - $this->class_info["basic"] = array ( - "class_name" => "Basic", - "class_version" => "0.9.0", - "class_created" => "2003-03-24", - "class_author" => 'Clemens "Gullevek" Schwaighofer (.at)' - ); - - // set the page name - $this->page_name = $this->get_page_name(); - $this->host_name = $this->get_host_name(); - - // set the paths matching to the valid file types - $this->data_path = array ( - 'P' => PICTURES, - 'F' => FLASH, - 'V' => VIDEOS, - 'D' => DOCUMENTS, - 'A' => PDFS, - 'B' => BINARIES - ); - - // if given via parameters, only for all - $this->debug_output_all = $debug_all; - $this->echo_output_all = $echo_all; - $this->print_output_all = $print_all; - // globals overrule given settings, for one (array), eg $ECHO['db'] = 1; - if (isset($GLOBALS['DEBUG'])) - $this->debug_output = $GLOBALS['DEBUG']; - if (isset($GLOBALS['ECHO'])) - $this->echo_output = $GLOBALS['ECHO']; - if (isset($GLOBALS['PRINT'])) - $this->print_output = $GLOBALS['PRINT']; - - // exclude these ones from output - if (isset($GLOBALS['DEBUG_NOT'])) - $this->debug_output_not = $GLOBALS['DEBUG_NOT']; - if (isset($GLOBALS['ECHO_NOT'])) - $this->echo_output_not = $GLOBALS['ECHO_NOT']; - if (isset($GLOBALS['PRINT_NOT'])) - $this->print_output_not = $GLOBALS['PRINT_NOT']; - - // all overrule - if (isset($GLOBALS['DEBUG_ALL'])) - $this->debug_output_all = $GLOBALS['DEBUG_ALL']; - if (isset($GLOBALS['ECHO_ALL'])) - $this->echo_output_all = $GLOBALS['ECHO_ALL']; - if (isset($GLOBALS['PRINT_ALL'])) - $this->print_output_all = $GLOBALS['PRINT_ALL']; - - // GLOBAL rules for log writing - if (isset($GLOBALS['LOG_PRINT_FILE_DATE'])) - $this->log_print_file_date = $GLOBALS['LOG_PRINT_FILE_DATE']; - if (isset($GLOBALS['LOG_PER_LEVEL'])) - $this->log_per_level = $GLOBALS['LOG_PER_LEVEL']; - if (isset($GLOBALS['LOG_PER_CLASS'])) - $this->log_per_class = $GLOBALS['LOG_PER_CLASS']; - if (isset($GLOBALS['LOG_PER_PAGE'])) - $this->log_per_page = $GLOBALS['LOG_PER_PAGE']; - if (isset($GLOBALS['LOG_PER_RUN'])) - $this->log_per_run = $GLOBALS['LOG_PER_RUN']; - - // set the regex for checking emails - $this->email_regex = "^[A-Za-z0-9!#$%&'*+-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+-\/=?^_`{|}~\.]{0,63}@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$"; - // this is for error check parts in where the email regex failed - $this->email_regex_check = array ( - 1 => "@(.*)@(.*)", // double @ - 2 => "^[A-Za-z0-9!#$%&'*+-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+-\/=?^_`{|}~\.]{0,63}@", // wrong part before @ - 3 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$", // wrong part after @ - 4 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.", // wrong domain name part - 5 => "\.([a-zA-Z]{2,6}){1}$", // wrong top level part - 6 => "@(.*)\.{2,}", // double .. in domain name part - 7 => "@.*\.$" // ends with a dot, top level, domain missing - ); - // the array with the mobile types that are valid - $this->mobile_email_type = array ( - '.*@docomo\.ne\.jp$' => 'keitai_docomo', - '.*@([a-z0-9]{2}\.)?ezweb\.ne\.jp$' => 'keitai_kddi_ezweb', # correct are a[2-4], b2, c[1-9], e[2-9], h[2-4], t[1-9] - '.*@(ez[a-j]{1}\.)?ido\.ne\.jp$' => 'keitai_kddi_ido', # ez[a-j] or nothing - '.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka', # (sky group) - '.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky', # (sky group) [tkk,tkc only] - '.*@([a-z]{2}\.)?sky\.dtg\.ne\.jp$' => 'keitai_kddi_dtg', # dtg (sky group) - '.*@[tkdhcrnsq]{1}\.vodafone\.ne\.jp$' => 'keitai_softbank_vodafone', # old vodafone [t,k,d,h,c,r,n,s,q] - '.*@jp-[dhtkrsnqc]{1}\.ne\.jp$' => 'keitai_softbank_j-phone', # very old j-phone (pre vodafone) [d,h,t,k,r,s,n,q,c] - '.*@([dhtcrknsq]{1}\.)?softbank\.ne\.jp$' => 'keitai_softbank', # add i for iphone also as keitai, others similar to the vodafone group - '.*@i{1}\.softbank(\.ne)?\.jp$' => 'smartphone_softbank_iphone', # add iPhone also as keitai and not as pc - '.*@disney\.ne\.jp$' => 'keitai_softbank_disney', # (kids) - '.*@willcom\.ne\.jp$' => 'keitai_willcom', - '.*@willcom\.com$' => 'keitai_willcom', # new for pdx.ne.jp address - '.*@wcm\.ne\.jp$' => 'keitai_willcom', # old willcom wcm.ne.jp - '.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', # old pdx address for willcom - '.*@bandai\.jp$' => 'keitai_willcom_bandai', # willcom paipo! (kids) - '.*@pipopa\.ne\.jp$' => 'keitai_willcom_pipopa', # willcom paipo! (kids) - '.*@([a-z0-9]{2,4}\.)?pdx\.ne\.jp$' => 'keitai_willcom_pdx', # actually only di,dj,dk,wm -> all others are "wrong", but none also allowed? - '.*@ymobile([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile', # ymobile, ymobile1 techincally not willcom, but I group them there - '.*@y-mobile\.ne\.jp$' => 'keitai_willcom_ymobile', # y-mobile techincally not willcom, but I group them there - '.*@emnet\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom - '.*@emobile\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom - '.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom - ); - // short list for mobile email types - $this->mobile_email_type_short = array ( - 'keitai_docomo' => 'docomo', - 'keitai_kddi_ezweb' => 'kddi', - 'keitai_kddi' => 'kddi', - 'keitai_kddi_tu-ka' => 'kddi', - 'keitai_kddi_sky' => 'kddi', - 'keitai_softbank' => 'softbank', - 'smartphone_softbank_iphone' => 'iphone', - 'keitai_softbank_disney' => 'softbank', - 'keitai_softbank_vodafone' => 'softbank', - 'keitai_softbank_j-phone' => 'softbank', - 'keitai_willcom' => 'willcom', - 'keitai_willcom_pdx' => 'willcom', - 'keitai_willcom_bandai' => 'willcom', - 'keitai_willcom_pipopa' => 'willcom', - 'keitai_willcom_ymobile' => 'willcom', - 'keitai_willcom_emnet' => 'willcom', - 'pc_html' => 'pc', - // old sets -> to be removed later - 'docomo' => 'docomo', - 'kddi_ezweb' => 'kddi', - 'kddi' => 'kddi', - 'kddi_tu-ka' => 'kddi', - 'kddi_sky' => 'kddi', - 'softbank' => 'softbank', - 'keitai_softbank_iphone' => 'iphone', - 'softbank_iphone' => 'iphone', - 'softbank_disney' => 'softbank', - 'softbank_vodafone' => 'softbank', - 'softbank_j-phone' => 'softbank', - 'willcom' => 'willcom', - 'willcom_pdx' => 'willcom', - 'willcom_bandai' => 'willcom', - 'willcom_pipopa' => 'willcom', - 'willcom_ymobile' => 'willcom', - 'willcom_emnet' => 'willcom', - 'pc' => 'pc' - ); - - // initial the session if there is no session running already - if (!session_id()) - { - // check if we have an external session name given, else skip this step - if (SET_SESSION_NAME) - { - // set the session name for possible later check - $this->session_name = SET_SESSION_NAME; - session_name($this->session_name); - } - // start session - session_start(); - // set internal session id, we can use that later for protection check - $this->session_id = session_id(); - } - - // init crypt settings - $this->cryptInit(); - - // start logging running time - $this->running_time(); + // if given via parameters, only for all + $this->debug_output_all = $debug_all; + $this->echo_output_all = $echo_all; + $this->print_output_all = $print_all; + // globals overrule given settings, for one (array), eg $ECHO['db'] = 1; + if (isset($GLOBALS['DEBUG'])) { + $this->debug_output = $GLOBALS['DEBUG']; + } + if (isset($GLOBALS['ECHO'])) { + $this->echo_output = $GLOBALS['ECHO']; + } + if (isset($GLOBALS['PRINT'])) { + $this->print_output = $GLOBALS['PRINT']; } - // METHOD __destruct - // PARAMS none - // RETURN if debug is on, return error data - // DESC basic deconstructor (should be called from all deconstructors in higher classes) - // writes out $error_msg to global var - public function __destruct() - { - // this has to be changed, not returned here, this is the last class to close + // exclude these ones from output + if (isset($GLOBALS['DEBUG_NOT'])) { + $this->debug_output_not = $GLOBALS['DEBUG_NOT']; + } + if (isset($GLOBALS['ECHO_NOT'])) { + $this->echo_output_not = $GLOBALS['ECHO_NOT']; + } + if (isset($GLOBALS['PRINT_NOT'])) { + $this->print_output_not = $GLOBALS['PRINT_NOT']; + } + + // all overrule + if (isset($GLOBALS['DEBUG_ALL'])) { + $this->debug_output_all = $GLOBALS['DEBUG_ALL']; + } + if (isset($GLOBALS['ECHO_ALL'])) { + $this->echo_output_all = $GLOBALS['ECHO_ALL']; + } + if (isset($GLOBALS['PRINT_ALL'])) { + $this->print_output_all = $GLOBALS['PRINT_ALL']; + } + + // GLOBAL rules for log writing + if (isset($GLOBALS['LOG_PRINT_FILE_DATE'])) { + $this->log_print_file_date = $GLOBALS['LOG_PRINT_FILE_DATE']; + } + if (isset($GLOBALS['LOG_PER_LEVEL'])) { + $this->log_per_level = $GLOBALS['LOG_PER_LEVEL']; + } + if (isset($GLOBALS['LOG_PER_CLASS'])) { + $this->log_per_class = $GLOBALS['LOG_PER_CLASS']; + } + if (isset($GLOBALS['LOG_PER_PAGE'])) { + $this->log_per_page = $GLOBALS['LOG_PER_PAGE']; + } + if (isset($GLOBALS['LOG_PER_RUN'])) { + $this->log_per_run = $GLOBALS['LOG_PER_RUN']; + } + + // set the regex for checking emails + $this->email_regex = "^[A-Za-z0-9!#$%&'*+-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+-\/=?^_`{|}~\.]{0,63}@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$"; + // this is for error check parts in where the email regex failed + $this->email_regex_check = array ( + 1 => "@(.*)@(.*)", // double @ + 2 => "^[A-Za-z0-9!#$%&'*+-\/=?^_`{|}~][A-Za-z0-9!#$%:\(\)&'*+-\/=?^_`{|}~\.]{0,63}@", // wrong part before @ + 3 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.([a-zA-Z]{2,}){1}$", // wrong part after @ + 4 => "@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]{1,})*\.", // wrong domain name part + 5 => "\.([a-zA-Z]{2,6}){1}$", // wrong top level part + 6 => "@(.*)\.{2,}", // double .. in domain name part + 7 => "@.*\.$" // ends with a dot, top level, domain missing + ); + // the array with the mobile types that are valid + $this->mobile_email_type = array ( + '.*@docomo\.ne\.jp$' => 'keitai_docomo', + '.*@([a-z0-9]{2}\.)?ezweb\.ne\.jp$' => 'keitai_kddi_ezweb', # correct are a[2-4], b2, c[1-9], e[2-9], h[2-4], t[1-9] + '.*@(ez[a-j]{1}\.)?ido\.ne\.jp$' => 'keitai_kddi_ido', # ez[a-j] or nothing + '.*@([a-z]{2}\.)?sky\.tu-ka\.ne\.jp$' => 'keitai_kddi_tu-ka', # (sky group) + '.*@([a-z]{2}\.)?sky\.tk[kc]{1}\.ne\.jp$' => 'keitai_kddi_sky', # (sky group) [tkk,tkc only] + '.*@([a-z]{2}\.)?sky\.dtg\.ne\.jp$' => 'keitai_kddi_dtg', # dtg (sky group) + '.*@[tkdhcrnsq]{1}\.vodafone\.ne\.jp$' => 'keitai_softbank_vodafone', # old vodafone [t,k,d,h,c,r,n,s,q] + '.*@jp-[dhtkrsnqc]{1}\.ne\.jp$' => 'keitai_softbank_j-phone', # very old j-phone (pre vodafone) [d,h,t,k,r,s,n,q,c] + '.*@([dhtcrknsq]{1}\.)?softbank\.ne\.jp$' => 'keitai_softbank', # add i for iphone also as keitai, others similar to the vodafone group + '.*@i{1}\.softbank(\.ne)?\.jp$' => 'smartphone_softbank_iphone', # add iPhone also as keitai and not as pc + '.*@disney\.ne\.jp$' => 'keitai_softbank_disney', # (kids) + '.*@willcom\.ne\.jp$' => 'keitai_willcom', + '.*@willcom\.com$' => 'keitai_willcom', # new for pdx.ne.jp address + '.*@wcm\.ne\.jp$' => 'keitai_willcom', # old willcom wcm.ne.jp + '.*@pdx\.ne\.jp$' => 'keitai_willcom_pdx', # old pdx address for willcom + '.*@bandai\.jp$' => 'keitai_willcom_bandai', # willcom paipo! (kids) + '.*@pipopa\.ne\.jp$' => 'keitai_willcom_pipopa', # willcom paipo! (kids) + '.*@([a-z0-9]{2,4}\.)?pdx\.ne\.jp$' => 'keitai_willcom_pdx', # actually only di,dj,dk,wm -> all others are "wrong", but none also allowed? + '.*@ymobile([1]{1})?\.ne\.jp$' => 'keitai_willcom_ymobile', # ymobile, ymobile1 techincally not willcom, but I group them there + '.*@y-mobile\.ne\.jp$' => 'keitai_willcom_ymobile', # y-mobile techincally not willcom, but I group them there + '.*@emnet\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom + '.*@emobile\.ne\.jp$' => 'keitai_willcom_emnet', # e-mobile, group will willcom + '.*@emobile-s\.ne\.jp$' => 'keitai_willcom_emnet' # e-mobile, group will willcom + ); + // short list for mobile email types + $this->mobile_email_type_short = array ( + 'keitai_docomo' => 'docomo', + 'keitai_kddi_ezweb' => 'kddi', + 'keitai_kddi' => 'kddi', + 'keitai_kddi_tu-ka' => 'kddi', + 'keitai_kddi_sky' => 'kddi', + 'keitai_softbank' => 'softbank', + 'smartphone_softbank_iphone' => 'iphone', + 'keitai_softbank_disney' => 'softbank', + 'keitai_softbank_vodafone' => 'softbank', + 'keitai_softbank_j-phone' => 'softbank', + 'keitai_willcom' => 'willcom', + 'keitai_willcom_pdx' => 'willcom', + 'keitai_willcom_bandai' => 'willcom', + 'keitai_willcom_pipopa' => 'willcom', + 'keitai_willcom_ymobile' => 'willcom', + 'keitai_willcom_emnet' => 'willcom', + 'pc_html' => 'pc', + // old sets -> to be removed later + 'docomo' => 'docomo', + 'kddi_ezweb' => 'kddi', + 'kddi' => 'kddi', + 'kddi_tu-ka' => 'kddi', + 'kddi_sky' => 'kddi', + 'softbank' => 'softbank', + 'keitai_softbank_iphone' => 'iphone', + 'softbank_iphone' => 'iphone', + 'softbank_disney' => 'softbank', + 'softbank_vodafone' => 'softbank', + 'softbank_j-phone' => 'softbank', + 'willcom' => 'willcom', + 'willcom_pdx' => 'willcom', + 'willcom_bandai' => 'willcom', + 'willcom_pipopa' => 'willcom', + 'willcom_ymobile' => 'willcom', + 'willcom_emnet' => 'willcom', + 'pc' => 'pc' + ); + + // initial the session if there is no session running already + if (!session_id()) { + // check if we have an external session name given, else skip this step + if (SET_SESSION_NAME) { + // set the session name for possible later check + $this->session_name = SET_SESSION_NAME; + session_name($this->session_name); + } + // start session + session_start(); + // set internal session id, we can use that later for protection check + $this->session_id = session_id(); + } + + // init crypt settings + $this->cryptInit(); + + // start logging running time + $this->running_time(); + } + + // METHOD __destruct + // PARAMS none + // RETURN if debug is on, return error data + // DESC basic deconstructor (should be called from all deconstructors in higher classes) + // writes out $error_msg to global var + public function __destruct() + { + // this has to be changed, not returned here, this is the last class to close // return $this->error_msg; - // close open file handles + // close open file handles // $this->fdebug_fp('c'); + } + + // ************************************************************* + // GENERAL METHODS + // ************************************************************* + + // METHOD db_io_info + // PARAMS show, default 1, if set to 0 won't write to error_msg var + // RETURN string with info + // DESC default class info (prints out class info) + public function info($class_name = "basic", $stdio = 0) + { + unset($string); + list($major, $minor, $patchlvl) = explode(".", $this->class_info[$class_name]["class_version"]); + $string .= "-Class-info-[".$class_name."]-> Class Name: ".$this->class_info[$class_name]["class_name"]."
"; + $string .= "-Class-info-[".$class_name."]-> Class Author: ".$this->class_info[$class_name]["class_author"]."
"; + $string .= "-Class-info-[".$class_name."]-> Class Version: ".$this->class_info[$class_name]["class_version"]."
"; + $string .= "-Class-info-[".$class_name."]-> Class Revision: ".$this->class_info[$class_name]["class_revision"]."
"; + $string .= "-Class-info-[".$class_name."]-> Class Created: ".$this->class_info[$class_name]["class_created"]."
"; + $string .= "-Class-info-[".$class_name."]-> Class Last Change: ".$this->class_info[$class_name]["class_last_changed"].""; + if ($stdio) { + echo $string.'
'; + } else { + $this->debug('info', '
'.$string); } + return $string; + } - // ************************************************************* - // GENERAL METHODS - // ************************************************************* - - // METHOD db_io_info - // PARAMS show, default 1, if set to 0 won't write to error_msg var - // RETURN string with info - // DESC default class info (prints out class info) - public function info($class_name = "basic", $stdio = 0) - { - unset($string); - list($major, $minor, $patchlvl) = explode(".", $this->class_info[$class_name]["class_version"]); - $string .= "-Class-info-[".$class_name."]-> Class Name: ".$this->class_info[$class_name]["class_name"]."
"; - $string .= "-Class-info-[".$class_name."]-> Class Author: ".$this->class_info[$class_name]["class_author"]."
"; - $string .= "-Class-info-[".$class_name."]-> Class Version: ".$this->class_info[$class_name]["class_version"]."
"; - $string .= "-Class-info-[".$class_name."]-> Class Revision: ".$this->class_info[$class_name]["class_revision"]."
"; - $string .= "-Class-info-[".$class_name."]-> Class Created: ".$this->class_info[$class_name]["class_created"]."
"; - $string .= "-Class-info-[".$class_name."]-> Class Last Change: ".$this->class_info[$class_name]["class_last_changed"].""; - if ($stdio) - { - echo $string.'
'; - } else - { - $this->debug('info', '
'.$string); - } - return $string; + public function running_time($simple = false) + { + list($micro, $timestamp) = explode(" ", microtime()); + $string = ''; + $running_time = ''; + if (!$this->starttime) { + $this->starttime = ((float)$micro + (float)$timestamp); + $string .= $simple ? 'Start: ' : "Started at: "; + } else { + $this->endtime = ((float)$micro + (float)$timestamp); + $string .= $simple ? 'End: ' : "Stopped at: "; + } + $string .= date("Y-m-d H:i:s", $timestamp); + $string .= " ".$micro; + if ($this->starttime && $this->endtime) { + $running_time = $this->endtime - $this->starttime; + $string .= ($simple ? 'Run: ' : "
Script running time: ").$running_time." s"; } - - public function running_time($simple = false) - { - list($micro, $timestamp) = explode(" ", microtime()); - $string = ''; - $running_time = ''; - if (!$this->starttime) - { - $this->starttime = ((float)$micro + (float)$timestamp); - $string .= $simple ? 'Start: ' : "Started at: "; - } - else - { - $this->endtime = ((float)$micro + (float)$timestamp); - $string .= $simple ? 'End: ' : "Stopped at: "; - } - $string .= date("Y-m-d H:i:s", $timestamp); - $string .= " ".$micro; - if ($this->starttime && $this->endtime) - { - $running_time = $this->endtime - $this->starttime; - $string .= ($simple ? 'Run: ' : "
Script running time: ").$running_time." s"; - } // $this->debug('info', $string); - return $running_time; + return $running_time; + } + + // METHOD print_time + // PARAMS $set_microtime, 0 shows none, default (-1) shows all, positive number is for rounding + // RETURN formated datetime string + // DESCRIPTION + // wrapper around microtime function to print out y-m-d h:i:s.ms + public static function print_time($set_microtime = -1) + { + list($microtime, $timestamp) = explode(" ", microtime()); + $string = date("Y-m-d H:i:s", $timestamp); + // if microtime flag is -1 no round, if 0, no microtime, if >= 1, round that size + if ($set_microtime == -1) { + $string .= substr($microtime, 1); + } elseif ($set_microtime >= 1) { + $string .= substr(round($microtime, $set_microtime), 1); } + return $string; + } - // METHOD print_time - // PARAMS $set_microtime, 0 shows none, default (-1) shows all, positive number is for rounding - // RETURN formated datetime string - // DESCRIPTION - // wrapper around microtime function to print out y-m-d h:i:s.ms - public static function print_time($set_microtime = -1) - { - list($microtime, $timestamp) = explode(" ", microtime()); - $string = date("Y-m-d H:i:s", $timestamp); - // if microtime flag is -1 no round, if 0, no microtime, if >= 1, round that size - if ($set_microtime == -1) - { - $string .= substr($microtime, 1); + + // METHOD fdebug + // PARAMS $string: data to write to file + // $enter: default on true, if set to false, no linebreak (\n) will be put at the end + // RETURN none + // DESCRIPTION + // writes a string to a file immediatly, for fast debug output + public function fdebug($string, $enter = 1) + { + if ($this->debug_filename) { + $this->fdebug_fp(); + if ($enter) { + $string .= "\n"; } - elseif ($set_microtime >= 1) - { - $string .= substr(round($microtime, $set_microtime), 1); - } - return $string; + $string = "[".$this->print_time()."] [".$this->get_page_name(2)."] - ".$string; + fwrite($this->debug_fp, $string); + $this->fdebug_fp(); } + } - - // METHOD fdebug - // PARAMS $string: data to write to file - // $enter: default on true, if set to false, no linebreak (\n) will be put at the end - // RETURN none - // DESCRIPTION - // writes a string to a file immediatly, for fast debug output - public function fdebug($string, $enter = 1) - { - if ($this->debug_filename) - { - $this->fdebug_fp(); - if ($enter) - $string .= "\n"; - $string = "[".$this->print_time()."] [".$this->get_page_name(2)."] - ".$string; - fwrite($this->debug_fp, $string); - $this->fdebug_fp(); - } + // METHOD fdebug_fp + // PARAMS $flag: default '', 'o' -> open, 'c' -> close + // RETURN none + // DESCRIPTION + // if no debug_fp found, opens a new one; if fp exists close it + private function fdebug_fp($flag = '') + { + if (!$this->debug_fp || $flag == 'o') { + $fn = ROOT.LOG.$this->debug_filename; + $this->debug_fp = @fopen($fn, 'a'); + } elseif ($this->debug_fp || $flag == 'c') { + fclose($this->debug_fp); } + } - // METHOD fdebug_fp - // PARAMS $flag: default '', 'o' -> open, 'c' -> close - // RETURN none - // DESCRIPTION - // if no debug_fp found, opens a new one; if fp exists close it - private function fdebug_fp($flag = '') - { - if (!$this->debug_fp || $flag == 'o') - { - $fn = ROOT.LOG.$this->debug_filename; - $this->debug_fp = @fopen($fn, 'a'); - } - else if ($this->debug_fp || $flag == 'c') - { - fclose($this->debug_fp); - } - } - - // METHOD debug_for - // PARAMS $type: error, echo, print - // $flag: on/off - // $array of levels to turn on/off debug - // RETURN none - // DESCRIPTION - // passes list of level names, to turn on debug - // eg $foo->debug_for('print', 'on', array('LOG', 'DEBUG', 'INFO')); - public function debug_for($type, $flag) - { - $debug_on = func_get_args(); - array_shift($debug_on); // kick out type - array_shift($debug_on); // kick out flag (on/off) - if (count($debug_on) >= 1) - { - foreach ($debug_on as $level) - { - $switch = $type."_output"; - if ($flag == 'off') - $switch .= '_not'; - $this->{$switch}[$level] = 1; + // METHOD debug_for + // PARAMS $type: error, echo, print + // $flag: on/off + // $array of levels to turn on/off debug + // RETURN none + // DESCRIPTION + // passes list of level names, to turn on debug + // eg $foo->debug_for('print', 'on', array('LOG', 'DEBUG', 'INFO')); + public function debug_for($type, $flag) + { + $debug_on = func_get_args(); + array_shift($debug_on); // kick out type + array_shift($debug_on); // kick out flag (on/off) + if (count($debug_on) >= 1) { + foreach ($debug_on as $level) { + $switch = $type."_output"; + if ($flag == 'off') { + $switch .= '_not'; } + $this->{$switch}[$level] = 1; } } + } - // METHOD debug - // PARAMS $level: id for error message, groups messages together - // $string: the actual error message - // $strip: default on false, if set to true, all html tags will be stripped and
changed to \n - // this is only used for debug output - // RETURN none - // DESCRIPTION - // write debug data to error_msg array - public function debug($level, $string, $strip = false) - { - if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) - { - if (!isset($this->error_msg[$level])) - $this->error_msg[$level] = ''; - $error_string = '
'; - $error_string .= '['.$this->print_time().'] ['.$level.'] ['.$this->host_name.'] ['.$this->page_name.'] ['.$this->running_uid.'] {'.get_class($this).'} - '.$string; - $error_string .= "
"; - if ($strip) - { - // find any
and replace them with \n - $string = str_replace('
', "\n", $string); - // strip rest of html elements - $string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $string); + // METHOD debug + // PARAMS $level: id for error message, groups messages together + // $string: the actual error message + // $strip: default on false, if set to true, all html tags will be stripped and
changed to \n + // this is only used for debug output + // RETURN none + // DESCRIPTION + // write debug data to error_msg array + public function debug($level, $string, $strip = false) + { + if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) { + if (!isset($this->error_msg[$level])) { + $this->error_msg[$level] = ''; + } + $error_string = '
'; + $error_string .= '['.$this->print_time().'] '; + $error_string .= '['.$level.'] '; + $error_string .= '['.$this->host_name.'] '; + $error_string .= '['.$this->page_name.'] '; + $error_string .= '['.$this->running_uid.'] '; + $error_string .= '{'.get_class($this).'} - '.$string; + $error_string .= "
"; + if ($strip) { + // find any
and replace them with \n + $string = str_replace('
', "\n", $string); + // strip rest of html elements + $string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $string); + } + // same string put for print (no html crap inside) + $error_string_print = '['.$this->print_time().'] ['.$this->host_name.'] ['.$this->get_page_name(2).'] ['.$this->running_uid.'] {'.get_class($this).'} <'.$level.'> - '.$string; + $error_string_print .= "\n"; + // write to file if set + $this->write_error_msg($level, $error_string_print); + // write to error level + if (($this->echo_output[$level] || $this->echo_output_all) && !$this->echo_output_not[$level]) { + $this->error_msg[$level] .= $error_string; + } + } + } + + // METHOD: get_caller_method + // PARAMS: none (optional later: which level to deb ug) + // RETURN: null or the function that called the function where this methid is called + // DESC : if there is a need to find out which parent method called a child method, eg for debugging, this function does this + // call this method in the child method and you get the parent function that called it + public function get_caller_method($level = 2) + { + $traces = debug_backtrace(); + // extended info (later) + /* + * $file = $trace[$level]['file']; + * $line = $trace[$level]['line']; + * $object = $trace[$level]['object']; + * if (is_object($object)) { $object = get_class($object); } + * + * return "Where called: line $line of $object \n(in $file)"; + */ + // sets the start point here, and in level two (the sub call) we find this + if (isset($traces[$level])) { + return $traces[$level]['function']; + } + return null; + } + + // METHOD merge_errors + // PARAMS error array + // RETURN none + // DESC merges the given error array with the one from this class + // only merges visible ones + public function merge_errors($error_msg = array ()) + { + if (!is_array($error_msg)) { + $error_msg = array (); + } + foreach ($error_msg as $level => $msg) { + $this->error_msg[$level] .= $msg; + } + } + + // METHOD print_error_msg + // PARAMS $string: prefix string for header + // RETURN error msg for all levels + // DESCRIPTION + // prints out the error string + public function print_error_msg($string = '') + { + $string_output = ''; + if ($this->debug_output_all) { + if ($this->error_msg_prefix) { + $string = $this->error_msg_prefix; + } + $script_end = $this->running_time(); + while (list($level, $temp_debug_output) = each($this->error_msg)) { + if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) { + if (($this->echo_output[$level] || $this->echo_output_all) && !$this->echo_output_not[$level]) { + $string_output .= '
['.$level.'] '.(($string) ? "**** ".$this->htmlent($string)." ****\n" : "").'
'; + $string_output .= $temp_debug_output; + } // echo it out + } // do printout + } // for each level + // create the output wrapper around, so we have a nice formated output per class + if ($string_output) { + $string_prefix = '
'; + $string_prefix .= '
{'.get_class($this).'}
'; + $string_output = $string_prefix.$string_output; + $string_output .= '
Script Run Time: '.$script_end.'
'; + $string_output .= '
'; + } + } + return $string_output; + } + + // METHOD write_error_msg + // PARAMS $level: the level to write + // RETURN none + // DESCRIPTION + // writes error msg data to file for current level + private function write_error_msg($level, $error_string) + { + if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) { + // only write if write is requested + if (($this->print_output[$level] || $this->print_output_all) && !$this->print_output_not[$level]) { + // replace all html tags + // $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "##\\2##", $error_string); + // $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $error_string); + // replace special line break tag + // $error_string = str_replace('', "\n", $error_string); + + // init output variable + $output = $error_string; // output formated error string to output file + // init base file path + $fn = ROOT.LOG.$this->log_print_file.'.'.$this->log_file_name_ext; + // log ID prefix settings, if not valid, replace with empty + if (preg_match("/^[A-Za-z0-9]+$/", $this->log_file_id)) { + $rpl_string = '_'.$this->log_file_id; + } else { + $rpl_string = ''; } - // same string put for print (no html crap inside) - $error_string_print = '['.$this->print_time().'] ['.$this->host_name.'] ['.$this->get_page_name(2).'] ['.$this->running_uid.'] {'.get_class($this).'} <'.$level.'> - '.$string; - $error_string_print .= "\n"; - // write to file if set - $this->write_error_msg($level, $error_string_print); - // write to error level - if (($this->echo_output[$level] || $this->echo_output_all) && !$this->echo_output_not[$level]) - $this->error_msg[$level] .= $error_string; - } - } + $fn = str_replace('##LOGID##', $rpl_string, $fn); // log id (like a log file prefix) - // METHOD: get_caller_method - // PARAMS: none (optional later: which level to deb ug) - // RETURN: null or the function that called the function where this methid is called - // DESC : if there is a need to find out which parent method called a child method, eg for debugging, this function does this - // call this method in the child method and you get the parent function that called it - public function get_caller_method($level = 2) - { - $traces = debug_backtrace(); - // extended info (later) - /* - * $file = $trace[$level]['file']; - * $line = $trace[$level]['line']; - * $object = $trace[$level]['object']; - * if (is_object($object)) { $object = get_class($object); } - * - * return "Where called: line $line of $object \n(in $file)"; - */ - // sets the start point here, and in level two (the sub call) we find this - if (isset($traces[$level])) - return $traces[$level]['function']; - return null; - } - - // METHOD merge_errors - // PARAMS error array - // RETURN none - // DESC merges the given error array with the one from this class - // only merges visible ones - public function merge_errors($error_msg = array ()) - { - if (!is_array($error_msg)) - $error_msg = array (); - foreach ($error_msg as $level => $msg) - { - $this->error_msg[$level] .= $msg; - } - } - - // METHOD print_error_msg - // PARAMS $string: prefix string for header - // RETURN error msg for all levels - // DESCRIPTION - // prints out the error string - public function print_error_msg($string = '') - { - $string_output = ''; - if ($this->debug_output_all) - { - if ($this->error_msg_prefix) - $string = $this->error_msg_prefix; - $script_end = $this->running_time(); - while (list($level, $temp_debug_output) = each($this->error_msg)) - { - if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) - { - if (($this->echo_output[$level] || $this->echo_output_all) && !$this->echo_output_not[$level]) - { - $string_output .= '
['.$level.'] '.(($string) ? "**** ".$this->htmlent($string)." ****\n" : "").'
'; - $string_output .= $temp_debug_output; - } // echo it out - } // do printout - } // for each level - // create the output wrapper around, so we have a nice formated output per class - if ($string_output) - { - $string_output = '
{'.get_class($this).'}
'.$string_output; - $string_output .= '
Script Run Time: '.$script_end.'
'; - $string_output .= '
'; + if ($this->log_per_run) { + if ($GLOBALS['LOG_FILE_UNIQUE_ID']) { + $this->log_file_unique_id = $GLOBALS['LOG_FILE_UNIQUE_ID']; + } + if (!$this->log_file_unique_id) { + $GLOBALS['LOG_FILE_UNIQUE_ID'] = $this->log_file_unique_id = date('Y-m-d_His').'_U_'.substr(hash('sha1', uniqid(mt_rand(), true)), 0, 8); + } + $rpl_string = '_'.$this->log_file_unique_id; // add 8 char unique string + } else { + $rpl_string = !$this->log_print_file_date ? '' : '_'.date('Y-m-d'); // add date to file } - } - return $string_output; - } + $fn = str_replace('##DATE##', $rpl_string, $fn); // create output filename - // METHOD write_error_msg - // PARAMS $level: the level to write - // RETURN none - // DESCRIPTION - // writes error msg data to file for current level - private function write_error_msg($level, $error_string) - { - if (($this->debug_output[$level] || $this->debug_output_all) && !$this->debug_output_not[$level]) - { - // only write if write is requested - if (($this->print_output[$level] || $this->print_output_all) && !$this->print_output_not[$level]) - { - // replace all html tags -// $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "##\\2##", $error_string); -// $error_string = preg_replace("/(<\/?)(\w+)([^>]*>)/", "", $error_string); - // replace special line break tag -// $error_string = str_replace('', "\n", $error_string); + $rpl_string = !$this->log_per_level ? '' : '_'.$level; // if request to write to one file + $fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename - // init output variable - $output = $error_string; // output formated error string to output file - // init base file path - $fn = ROOT.LOG.$this->log_print_file.'.'.$this->log_file_name_ext; - // log ID prefix settings, if not valid, replace with empty - if (preg_match("/^[A-Za-z0-9]+$/", $this->log_file_id)) - $rpl_string = '_'.$this->log_file_id; - else - $rpl_string = ''; - $fn = str_replace('##LOGID##', $rpl_string, $fn); // log id (like a log file prefix) + $rpl_string = !$this->log_per_class ? '' : '_'.get_class($this); // set sub class settings + $fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename - if ($this->log_per_run) - { - if ($GLOBALS['LOG_FILE_UNIQUE_ID']) - $this->log_file_unique_id = $GLOBALS['LOG_FILE_UNIQUE_ID']; - if (!$this->log_file_unique_id) - $GLOBALS['LOG_FILE_UNIQUE_ID'] = $this->log_file_unique_id = date('Y-m-d_His').'_U_'.substr(hash('sha1', uniqid(mt_rand(), true)), 0, 8); - $rpl_string = '_'.$this->log_file_unique_id; // add 8 char unique string - } - else - { - $rpl_string = !$this->log_print_file_date ? '' : '_'.date('Y-m-d'); // add date to file - } - $fn = str_replace('##DATE##', $rpl_string, $fn); // create output filename + $rpl_string = !$this->log_per_page ? '' : '_'.$this->get_page_name(1); // if request to write to one file + $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename - $rpl_string = !$this->log_per_level ? '' : '_'.$level; // if request to write to one file - $fn = str_replace('##LEVEL##', $rpl_string, $fn); // create output filename - - $rpl_string = !$this->log_per_class ? '' : '_'.get_class($this); // set sub class settings - $fn = str_replace('##CLASS##', $rpl_string, $fn); // create output filename - - $rpl_string = !$this->log_per_page ? '' : '_'.$this->get_page_name(1); // if request to write to one file - $fn = str_replace('##PAGENAME##', $rpl_string, $fn); // create output filename - - // write to file - // first check if max file size is is set and file is bigger - if ($this->log_max_filesize > 0 && ((filesize($fn) / 1024) > $this->log_max_filesize)) - { - // for easy purpose, rename file only to attach timestamp, nur sequence numbering - rename($fn, $fn.'.'.date("YmdHis")); - } - $fp = fopen($fn, 'a'); - if ($fp !== false) - { - fwrite($fp, $output); - fclose($fp); - } - else - { - echo ""; - } - - } // do write to file - } - } - - // METHOD reset_error_msg - // PARAMS level -> optional level - // RETURN none - // DESC unsests the error message array - // can be used if writing is primary to file - // if no level given resets all - public function reset_error_msg($level = '') - { - if (!$level) - unset($this->error_msg); - else - unset($this->error_msg[$level]); - } - - // METHOD ErrorHandler - // PARAMS none - // RETURN none - // DESC catch function to handle all errors that are not handled by php itself - // eg all errors that would be surpressed are written to a log file if this function is enabled - // to use it call with set_error_handler(array("baisc", "ErrorHandler")); - // NOTE: this will only catch any additional erros created AFTER the set_error_hanlder was set, so mostly no strict/notices from the classes are visible - public static function ErrorHandler($type, $message, $file, $line, $context) - { - // error levels for PHP - // values based on 5.3 - $error_level = array ( - 1 => 'E_ERROR', - 2 => 'E_WARNING', - 4 => 'E_PARSE', - 8 => 'E_NOTICE', - 16 => 'E_CORE_ERROR', - 32 => 'E_CORE_WARNING', - 64 => 'E_COMPILE_ERROR', - 128 => 'E_COMPILE_WARNING', - 256 => 'E_USER_ERROR', - 512 => 'E_USER_WARNING', - 1024 => 'E_USER_NOTICE', - 2048 => 'E_STRICT', - 4096 => 'E_RECOVERABLE_ERROR', // since 5.2 - 8192 => 'E_DEPRICATED', // since 5.3 - 16384 => 'E_USER_DEPRICATED', // since 5.3 - 30719 => 'E_ALL' // 6143 in 5.2, 2047 in previous versions - ); - - $fn = ROOT.LOG.'php_errors-'.date('Y-m-d').'.log'; - $output = '['.basic::print_time().'] {'.basic::get_page_name().'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message."\n"; - $fp = fopen($fn, 'a'); - fwrite($fp, $output); - fclose($fp); - return false; - } - - // METHOD print_ar - // PARAMS $array - // RETURN string html formatted - // DESCRIPTION - // prints a html formatted (pre) array - public static function print_ar($array) - { - return "
".print_r($array, 1)."
"; - } - - // METHOD checked - // PARAMS haystack (search in), needle (search for), type: 0: returns selected, 1, returns checked - // haystack can be an array or a string - // RETURN returns checked or selected, else returns nothing (empty return) - // DESCRIPTION - // returns 'checked' or 'selected' if okay - // $needle is a var, $haystack an array - // **** THE RETURN VALUE WILL CHANGE TO A DEFAULT "FALSE" **** - public static function checked($haystack, $needle, $type = 0) - { - if (is_array($haystack)) - { - if (in_array((string)$needle, $haystack)) - return (($type) ? "checked" : "selected"); - } - else - { - if ($haystack == $needle) - return (($type) ? "checked" : "selected"); - } - } - - // METHOD magic_links - // PARAMS string: data to transform to a valud HTML url, target: default _blank - // RETURN correctly formed html url link - // DESCRIPTION - // tries to find mailto:user@bubu.at and changes it into ->
E-Mail senden - // or tries to take any url (http, ftp, etc) and transform it into a valid URL - // the string is in the format: some url|name#css|, same for email - public function magic_links($string, $target = "_blank") - { - $output = $string; - $protList = array("http", "https", "ftp", "news", "nntp"); - - // find urls w/o protocol - $output = preg_replace ("/([^\/])www\.([\w\.-]+)\.([a-zA-Z]{2,4})/", "\\1http://www.\\2.\\3", $output); - $output = preg_replace ("/([^\/])ftp\.([\w\.-]+)\.([a-zA-Z]{2,4})/", "\\1ftp://ftp.\\2.\\3", $output); - - // remove doubles, generate protocol-regex - // DIRTY HACK - $protRegex = ""; - foreach ($protList as $protocol) - { - if ($protRegex) $protRegex .= "|"; - { - $protRegex .= "$protocol:\/\/"; + // write to file + // first check if max file size is is set and file is bigger + if ($this->log_max_filesize > 0 && ((filesize($fn) / 1024) > $this->log_max_filesize)) { + // for easy purpose, rename file only to attach timestamp, nur sequence numbering + rename($fn, $fn.'.'.date("YmdHis")); } - } + $fp = fopen($fn, 'a'); + if ($fp !== false) { + fwrite($fp, $output); + fclose($fp); + } else { + echo ""; + } + } // do write to file + } + } - // find urls w/ protocol - // cs: escaped -, added / for http urls - // added | |, this time mandatory, todo: if no | |use \\1\\2 - // backslash at the end of a url also allowed now - // do not touch <.*=".."> things! - // _1: URL or email - // _2: atag (>) - // _3: (_1) part of url or email [main url or email pre @ part] - // _4: (_2) parameters of url or email post @ part - // _5: (_3) parameters of url or tld part of email - // _7: link name/email link name - // _9: style sheet class - $self = $this; + // METHOD reset_error_msg + // PARAMS level -> optional level + // RETURN none + // DESC unsests the error message array + // can be used if writing is primary to file + // if no level given resets all + public function reset_error_msg($level = '') + { + if (!$level) { + unset($this->error_msg); + } else { + unset($this->error_msg[$level]); + } + } + + // METHOD ErrorHandler + // PARAMS none + // RETURN none + // DESC catch function to handle all errors that are not handled by php itself + // eg all errors that would be surpressed are written to a log file if this function is enabled + // to use it call with set_error_handler(array("baisc", "ErrorHandler")); + // NOTE: this will only catch any additional erros created AFTER the set_error_hanlder was set, so mostly no strict/notices from the classes are visible + public static function ErrorHandler($type, $message, $file, $line, $context) + { + // error levels for PHP + // values based on 5.3 + $error_level = array ( + 1 => 'E_ERROR', + 2 => 'E_WARNING', + 4 => 'E_PARSE', + 8 => 'E_NOTICE', + 16 => 'E_CORE_ERROR', + 32 => 'E_CORE_WARNING', + 64 => 'E_COMPILE_ERROR', + 128 => 'E_COMPILE_WARNING', + 256 => 'E_USER_ERROR', + 512 => 'E_USER_WARNING', + 1024 => 'E_USER_NOTICE', + 2048 => 'E_STRICT', + 4096 => 'E_RECOVERABLE_ERROR', // since 5.2 + 8192 => 'E_DEPRICATED', // since 5.3 + 16384 => 'E_USER_DEPRICATED', // since 5.3 + 30719 => 'E_ALL' // 6143 in 5.2, 2047 in previous versions + ); + + $fn = ROOT.LOG.'php_errors-'.date('Y-m-d').'.log'; + $output = '['.basic::print_time().'] {'.basic::get_page_name().'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message."\n"; + $fp = fopen($fn, 'a'); + fwrite($fp, $output); + fclose($fp); + return false; + } + + // METHOD print_ar + // PARAMS $array + // RETURN string html formatted + // DESCRIPTION + // prints a html formatted (pre) array + public static function print_ar($array) + { + return "
".print_r($array, 1)."
"; + } + + // METHOD checked + // PARAMS haystack (search in), needle (search for), type: 0: returns selected, 1, returns checked + // haystack can be an array or a string + // RETURN returns checked or selected, else returns nothing (empty return) + // DESCRIPTION + // returns 'checked' or 'selected' if okay + // $needle is a var, $haystack an array + // **** THE RETURN VALUE WILL CHANGE TO A DEFAULT "FALSE" **** + public static function checked($haystack, $needle, $type = 0) + { + if (is_array($haystack)) { + if (in_array((string)$needle, $haystack)) { + return (($type) ? "checked" : "selected"); + } + } else { + if ($haystack == $needle) { + return (($type) ? "checked" : "selected"); + } + } + } + + // METHOD magic_links + // PARAMS string: data to transform to a valud HTML url, target: default _blank + // RETURN correctly formed html url link + // DESCRIPTION + // tries to find mailto:user@bubu.at and changes it into -> E-Mail senden + // or tries to take any url (http, ftp, etc) and transform it into a valid URL + // the string is in the format: some url|name#css|, same for email + public function magic_links($string, $target = "_blank") + { + $output = $string; + $protList = array("http", "https", "ftp", "news", "nntp"); + + // find urls w/o protocol + $output = preg_replace("/([^\/])www\.([\w\.-]+)\.([a-zA-Z]{2,4})/", "\\1http://www.\\2.\\3", $output); + $output = preg_replace("/([^\/])ftp\.([\w\.-]+)\.([a-zA-Z]{2,4})/", "\\1ftp://ftp.\\2.\\3", $output); + + // remove doubles, generate protocol-regex + // DIRTY HACK + $protRegex = ""; + foreach ($protList as $protocol) { + if ($protRegex) { + $protRegex .= "|"; + } + $protRegex .= "$protocol:\/\/"; + } + + // find urls w/ protocol + // cs: escaped -, added / for http urls + // added | |, this time mandatory, todo: if no | |use \\1\\2 + // backslash at the end of a url also allowed now + // do not touch <.*=".."> things! + // _1: URL or email + // _2: atag (>) + // _3: (_1) part of url or email [main url or email pre @ part] + // _4: (_2) parameters of url or email post @ part + // _5: (_3) parameters of url or tld part of email + // _7: link name/email link name + // _9: style sheet class + $self = $this; // $this->debug('URL', 'Before: '.$output); - $output = preg_replace_callback("/(href=\")?(\>)?\b($protRegex)([\w\.\-?&=+%#~,;\/]+)\b([\.\-?&=+%#~,;\/]*)(\|([^\||^#]+)(#([^\|]+))?\|)?/", - function ($matches) use ($self) - { - return @$self->create_url($matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[7], $matches[9]); - }, - $output - ); - // find email-addresses, but not mailto prefix ones - $output = preg_replace_callback("/(mailto:)?(\>)?\b([\w\.-]+)@([\w\.\-]+)\.([a-zA-Z]{2,4})\b(\|([^\||^#]+)(#([^\|]+))?\|)?/", - function ($matches) use ($self) - { - return @$self->create_email($matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[7], $matches[9]); - }, - $output - ); + $output = preg_replace_callback( + "/(href=\")?(\>)?\b($protRegex)([\w\.\-?&=+%#~,;\/]+)\b([\.\-?&=+%#~,;\/]*)(\|([^\||^#]+)(#([^\|]+))?\|)?/", + function ($matches) use ($self) { + return @$self->create_url($matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[7], $matches[9]); + }, + $output + ); + // find email-addresses, but not mailto prefix ones + $output = preg_replace_callback( + "/(mailto:)?(\>)?\b([\w\.-]+)@([\w\.\-]+)\.([a-zA-Z]{2,4})\b(\|([^\||^#]+)(#([^\|]+))?\|)?/", + function ($matches) use ($self) { + return @$self->create_email($matches[1], $matches[2], $matches[3], $matches[4], $matches[5], $matches[7], $matches[9]); + }, + $output + ); - $this->debug('URL', 'After: '.$output); + $this->debug('URL', 'After: '.$output); // // we have one slashes after the Protocol -> internal link no domain, strip out the proto // $output = preg_replace("/($protRegex)\/(.*)/e", "\\2", $ouput); // $this->debug('URL', "$output"); - // post processing - $output = str_replace ("{TARGET}", $target, $output); - $output = str_replace ("##LT##", "<", $output); - $output = str_replace ("##GT##", ">", $output); - $output = str_replace ("##QUOT##", "\"", $output); + // post processing + $output = str_replace("{TARGET}", $target, $output); + $output = str_replace("##LT##", "<", $output); + $output = str_replace("##GT##", ">", $output); + $output = str_replace("##QUOT##", "\"", $output); - return $output; - } + return $output; + } - // METHOD create_url [INTERNAL] - // PARAMS url link, anchor tag (define both type or url), - // _1, _2, _3 = part of thel URL, if atag is set, _1 is not used - // target: link target, name: name for the url, if not given _2 + _3 is used - // class: style sheet - // RETURN correct string for url href process - // DESCRIPTION - // internal function, called by the magic url create functions. - // checks if title $_4 exists, if not, set url as title - private function create_url($href, $atag, $_1, $_2, $_3, $name, $class) - { + // METHOD create_url [INTERNAL] + // PARAMS url link, anchor tag (define both type or url), + // _1, _2, _3 = part of thel URL, if atag is set, _1 is not used + // target: link target, name: name for the url, if not given _2 + _3 is used + // class: style sheet + // RETURN correct string for url href process + // DESCRIPTION + // internal function, called by the magic url create functions. + // checks if title $_4 exists, if not, set url as title + private function create_url($href, $atag, $_1, $_2, $_3, $name, $class) + { // $this->debug('URL', "1: $_1 - 2: $_2 - $_3 - atag: $atag - name: $name - class: $class"); - // if $_1 ends with //, then we strip $_1 complete & target is also blanked (its an internal link) - if (preg_match("/\/\/$/", $_1) && preg_match("/^\//", $_2)) - { - $_1 = ''; - $target = ''; - } - else - { - $target = '{TARGET}'; - } - // if it is a link already just return the original link do not touch anything - if (!$href && !$atag) - return "##LT##a href=##QUOT##".$_1.$_2.$_3."##QUOT##".(($class) ? ' class=##QUOT##'.$class.'##QUOT##' : '').(($target) ? " target=##QUOT##".$target."##QUOT##" : '')."##GT##".(($name) ? $name : $_2.$_3)."##LT##/a##GT##"; - elseif ($href && !$atag) - return "href=##QUOT##$_1$_2$_3##QUOT##"; - elseif ($atag) - return $atag.$_2.$_3; + // if $_1 ends with //, then we strip $_1 complete & target is also blanked (its an internal link) + if (preg_match("/\/\/$/", $_1) && preg_match("/^\//", $_2)) { + $_1 = ''; + $target = ''; + } else { + $target = '{TARGET}'; } - - // METHOD create_email [INTERNAL] - // PARAMS: email address, atag (define type of url) - // _1, _2, _3: parts of the email _1 before @, _2 after @, 3_ tld - // title: name for the link, if not given use email - // class: style sheet - // DESCRIPTION - // internal function for createing email, returns data to magic_url method - private function create_email($mailto, $atag, $_1, $_2, $_3, $title, $class) - { - $email = $_1."@".$_2.".".$_3; - if (!$mailto && !$atag) - return "##LT##a href=##QUOT##mailto:".$email."##QUOT##".(($class) ? ' class=##QUOT##'.$class.'##QUOT##' : '')."##GT##".(($title) ? $title : $email)."##LT##/a##GT##"; - elseif ($mailto && !$atag) - return "mailto:".$email; - elseif ($atag) - return $atag.$email; - } - - // METHOD get_host_name - // PARAMS none - // RETURN host name - // DESCRIPTION - // get the host name without the port as given by the SELF var - public function get_host_name() - { - $port = ''; - if ($_SERVER['HTTP_HOST'] && preg_match("/:/", $_SERVER['HTTP_HOST'])) - list($host_name, $port) = explode(":", $_SERVER['HTTP_HOST']); - elseif ($_SERVER['HTTP_HOST']) - $host_name = $_SERVER['HTTP_HOST']; - else - $host_name = 'NA'; - $this->host_port = $port ? $port : 80; - return $host_name; - } - - // METHOD get_page_name - // PARAMS 1: strip page file name extension - // 0: keep filename as is - // 2: keep filename as is, but add dirname too - // RETURN filename - // DESCRIPTION - // get the page name of the curronte page: - public static function get_page_name($strip_ext = 0) - { - // get the file info - $page_temp = pathinfo($_SERVER["PHP_SELF"]); - if ($strip_ext == 1) - return $page_temp['filename']; - elseif ($strip_ext == 2) - return $_SERVER['PHP_SELF']; - else - return $page_temp['basename']; - } - - // METHOD get_file_name_ending - // PARAMS filename - // RETURN extension of the file name - // DESCRIPTION - // quick return the extension of the given file name - public static function get_filename_ending($filename) - { - $page_temp = pathinfo($filename); - return $page_temp['extension']; - } - - // METHOD array_search_recursive - // PARAMS needle (search for) - // haystack (search in) - // key_lookin: the key to look out for, default empty - // RETURN array with the elements where the needle can be found in the haystack array - // DESCRIPTION - // searches key = value in an array / array - // only returns the first one found - public static function array_search_recursive($needle, $haystack, $key_lookin = "") - { - $path = NULL; - if (!is_array($haystack)) - $haystack = array(); - if (!is_array($key_lookin) && !empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) - { - $path[] = $key_lookin; - } - else - { - foreach($haystack as $key => $val) - { - if (is_scalar($val) && $val === $needle && empty($key_lookin)) - { -//echo "BAR FOUND $needle
"; - $path[] = $key; - break; - } - elseif (is_scalar($val) && !empty($key_lookin) && $key === $key_lookin && $val == $needle) - { -//echo "FOO FOUND $needle | $key | $val
"; - $path[] = $key; - break; - } - elseif (is_array($val) && $path = basic::array_search_recursive($needle, $val, $key_lookin)) - { -//echo "BAS FOUND $needle | ".print_r($path)."
"; - array_unshift($path, $key); - break; - } - } - } - return $path; - } - - // METHOD array_search_recursive_all - // PARAMS needle (search for) - // haystack (search in) - // key: the key to look for in - // path: recursive call for previous path - // RETURN all array elements paths where the element was found - // DESCRIPTION - // recursive array search function, which returns all found not only the first one - public static function array_search_recursive_all($needle, $haystack, $key, $path = NULL) - { - if (!isset($path['level'])) - $path['level'] = 0; - if (!isset($path['work'])) - $path['work'] = array(); - if (!isset($haystack)) - $haystack = array(); - - // go through the array, - foreach ($haystack as $_key => $_value) - { - // only value matches - if (is_scalar($_value) && $_value == $needle && !$key) - { - $path['work'][$path['level']] = $_key; - $path['found'][] = $path['work']; - } - // key and value matches - elseif (is_scalar($_value) && $_value == $needle && $_key == $key) - { - $path['work'][$path['level']] = $_key; - $path['found'][] = $path['work']; - } - elseif (is_array($_value)) - { - // add position to working - $path['work'][$path['level']] = $_key; - // we will up a level - $path['level'] += 1; - // call recursive - $path = basic::array_search_recursive_all($needle, $_value, $key, $path); - } - } - // cut all that is >= level - array_splice($path['work'], $path['level']); - // step back a level - $path['level'] -= 1; - return $path; - } - - // METHOD array_search_simple - // PARAMS array (search in), key (key to search in), value (what to find - // RETURN true on found, false on not found - // DESCRIPTION - // array search simple. looks for key, value combination, if found, returns true - public static function array_search_simple($array, $key, $value) - { - if (!is_array($array)) - $array = array (); - foreach ($array as $_key => $_value) - { - // if value is an array, we search - if (is_array($_value)) - { - // call recursive, and return result if it is true, else continue - if (($result = basic::array_search_simple($_value, $key, $value)) !== false) - return $result; - } - elseif ($_key == $key && $_value = $value) - { - return true; - } - } - // no true returned, not found - return false; - } - - // METHOD _mb_mime_encode - // PARAMS string to encode, encoding to encode in - // RETURN encoded string - // DESCRIPTION - // wrapper function for mb mime convert, for correct conversion with long strings - public static function _mb_mime_encode($string, $encoding) - { - // set internal encoding, so the mimeheader encode works correctly - mb_internal_encoding($encoding); - // if a subject, make a work around for the broken mb_mimencode - $pos = 0; - $split = 36; // after 36 single bytes characters, if then comes MB, it is broken - // has to 2 x 36 < 74 so the mb_encode_mimeheader 74 hardcoded split does not get triggered - while ($pos < mb_strlen($string, $encoding)) - { - $output = mb_strimwidth($string, $pos, $split, "", $encoding); - $pos += mb_strlen($output, $encoding); - // if the strinlen is 0 here, get out of the loop - if (!mb_strlen($output, $encoding)) - { - $pos += mb_strlen($string, $encoding); - } - $_string_encoded = mb_encode_mimeheader($output, $encoding); - // only make linebreaks if we have mime encoded code inside - // the space only belongs in the second line - if ($_string && preg_match("/^=\?/", $_string_encoded)) - $_string .= "\n "; - $_string .= $_string_encoded; - } - // strip out any spaces BEFORE a line break - $string = str_replace(" \n", "\n", $_string); - return $string; - } - - // METHOD: ByteStringFormat - // PARAMS: int bytes, boolean for space, default is set - // RETURN: string - // DESC: converts bytes into formated string with KB, MB, etc - public static function ByteStringFormat($number, $space = true) - { - if (is_numeric($number) && $number > 0) - { - // labels in order of size - $labels = array('B', 'KB', 'MB', 'GB', 'TB'); - // calc file size, round down too two digits, add label based max change - return round($number / pow(1024, ($i = floor(log($number, 1024)))), 2).($space ? ' ' : '').$labels[$i]; - } - return $number; - } - - // METHOD: StringByteFormat - // PARAMS: string - // RETURN: int - // DESC: calculates the bytes based on a string with nnG, nnM, etc - public static function StringByteFormat($number) - { - $number = trim($number); - $last = strtolower($number[strlen($number) - 1]); - switch ($last) - { - case 'g': $number *= 1024; - case 'm': $number *= 1024; - case 'k': $number *= 1024; - } - return $number; - } - - // METHOD: DateStringFormat - // PARAMS: unix timestamp, true/false to show microtime - // RETURN: string formated date+time in Y-M-D h:m:s - // DESC : a simple wrapper for the date format - public static function DateStringFormat($timestamp, $show_micro = true) - { - list ($timestamp, $ms) = explode('.', round($timestamp, 4)); - if ($show_micro) - $string = date("Y-m-d H:i:s", $timestamp).' '.$ms.'ms'; - else - $string = date("Y-m-d H:i:s", $timestamp); - return $string; - } - - // METHOD: TimeStringFormat - // PARAMS: seconds - // RETURN: formated time string - // DESC: formats a timestamp into time from. not a date - public static function TimeStringFormat($timestamp, $show_micro = true) - { - // check if the timestamp has any h/m/s/ms inside, if yes skip - if (!preg_match("/(h|m|s|ms)/", $timestamp)) - { - $ms = 0; - list ($timestamp, $ms) = explode('.', round($timestamp, 4)); - $timegroups = array (86400, 3600, 60, 1); - $labels = array ('d', 'h', 'm', 's'); - $time_string = ''; - for ($i = 0; $i < count($timegroups); $i ++) - { - $output = floor($timestamp / $timegroups[$i]); - $timestamp = $timestamp % $timegroups[$i]; - // output has days|hours|min|sec - if ($output || $time_string) - $time_string .= $output.$labels[$i].(($i + 1) != count($timegroups) ? ' ' : ''); - } - // if we have ms and it has leading zeros, remove them - $ms = preg_replace("/^0+/", '', $ms); - // add ms if there - if ($show_micro) - $time_string .= ' '.(!$ms ? 0 : $ms).'ms'; - elseif (!$time_string) - $time_string .= (!$ms ? 0 : $ms).'ms'; - } - else - { - $time_string = $timestamp; - } - return $time_string; - } - - // METHOD: StringToTime - // PARAMS: TimeStringFormat string - // RETURN: timestamp with microseconds - // DESC : does a reverse of the TimeStringFormat and converts the string from - // xd xh xm xs xms to a timestamp.microtime format - public static function StringToTime($timestring) - { - $timestamp = ''; - if (preg_match("/(d|h|m|s|ms)/", $timestring)) - { - $timegroups = array (1 => 86400, 3 => 3600, 5 => 60, 7 => 1); - preg_match("/^((\d+)d ?)?((\d+)h ?)?((\d+)m ?)?((\d+)s ?)?((\d+)ms)?$/", $timestring, $matches); - // multiply the returned matches and sum them up. the last one (ms) is added with . - for ($i = 1; $i <= 7; $i += 2) - { - if ($matches[$i]) - { - $timestamp += ($matches[($i + 1)] * $timegroups[$i]); - } - } - if ($matches[10]) - $timestamp .= '.'.$matches[10]; - return $timestamp; - } - else - { - return $timestring; - } - } - - // METHOD: GenAssocArray - // PARAMS: db array, key, value part, flag if set all or only set - // RETURN: returns and associative array - // DESC: creates out of a normal db_return array an assoc array - public static function GenAssocArray($db_array, $key, $value, $set_only = 0) - { - for ($i = 0; $i < count($db_array); $i ++) - { - // if no key then we make an order reference - if ($key && $value && (($set_only && $db_array[$i][$value]) || (!$set_only))) - $ret_array[$db_array[$i][$key]] = $db_array[$i][$value]; - elseif (!$key && $value) - $ret_array[] = $db_array[$i][$value]; - elseif ($key && !$value) - $ret_array[$db_array[$i][$key]] = $i; - } - return $ret_array; - } - - // METHOD: CheckDate - // PARAMS: date (YYYY-MM-DD) - // RETURN: true if valid date, false if date not valid - // DESC: splits & checks date, wrap around for check_date function - public static function CheckDate($date) - { - list ($year, $month, $day) = preg_split("/[\/-]/", $date); - if (!$year || !$month || !$day) - return false; - if (!checkdate($month, $day, $year)) - return false; - return true; - } - - // METHOD: CheckDateTime - // PARAMS: date (YYYY-MM-DD) + time (HH:MM:SS), SS can be dropped - // RETURN: true if valid date, false if date not valid - // DESC: splits & checks date, wrap around for check_date function - public static function CheckDateTime($datetime) - { - list ($year, $month, $day, $hour, $min, $sec) = preg_split("/[\/\- :]/", $datetime); - if (!$year || !$month || !$day) - return false; - if (!checkdate($month, $day, $year)) - return false; - if (!$hour || !$min) - return false; - if (($hour < 0 && $hour > 24) || ($min < 0 && $hour > 60) || ($sec && $sec < 0 && $sec > 60)) - return false; - return true; - } - - // METHOD: CompareDate - // PARAMS: start_date, end_date (both: YYYY-MM-DD) - // RETURN: -1 if the first date is smaller the last, 0 if both are equal, 1 if the end date is bigger than the last - // DESC: splits & checks date, wrap around for check_date function - public static function CompareDate($start_date, $end_date) - { - // pre check for empty or wrong - if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) - return FALSE; - - // splits the data up with / or - - list ($start_year, $start_month, $start_day) = preg_split('/[\/-]/', $start_date); - list ($end_year, $end_month, $end_day) = preg_split('/[\/-]/', $end_date); - // check that month & day are two digits and then combine - foreach (array('start', 'end') as $prefix) - { - foreach (array('month', 'day') as $date_part) - { - $_date = $prefix.'_'.$date_part; - if ($$_date < 10 && !preg_match("/^0/", $$_date)) - $$_date = '0'.$$_date; - } - $_date = $prefix.'_date'; - $$_date = ''; - foreach (array('year', 'month', 'day') as $date_part) - { - $_sub_date = $prefix.'_'.$date_part; - $$_date .= $$_sub_date; - } - } - // now do the compare - if ($start_date < $end_date) - return -1; - if ($start_date == $end_date) - return 0; - if ($start_date > $end_date) - return 1; - } - - // METHOD: CompareDateTime - // PARAMS: start_datetime, end_datetime (both YYYY-MM-DD HH:mm:ss) - // RETURN: -1 if the first date is smaller the last, 0 if both are equal, 1 if the end date is bigger than the last - // DESC : compares the two dates + times. if seconds missing in one set, add :00, converts / to - - public static function CompareDateTime($start_datetime, $end_datetime) - { - // pre check for empty or wrong - if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) - return FALSE; - $start_timestamp = strtotime($start_datetime); - $end_timestamp = strtotime($end_datetime); - if ($start_timestamp < $end_timestamp) - return -1; - if ($start_timestamp == $end_timestamp) - return 0; - if ($start_timestamp > $end_timestamp) - return 1; - } - - // METHOD: ArrayToString - // PARAMS: array, connect char - // RETRUN: string - // DESC: wrapper for join, but checks if input is an array and if not returns null - public static function ArrayToString($array, $connect_char) - { - if (is_array($array)) - return join($connect_char, $array); - else - return FALSE; - } - - // METHOD: CreateThumbnail - // PARAMS: pic -> picture where from we create a thumbnail - // x -> max x size of thumbnail - // y -> max y size of thumbnail - // dummy -> empty, or file_type to show an icon instead of nothing if file is not found - // path -> if source start is not ROOT path, if empty ROOT is choosen - // cache -> cache path, if not given TMP is used - // clear cache -> if set to true, will create thumb all the tame - // RETURN: thumbnail name - // DESC: converts picture to a thumbnail with max x and max y size - public static function CreateThumbnail($pic, $size_x, $size_y, $dummy = "", $path = "", $cache_source = "", $clear_cache = false) - { - // get image type flags - $image_types = array ( - 1 => 'gif', - 2 => 'jpg', - 3 => 'png' - ); - - if ($cache_source) - $tmp_src = $cache_source; - else - $tmp_src = ROOT.TMP; - // check if pic has a path, and override next sets - if (strstr($pic, '/') === FALSE) - { - if (!$path) - $path = ROOT; - $filename = $path.MEDIA.PICTURES.$pic; - } - else - { - $filename = $pic; - // and get the last part for pic (the filename) - $tmp = explode('/', $pic); - $pic = $tmp[(count($tmp) - 1)]; - } - // does this picture exist and is it a picture - if (file_exists($filename) && is_file($filename)) - { - list($width, $height, $type) = getimagesize($filename); - $convert_prefix = ''; - $create_file = false; - // check if we can skip the PDF creation: if we have size, if do not have type, we assume type png - if (!$type && is_numeric($size_x) && is_numeric($size_y)) - { - $check_thumb = $tmp_src.'thumb_'.$pic.'_'.$size_x.'x'.$size_y.'.'.$image_types[3]; - if (!is_file($check_thumb)) - $create_file = true; - else - $type = 3; - } - // if type is not in the list, but returns as PDF, we need to convert to JPEG before - if (!$type) - { - // is this a PDF, if no, return from here with nothing - $convert_prefix = 'png:'; - # TEMP convert to PNG, we then override the file name - $convert_string = CONVERT.' '.$filename.' '.$convert_prefix.$filename.'_TEMP'; - $status = exec($convert_string, $output, $return); - $filename .= '_TEMP'; - // for delete, in case we need to glob - $delete_filename = $filename; - // find file, if we can't find base name, use -0 as the first one (ignore other pages in multiple ones) - if (!is_file($filename)) - $filename .= '-0'; - list($width, $height, $type) = getimagesize($filename); - } - // if no size given, set size to original - if (!$size_x || $size_x < 1 || !is_numeric($size_x)) - $size_x = $width; - if (!$size_y || $size_y < 1 || !is_numeric($size_y)) - $size_y = $height; - $thumb = 'thumb_'.$pic.'_'.$size_x.'x'.$size_y.'.'.$image_types[$type]; - $thumbnail = $tmp_src.$thumb; - // check if we already have this picture converted - if (!is_file($thumbnail) || $clear_cache == true) - { - // convert the picture - if ($width > $size_x) - { - $convert_string = CONVERT.' -geometry '.$size_x.'x '.$filename.' '.$thumbnail; - $status = exec($convert_string, $output, $return); - // get the size of the converted data, if converted - if (is_file($thumbnail)) - list ($width, $height, $type) = getimagesize($thumbnail); - } - if ($height > $size_y) - { - $convert_string = CONVERT.' -geometry x'.$size_y.' '.$filename.' '.$thumbnail; - $status = exec($convert_string, $output, $return); - } - } - if (!is_file($thumbnail)) - { - copy($filename, $thumbnail); - } - $return_data = $thumb; - // if we have a delete filename, delete here with glob - if ($delete_filename) - { - array_map('unlink', glob($delete_filename.'*')); - } - } - else - { - if ($dummy && strstr($dummy, '/') === FALSE) - { - // check if we have the "dummy" image flag set - $filename = PICTURES.ICONS.strtoupper($dummy).".png"; - if ($dummy && file_exists($filename) && is_file($filename)) - $return_data = $filename; - else - $return_data = FALSE; - } - else - { - $filename = $dummy; - } - } - return $return_data; - } - - // *** DEPRICATED CALL *** - // should be removed later - public function checkConvert($string, $from_encoding, $to_encoding) - { - $this->debug('DEPRICATED CALL', 'Depricated call for method: checkConvert [NOW: checkConvertEncoding]'); - return $this->checkConvertEncoding($string, $from_encoding, $to_encoding); - } - - // METHOD: checkConvertEncoding - // PARAMS: string: string to test - // from_encoding: source encoding of this string - // to_encoding: target encoding of this string - // RETURN: false if no problem - // on error, return array with characters that failed in the convert - // DESC: test if a string can be safely convert between encodings. mostly utf8 to shift jis - // the default compare has a possibility of failure, especially with windows - // it is recommended to the following in the script which uses this method: - // mb_substitute_character(0x2234); - // $class->mbErrorChar = '∴'; - // if check to Shift JIS - // if check to ISO-2022-JP - // if check to ISO-2022-JP-MS - // set three dots (∴) as wrong character for correct convert error detect - // (this char is used, because it is one of the least used ones) - public function checkConvertEncoding($string, $from_encoding, $to_encoding) - { - // convert to target encoding and convert back - $temp = mb_convert_encoding($string, $to_encoding, $from_encoding); - $compare = mb_convert_encoding($temp, $from_encoding, $to_encoding); - // if string does not match anymore we have a convert problem - if ($string != $compare) - { - // go through each character and find the ones that do not match - for ($i = 0; $i < mb_strlen($string, $from_encoding); $i ++) - { - $char = mb_substr($string, $i, 1, $from_encoding); - $r_char = mb_substr($compare, $i, 1, $from_encoding); - // the ord 194 is a hack to fix the IE7/IE8 bug with line break and illegal character -// $this->debug('CHECK CONVERTT', '['.$this->mbErrorChar.'] O: '.$char.', C: '.$r_char); - if ((($char != $r_char && !$this->mbErrorChar) || ($char != $r_char && $r_char == $this->mbErrorChar && $this->mbErrorChar)) && ord($char) != 194) - { - $this->debug('CHARS', "'".$char."'".' == '.$r_char.' ('.ord($char).')'); - $failed[] = $char; - } - } - return $failed; - } - else - { - return false; - } - } - - // METHOD: convertEncoding - // PARAMS: string to convert - // target encoding (to which to convert to) - // optional source encoding - // RETURN: converted string - // DESC : detects the source encoding of the string and if doesn't match to the given target encoding it convert is - public static function convertEncoding($string, $to_encoding, $source_encoding = '') - { - // set if not given - if (!$source_encoding) - $source_encoding = mb_detect_encoding($string); - if ($source_encoding != $to_encoding) - if ($source_encoding) - $string = mb_convert_encoding($string, $to_encoding, $source_encoding); - else - $string = mb_convert_encoding($string, $to_encoding); - return $string; - } - - // METHOD: _crc32b - // PARAMS: string - // RETURN: old (wrong) crc32b hash - // DESC: checks php version and if >=5.2.7 it will flip the string - public function _crc32b($string) - { - // do normal hash crc32b - $string = hash('crc32b', $string); - // if bigger than 5.2.7, we need to "unfix" the fix - if ($this->checkPHPVersion('5.2.7')) - { - // flip it back to old (two char groups) - $string = preg_replace("/^([a-z0-9]{2})([a-z0-9]{2})([a-z0-9]{2})([a-z0-9]{2})$/", "$4$3$2$1", $string); - } - return $string; - } - - // METHOD: _sha1_short - // PARAMS: string, flag to use sha - // RETURN: sha1 short (9 chars), but current calls _crc32b - // DESC : replacement for _crc32b call - public function _sha1_short($string, $use_sha = false) - { - if ($use_sha) - return substr(hash('sha1', $string), 0, 9); - else - return $this->_crc32b($string); - } - - // METHOD: _hash - // PARAMS: string, type of hash to use - // RETURN: hashed string - // DESC : replacemend for _crc32b call (alternate) - // defaults to adler 32, fnv132, fnv1a32, joaat - // all that create 8 char long hashes - public function _hash($string, $hash_type = 'adler32') - { - if (!in_array($hash_type, array('adler32', 'fnv132', 'fnv1a32', 'joaat'))) - $hash_type = 'adler32'; - return hash($hash_type, $string); - } - - // METHOD: checkPHPVersion - // PARAMS: $min_version: minimum version. in format x, x.y or x.y.z - // $max_version: default empty, else in same format as min version - // RETURN: true if ok, false if not matching version - public static function checkPHPVersion($min_version, $max_version = '') - { - // exit with false if the min/max strings are wrong - if (!preg_match("/^\d{1}(\.\d{1})?(\.\d{1,2})?$/", $min_version)) - return false; - // max is only chcked if it is set - if ($max_version && !preg_match("/^\d{1}(\.\d{1})?(\.\d{1,2})?$/", $max_version)) - return false; - // split up the version strings to calc the compare number - $version = explode('.', $min_version); - $min_version = $version[0] * 10000 + $version[1] * 100 + $version[2]; - if ($max_version) - { - $version = explode('.', $max_version); - $max_version = $version[0] * 10000 + $version[1] * 100 + $version[2]; - // drop out if min is bigger max, equal size is okay, that would be only THIS - if ($min_version > $max_version) - return false; - } - // set the php version id - if (!defined('PHP_VERSION_ID')) - { - $version = explode('.', phpversion()); - // creates something like 50107 - define('PHP_VERSION_ID', $version[0] * 10000 + $version[1] * 100 + $version[2]); - } - // check if matching for version - if ($min_version && !$max_version) - { - if (PHP_VERSION_ID >= $min_version) - return true; - } - elseif ($min_version && $max_version) - { - if (PHP_VERSION_ID >= $min_version && PHP_VERSION_ID <= $max_version) - return true; - } - // if no previous return, fail - return false; - } - - // METHOD: cryptInit - // PARAMS: none - // RETURN: none - // DESC: inits crypt settings for the crypt functions - // this function NEEDS (!) to be called BEFORE any of the crypt functions is called - // there is no auto init for this at the moment - private function cryptInit() - { - // SET CRYPT SALT PREFIX: - // the prefix string is defined by what the server can do - // first we check if we can do blowfish, if not we try md5 and then des - // WARNING: des is very bad, only first 6 chars get used for the password - // MD5 is a bit better but is already broken - // problem with PHP < 5.3 is that you mostly don't have access to blowfish - if (CRYPT_BLOWFISH == 1 || $this->checkPHPVersion('5.3.0')) - { - // blowfish salt prefix - // for < 5.3.7 use the old one for anything newer use the new version - if ($this->checkPHPVersion('5.3.7')) - $this->cryptSaltPrefix = '$2y$'; - else - $this->cryptSaltPrefix = '$2a$'; - // add the iteration cost prefix (currently fixed 07) - $this->cryptSaltPrefix .= chr(ord('0') + $this->cryptIterationCost / 10); - $this->cryptSaltPrefix .= chr(ord('0') + $this->cryptIterationCost % 10); - $this->cryptSaltPrefix .= '$'; - $this->cryptSaltSuffix = '$'; - } - else - { - // any version lower 5.3 we do check - if (CRYPT_MD5 == 1) - { - $this->cryptSaltPrefix = '$1$'; - $this->cryptSaltSize = 6; - $this->cryptSaltSuffix = '$'; - } - elseif (CRYPT_STD_DES == 1) - { - // so I know this is standard DES, I prefix this with $ and have only one random char - $this->cryptSaltPrefix = '$'; - $this->cryptSaltSize = 1; - $this->cryptSaltSuffix = '$'; - } - else // emergency fallback - { - $this->cryptSaltPrefix = '$0'; - $this->cryptSaltSuffix = '$'; - } - } - } - - // METHOD: cryptSaltString - // PARAMS: random string length, default is 22 (for blowfish crypt) - // RETURN: random string - // DESC: creates a random string from alphanumeric characters: A-Z a-z 0-9 ./ - private function cryptSaltString($nSize = 22) - { - // A-Z is 65,90 - // a-z is 97,122 - // 0-9 is 48,57 - // ./ is 46,47 (so first lower limit is 46) - $min = array (46, 65, 97); - $max = array (57, 90, 122); - $chars = array (); - for ($i = 0; $i < count($min); $i ++) - { - for ($j = $min[$i]; $j <= $max[$i]; $j ++) - { - $chars[] = chr($j); - } - } - // max should be 63 for this case - $max_rand = count($chars) - 1; - // create the salt part - for ($i = 1; $i <= $nSize; $i ++) - { - $salt_string .= $chars[mt_rand(0, $max_rand)]; - } - return $salt_string; - } - - // METHOD: cryptString - // PARAMS: string to be crypted (one way) - // RETURN: encrypted string - // DESC: encrypts the string with blowfish and returns the full string + salt part that needs to be stored somewhere (eg DB) - public function cryptString($string) - { - // the crypt prefix is set in the init of the class - // uses the random string method to create the salt - return crypt($string, $this->cryptSaltPrefix.$this->cryptSaltString($this->cryptSaltSize).$this->cryptSaltSuffix); - } - - // METHOD: verifyCryptString - // PARAMS: plain string (eg password) - // full crypted string (from cryptString - // RETURN: true on matching or false for not matching - // DESC: compares the string with the crypted one, is counter method to cryptString - public function verifyCryptString($string, $crypt) - { - // the full crypted string needs to be passed on to the salt, so the init (for blowfish) and salt are passed on - if (crypt($string, $crypt) == $crypt) - return true; - else - return false; - } - - // *** COLORS *** - - // METHOD: hex2rgb - // PARAMS: hexstring, flag to return as string (true/false), string seperator: default: , - // RETURN: array with RGB or a string with the seperator - // DESC: converts a hex RGB color to the int numbers - public static function hex2rgb($hexStr, $returnAsString = false, $seperator = ',') - { - $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string - $rgbArray = array(); - if (strlen($hexStr) == 6) - { - // If a proper hex code, convert using bitwise operation. No overhead... faster - $colorVal = hexdec($hexStr); - $rgbArray['R'] = 0xFF & ($colorVal >> 0x10); - $rgbArray['G'] = 0xFF & ($colorVal >> 0x8); - $rgbArray['B'] = 0xFF & $colorVal; - } - elseif (strlen($hexStr) == 3) - { - // If shorthand notation, need some string manipulations - $rgbArray['R'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2)); - $rgbArray['G'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2)); - $rgbArray['B'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2)); - } - else - { - return false; //Invalid hex color code - } - return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array - } - - // METHOD: rgb2hex - // PARAMS: red, green, blue (0-255) - // RETURN: string with hex rgb color plus # in front - // DESC: converts the rgb values from int data to the valid rgb html hex string - public static function rgb2hex($red, $green, $blue) - { - $hex_color = '#'; - foreach (array ('red', 'green', 'blue') as $color) - { - // pad left with 0 - $hex_color .= str_pad(dechex($$color), 2, '0', STR_PAD_LEFT); - } - return $hex_color; - } - - // METHOD: rgb2hsb - // PARAMS: red, green, blue (0-255) - // RETURN: array with hue (0-360), sat (0-100%), brightness/value (0-100%) - // DESC : converts RGB to HSB/V values - public static function rgb2hsb($r, $g, $b) - { - // check that rgb is from 0 to 255 - foreach (array('r', 'g', 'b') as $c) - { - if ($$c < 0 || $$c > 255) - $$c = 0; - - $$c = $$c / 255; - } - - $MAX = max($r, $g, $b); - $MIN = min($r, $g, $b); - - if ($MAX == $MIN) - return array(0, 0, round($MAX * 100)); - if ($r == $MAX) - $HUE = ($g - $b) / ($MAX - $MIN); - elseif ($g == $MAX) - $HUE = 2 + (($b - $r) / ($MAX - $MIN)); - elseif ($b == $MAX) - $HUE = 4 + (($r - $g) / ($MAX - $MIN)); - $HUE *= 60; - if ($HUE < 0) - $HUE += 360; - - return array(round($HUE), round((($MAX - $MIN) / $MAX) * 100), round($MAX * 100)); - } - - // METHOD: hsb2rgb - // PARAMS: hue (0-360), saturation (0-1), brightness/value (0-1) - // RETURN: array with red, blue, green - // DESC : converts HSB/V to RGB values RGB is full INT - public static function hsb2rgb($H, $S, $V) - { - // check that H is 0 to 359, 360 = 0 - // and S and V are 0 to 1 - if ($H < 0 || $H > 359 || $H == 360) - $H = 0; - if ($S < 0 || $S > 1) - $S = 0; - if ($V < 0 || $V > 1) - $V = 0; - - if ($S == 0) - return array($V * 255, $V * 255, $V * 255); - - $Hi = floor($H / 60); - $f = ($H / 60) - $Hi; - $p = $V * (1 - $S); - $q = $V * (1 - ($S * $f)); - $t = $V * (1 - ($S * (1 - $f))); - - switch ( $Hi ) - { - case 0 : $red = $V; $gre = $t; $blu = $p; break; - case 1 : $red = $q; $gre = $V; $blu = $p; break; - case 2 : $red = $p; $gre = $V; $blu = $t; break; - case 3 : $red = $p; $gre = $q; $blu = $V; break; - case 4 : $red = $t; $gre = $p; $blu = $V; break; - case 5 : $red = $V; $gre = $p; $blu = $q; break; - default : $red = 0; $gre = 0; $blue = 0; - } - - return array(round($red * 255), round($gre * 255), round($blu * 255)); - } - - // METHOD: rgb2hsl - // PARAMS: red, blue, green (all 0-255) - // RETURN: array with hue (0-360), saturation (0-100%) and luminance (0-100%) - // DESC : converts a RGB (0-255) to HSL - public static function rgb2hsl($r, $g, $b) - { - // check that rgb is from 0 to 255 - foreach (array('r', 'g', 'b') as $c) - { - if ($$c < 0 || $$c > 255) - $$c = 0; - $$c = $$c / 255; - } - - $MIN = min($r, $g, $b); - $MAX = max($r, $g, $b); - // luminance - $L = round((($MAX + $MIN) / 2) * 100); - - if ($MIN == $MAX) - { - // H, S, L - return array(0, 0, $L); - } - else - { - // HUE to 0~360 - if ($r == $MAX) - $HUE = ($g - $b) / ($MAX - $MIN); - elseif ($g == $MAX) - $HUE = 2 + (($b - $r) / ($MAX - $MIN)); - elseif ($b == $MAX) - $HUE = 4 + (($r - $g) / ($MAX - $MIN)); - $HUE *= 60; - if ($HUE < 0) - $HUE += 360; - - // H, S, L - // S= L <= 0.5 ? C/2L : C/2 - 2L - return array(round($HUE), round((($MAX - $MIN) / (($L <= 0.5) ? ($MAX + $MIN) : (2 - $MAX - $MIN))) * 100), $L); - } - } - - // METHOD: hsl2rgb - // PARAMS: hue: 0-360 (degrees) - // saturation: 0-1 - // luminance: 0-1 - // RETURN: array with RGB as full int - // DESC : converts an HSL to RGB - public static function hsl2rgb($h, $s, $l) - { - $h = (1 / 360) * $h; // calc to internal convert value for hue - // if saturation is 0 - if ($s == 0) - { - return array($l * 255, $l * 255, $l * 255); - } - else - { - $m2 = ($l < 0.5) ? $l * ($s + 1) : ($l + $s) - ($l * $s); - $m1 = $l * 2 - $m2; - $hue = function ($base) use ($m1, $m2) - { - // base = hue, hue > 360 (1) - 360 (1), else < 0 + 360 (1) - $base = ($base < 0) ? $base + 1 : (($base > 1) ? $base - 1 : $base); - // 6: 60, 2: 180, 3: 240 - // 2/3 = 240 - // 1/3 = 120 (all from 360) - if ($base * 6 < 1) - return $m1 + ($m2 - $m1) * $base * 6; - if ($base * 2 < 1) - return $m2; - if ($base * 3 < 2) - return $m1 + ($m2 - $m1) * ((2 / 3) - $base) * 6; - return $m1; - }; - - return array(round(255 * $hue($h + (1 / 3))), round(255 * $hue($h)), round(255 * $hue($h - (1 / 3)))); - } - } - - // METHOD: rgb2html - // PARAMS: red, green, blue - // RETRUN: valid # prefix hex html color string - // DESC : converts and int RGB to the HTML color string in hex format - public static function rgb2html($red, $green, $blue) - { - // check that each color is between 0 and 255 - foreach (array('red', 'green', 'blue') as $color) - { - if ($$color < 0 || $$color > 255) - $$color = 125; - // convert to HEX value - $$color = dechex($$color); - // prefix with 0 if only one char - $$color = ((strlen($$color) < 2) ? '0' : '').$$color; - } - // prefix hex parts with 0 if they are just one char long and return the html color string - return '#'.$red.$green.$blue; - } - - // METHOD: in_array_any - // PARAMS: needle: array - // haystack: array - // RETURN: found elements: array - // DESC: search for the needle array elements in haystack and return the ones found as an array, is there nothing found, it returns FALSE (boolean) - public static function in_array_any($needle, $haystack) - { - if (!is_array($needle)) - return false; - if (!is_array($haystack)) - return false; - $found = array (); - foreach ($needle as $element) - { - if (in_array($element, $haystack)) - $found[] = $element; - } - if (count($found) == 0) - return false; - else - return $found; - } - - // METHOD: getEmailType - // PARAMS: email, short == false - // RETURN: string for email type, eg "pc", "docomo", etc - // DESC: guesses the email type (mostly for mobile) from the domain - // if second is set to true, it will return short naming scheme (only provider) - public function getEmailType($email, $short = false) - { - // trip if there is no email address - if (!$email) - return "invalid"; - // loop until we match a mobile type, return this first found type - foreach ($this->mobile_email_type as $email_regex => $email_type) - { - if (preg_match("/$email_regex/", $email)) - { - if ($short) - return $this->getShortEmailType($email_type); - else - return $email_type; - } - } - // if no previous return we assume this is a pc address - if ($short) - return "pc"; - else - return "pc_html"; - } - - // METHOD: getShortEmailType - // PARAMS: long email type (not email) - // RETURN: short email type - // DESC : gets the short email type from a long email type - public function getShortEmailType($email_type) - { - return $this->mobile_email_type_short[$email_type]; - } - - // METHOD: printDateTime - // PARAMS: year, month, day, hour, min: the date and time values - // suffix: additional info printed after the date time variable in the drop down, also used for ID in the on change JS call - // min_steps: default is 1 (minute), can set to anything, is used as sum up from 0 - // RETURN: HTML formated strings for drop down lists of date and time - // DESC: print the date/time drop downs, used in any queue/send/insert at date/time place - public static function printDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) - { - // if suffix given, add _ before - if ($suffix) - $suffix = '_'.$suffix; - - $on_change_call = 'dt_list(\''.$suffix.'\');'; - - // always be 1h ahead (for safety) - $timestamp = time() + 3600; // in seconds - - // the max year is this year + 1; - $max_year = date("Y", $timestamp) + 1; - - // preset year, month, ... - $year = (!$year) ? date("Y", $timestamp) : $year; - $month = (!$month) ? date("m", $timestamp) : $month; - $day = (!$day) ? date("d", $timestamp) : $day; - $hour = (!$hour) ? date("H", $timestamp) : $hour; - $min = (!$min) ? date("i", $timestamp) : $min; // add to five min? - // max days in selected month - $days_in_month = date("t", strtotime($year."-".$month."-".$day." ".$hour.":".$min.":0")); - - // from now to ? - $string = 'Year '; - $string .= ' Month '; - $string .= ' Day '; - $string .= ' Hour '; - $string .= ' Minute '; - $string .= ''; - // return the datetime select string - return $string; - } - - // METHOD: htmlent - // PARAMS: string to encode - // RETURN: encoded string - // DESC : full wrapper for html entities - public function htmlent($string) - { - return htmlentities($string, ENT_COMPAT|ENT_HTML401, 'UTF-8', false); - } - - // METHOD: setFormToken - // PARAMS: session name, if not set then default is form_token - // RETURN: form token - // DESC : sets a form token in a session and returns form token - public function setFormToken($name = 'form_token') - { - // current hard set to sha256 - $token = uniqid(hash('sha256', rand())); - $_SESSION[$name] = $token; - return $token; - } - - // METHOD: validateFormToken - // PARAMS: form token, session name (default form_token) - // RETURN: true or false - // DESC : checks if the form token matches the session set form token - public function validateFormToken($token, $name = 'form_token') - { - return $_SESSION[$name] === $token; + // if it is a link already just return the original link do not touch anything + if (!$href && !$atag) { + return "##LT##a href=##QUOT##".$_1.$_2.$_3."##QUOT##".(($class) ? ' class=##QUOT##'.$class.'##QUOT##' : '').(($target) ? " target=##QUOT##".$target."##QUOT##" : '')."##GT##".(($name) ? $name : $_2.$_3)."##LT##/a##GT##"; + } elseif ($href && !$atag) { + return "href=##QUOT##$_1$_2$_3##QUOT##"; + } elseif ($atag) { + return $atag.$_2.$_3; } } -?> + + // METHOD create_email [INTERNAL] + // PARAMS: email address, atag (define type of url) + // _1, _2, _3: parts of the email _1 before @, _2 after @, 3_ tld + // title: name for the link, if not given use email + // class: style sheet + // DESCRIPTION + // internal function for createing email, returns data to magic_url method + private function create_email($mailto, $atag, $_1, $_2, $_3, $title, $class) + { + $email = $_1."@".$_2.".".$_3; + if (!$mailto && !$atag) { + return "##LT##a href=##QUOT##mailto:".$email."##QUOT##".(($class) ? ' class=##QUOT##'.$class.'##QUOT##' : '')."##GT##".(($title) ? $title : $email)."##LT##/a##GT##"; + } elseif ($mailto && !$atag) { + return "mailto:".$email; + } elseif ($atag) { + return $atag.$email; + } + } + + // METHOD get_host_name + // PARAMS none + // RETURN host name + // DESCRIPTION + // get the host name without the port as given by the SELF var + public function get_host_name() + { + $port = ''; + if ($_SERVER['HTTP_HOST'] && preg_match("/:/", $_SERVER['HTTP_HOST'])) { + list($host_name, $port) = explode(":", $_SERVER['HTTP_HOST']); + } elseif ($_SERVER['HTTP_HOST']) { + $host_name = $_SERVER['HTTP_HOST']; + } else { + $host_name = 'NA'; + } + $this->host_port = $port ? $port : 80; + return $host_name; + } + + // METHOD get_page_name + // PARAMS 1: strip page file name extension + // 0: keep filename as is + // 2: keep filename as is, but add dirname too + // RETURN filename + // DESCRIPTION + // get the page name of the curronte page: + public static function get_page_name($strip_ext = 0) + { + // get the file info + $page_temp = pathinfo($_SERVER["PHP_SELF"]); + if ($strip_ext == 1) { + return $page_temp['filename']; + } elseif ($strip_ext == 2) { + return $_SERVER['PHP_SELF']; + } else { + return $page_temp['basename']; + } + } + + // METHOD get_file_name_ending + // PARAMS filename + // RETURN extension of the file name + // DESCRIPTION + // quick return the extension of the given file name + public static function get_filename_ending($filename) + { + $page_temp = pathinfo($filename); + return $page_temp['extension']; + } + + // METHOD array_search_recursive + // PARAMS needle (search for) + // haystack (search in) + // key_lookin: the key to look out for, default empty + // RETURN array with the elements where the needle can be found in the haystack array + // DESCRIPTION + // searches key = value in an array / array + // only returns the first one found + public static function array_search_recursive($needle, $haystack, $key_lookin = "") + { + $path = null; + if (!is_array($haystack)) { + $haystack = array(); + } + if (!is_array($key_lookin) && !empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) { + $path[] = $key_lookin; + } else { + foreach ($haystack as $key => $val) { + if (is_scalar($val) && $val === $needle && empty($key_lookin)) { +//echo "BAR FOUND $needle
"; + $path[] = $key; + break; + } elseif (is_scalar($val) && !empty($key_lookin) && $key === $key_lookin && $val == $needle) { +//echo "FOO FOUND $needle | $key | $val
"; + $path[] = $key; + break; + } elseif (is_array($val) && $path = basic::array_search_recursive($needle, $val, $key_lookin)) { +//echo "BAS FOUND $needle | ".print_r($path)."
"; + array_unshift($path, $key); + break; + } + } + } + return $path; + } + + // METHOD array_search_recursive_all + // PARAMS needle (search for) + // haystack (search in) + // key: the key to look for in + // path: recursive call for previous path + // RETURN all array elements paths where the element was found + // DESCRIPTION + // recursive array search function, which returns all found not only the first one + public static function array_search_recursive_all($needle, $haystack, $key, $path = null) + { + if (!isset($path['level'])) { + $path['level'] = 0; + } + if (!isset($path['work'])) { + $path['work'] = array(); + } + if (!isset($haystack)) { + $haystack = array(); + } + + // go through the array, + foreach ($haystack as $_key => $_value) { + if (is_scalar($_value) && $_value == $needle && !$key) { + // only value matches + $path['work'][$path['level']] = $_key; + $path['found'][] = $path['work']; + } elseif (is_scalar($_value) && $_value == $needle && $_key == $key) { + // key and value matches + $path['work'][$path['level']] = $_key; + $path['found'][] = $path['work']; + } elseif (is_array($_value)) { + // add position to working + $path['work'][$path['level']] = $_key; + // we will up a level + $path['level'] += 1; + // call recursive + $path = basic::array_search_recursive_all($needle, $_value, $key, $path); + } + } + // cut all that is >= level + array_splice($path['work'], $path['level']); + // step back a level + $path['level'] -= 1; + return $path; + } + + // METHOD array_search_simple + // PARAMS array (search in), key (key to search in), value (what to find + // RETURN true on found, false on not found + // DESCRIPTION + // array search simple. looks for key, value combination, if found, returns true + public static function array_search_simple($array, $key, $value) + { + if (!is_array($array)) { + $array = array (); + } + foreach ($array as $_key => $_value) { + // if value is an array, we search + if (is_array($_value)) { + // call recursive, and return result if it is true, else continue + if (($result = basic::array_search_simple($_value, $key, $value)) !== false) { + return $result; + } + } elseif ($_key == $key && $_value = $value) { + return true; + } + } + // no true returned, not found + return false; + } + + // METHOD _mb_mime_encode + // PARAMS string to encode, encoding to encode in + // RETURN encoded string + // DESCRIPTION + // wrapper function for mb mime convert, for correct conversion with long strings + public static function _mb_mime_encode($string, $encoding) + { + // set internal encoding, so the mimeheader encode works correctly + mb_internal_encoding($encoding); + // if a subject, make a work around for the broken mb_mimencode + $pos = 0; + $split = 36; // after 36 single bytes characters, if then comes MB, it is broken + // has to 2 x 36 < 74 so the mb_encode_mimeheader 74 hardcoded split does not get triggered + while ($pos < mb_strlen($string, $encoding)) { + $output = mb_strimwidth($string, $pos, $split, "", $encoding); + $pos += mb_strlen($output, $encoding); + // if the strinlen is 0 here, get out of the loop + if (!mb_strlen($output, $encoding)) { + $pos += mb_strlen($string, $encoding); + } + $_string_encoded = mb_encode_mimeheader($output, $encoding); + // only make linebreaks if we have mime encoded code inside + // the space only belongs in the second line + if ($_string && preg_match("/^=\?/", $_string_encoded)) { + $_string .= "\n "; + } + $_string .= $_string_encoded; + } + // strip out any spaces BEFORE a line break + $string = str_replace(" \n", "\n", $_string); + return $string; + } + + // METHOD: ByteStringFormat + // PARAMS: int bytes, boolean for space, default is set + // RETURN: string + // DESC: converts bytes into formated string with KB, MB, etc + public static function ByteStringFormat($number, $space = true) + { + if (is_numeric($number) && $number > 0) { + // labels in order of size + $labels = array('B', 'KB', 'MB', 'GB', 'TB'); + // calc file size, round down too two digits, add label based max change + return round($number / pow(1024, ($i = floor(log($number, 1024)))), 2).($space ? ' ' : '').$labels[$i]; + } + return $number; + } + + // METHOD: StringByteFormat + // PARAMS: string + // RETURN: int + // DESC: calculates the bytes based on a string with nnG, nnM, etc + public static function StringByteFormat($number) + { + $number = trim($number); + $last = strtolower($number[strlen($number) - 1]); + switch ($last) { + case 'g': + $number *= 1024; + // no break: if we have giga we do first multiplication before the others + case 'm': + $number *= 1024; + // no break: if we have mega, do first before we do final kilo + case 'k': + $number *= 1024; + } + return $number; + } + + // METHOD: DateStringFormat + // PARAMS: unix timestamp, true/false to show microtime + // RETURN: string formated date+time in Y-M-D h:m:s + // DESC : a simple wrapper for the date format + public static function DateStringFormat($timestamp, $show_micro = true) + { + list ($timestamp, $ms) = explode('.', round($timestamp, 4)); + if ($show_micro) { + $string = date("Y-m-d H:i:s", $timestamp).' '.$ms.'ms'; + } else { + $string = date("Y-m-d H:i:s", $timestamp); + } + return $string; + } + + // METHOD: TimeStringFormat + // PARAMS: seconds + // RETURN: formated time string + // DESC: formats a timestamp into time from. not a date + public static function TimeStringFormat($timestamp, $show_micro = true) + { + // check if the timestamp has any h/m/s/ms inside, if yes skip + if (!preg_match("/(h|m|s|ms)/", $timestamp)) { + $ms = 0; + list ($timestamp, $ms) = explode('.', round($timestamp, 4)); + $timegroups = array (86400, 3600, 60, 1); + $labels = array ('d', 'h', 'm', 's'); + $time_string = ''; + for ($i = 0; $i < count($timegroups); $i ++) { + $output = floor($timestamp / $timegroups[$i]); + $timestamp = $timestamp % $timegroups[$i]; + // output has days|hours|min|sec + if ($output || $time_string) { + $time_string .= $output.$labels[$i].(($i + 1) != count($timegroups) ? ' ' : ''); + } + } + // if we have ms and it has leading zeros, remove them + $ms = preg_replace("/^0+/", '', $ms); + // add ms if there + if ($show_micro) { + $time_string .= ' '.(!$ms ? 0 : $ms).'ms'; + } elseif (!$time_string) { + $time_string .= (!$ms ? 0 : $ms).'ms'; + } + } else { + $time_string = $timestamp; + } + return $time_string; + } + + // METHOD: StringToTime + // PARAMS: TimeStringFormat string + // RETURN: timestamp with microseconds + // DESC : does a reverse of the TimeStringFormat and converts the string from + // xd xh xm xs xms to a timestamp.microtime format + public static function StringToTime($timestring) + { + $timestamp = ''; + if (preg_match("/(d|h|m|s|ms)/", $timestring)) { + $timegroups = array (1 => 86400, 3 => 3600, 5 => 60, 7 => 1); + preg_match("/^((\d+)d ?)?((\d+)h ?)?((\d+)m ?)?((\d+)s ?)?((\d+)ms)?$/", $timestring, $matches); + // multiply the returned matches and sum them up. the last one (ms) is added with . + for ($i = 1; $i <= 7; $i += 2) { + if ($matches[$i]) { + $timestamp += ($matches[($i + 1)] * $timegroups[$i]); + } + } + if ($matches[10]) { + $timestamp .= '.'.$matches[10]; + } + return $timestamp; + } else { + return $timestring; + } + } + + // METHOD: GenAssocArray + // PARAMS: db array, key, value part, flag if set all or only set + // RETURN: returns and associative array + // DESC: creates out of a normal db_return array an assoc array + public static function GenAssocArray($db_array, $key, $value, $set_only = 0) + { + for ($i = 0; $i < count($db_array); $i ++) { + // if no key then we make an order reference + if ($key && $value && (($set_only && $db_array[$i][$value]) || (!$set_only))) { + $ret_array[$db_array[$i][$key]] = $db_array[$i][$value]; + } elseif (!$key && $value) { + $ret_array[] = $db_array[$i][$value]; + } elseif ($key && !$value) { + $ret_array[$db_array[$i][$key]] = $i; + } + } + return $ret_array; + } + + // METHOD: CheckDate + // PARAMS: date (YYYY-MM-DD) + // RETURN: true if valid date, false if date not valid + // DESC: splits & checks date, wrap around for check_date function + public static function CheckDate($date) + { + list ($year, $month, $day) = preg_split("/[\/-]/", $date); + if (!$year || !$month || !$day) { + return false; + } + if (!checkdate($month, $day, $year)) { + return false; + } + return true; + } + + // METHOD: CheckDateTime + // PARAMS: date (YYYY-MM-DD) + time (HH:MM:SS), SS can be dropped + // RETURN: true if valid date, false if date not valid + // DESC: splits & checks date, wrap around for check_date function + public static function CheckDateTime($datetime) + { + list ($year, $month, $day, $hour, $min, $sec) = preg_split("/[\/\- :]/", $datetime); + if (!$year || !$month || !$day) { + return false; + } + if (!checkdate($month, $day, $year)) { + return false; + } + if (!$hour || !$min) { + return false; + } + if (($hour < 0 && $hour > 24) || ($min < 0 && $hour > 60) || ($sec && $sec < 0 && $sec > 60)) { + return false; + } + return true; + } + + // METHOD: CompareDate + // PARAMS: start_date, end_date (both: YYYY-MM-DD) + // RETURN: -1 if the first date is smaller the last, 0 if both are equal, 1 if the end date is bigger than the last + // DESC: splits & checks date, wrap around for check_date function + public static function CompareDate($start_date, $end_date) + { + // pre check for empty or wrong + if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) { + return false; + } + + // splits the data up with / or - + list ($start_year, $start_month, $start_day) = preg_split('/[\/-]/', $start_date); + list ($end_year, $end_month, $end_day) = preg_split('/[\/-]/', $end_date); + // check that month & day are two digits and then combine + foreach (array('start', 'end') as $prefix) { + foreach (array('month', 'day') as $date_part) { + $_date = $prefix.'_'.$date_part; + if ($$_date < 10 && !preg_match("/^0/", $$_date)) { + $$_date = '0'.$$_date; + } + } + $_date = $prefix.'_date'; + $$_date = ''; + foreach (array('year', 'month', 'day') as $date_part) { + $_sub_date = $prefix.'_'.$date_part; + $$_date .= $$_sub_date; + } + } + // now do the compare + if ($start_date < $end_date) { + return -1; + } + if ($start_date == $end_date) { + return 0; + } + if ($start_date > $end_date) { + return 1; + } + } + + // METHOD: CompareDateTime + // PARAMS: start_datetime, end_datetime (both YYYY-MM-DD HH:mm:ss) + // RETURN: -1 if the first date is smaller the last, 0 if both are equal, 1 if the end date is bigger than the last + // DESC : compares the two dates + times. if seconds missing in one set, add :00, converts / to - + public static function CompareDateTime($start_datetime, $end_datetime) + { + // pre check for empty or wrong + if ($start_date == '--' || $end_date == '--' || !$start_date || !$end_date) { + return false; + } + $start_timestamp = strtotime($start_datetime); + $end_timestamp = strtotime($end_datetime); + if ($start_timestamp < $end_timestamp) { + return -1; + } + if ($start_timestamp == $end_timestamp) { + return 0; + } + if ($start_timestamp > $end_timestamp) { + return 1; + } + } + + // METHOD: ArrayToString + // PARAMS: array, connect char + // RETRUN: string + // DESC: wrapper for join, but checks if input is an array and if not returns null + public static function ArrayToString($array, $connect_char) + { + if (is_array($array)) { + return join($connect_char, $array); + } else { + return false; + } + } + + // METHOD: CreateThumbnail + // PARAMS: pic -> picture where from we create a thumbnail + // x -> max x size of thumbnail + // y -> max y size of thumbnail + // dummy -> empty, or file_type to show an icon instead of nothing if file is not found + // path -> if source start is not ROOT path, if empty ROOT is choosen + // cache -> cache path, if not given TMP is used + // clear cache -> if set to true, will create thumb all the tame + // RETURN: thumbnail name + // DESC: converts picture to a thumbnail with max x and max y size + public static function CreateThumbnail($pic, $size_x, $size_y, $dummy = "", $path = "", $cache_source = "", $clear_cache = false) + { + // get image type flags + $image_types = array ( + 1 => 'gif', + 2 => 'jpg', + 3 => 'png' + ); + + if ($cache_source) { + $tmp_src = $cache_source; + } else { + $tmp_src = ROOT.TMP; + } + // check if pic has a path, and override next sets + if (strstr($pic, '/') === false) { + if (!$path) { + $path = ROOT; + } + $filename = $path.MEDIA.PICTURES.$pic; + } else { + $filename = $pic; + // and get the last part for pic (the filename) + $tmp = explode('/', $pic); + $pic = $tmp[(count($tmp) - 1)]; + } + // does this picture exist and is it a picture + if (file_exists($filename) && is_file($filename)) { + list($width, $height, $type) = getimagesize($filename); + $convert_prefix = ''; + $create_file = false; + // check if we can skip the PDF creation: if we have size, if do not have type, we assume type png + if (!$type && is_numeric($size_x) && is_numeric($size_y)) { + $check_thumb = $tmp_src.'thumb_'.$pic.'_'.$size_x.'x'.$size_y.'.'.$image_types[3]; + if (!is_file($check_thumb)) { + $create_file = true; + } else { + $type = 3; + } + } + // if type is not in the list, but returns as PDF, we need to convert to JPEG before + if (!$type) { + // is this a PDF, if no, return from here with nothing + $convert_prefix = 'png:'; + # TEMP convert to PNG, we then override the file name + $convert_string = CONVERT.' '.$filename.' '.$convert_prefix.$filename.'_TEMP'; + $status = exec($convert_string, $output, $return); + $filename .= '_TEMP'; + // for delete, in case we need to glob + $delete_filename = $filename; + // find file, if we can't find base name, use -0 as the first one (ignore other pages in multiple ones) + if (!is_file($filename)) { + $filename .= '-0'; + } + list($width, $height, $type) = getimagesize($filename); + } + // if no size given, set size to original + if (!$size_x || $size_x < 1 || !is_numeric($size_x)) { + $size_x = $width; + } + if (!$size_y || $size_y < 1 || !is_numeric($size_y)) { + $size_y = $height; + } + $thumb = 'thumb_'.$pic.'_'.$size_x.'x'.$size_y.'.'.$image_types[$type]; + $thumbnail = $tmp_src.$thumb; + // check if we already have this picture converted + if (!is_file($thumbnail) || $clear_cache == true) { + // convert the picture + if ($width > $size_x) { + $convert_string = CONVERT.' -geometry '.$size_x.'x '.$filename.' '.$thumbnail; + $status = exec($convert_string, $output, $return); + // get the size of the converted data, if converted + if (is_file($thumbnail)) { + list ($width, $height, $type) = getimagesize($thumbnail); + } + } + if ($height > $size_y) { + $convert_string = CONVERT.' -geometry x'.$size_y.' '.$filename.' '.$thumbnail; + $status = exec($convert_string, $output, $return); + } + } + if (!is_file($thumbnail)) { + copy($filename, $thumbnail); + } + $return_data = $thumb; + // if we have a delete filename, delete here with glob + if ($delete_filename) { + array_map('unlink', glob($delete_filename.'*')); + } + } else { + if ($dummy && strstr($dummy, '/') === false) { + // check if we have the "dummy" image flag set + $filename = PICTURES.ICONS.strtoupper($dummy).".png"; + if ($dummy && file_exists($filename) && is_file($filename)) { + $return_data = $filename; + } else { + $return_data = false; + } + } else { + $filename = $dummy; + } + } + return $return_data; + } + + // *** DEPRICATED CALL *** + // should be removed later + public function checkConvert($string, $from_encoding, $to_encoding) + { + $this->debug('DEPRICATED CALL', 'Depricated call for method: checkConvert [NOW: checkConvertEncoding]'); + return $this->checkConvertEncoding($string, $from_encoding, $to_encoding); + } + + // METHOD: checkConvertEncoding + // PARAMS: string: string to test + // from_encoding: source encoding of this string + // to_encoding: target encoding of this string + // RETURN: false if no problem + // on error, return array with characters that failed in the convert + // DESC: test if a string can be safely convert between encodings. mostly utf8 to shift jis + // the default compare has a possibility of failure, especially with windows + // it is recommended to the following in the script which uses this method: + // mb_substitute_character(0x2234); + // $class->mbErrorChar = '∴'; + // if check to Shift JIS + // if check to ISO-2022-JP + // if check to ISO-2022-JP-MS + // set three dots (∴) as wrong character for correct convert error detect + // (this char is used, because it is one of the least used ones) + public function checkConvertEncoding($string, $from_encoding, $to_encoding) + { + // convert to target encoding and convert back + $temp = mb_convert_encoding($string, $to_encoding, $from_encoding); + $compare = mb_convert_encoding($temp, $from_encoding, $to_encoding); + // if string does not match anymore we have a convert problem + if ($string != $compare) { + // go through each character and find the ones that do not match + for ($i = 0; $i < mb_strlen($string, $from_encoding); $i ++) { + $char = mb_substr($string, $i, 1, $from_encoding); + $r_char = mb_substr($compare, $i, 1, $from_encoding); + // the ord 194 is a hack to fix the IE7/IE8 bug with line break and illegal character +// $this->debug('CHECK CONVERTT', '['.$this->mbErrorChar.'] O: '.$char.', C: '.$r_char); + if ((($char != $r_char && !$this->mbErrorChar) || ($char != $r_char && $r_char == $this->mbErrorChar && $this->mbErrorChar)) && ord($char) != 194) { + $this->debug('CHARS', "'".$char."'".' == '.$r_char.' ('.ord($char).')'); + $failed[] = $char; + } + } + return $failed; + } else { + return false; + } + } + + // METHOD: convertEncoding + // PARAMS: string to convert + // target encoding (to which to convert to) + // optional source encoding + // RETURN: converted string + // DESC : detects the source encoding of the string and if doesn't match to the given target encoding it convert is + public static function convertEncoding($string, $to_encoding, $source_encoding = '') + { + // set if not given + if (!$source_encoding) { + $source_encoding = mb_detect_encoding($string); + } + if ($source_encoding != $to_encoding) { + if ($source_encoding) { + $string = mb_convert_encoding($string, $to_encoding, $source_encoding); + } else { + $string = mb_convert_encoding($string, $to_encoding); + } + } + return $string; + } + + // METHOD: _crc32b + // PARAMS: string + // RETURN: old (wrong) crc32b hash + // DESC: checks php version and if >=5.2.7 it will flip the string + public function _crc32b($string) + { + // do normal hash crc32b + $string = hash('crc32b', $string); + // if bigger than 5.2.7, we need to "unfix" the fix + if ($this->checkPHPVersion('5.2.7')) { + // flip it back to old (two char groups) + $string = preg_replace("/^([a-z0-9]{2})([a-z0-9]{2})([a-z0-9]{2})([a-z0-9]{2})$/", "$4$3$2$1", $string); + } + return $string; + } + + // METHOD: _sha1_short + // PARAMS: string, flag to use sha + // RETURN: sha1 short (9 chars), but current calls _crc32b + // DESC : replacement for _crc32b call + public function _sha1_short($string, $use_sha = false) + { + if ($use_sha) { + return substr(hash('sha1', $string), 0, 9); + } else { + return $this->_crc32b($string); + } + } + + // METHOD: _hash + // PARAMS: string, type of hash to use + // RETURN: hashed string + // DESC : replacemend for _crc32b call (alternate) + // defaults to adler 32, fnv132, fnv1a32, joaat + // all that create 8 char long hashes + public function _hash($string, $hash_type = 'adler32') + { + if (!in_array($hash_type, array('adler32', 'fnv132', 'fnv1a32', 'joaat'))) { + $hash_type = 'adler32'; + } + return hash($hash_type, $string); + } + + // METHOD: checkPHPVersion + // PARAMS: $min_version: minimum version. in format x, x.y or x.y.z + // $max_version: default empty, else in same format as min version + // RETURN: true if ok, false if not matching version + public static function checkPHPVersion($min_version, $max_version = '') + { + // exit with false if the min/max strings are wrong + if (!preg_match("/^\d{1}(\.\d{1})?(\.\d{1,2})?$/", $min_version)) { + return false; + } + // max is only chcked if it is set + if ($max_version && !preg_match("/^\d{1}(\.\d{1})?(\.\d{1,2})?$/", $max_version)) { + return false; + } + // split up the version strings to calc the compare number + $version = explode('.', $min_version); + $min_version = $version[0] * 10000 + $version[1] * 100 + $version[2]; + if ($max_version) { + $version = explode('.', $max_version); + $max_version = $version[0] * 10000 + $version[1] * 100 + $version[2]; + // drop out if min is bigger max, equal size is okay, that would be only THIS + if ($min_version > $max_version) { + return false; + } + } + // set the php version id + if (!defined('PHP_VERSION_ID')) { + $version = explode('.', phpversion()); + // creates something like 50107 + define('PHP_VERSION_ID', $version[0] * 10000 + $version[1] * 100 + $version[2]); + } + // check if matching for version + if ($min_version && !$max_version) { + if (PHP_VERSION_ID >= $min_version) { + return true; + } + } elseif ($min_version && $max_version) { + if (PHP_VERSION_ID >= $min_version && PHP_VERSION_ID <= $max_version) { + return true; + } + } + // if no previous return, fail + return false; + } + + // METHOD: cryptInit + // PARAMS: none + // RETURN: none + // DESC: inits crypt settings for the crypt functions + // this function NEEDS (!) to be called BEFORE any of the crypt functions is called + // there is no auto init for this at the moment + private function cryptInit() + { + // SET CRYPT SALT PREFIX: + // the prefix string is defined by what the server can do + // first we check if we can do blowfish, if not we try md5 and then des + // WARNING: des is very bad, only first 6 chars get used for the password + // MD5 is a bit better but is already broken + // problem with PHP < 5.3 is that you mostly don't have access to blowfish + if (CRYPT_BLOWFISH == 1 || $this->checkPHPVersion('5.3.0')) { + // blowfish salt prefix + // for < 5.3.7 use the old one for anything newer use the new version + if ($this->checkPHPVersion('5.3.7')) { + $this->cryptSaltPrefix = '$2y$'; + } else { + $this->cryptSaltPrefix = '$2a$'; + } + // add the iteration cost prefix (currently fixed 07) + $this->cryptSaltPrefix .= chr(ord('0') + $this->cryptIterationCost / 10); + $this->cryptSaltPrefix .= chr(ord('0') + $this->cryptIterationCost % 10); + $this->cryptSaltPrefix .= '$'; + $this->cryptSaltSuffix = '$'; + } else { + // any version lower 5.3 we do check + if (CRYPT_MD5 == 1) { + $this->cryptSaltPrefix = '$1$'; + $this->cryptSaltSize = 6; + $this->cryptSaltSuffix = '$'; + } elseif (CRYPT_STD_DES == 1) { + // so I know this is standard DES, I prefix this with $ and have only one random char + $this->cryptSaltPrefix = '$'; + $this->cryptSaltSize = 1; + $this->cryptSaltSuffix = '$'; + } else { + // emergency fallback + $this->cryptSaltPrefix = '$0'; + $this->cryptSaltSuffix = '$'; + } + } + } + + // METHOD: cryptSaltString + // PARAMS: random string length, default is 22 (for blowfish crypt) + // RETURN: random string + // DESC: creates a random string from alphanumeric characters: A-Z a-z 0-9 ./ + private function cryptSaltString($nSize = 22) + { + // A-Z is 65,90 + // a-z is 97,122 + // 0-9 is 48,57 + // ./ is 46,47 (so first lower limit is 46) + $min = array (46, 65, 97); + $max = array (57, 90, 122); + $chars = array (); + for ($i = 0; $i < count($min); $i ++) { + for ($j = $min[$i]; $j <= $max[$i]; $j ++) { + $chars[] = chr($j); + } + } + // max should be 63 for this case + $max_rand = count($chars) - 1; + // create the salt part + for ($i = 1; $i <= $nSize; $i ++) { + $salt_string .= $chars[mt_rand(0, $max_rand)]; + } + return $salt_string; + } + + // METHOD: cryptString + // PARAMS: string to be crypted (one way) + // RETURN: encrypted string + // DESC: encrypts the string with blowfish and returns the full string + salt part that needs to be stored somewhere (eg DB) + public function cryptString($string) + { + // the crypt prefix is set in the init of the class + // uses the random string method to create the salt + return crypt($string, $this->cryptSaltPrefix.$this->cryptSaltString($this->cryptSaltSize).$this->cryptSaltSuffix); + } + + // METHOD: verifyCryptString + // PARAMS: plain string (eg password) + // full crypted string (from cryptString + // RETURN: true on matching or false for not matching + // DESC: compares the string with the crypted one, is counter method to cryptString + public function verifyCryptString($string, $crypt) + { + // the full crypted string needs to be passed on to the salt, so the init (for blowfish) and salt are passed on + if (crypt($string, $crypt) == $crypt) { + return true; + } else { + return false; + } + } + + // *** COLORS *** + + // METHOD: hex2rgb + // PARAMS: hexstring, flag to return as string (true/false), string seperator: default: , + // RETURN: array with RGB or a string with the seperator + // DESC: converts a hex RGB color to the int numbers + public static function hex2rgb($hexStr, $returnAsString = false, $seperator = ',') + { + $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string + $rgbArray = array(); + if (strlen($hexStr) == 6) { + // If a proper hex code, convert using bitwise operation. No overhead... faster + $colorVal = hexdec($hexStr); + $rgbArray['R'] = 0xFF & ($colorVal >> 0x10); + $rgbArray['G'] = 0xFF & ($colorVal >> 0x8); + $rgbArray['B'] = 0xFF & $colorVal; + } elseif (strlen($hexStr) == 3) { + // If shorthand notation, need some string manipulations + $rgbArray['R'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2)); + $rgbArray['G'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2)); + $rgbArray['B'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2)); + } else { + return false; //Invalid hex color code + } + return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array + } + + // METHOD: rgb2hex + // PARAMS: red, green, blue (0-255) + // RETURN: string with hex rgb color plus # in front + // DESC: converts the rgb values from int data to the valid rgb html hex string + public static function rgb2hex($red, $green, $blue) + { + $hex_color = '#'; + foreach (array ('red', 'green', 'blue') as $color) { + // pad left with 0 + $hex_color .= str_pad(dechex($$color), 2, '0', STR_PAD_LEFT); + } + return $hex_color; + } + + // METHOD: rgb2hsb + // PARAMS: red, green, blue (0-255) + // RETURN: array with hue (0-360), sat (0-100%), brightness/value (0-100%) + // DESC : converts RGB to HSB/V values + public static function rgb2hsb($r, $g, $b) + { + // check that rgb is from 0 to 255 + foreach (array('r', 'g', 'b') as $c) { + if ($$c < 0 || $$c > 255) { + $$c = 0; + } + $$c = $$c / 255; + } + + $MAX = max($r, $g, $b); + $MIN = min($r, $g, $b); + + if ($MAX == $MIN) { + return array(0, 0, round($MAX * 100)); + } + if ($r == $MAX) { + $HUE = ($g - $b) / ($MAX - $MIN); + } elseif ($g == $MAX) { + $HUE = 2 + (($b - $r) / ($MAX - $MIN)); + } elseif ($b == $MAX) { + $HUE = 4 + (($r - $g) / ($MAX - $MIN)); + } + $HUE *= 60; + if ($HUE < 0) { + $HUE += 360; + } + + return array(round($HUE), round((($MAX - $MIN) / $MAX) * 100), round($MAX * 100)); + } + + // METHOD: hsb2rgb + // PARAMS: hue (0-360), saturation (0-1), brightness/value (0-1) + // RETURN: array with red, blue, green + // DESC : converts HSB/V to RGB values RGB is full INT + public static function hsb2rgb($H, $S, $V) + { + // check that H is 0 to 359, 360 = 0 + // and S and V are 0 to 1 + if ($H < 0 || $H > 359 || $H == 360) { + $H = 0; + } + if ($S < 0 || $S > 1) { + $S = 0; + } + if ($V < 0 || $V > 1) { + $V = 0; + } + + if ($S == 0) { + return array($V * 255, $V * 255, $V * 255); + } + + $Hi = floor($H / 60); + $f = ($H / 60) - $Hi; + $p = $V * (1 - $S); + $q = $V * (1 - ($S * $f)); + $t = $V * (1 - ($S * (1 - $f))); + + switch ($Hi) { + case 0: + $red = $V; + $gre = $t; + $blu = $p; + break; + case 1: + $red = $q; + $gre = $V; + $blu = $p; + break; + case 2: + $red = $p; + $gre = $V; + $blu = $t; + break; + case 3: + $red = $p; + $gre = $q; + $blu = $V; + break; + case 4: + $red = $t; + $gre = $p; + $blu = $V; + break; + case 5: + $red = $V; + $gre = $p; + $blu = $q; + break; + default: + $red = 0; + $gre = 0; + $blue = 0; + } + + return array(round($red * 255), round($gre * 255), round($blu * 255)); + } + + // METHOD: rgb2hsl + // PARAMS: red, blue, green (all 0-255) + // RETURN: array with hue (0-360), saturation (0-100%) and luminance (0-100%) + // DESC : converts a RGB (0-255) to HSL + public static function rgb2hsl($r, $g, $b) + { + // check that rgb is from 0 to 255 + foreach (array('r', 'g', 'b') as $c) { + if ($$c < 0 || $$c > 255) { + $$c = 0; + } + $$c = $$c / 255; + } + + $MIN = min($r, $g, $b); + $MAX = max($r, $g, $b); + // luminance + $L = round((($MAX + $MIN) / 2) * 100); + + if ($MIN == $MAX) { + // H, S, L + return array(0, 0, $L); + } else { + // HUE to 0~360 + if ($r == $MAX) { + $HUE = ($g - $b) / ($MAX - $MIN); + } elseif ($g == $MAX) { + $HUE = 2 + (($b - $r) / ($MAX - $MIN)); + } elseif ($b == $MAX) { + $HUE = 4 + (($r - $g) / ($MAX - $MIN)); + } + $HUE *= 60; + if ($HUE < 0) { + $HUE += 360; + } + + // H, S, L + // S= L <= 0.5 ? C/2L : C/2 - 2L + return array(round($HUE), round((($MAX - $MIN) / (($L <= 0.5) ? ($MAX + $MIN) : (2 - $MAX - $MIN))) * 100), $L); + } + } + + // METHOD: hsl2rgb + // PARAMS: hue: 0-360 (degrees) + // saturation: 0-1 + // luminance: 0-1 + // RETURN: array with RGB as full int + // DESC : converts an HSL to RGB + public static function hsl2rgb($h, $s, $l) + { + $h = (1 / 360) * $h; // calc to internal convert value for hue + // if saturation is 0 + if ($s == 0) { + return array($l * 255, $l * 255, $l * 255); + } else { + $m2 = ($l < 0.5) ? $l * ($s + 1) : ($l + $s) - ($l * $s); + $m1 = $l * 2 - $m2; + $hue = function ($base) use ($m1, $m2) { + // base = hue, hue > 360 (1) - 360 (1), else < 0 + 360 (1) + $base = ($base < 0) ? $base + 1 : (($base > 1) ? $base - 1 : $base); + // 6: 60, 2: 180, 3: 240 + // 2/3 = 240 + // 1/3 = 120 (all from 360) + if ($base * 6 < 1) { + return $m1 + ($m2 - $m1) * $base * 6; + } + if ($base * 2 < 1) { + return $m2; + } + if ($base * 3 < 2) { + return $m1 + ($m2 - $m1) * ((2 / 3) - $base) * 6; + } + return $m1; + }; + + return array(round(255 * $hue($h + (1 / 3))), round(255 * $hue($h)), round(255 * $hue($h - (1 / 3)))); + } + } + + // METHOD: rgb2html + // PARAMS: red, green, blue + // RETRUN: valid # prefix hex html color string + // DESC : converts and int RGB to the HTML color string in hex format + public static function rgb2html($red, $green, $blue) + { + // check that each color is between 0 and 255 + foreach (array('red', 'green', 'blue') as $color) { + if ($$color < 0 || $$color > 255) { + $$color = 125; + } + // convert to HEX value + $$color = dechex($$color); + // prefix with 0 if only one char + $$color = ((strlen($$color) < 2) ? '0' : '').$$color; + } + // prefix hex parts with 0 if they are just one char long and return the html color string + return '#'.$red.$green.$blue; + } + + // METHOD: in_array_any + // PARAMS: needle: array + // haystack: array + // RETURN: found elements: array + // DESC: search for the needle array elements in haystack and return the ones found as an array, is there nothing found, it returns FALSE (boolean) + public static function in_array_any($needle, $haystack) + { + if (!is_array($needle)) { + return false; + } + if (!is_array($haystack)) { + return false; + } + $found = array (); + foreach ($needle as $element) { + if (in_array($element, $haystack)) { + $found[] = $element; + } + } + if (count($found) == 0) { + return false; + } else { + return $found; + } + } + + // METHOD: getEmailType + // PARAMS: email, short == false + // RETURN: string for email type, eg "pc", "docomo", etc + // DESC: guesses the email type (mostly for mobile) from the domain + // if second is set to true, it will return short naming scheme (only provider) + public function getEmailType($email, $short = false) + { + // trip if there is no email address + if (!$email) { + return "invalid"; + } + // loop until we match a mobile type, return this first found type + foreach ($this->mobile_email_type as $email_regex => $email_type) { + if (preg_match("/$email_regex/", $email)) { + if ($short) { + return $this->getShortEmailType($email_type); + } else { + return $email_type; + } + } + } + // if no previous return we assume this is a pc address + if ($short) { + return "pc"; + } else { + return "pc_html"; + } + } + + // METHOD: getShortEmailType + // PARAMS: long email type (not email) + // RETURN: short email type + // DESC : gets the short email type from a long email type + public function getShortEmailType($email_type) + { + return $this->mobile_email_type_short[$email_type]; + } + + // METHOD: printDateTime + // PARAMS: year, month, day, hour, min: the date and time values + // suffix: additional info printed after the date time variable in the drop down, also used for ID in the on change JS call + // min_steps: default is 1 (minute), can set to anything, is used as sum up from 0 + // RETURN: HTML formated strings for drop down lists of date and time + // DESC: print the date/time drop downs, used in any queue/send/insert at date/time place + public static function printDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) + { + // if suffix given, add _ before + if ($suffix) { + $suffix = '_'.$suffix; + } + + $on_change_call = 'dt_list(\''.$suffix.'\');'; + + // always be 1h ahead (for safety) + $timestamp = time() + 3600; // in seconds + + // the max year is this year + 1; + $max_year = date("Y", $timestamp) + 1; + + // preset year, month, ... + $year = (!$year) ? date("Y", $timestamp) : $year; + $month = (!$month) ? date("m", $timestamp) : $month; + $day = (!$day) ? date("d", $timestamp) : $day; + $hour = (!$hour) ? date("H", $timestamp) : $hour; + $min = (!$min) ? date("i", $timestamp) : $min; // add to five min? + // max days in selected month + $days_in_month = date("t", strtotime($year."-".$month."-".$day." ".$hour.":".$min.":0")); + + // from now to ? + $string = 'Year '; + $string .= ' Month '; + $string .= ' Day '; + $string .= ' Hour '; + $string .= ' Minute '; + $string .= ''; + // return the datetime select string + return $string; + } + + // METHOD: htmlent + // PARAMS: string to encode + // RETURN: encoded string + // DESC : full wrapper for html entities + public function htmlent($string) + { + return htmlentities($string, ENT_COMPAT|ENT_HTML401, 'UTF-8', false); + } + + // METHOD: setFormToken + // PARAMS: session name, if not set then default is form_token + // RETURN: form token + // DESC : sets a form token in a session and returns form token + public function setFormToken($name = 'form_token') + { + // current hard set to sha256 + $token = uniqid(hash('sha256', rand())); + $_SESSION[$name] = $token; + return $token; + } + + // METHOD: validateFormToken + // PARAMS: form token, session name (default form_token) + // RETURN: true or false + // DESC : checks if the form token matches the session set form token + public function validateFormToken($token, $name = 'form_token') + { + return $_SESSION[$name] === $token; + } +} diff --git a/www/libs/Class.DB.Array.IO.inc b/www/libs/Class.DB.Array.IO.inc index f43d686c..70a9fcbe 100644 --- a/www/libs/Class.DB.Array.IO.inc +++ b/www/libs/Class.DB.Array.IO.inc @@ -1,515 +1,497 @@ 21 and 12->22 - * 2003-02-26: db_array_io is no longer single class but extens db_io, - * as it needs it anyway - * moved the class info vars into class_info array into - * the constructor, removed info function - * 2003-02-24: in db_delete moved query build to top, or pk_name/value - * will be reset before delete is done - * 2002-12-20: just added info() method - * 2002-12-17: splitted the class from other file (with main db wrapper) - *********************************************************************/ +/********************************************************************* +* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) +* CREATED: 2002/12/17 +* VERSION: 0.4.0 +* RELEASED LICENSE: GNU GPL 3 +* SHORT DESCRIPTION: +* DB Array IO Class: +* writes, reads or deletes a complete array (one data set) in/out a +* table from the connected DB. +* you don't have to write any SQL queries, worry over update/insert +* +* PUBLIC VARIABLES +* +* PRIVATE VARIABLES +* +* PUBLIC METHODS +* +* PRIVATE METHODS +* +* HISTORY: +* 2005/07/07 (cs) updated array class for postgres: set 0 & NULL if int field given, insert uses () values () syntax +* 2005/03/31 (cs) fixed the class call with all debug vars +* 2003-03-10: error_ids where still wrong chagned 11->21 and 12->22 +* 2003-02-26: db_array_io is no longer single class but extens db_io, +* as it needs it anyway +* moved the class info vars into class_info array into +* the constructor, removed info function +* 2003-02-24: in db_delete moved query build to top, or pk_name/value +* will be reset before delete is done +* 2002-12-20: just added info() method +* 2002-12-17: splitted the class from other file (with main db wrapper) +*********************************************************************/ - // picture upload should be taken out from here and out in media_class - // as it actually has nothing to do with this one here ? (or at least - // put into separete function in this class) +// picture upload should be taken out from here and out in media_class +// as it actually has nothing to do with this one here ? (or at least +// put into separete function in this class) - // try to include file from LIBS path, or from normal path - _spl_autoload('Class.DB.IO.inc'); +// try to include file from LIBS path, or from normal path +_spl_autoload('Class.DB.IO.inc'); - // subclass for one array handling - class db_array_io extends db_io +// subclass for one array handling +class db_array_io extends db_io +{ + // main calss variables + public $table_array; // the array from the table to work on + public $table_name; // the table_name + public $pk_name; // the primary key from this table + public $pk_id; // the PK id + + // METHOD db_array_io + // PARAMS db_config -> db_io class init vars + // table_array -> the array from the table + // table_name -> name of the table (for the array) + // db_debug -> turn on db_io debug output (DB_DEBUG as global var does the same) + // RETURN none + // DESC constructor for the array io class, set the + // primary key name automatically (from array) + public function __construct($db_config, $table_array, $table_name, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) { - // main calss variables - public $table_array; // the array from the table to work on - public $table_name; // the table_name - public $pk_name; // the primary key from this table - public $pk_id; // the PK id + // instance db_io class + parent::__construct($db_config, $debug, $db_debug, $echo, $print); + // more error vars for this class + $this->error_string["21"] = "No Primary Key given"; + $this->error_string["22"] = "Could not run Array Query"; - // METHOD db_array_io - // PARAMS db_config -> db_io class init vars - // table_array -> the array from the table - // table_name -> name of the table (for the array) - // db_debug -> turn on db_io debug output (DB_DEBUG as global var does the same) - // RETURN none - // DESC constructor for the array io class, set the - // primary key name automatically (from array) - public function __construct($db_config, $table_array, $table_name, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) - { - // instance db_io class - parent::__construct($db_config, $debug, $db_debug, $echo, $print); - // more error vars for this class - $this->error_string["21"] = "No Primary Key given"; - $this->error_string["22"] = "Could not run Array Query"; + $this->table_array = $table_array; + $this->table_name = $table_name; - $this->table_array = $table_array; - $this->table_name = $table_name; - - // set primary key for given table_array - if ($this->table_array) - { - while (list($key, $value) = each($table_array)) - { - if ($value["pk"]) - $this->pk_name = $key; + // set primary key for given table_array + if ($this->table_array) { + while (list($key, $value) = each($table_array)) { + if ($value["pk"]) { + $this->pk_name = $key; } - } // set pk_name IF table_array was given - // internal - $this->class_info["db_array_io"] = array( - "class_name" => "DB Array IO", - "class_version" => "0.4.0", - "class_created" => "2002/12/17", - "class_author" => "cs/gullevek/at" - ); - } - - // deconstruktor - public function __destruct() - { - parent::__destruct(); - } - - // METHOD convert_data - // PARAMS string -> the string that should be changed - // RETURN string -> the altered string - // DESC changes all previously alterd HTML code into visible one, - // works for ,, and (thought can be / or should - // be handled with the magic links functions - // used with the read function - public function convert_data($text) - { - $text = eregi_replace ('<b>', '', $text); - $text = eregi_replace ('</b>', '', $text); - $text = eregi_replace ('<i>', '', $text); - $text = eregi_replace ('</i>', '', $text); - // my need a change - $text = eregi_replace ('<a href="', '', $text); - $text = eregi_replace ('</a>', '', $text); - return $text; - } - - // METHOD convert_entities - // PARAMS string -> string to be changed - // RETURN string -> altered string - // DESC changeds all HTML entities into non HTML ones - public function convert_entities($text) - { - $text = str_replace('<', '<', $text); - $text = str_replace('>', '>', $text); - $text = str_replace('&', '&', $text); - $text = str_replace('"', '"', $text); - $text = str_replace(''', "'", $text); - return $text; - } - - // METHOD db_dump_array - // PARAMS none - // RETURN returns the current array - // DESC dumps the current data - public function db_dump_array($write = 0) - { - reset($this->table_array); - while(list($column, $data_array) = each($this->table_array)) - { - $string .= "".$column." -> ".$data_array["value"]."
"; } - // add output to internal error_msg - if ($write) - $this->error_msg['db'] .= $string; - return $string; - } + } // set pk_name IF table_array was given + // internal + $this->class_info["db_array_io"] = array( + "class_name" => "DB Array IO", + "class_version" => "0.4.0", + "class_created" => "2002/12/17", + "class_author" => "cs/gullevek/at" + ); + } - // METHOD _db_error - // PARAMS none - // RETURN none - // DESC writes errors to internal error string + // deconstruktor + public function __destruct() + { + parent::__destruct(); + } + + // METHOD convert_data + // PARAMS string -> the string that should be changed + // RETURN string -> the altered string + // DESC changes all previously alterd HTML code into visible one, + // works for ,, and (thought can be / or should + // be handled with the magic links functions + // used with the read function + public function convert_data($text) + { + $text = str_replace('<b>', '', $text); + $text = str_replace('</b>', '', $text); + $text = str_replace('<i>', '', $text); + $text = str_replace('</i>', '', $text); + // my need a change + $text = str_replace('<a href="', '', $text); + $text = str_replace('</a>', '', $text); + return $text; + } + + // METHOD convert_entities + // PARAMS string -> string to be changed + // RETURN string -> altered string + // DESC changeds all HTML entities into non HTML ones + public function convert_entities($text) + { + $text = str_replace('<', '<', $text); + $text = str_replace('>', '>', $text); + $text = str_replace('&', '&', $text); + $text = str_replace('"', '"', $text); + $text = str_replace(''', "'", $text); + return $text; + } + + // METHOD db_dump_array + // PARAMS none + // RETURN returns the current array + // DESC dumps the current data + public function db_dump_array($write = 0) + { + reset($this->table_array); + while (list($column, $data_array) = each($this->table_array)) { + $string .= "".$column." -> ".$data_array["value"]."
"; + } + // add output to internal error_msg + if ($write) { + $this->error_msg['db'] .= $string; + } + return $string; + } + + // METHOD _db_error + // PARAMS none + // RETURN none + // DESC writes errors to internal error string /* function _db_error() + { + // if error occured + if ($this->error_id) { - // if error occured - if ($this->error_id) - { - $this->error_msg['db'] .= "-DB_ARRAY-error-> ".$this->error_id.": ".$this->error_string[$this->error_id]."
"; - } - } */ - - // METHOD db_check_pk_set - // PARAMS none - // RETURN none - // DESC checks if pk is set and if not, set from pk_id and if this also not set return 0 - public function db_check_pk_set() - { - // if pk_id is set, overrule ... - if ($this->pk_id) - $this->table_array[$this->pk_name]["value"] = $this->pk_id; - // if not set ... produce error - if (!$this->table_array[$this->pk_name]["value"]) - { - // if no PK found, error ... - $this->error_id = 21; - $this->_db_error(); - return 0; - } - else - return 1; + $this->error_msg['db'] .= "-DB_ARRAY-error-> ".$this->error_id.": ".$this->error_string[$this->error_id]."
"; } + } */ - // METHOD db_reset_array - // PARAMS reset_pk -> if set reset the pk too - // RETURN none - // DESC resets the whole array - public function db_reset_array($reset_pk = 0) - { - reset($this->table_array); - while(list($column, $data_array) = each($this->table_array)) - { - if (!$this->table_array[$column]["pk"]) - unset($this->table_array[$column]["value"]); - else if ($reset_pk) - unset($this->table_array[$column]["value"]); - } + // METHOD db_check_pk_set + // PARAMS none + // RETURN none + // DESC checks if pk is set and if not, set from pk_id and if this also not set return 0 + public function db_check_pk_set() + { + // if pk_id is set, overrule ... + if ($this->pk_id) { + $this->table_array[$this->pk_name]["value"] = $this->pk_id; } + // if not set ... produce error + if (!$this->table_array[$this->pk_name]["value"]) { + // if no PK found, error ... + $this->error_id = 21; + $this->_db_error(); + return 0; + } else { + return 1; + } + } - // METHOD db_delete - // PARAMS optional the table_array, if not given uses class var - // RETURN 1 for successfull delete or 0 for error - // DESC deletes one dataset - public function db_delete($table_array = 0) - { - if (is_array($table_array)) - $this->table_array = $table_array; - if (!$this->db_check_pk_set()) - return $this->table_array; - // delete query - $q = "DELETE FROM ".$this->table_name." WHERE "; - $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; - // delete files and build FK query - reset($this->table_array); - while(list($column, $data_array) = each($this->table_array)) - { - // suchen nach bildern und löschen ... - if ($this->table_array[$column]["file"] && file_exists($this->table_array[$column]["url"].$this->table_array[$column]["value"])) - { - if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) - unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); - $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]); - if (file_exists($this->table_array[$column]["path"].$dateiname)) - unlink($this->table_array[$column]["path"].$dateiname); - } - - if ($this->table_array[$column]["fk"]) - { - // zusammenstellen der FKs - if ($q_where) - $q_where .= " AND "; - $q_where .= $column." = ".$this->table_array[$column]["value"]; - } - // allgemeines zurücksetzen des arrays + // METHOD db_reset_array + // PARAMS reset_pk -> if set reset the pk too + // RETURN none + // DESC resets the whole array + public function db_reset_array($reset_pk = 0) + { + reset($this->table_array); + while (list($column, $data_array) = each($this->table_array)) { + if (!$this->table_array[$column]["pk"]) { + unset($this->table_array[$column]["value"]); + } elseif ($reset_pk) { unset($this->table_array[$column]["value"]); } + } + } - // attach fk row if there ... - if ($q_where) - $q .= " AND ".$q_where; - // if 0, error - unset ($this->pk_id); - if (!$this->db_exec($q)) - { - $this->error_id=22; - $this->_db_error(); - } + // METHOD db_delete + // PARAMS optional the table_array, if not given uses class var + // RETURN 1 for successfull delete or 0 for error + // DESC deletes one dataset + public function db_delete($table_array = 0) + { + if (is_array($table_array)) { + $this->table_array = $table_array; + } + if (!$this->db_check_pk_set()) { return $this->table_array; } - - // METHOD db_read - // PARAMS edit -> if 1 data will not be altered for output, optional the table_array, if not given uses class var - // RETURN true or false for reading - // DESC reads one row into the array - public function db_read($edit = 0, $table_array = 0) - { - // if array give, overrules internal array - if (is_array($table_array)) - $this->table_array = $table_array; - if (!$this->db_check_pk_set()) - return $this->table_array; - reset($this->table_array); - // create select part & addition FK part - while (list($column, $data_array)=each($this->table_array)) - { - if ($q_select) - $q_select .= ", "; - $q_select .= $column; - - // check FK ... - if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) - { - if ($q_where) - $q_where .= " AND "; - $q_where .= $column .= " = ".$this->table_array[$column]["value"]; + // delete query + $q = "DELETE FROM ".$this->table_name." WHERE "; + $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; + // delete files and build FK query + reset($this->table_array); + while (list($column, $data_array) = each($this->table_array)) { + // suchen nach bildern und löschen ... + if ($this->table_array[$column]["file"] && file_exists($this->table_array[$column]["url"].$this->table_array[$column]["value"])) { + if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) { + unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); + } + $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]); + if (file_exists($this->table_array[$column]["path"].$dateiname)) { + unlink($this->table_array[$column]["path"].$dateiname); } } - $q = "SELECT "; - $q .= $q_select; - $q .= " FROM ".$this->table_name." WHERE "; - $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; - if ($q_where) - $q .= " AND ".$q_where; + if ($this->table_array[$column]["fk"]) { + // zusammenstellen der FKs + if ($q_where) { + $q_where .= " AND "; + } + $q_where .= $column." = ".$this->table_array[$column]["value"]; + } + // allgemeines zurücksetzen des arrays + unset($this->table_array[$column]["value"]); + } - // if query was executed okay, else set error - if ($this->db_exec($q)) - { - if ($res = $this->db_fetch_array()) - { - reset($this->table_array); - while (list($column, $data_array) = each($this->table_array)) - { - // wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten für ausgabe - // ?? sollte das nicht draußen ??? man weis ja net was da drin steht --> is noch zu überlegen -// echo "EDIT: $edit | Spalte: $column | type: ".$this->table_array[$column]["type"]." | Res: ".$res[$column]."
"; - if ($edit) - { - $this->table_array[$column]["value"] = $res[$column]; - // if password, also write to hidden - if ($this->table_array[$column]["type"] == "password") - { - $this->table_array[$column]["HIDDEN_value"] = $res[$column]; - } - } - else - { - $this->table_array[$column]["value"] = $this->convert_data(nl2br($res[$column])); - // had to put out the htmlentities from the line above as it breaks japanese characters + // attach fk row if there ... + if ($q_where) { + $q .= " AND ".$q_where; + } + // if 0, error + unset($this->pk_id); + if (!$this->db_exec($q)) { + $this->error_id=22; + $this->_db_error(); + } + return $this->table_array; + } + + // METHOD db_read + // PARAMS edit -> if 1 data will not be altered for output, optional the table_array, if not given uses class var + // RETURN true or false for reading + // DESC reads one row into the array + public function db_read($edit = 0, $table_array = 0) + { + // if array give, overrules internal array + if (is_array($table_array)) { + $this->table_array = $table_array; + } + if (!$this->db_check_pk_set()) { + return $this->table_array; + } + reset($this->table_array); + // create select part & addition FK part + while (list($column, $data_array)=each($this->table_array)) { + if ($q_select) { + $q_select .= ", "; + } + $q_select .= $column; + + // check FK ... + if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) { + if ($q_where) { + $q_where .= " AND "; + } + $q_where .= $column .= " = ".$this->table_array[$column]["value"]; + } + } + + $q = "SELECT "; + $q .= $q_select; + $q .= " FROM ".$this->table_name." WHERE "; + $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; + if ($q_where) { + $q .= " AND ".$q_where; + } + + // if query was executed okay, else set error + if ($this->db_exec($q)) { + if ($res = $this->db_fetch_array()) { + reset($this->table_array); + while (list($column, $data_array) = each($this->table_array)) { + // wenn "edit" dann gib daten wie in DB zurück, ansonten aufbereiten für ausgabe + // ?? sollte das nicht draußen ??? man weis ja net was da drin steht --> is noch zu überlegen + // echo "EDIT: $edit | Spalte: $column | type: ".$this->table_array[$column]["type"]." | Res: ".$res[$column]."
"; + if ($edit) { + $this->table_array[$column]["value"] = $res[$column]; + // if password, also write to hidden + if ($this->table_array[$column]["type"] == "password") { + $this->table_array[$column]["HIDDEN_value"] = $res[$column]; } + } else { + $this->table_array[$column]["value"] = $this->convert_data(nl2br($res[$column])); + // had to put out the htmlentities from the line above as it breaks japanese characters } } - // possible db_fetch_array errors ... - $this->pk_id = $this->table_array[$this->pk_name]["value"]; } - else - { - $this->error_id = 22; - $this->_db_error(); - } - return $this->table_array; + // possible db_fetch_array errors ... + $this->pk_id = $this->table_array[$this->pk_name]["value"]; + } else { + $this->error_id = 22; + $this->_db_error(); + } + return $this->table_array; + } + + // METHOD db_write + // PARAMS addslashes -> if 1 will make an addslashes for each array field, optional the table_array, if not given uses class var + // RETURN true or false on write + // DESC writes on set into DB or updates one set (if PK exists) + public function db_write($addslashes = 0, $table_array = 0) + { + if (is_array($table_array)) { + $this->table_array = $table_array; + } + // PK ID check + // if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) { + // $this->table_array[$this->pk_name]["value"]=$this->pk_id; + // } + // checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR! + if (!$this->table_array[$this->pk_name]["value"]) { + $insert = 1; + } else { + $insert = 0; } - // METHOD db_write - // PARAMS addslashes -> if 1 will make an addslashes for each array field, optional the table_array, if not given uses class var - // RETURN true or false on write - // DESC writes on set into DB or updates one set (if PK exists) - public function db_write($addslashes = 0, $table_array = 0) - { - if (is_array($table_array)) - $this->table_array = $table_array; - // PK ID check -// if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) -// $this->table_array[$this->pk_name]["value"]=$this->pk_id; - // checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR! - if (!$this->table_array[$this->pk_name]["value"]) - $insert = 1; - else - $insert = 0; - - reset ($this->table_array); - while (list($column, $data_array) = each($this->table_array)) - { + reset($this->table_array); + while (list($column, $data_array) = each($this->table_array)) { /********************************* START FILE *************************************/ - // file upload - if ($this->table_array[$column]["file"]) - { - // falls was im tmp drinnen, sprich ein upload, datei kopieren, Dateinamen in db schreiben - // falls datei schon am server (physischer pfad), dann einfach url in db schreiben (update) - // falls in "delete" "ja" dann loeschen (und gibts eh nur beim update) - if ($this->table_array[$column]["delete"]) - { - unset($this->table_array[$column]["delete"]); - if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) - unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); - $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]); - if (file_exists($this->table_array[$column]["path"].$dateiname)) - unlink($this->table_array[$column]["path"].$dateiname); - $this->table_array[$column]["value"] = ""; + // file upload + if ($this->table_array[$column]["file"]) { + // falls was im tmp drinnen, sprich ein upload, datei kopieren, Dateinamen in db schreiben + // falls datei schon am server (physischer pfad), dann einfach url in db schreiben (update) + // falls in "delete" "ja" dann loeschen (und gibts eh nur beim update) + if ($this->table_array[$column]["delete"]) { + unset($this->table_array[$column]["delete"]); + if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) { + unlink($this->table_array[$column]["path"].$this->table_array[$column]["value"]); } - else - { - if ($this->table_array[$column]["tmp"] != "none" && $this->table_array[$column]["tmp"]) - { - // Dateiname zusammenbasteln: org-name + _pkid liste + .ext - list($name, $ext) = explode(".",$this->table_array[$column]["dn"]); + $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]); + if (file_exists($this->table_array[$column]["path"].$dateiname)) { + unlink($this->table_array[$column]["path"].$dateiname); + } + $this->table_array[$column]["value"] = ""; + } else { + if ($this->table_array[$column]["tmp"] != "none" && $this->table_array[$column]["tmp"]) { + // Dateiname zusammenbasteln: org-name + _pkid liste + .ext + list($name, $ext) = explode(".", $this->table_array[$column]["dn"]); - // mozilla, patch - $fn_name = explode("/", $this->table_array[$column]["dn"]); - $this->table_array[$column]["dn"] = $fn_name[count($fn_name)-1]; - $filename_parts = explode(".", $this->table_array[$column]["dn"]); - $ext = end($filename_parts); - array_splice($filename_parts, -1, 1); - $name = str_replace(" ", "_", implode(".", $filename_parts)); - //echo "PK: $pk_ids_file
"; - $dateiname = $name.$pk_ids_file.".".$ext; - //echo "Dn: $dateiname"; - copy($this->table_array[$column]["tmp"], $this->table_array[$column]["path"].$dateiname); - // automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild .. - if (strtolower($ext) == "jpeg" || strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") - { - $dateiname_tn = $name.$pk_ids_file."_tn.".$ext; - $eingang = $this->table_array[$column]["path"].$dateiname; - $ausgang = $this->table_array[$column]["path"].$dateiname_tn; - $com = "convert -geometry 115 $eingang $ausgang"; - exec($com); - $this->table_array[$column]["value"] = $dateiname_tn; - } - else - $this->table_array[$column]["value"] = $dateiname; + // mozilla, patch + $fn_name = explode("/", $this->table_array[$column]["dn"]); + $this->table_array[$column]["dn"] = $fn_name[count($fn_name)-1]; + $filename_parts = explode(".", $this->table_array[$column]["dn"]); + $ext = end($filename_parts); + array_splice($filename_parts, -1, 1); + $name = str_replace(" ", "_", implode(".", $filename_parts)); + //echo "PK: $pk_ids_file
"; + $dateiname = $name.$pk_ids_file.".".$ext; + //echo "Dn: $dateiname"; + copy($this->table_array[$column]["tmp"], $this->table_array[$column]["path"].$dateiname); + // automatisch thumbnail generieren, geht nur mit convert (ImageMagic!!!), aber nur bei bild .. + if (strtolower($ext) == "jpeg" || strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") { + $dateiname_tn = $name.$pk_ids_file."_tn.".$ext; + $eingang = $this->table_array[$column]["path"].$dateiname; + $ausgang = $this->table_array[$column]["path"].$dateiname_tn; + $com = "convert -geometry 115 $eingang $ausgang"; + exec($com); + $this->table_array[$column]["value"] = $dateiname_tn; + } else { + $this->table_array[$column]["value"] = $dateiname; } - else if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) - { - // mach gar nix, wenn bild schon da ??? - } - } // delete or upload - } // file IF + } elseif (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) { + // mach gar nix, wenn bild schon da ??? + } + } // delete or upload + } // file IF /********************************* END FILE **************************************/ - // do not write 'pk' (primary key) or 'view' values - if (!$this->table_array[$column]["pk"] && $this->table_array[$column]['type'] != 'view' && strlen($column) > 0 ) - { - // for password use hidden value if main is not set - if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) - $this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"]; - if (!$insert) - { - if (strlen($q_data)) - $q_data .= ", "; - $q_data .= $column." = "; + // do not write 'pk' (primary key) or 'view' values + if (!$this->table_array[$column]["pk"] && $this->table_array[$column]['type'] != 'view' && strlen($column) > 0) { + // for password use hidden value if main is not set + if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) { + $this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"]; + } + if (!$insert) { + if (strlen($q_data)) { + $q_data .= ", "; } - else + $q_data .= $column." = "; + } else { // this is insert - { - if (strlen($q_data)) - $q_data .= ", "; - if ($q_vars) - $q_vars .= ", "; - $q_vars .= $column; + if (strlen($q_data)) { + $q_data .= ", "; } - // integer is different - if ($this->table_array[$column]["int"] || $this->table_array[$column]["int_null"]) - { -$this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."] Foo: ".isset($this->table_array[$column]["value"])." | ".$this->table_array[$column]["int_null"]); - if (!$this->table_array[$column]["value"] && $this->table_array[$column]["int_null"]) - $_value = 'NULL'; - elseif (!isset($this->table_array[$column]["value"])) - $_value = 0; - else - $_value = $this->table_array[$column]["value"]; - $q_data .= $_value; + if ($q_vars) { + $q_vars .= ", "; } - elseif ($this->table_array[$column]["interval"]) - { - // for interval we check if no value, then we set null - if (!$this->table_array[$column]["value"]) - $_value = 'NULL'; - $q_data .= $_value; + $q_vars .= $column; + } + // integer is different + if ($this->table_array[$column]["int"] || $this->table_array[$column]["int_null"]) { + $this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."] Foo: ".isset($this->table_array[$column]["value"])." | ".$this->table_array[$column]["int_null"]); + if (!$this->table_array[$column]["value"] && $this->table_array[$column]["int_null"]) { + $_value = 'NULL'; + } elseif (!isset($this->table_array[$column]["value"])) { + $_value = 0; + } else { + $_value = $this->table_array[$column]["value"]; } - else + $q_data .= $_value; + } elseif ($this->table_array[$column]["interval"]) { + // for interval we check if no value, then we set null + if (!$this->table_array[$column]["value"]) { + $_value = 'NULL'; + } + $q_data .= $_value; + } else { // normal string - { - $q_data .= "'"; - // if add slashes do convert & add slashes else write AS is - if ($addslashes) - $q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"])); - else - $q_data .= $this->db_escape_string($this->table_array[$column]["value"]); - $q_data .= "'"; + $q_data .= "'"; + // if add slashes do convert & add slashes else write AS is + if ($addslashes) { + $q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"])); + } else { + $q_data .= $this->db_escape_string($this->table_array[$column]["value"]); } - } - } // while ... - - // NOW get PK, and FK settings (FK only for update query) - // get it at the end, cause now we can be more sure of no double IDs, etc - reset($this->table_array); - // create select part & addition FK part - while (list($column, $data_array) = each($this->table_array)) - { - // check FK ... - if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) - { - if ($q_where) - $q_where .= " AND "; - $q_where .= $column .= " = ".$this->table_array[$column]["value"]; + $q_data .= "'"; } } + } // while ... - // if no PK set, then get max ID from DB - if (!$this->table_array[$this->pk_name]["value"]) - { -// max id, falls INSERT - $q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name; - $res = $this->db_return_row($q); - if (!$res["pk_id"]) - $res["pk_id"] = 1; - $this->table_array[$this->pk_name]["value"] = $res["pk_id"]; + // NOW get PK, and FK settings (FK only for update query) + // get it at the end, cause now we can be more sure of no double IDs, etc + reset($this->table_array); + // create select part & addition FK part + while (list($column, $data_array) = each($this->table_array)) { + // check FK ... + if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) { + if ($q_where) { + $q_where .= " AND "; + } + $q_where .= $column .= " = ".$this->table_array[$column]["value"]; } - - if (!$insert) - { - $q = "UPDATE ".$this->table_name." SET "; - $q .= $q_data; - $q .= " WHERE "; - $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; - if ($q_where) - $q .= " AND ".$q_where; - // set pk_id ... if it has changed or so - $this->pk_id = $this->table_array[$this->pk_name]["value"]; - } - else - { - $q = "INSERT INTO ".$this->table_name." "; - $q .= "(".$q_vars.") "; - $q .= "VALUES (".$q_data.")"; - // write primary key too -/* if ($q_data) - $q .= ", "; - $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; - $this->pk_id = $this->table_array[$this->pk_name]["value"]; -*/ - } - // return success or not - if (!$this->db_exec($q)) - { - $this->error_id = 22; - $this->_db_error(); - } - // set primary key - if ($insert) - { - $this->table_array[$this->pk_name]["value"] = $this->insert_id; - $this->ok = $this->insert_id; - } - // return the table if needed - return $this->table_array; } - } // end of class -?> + + // if no PK set, then get max ID from DB + if (!$this->table_array[$this->pk_name]["value"]) { + // max id, falls INSERT + $q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name; + $res = $this->db_return_row($q); + if (!$res["pk_id"]) { + $res["pk_id"] = 1; + } + $this->table_array[$this->pk_name]["value"] = $res["pk_id"]; + } + + if (!$insert) { + $q = "UPDATE ".$this->table_name." SET "; + $q .= $q_data; + $q .= " WHERE "; + $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; + if ($q_where) { + $q .= " AND ".$q_where; + } + // set pk_id ... if it has changed or so + $this->pk_id = $this->table_array[$this->pk_name]["value"]; + } else { + $q = "INSERT INTO ".$this->table_name." "; + $q .= "(".$q_vars.") "; + $q .= "VALUES (".$q_data.")"; + // write primary key too + // if ($q_data) + // $q .= ", "; + // $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; + // $this->pk_id = $this->table_array[$this->pk_name]["value"]; + } + // return success or not + if (!$this->db_exec($q)) { + $this->error_id = 22; + $this->_db_error(); + } + // set primary key + if ($insert) { + $this->table_array[$this->pk_name]["value"] = $this->insert_id; + $this->ok = $this->insert_id; + } + // return the table if needed + return $this->table_array; + } +} // end of class diff --git a/www/libs/Class.DB.IO.inc b/www/libs/Class.DB.IO.inc index 0fe09658..66bb73b5 100644 --- a/www/libs/Class.DB.IO.inc +++ b/www/libs/Class.DB.IO.inc @@ -1,1837 +1,1746 @@ XX(qeury)) - * - * PUBLIC VARIABLES - * $class_name - * - the name of the class - * $class_version - * - the version as an array (major, minor, patchlvl, daypatch) - * $class_last_changed - * - date (mysql format) for the last change - * $class_created - * - date this file was created (more or less a fun thing and memory user) - * $class_author - * - me - * $db_name - * - the name of the database connected to - * $db_user - * - the username - * $db_host - * - the hostname (where the DB is located) - * $db_schema - * - what schema to connect to, if not given "public" is used - * $db_encoding - * - automatic convert to this encoding on output, if not set, keeps default db encoding - * $db_port - * - the port to connect to - * $db_type - * - what kind of DB it is (pgsql, mysql, ...) - * $db_ssl - * - for postgresql, what kind of SSL we try (disable, allow, prefer, require), default is allow - * $query - * - sets the SQL query (will be set with the $query parameter from method) - * if u leave the parameter free the class will try to use this var, but this - * method is not so reccomended - * $num_rows - * - the number of rows returned by a SELECT or alterd bei UPDATE/INSERT - * $num_fields - * - the number of fields from the SELECT, is usefull if u do a SELECT * - * $field_names - * - array of field names (in the order of the return) - * $insert_id - * - for INSERT with auto_increment PK, the ID is stored here - * $error_msg - * - all error/debug messages, will be dumped to global $error_msg when db_close() is called - * $to_encoding - * - if this is set, then conversion will be done if needed. [no check yet on wrong encoding] - * - * PRIVATE VARIABLES - * $db_pwd - * - password used for connecting [var might disappear of security reasons] - * $dbh - * - the DBH handler itself. DO NOT OVERWRITE OR CHANGE THIS VARIABLE! - * $db_debug - * - debug flag set via constructor or global $DB_DEBUG var (has to be set before class create) - * $cursor_ext - * - the extended cursor for db_return calls, stores all information (for cached use) - * $cursor - * - the normal cursor (will be filled from db_exec calles) - * $error_id - * - if an error occours this var will be filled, used by _db_error to write error information - * $error_string - * - array with descriptions to error - * $nbsp - * - used for recursive function [var might disappear if I have time to recode the recursive function] - * - * PUBLIC METHODS - * $mixed db_return($query,$reset=0) - * - executes query, returns data & caches it (1 = reset/destroy, 2 = reset/cache, 3 = reset/no cache) - * 1/0 db_cache_reset($query) - * - resets the cache for one query - * _db_io() - * - pseudo deconstructor - functionality moved to db_close - * $string info($show=1) - * - returns a string various info about class (version, authoer, etc), if $show set to 0, it will not be appended to the error_msgs string - * $string db_info($show=1) - * - returns a string with info about db connection, etc, if $show set to 0, it will not be appended to the error_msgs string - * $string db_dump_data($query=0) - * - returns a string with all data of that query or if no query given with all data in the cursor_ext - * 0/$cursor db_exec($query=0) - * - mysql_query wrapper, writes num_rows, num_fields, etc - * $mixed db_fetch_array($cursor=0) - * - mysql_fetch_array, returns a mixed result - * $mixed db_return_row($query) - * - gibt die erste Zeile zurück (als array) - * $array_of_hashes db_return_array($query) - * - return an array of hashes with all data - * db_close() - * - closes db connection and writes error_msg to global error_msg - * db_cursor_pos($query) - * - returns the current position the db_return - * $array_of_hashes db_show_table_meta_Data($table_name) - * - returns an hashed array of table column data - * function db_prepare($stm_name, $query) - * - prepares a query with the given stm name, returns false on error - * function db_execute($stm_name, $data = array()) - * - execute a query that was previously prepared - * $string db_escape_string($string) - * - correctly escapes string for db insert - * $string db_boolean(string) - * - if the string value is 't' or 'f' it returns correct TRUE/FALSE for php - * $primary_key db_write_data($write_array, $not_write_array, $primary_key, $table, $data = array ()) - * - writes into one table based on arrays of columns to write and not write, reads data from global vars or optional array - * $boolean db_set_schema(schema) - * - sets search path to a schema - * $boolean db_set_encoding(encoding) - * - sets an encoding for this database output and input - * $string db_time_format($age/datetime diff, $micro_time = false/true) - * - returns a nice formatted time string based on a age or datetime difference (postgres only), micro time is default false - * - * PRIVATE METHODS - * _db_error() - * - INTERNAL ONLY!! error that occured during execution - * $string _print_array($array) - * - returns string of an array (only for interal use) - * 1/0 _connect_to_db() - * - returns 1 for successfull DB connection or 0 for none - * 1/0 _check_query_for_select($query) - * - checks if the query has select in it, and if not returns 0 (for db_return* methods) - * 1/0 _check_query_for_insert($query) - * - checks if query is INSERT, UPDATE or DELETE - * row _db_convert_encoding($row) - * - converts the array from fetch_row to the correct output encoding if set - * string _db_debug_prepare($prepare_id, $data_array) - * - returns the prepared statement with the actual data. for debug purposes only - * none _db_debug($debug_id, $string, $id, $type) - * - wrapper for normal debug, adds prefix data from id & type and strips all HTML from the query data (color codes, etc) via flag to debug call - * - * HISTORY: - * 2008/10/25 (cs) add db_boolean to fix the postgres to php boolean var problem (TODO: implement this in any select return) - * 2008/07/03 (cs) add db_write_data function, original written for inventory tool "invSQLWriteData" - * 2008/04/16 (cs) add db_escape_string function for correct string escape - * 2007/11/14 (cs) add a prepare debug statement to replace the placeholders with the actual data in a prepared statement - * 2007/01/17 (cs) update db_prepare & db_execute error handling - * 2007/01/11 (cs) add prepare/execute pair (postgres only at the moment) - * 2006/04/03 (cs) added function to return meta data for a table - * 2005/07/19 (cs) add a function to get number for rows for a db cursor - * 2005/07/12 (cs) add named only param to db_return_array - * 2005/07/01 (cs) added db_cursor_pos to return the current pos in the db_return readout - * 2005/06/20 (cs) changed the error msg output from just writing to the var, to using the debug method - * 2005/06/17 (cs) adapted to the new error msg array format. all are to 'db' level - * 2005/03/31 (cs) added echo/print vars to define where to print out the debug messages - * 2004/11/15 (cs) error string is no longer echoed, but returned. methods _db_io changed - * 2004/09/30 (cs) fixed all old layout to new layout - * 2004/09/17 (cs) added the function to automatically convert the encoding to the correct output encoding - * 2004/08/06 (cs) two debug parameters, debug and db_debug - * 2004/07/15 (cs) changed the deconstructor to call _basic deconstructor - * 2003-06-20: added a '3' flag to db_return so NO caching is done at all (if array might get too big) - * 2003-06-19: made the error messages in DEBUG output red so they are better to see - * 2003-06-09: never started class_basic, insert this, for mobile phone detection - * 2003-04-10: moved the error handling out of the db_pgsql.inc back to db_io class - * 2003-04-09: major change as db_io does not hold any DB specific calls anymore, - * those are loaded dynamically during class start, from a include - * (db_dbname ...) - * 2003-03-24: removed/moved some basic vars away from this class to basic class and - * moved init of these vars to constructor - * 2003-02-26: adapted the error_msg var to 1x where 1 is for db_io error - * updated _db_error, moved mysql error printing into this function - * changed the "shape" of class info vars to fit into extend modell - * 2003-02-13: in db_exec the setting for the last insert id was still via the function, - * changed this to call the internal PHP mysql command. - * 2003-01-28: ugly bug within creating the field_names. The array was not reseted - * before, and so the field for the db_exec where not correct. - * 2003-01-16: fixed a "select" check in db_exec, - * added a privet method for checking query of INSERT, UPDATE, DELETE - * 2003-01-09: code cleanups and more inline documentation - * 2003-01-08: renamed db_exec_ext to db_return for obious reasons - * added a "check for select query" for all db_return* methods - * 2003-01-08: db_return gets another functionality: if u use 1 or 2 as reset value, - * the cursor will be reset BEFORE the read and no chaced data will be read. - * if you use 2, the md5 array will be kept so next read with no flag is cached, - * wheres with 1, the data gets DESTROYED at the end of the read - * (this makes the db_cache_reset function a bit obsolete) - * furthermore, the class trys to reconnect (db_exec & db_return) to the DB - * if no dbh was found (from session eg) - * 2003-01-07: fixed a small bug in return_array as he mixed up the order if you used - * SELECT * FROM ... - * 2002-12-26: changed strstr to stristr 'couse not everyone types SELECT, etc in capitals - * 2002-12-24: moved the debug output in db_return to the call if, - * so it is only printed once - * 2002-12-20: added db_dump_data function for printing out all data in - * cursor_ext (or from one query in it) - * 2002-12-20: testing and implemtenting of session storing the class (not fully tested!) - * documenting all the functions and some code cleenup - * 2002-12-19: implemented db_return which executes, returns & caches the query - * 2002-12-18: started idea of putting db_exec and db_fetch_array together - * 2002-12-17: splitted this file. basic db functions kept here, where the - * more complex (array based IO fkts) moved into a seperate file - * 2002-12-16: further reconstruction ... - * 2002-12-10: further improvment in changing db_mysql to a class - * 2002-10-18: renamed lesen to db_read, speichern to db_save and - * loeschen to db_delete - * 19.08.2002: 1 convertiert < > " & ĵ in original - * HTML zeichen zurück (für htmlspecialcharsfct) - * 09.08.2002: speichern() hat einen dritten parameter für - * addslashes (1=ja,0=nein/default) - * 04.04.2002: FK added to lesen() - * 10.07.2001: simple return row function geschrieben - * 03.07.2001: kein Thumbnail erzeugen wenn Datei nicht: - * JPG/JPEG/GIF/PNG als Endung hat - * 22.06.2001: Mozilla Fix für File upload - * 10.05.2001: alle fkt haben "db_" als pre zur identifizierung - * 10.05.2001: kleines problem mit call zu "convert_data" fkt - * 26.04.2001: umschreiben auf classen und einbiden db_io's - * 24.11.2000: erweitern um num_rows - * 23.11.2000: erster Test - *********************************************************************/ +/******************************************************************** +* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) +* CREATED: 2000/11/23 +* VERSION: 4.1.0 +* RELEASED LICENSE: GNU GPL 3 +* SHORT DESCRIPTON: +* 2013/10/10, prepare/excute were added, including auto RETURNING primary key if +* possible for any INSERT query in exec or prepare/execute, better debugging and +* data dumping. Proper string escape wrapper, special db exec writer for complex +* array inserts in auto calls. boolean converter from postresql to php +* +* 2003/12/08, one major change: renamed db_exec_ext to db_return, as it has not +* much in common with the normal db_exec wrapper, as it was written only for +* SELECT statements and better handling of those. +* +* 2002/12/20, extended the "simple" functionality to what I wanted +* to have in first place, with db_return u execute a query and get +* automatically data return which is also cached, which means on next +* call (if not swichted of via paramter) u will no longer exec the DB +* again (save time, etc) but get the data from cache. I also started to +* test session use, but it is not yet fully tested so handle with care if +* you try it ... (session must be started AFTER this class is included, but you +* do not need to start it actually, only if u want to do some real DB calls) +* +* ~2002/12/17, simple wrapper class for mysql php functions. when one query is +* executed (db_exec) a lot of other information os retrieved too, +* like num rows, etc which is needed quite often +* some other functions return one row or one array. all functions +* have build in error support for surpressing PHP errors & warnings +* +* ~2000/11/23, just a function collection for db wrapper, so if you change DB, +* you don't have to worry about your code as long your SQL is erm ... basic ;) +* +* Wrapper functions (via $class->XX(qeury)) +* +* PUBLIC VARIABLES +* $class_name +* - the name of the class +* $class_version +* - the version as an array (major, minor, patchlvl, daypatch) +* $class_last_changed +* - date (mysql format) for the last change +* $class_created +* - date this file was created (more or less a fun thing and memory user) +* $class_author +* - me +* $db_name +* - the name of the database connected to +* $db_user +* - the username +* $db_host +* - the hostname (where the DB is located) +* $db_schema +* - what schema to connect to, if not given "public" is used +* $db_encoding +* - automatic convert to this encoding on output, if not set, keeps default db encoding +* $db_port +* - the port to connect to +* $db_type +* - what kind of DB it is (pgsql, mysql, ...) +* $db_ssl +* - for postgresql, what kind of SSL we try (disable, allow, prefer, require), default is allow +* $query +* - sets the SQL query (will be set with the $query parameter from method) +* if u leave the parameter free the class will try to use this var, but this +* method is not so reccomended +* $num_rows +* - the number of rows returned by a SELECT or alterd bei UPDATE/INSERT +* $num_fields +* - the number of fields from the SELECT, is usefull if u do a SELECT * +* $field_names +* - array of field names (in the order of the return) +* $insert_id +* - for INSERT with auto_increment PK, the ID is stored here +* $error_msg +* - all error/debug messages, will be dumped to global $error_msg when db_close() is called +* $to_encoding +* - if this is set, then conversion will be done if needed. [no check yet on wrong encoding] +* +* PRIVATE VARIABLES +* $db_pwd +* - password used for connecting [var might disappear of security reasons] +* $dbh +* - the DBH handler itself. DO NOT OVERWRITE OR CHANGE THIS VARIABLE! +* $db_debug +* - debug flag set via constructor or global $DB_DEBUG var (has to be set before class create) +* $cursor_ext +* - the extended cursor for db_return calls, stores all information (for cached use) +* $cursor +* - the normal cursor (will be filled from db_exec calles) +* $error_id +* - if an error occours this var will be filled, used by _db_error to write error information +* $error_string +* - array with descriptions to error +* $nbsp +* - used for recursive function [var might disappear if I have time to recode the recursive function] +* +* PUBLIC METHODS +* $mixed db_return($query,$reset=0) +* - executes query, returns data & caches it (1 = reset/destroy, 2 = reset/cache, 3 = reset/no cache) +* 1/0 db_cache_reset($query) +* - resets the cache for one query +* _db_io() +* - pseudo deconstructor - functionality moved to db_close +* $string info($show=1) +* - returns a string various info about class (version, authoer, etc), if $show set to 0, it will not be appended to the error_msgs string +* $string db_info($show=1) +* - returns a string with info about db connection, etc, if $show set to 0, it will not be appended to the error_msgs string +* $string db_dump_data($query=0) +* - returns a string with all data of that query or if no query given with all data in the cursor_ext +* 0/$cursor db_exec($query=0) +* - mysql_query wrapper, writes num_rows, num_fields, etc +* $mixed db_fetch_array($cursor=0) +* - mysql_fetch_array, returns a mixed result +* $mixed db_return_row($query) +* - gibt die erste Zeile zurück (als array) +* $array_of_hashes db_return_array($query) +* - return an array of hashes with all data +* db_close() +* - closes db connection and writes error_msg to global error_msg +* db_cursor_pos($query) +* - returns the current position the db_return +* $array_of_hashes db_show_table_meta_Data($table_name) +* - returns an hashed array of table column data +* function db_prepare($stm_name, $query) +* - prepares a query with the given stm name, returns false on error +* function db_execute($stm_name, $data = array()) +* - execute a query that was previously prepared +* $string db_escape_string($string) +* - correctly escapes string for db insert +* $string db_boolean(string) +* - if the string value is 't' or 'f' it returns correct TRUE/FALSE for php +* $primary_key db_write_data($write_array, $not_write_array, $primary_key, $table, $data = array ()) +* - writes into one table based on arrays of columns to write and not write, reads data from global vars or optional array +* $boolean db_set_schema(schema) +* - sets search path to a schema +* $boolean db_set_encoding(encoding) +* - sets an encoding for this database output and input +* $string db_time_format($age/datetime diff, $micro_time = false/true) +* - returns a nice formatted time string based on a age or datetime difference (postgres only), micro time is default false +* +* PRIVATE METHODS +* _db_error() +* - INTERNAL ONLY!! error that occured during execution +* $string _print_array($array) +* - returns string of an array (only for interal use) +* 1/0 _connect_to_db() +* - returns 1 for successfull DB connection or 0 for none +* 1/0 _check_query_for_select($query) +* - checks if the query has select in it, and if not returns 0 (for db_return* methods) +* 1/0 _check_query_for_insert($query) +* - checks if query is INSERT, UPDATE or DELETE +* row _db_convert_encoding($row) +* - converts the array from fetch_row to the correct output encoding if set +* string _db_debug_prepare($prepare_id, $data_array) +* - returns the prepared statement with the actual data. for debug purposes only +* none _db_debug($debug_id, $string, $id, $type) +* - wrapper for normal debug, adds prefix data from id & type and strips all HTML from the query data (color codes, etc) via flag to debug call +* +* HISTORY: +* 2008/10/25 (cs) add db_boolean to fix the postgres to php boolean var problem (TODO: implement this in any select return) +* 2008/07/03 (cs) add db_write_data function, original written for inventory tool "invSQLWriteData" +* 2008/04/16 (cs) add db_escape_string function for correct string escape +* 2007/11/14 (cs) add a prepare debug statement to replace the placeholders with the actual data in a prepared statement +* 2007/01/17 (cs) update db_prepare & db_execute error handling +* 2007/01/11 (cs) add prepare/execute pair (postgres only at the moment) +* 2006/04/03 (cs) added function to return meta data for a table +* 2005/07/19 (cs) add a function to get number for rows for a db cursor +* 2005/07/12 (cs) add named only param to db_return_array +* 2005/07/01 (cs) added db_cursor_pos to return the current pos in the db_return readout +* 2005/06/20 (cs) changed the error msg output from just writing to the var, to using the debug method +* 2005/06/17 (cs) adapted to the new error msg array format. all are to 'db' level +* 2005/03/31 (cs) added echo/print vars to define where to print out the debug messages +* 2004/11/15 (cs) error string is no longer echoed, but returned. methods _db_io changed +* 2004/09/30 (cs) fixed all old layout to new layout +* 2004/09/17 (cs) added the function to automatically convert the encoding to the correct output encoding +* 2004/08/06 (cs) two debug parameters, debug and db_debug +* 2004/07/15 (cs) changed the deconstructor to call _basic deconstructor +* 2003-06-20: added a '3' flag to db_return so NO caching is done at all (if array might get too big) +* 2003-06-19: made the error messages in DEBUG output red so they are better to see +* 2003-06-09: never started class_basic, insert this, for mobile phone detection +* 2003-04-10: moved the error handling out of the db_pgsql.inc back to db_io class +* 2003-04-09: major change as db_io does not hold any DB specific calls anymore, +* those are loaded dynamically during class start, from a include +* (db_dbname ...) +* 2003-03-24: removed/moved some basic vars away from this class to basic class and +* moved init of these vars to constructor +* 2003-02-26: adapted the error_msg var to 1x where 1 is for db_io error +* updated _db_error, moved mysql error printing into this function +* changed the "shape" of class info vars to fit into extend modell +* 2003-02-13: in db_exec the setting for the last insert id was still via the function, +* changed this to call the internal PHP mysql command. +* 2003-01-28: ugly bug within creating the field_names. The array was not reseted +* before, and so the field for the db_exec where not correct. +* 2003-01-16: fixed a "select" check in db_exec, +* added a privet method for checking query of INSERT, UPDATE, DELETE +* 2003-01-09: code cleanups and more inline documentation +* 2003-01-08: renamed db_exec_ext to db_return for obious reasons +* added a "check for select query" for all db_return* methods +* 2003-01-08: db_return gets another functionality: if u use 1 or 2 as reset value, +* the cursor will be reset BEFORE the read and no chaced data will be read. +* if you use 2, the md5 array will be kept so next read with no flag is cached, +* wheres with 1, the data gets DESTROYED at the end of the read +* (this makes the db_cache_reset function a bit obsolete) +* furthermore, the class trys to reconnect (db_exec & db_return) to the DB +* if no dbh was found (from session eg) +* 2003-01-07: fixed a small bug in return_array as he mixed up the order if you used +* SELECT * FROM ... +* 2002-12-26: changed strstr to stristr 'couse not everyone types SELECT, etc in capitals +* 2002-12-24: moved the debug output in db_return to the call if, +* so it is only printed once +* 2002-12-20: added db_dump_data function for printing out all data in +* cursor_ext (or from one query in it) +* 2002-12-20: testing and implemtenting of session storing the class (not fully tested!) +* documenting all the functions and some code cleenup +* 2002-12-19: implemented db_return which executes, returns & caches the query +* 2002-12-18: started idea of putting db_exec and db_fetch_array together +* 2002-12-17: splitted this file. basic db functions kept here, where the +* more complex (array based IO fkts) moved into a seperate file +* 2002-12-16: further reconstruction ... +* 2002-12-10: further improvment in changing db_mysql to a class +* 2002-10-18: renamed lesen to db_read, speichern to db_save and +* loeschen to db_delete +* 19.08.2002: 1 convertiert < > " & ĵ in original +* HTML zeichen zurück (für htmlspecialcharsfct) +* 09.08.2002: speichern() hat einen dritten parameter für +* addslashes (1=ja,0=nein/default) +* 04.04.2002: FK added to lesen() +* 10.07.2001: simple return row function geschrieben +* 03.07.2001: kein Thumbnail erzeugen wenn Datei nicht: +* JPG/JPEG/GIF/PNG als Endung hat +* 22.06.2001: Mozilla Fix für File upload +* 10.05.2001: alle fkt haben "db_" als pre zur identifizierung +* 10.05.2001: kleines problem mit call zu "convert_data" fkt +* 26.04.2001: umschreiben auf classen und einbiden db_io's +* 24.11.2000: erweitern um num_rows +* 23.11.2000: erster Test +*********************************************************************/ - // try to include file from LIBS path, or from normal path - _spl_autoload('Class.Basic.inc'); +// try to include file from LIBS path, or from normal path +_spl_autoload('Class.Basic.inc'); - class db_io extends basic +class db_io extends basic +{ + // recommend to set private/protected and only allow setting via method + // can bet set from outside + // encoding to + public $to_encoding = ''; + public $query; // the query string at the moment + // only inside + // basic vars + private $dbh; // the dbh handler + public $db_debug; // DB_DEBUG ... (if set prints out debug msgs) + private $db_name; // the DB connected to + private $db_user; // the username used + private $db_pwd; // the password used + private $db_host; // the hostname + private $db_port; // default db port + private $db_schema; // optional DB schema, if not set uses public + private $db_encoding; // optional auto encoding convert, not used if not set + private $db_type; // type of db (mysql,postgres,...) + private $db_ssl; // ssl flag (for postgres only), disable, allow, prefer, require + // FOR BELOW: (This should be private and only readable through some method) + // cursor array for cached readings + public $cursor_ext; // hash of hashes + // per query vars + public $cursor; // actual cursor (DBH) + public $num_rows; // how many rows have been found + public $num_fields; // how many fields has the query + public $field_names; // array with the field names of the current query + public $insert_id; // last inserted ID + public $insert_id_ext; // extended insert ID (for data outside only primary key) + // other vars + private $nbsp = ''; // used by print_array recursion function + // error & warning id + private $error_id; + private $warning_id; + // sub include with the database functions + private $db_functions; + + // endless loop protection + private $MAX_QUERY_CALL; + private $query_called = array (); + // error string + private $error_string = array (); + // prepared list + public $prepare_cursor = array (); + // primary key per table list + // format is 'table' => 'pk_name' + public $pk_name_table = array (); + // internal primary key name, for cross calls in async + public $pk_name; + // if we use RETURNING in the INSERT call + private $returning_id = false; + // if a sync is running holds the md5 key of the query + private $async_running; + + // METHOD __construct + // PARAMS db_config -> array with db, user, password & host + // debug -> turns debugging output on or of (default 0), + // debugging can also be triggerd via DB_DEBUG var on global level + // RETURN nothing + // DESC constructor for db_clss + public function __construct($db_config, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) { - // recommend to set private/protected and only allow setting via method - // can bet set from outside - // encoding to - public $to_encoding = ''; - public $query; // the query string at the moment - // only inside - // basic vars - private $dbh; // the dbh handler - public $db_debug; // DB_DEBUG ... (if set prints out debug msgs) - private $db_name; // the DB connected to - private $db_user; // the username used - private $db_pwd; // the password used - private $db_host; // the hostname - private $db_port; // default db port - private $db_schema; // optional DB schema, if not set uses public - private $db_encoding; // optional auto encoding convert, not used if not set - private $db_type; // type of db (mysql,postgres,...) - private $db_ssl; // ssl flag (for postgres only), disable, allow, prefer, require - // FOR BELOW: (This should be private and only readable through some method) - // cursor array for cached readings - public $cursor_ext; // hash of hashes - // per query vars - public $cursor; // actual cursor (DBH) - public $num_rows; // how many rows have been found - public $num_fields; // how many fields has the query - public $field_names; // array with the field names of the current query - public $insert_id; // last inserted ID - public $insert_id_ext; // extended insert ID (for data outside only primary key) - // other vars - private $nbsp = ''; // used by print_array recursion function - // error & warning id - private $error_id; - private $warning_id; - // sub include with the database functions - private $db_functions; + // start basic class + parent::__construct($debug, $echo, $print); + // sets the names (for connect/reconnect) + $this->db_name = $db_config['db_name']; + $this->db_user = $db_config['db_user']; + $this->db_pwd = $db_config['db_pass']; + $this->db_host = $db_config['db_host']; + $this->db_port = array_key_exists('db_port', $db_config) ? $db_config['db_port'] : '5432'; + $this->db_schema = array_key_exists('db_schema', $db_config) ? $db_config['db_schema'] : ''; // do not set to 'public' if not set, because the default is already public + $this->db_encoding = array_key_exists('db_encoding', $db_config) ? $db_config['db_encoding'] : ''; + $this->db_type = 'db_'.$db_config['db_type']; + $this->db_ssl = array_key_exists('db_ssl', $db_config) ? $db_config['db_ssl'] : 'allow'; - // endless loop protection - private $MAX_QUERY_CALL; - private $query_called = array (); - // error string - private $error_string = array (); - // prepared list - public $prepare_cursor = array (); - // primary key per table list - // format is 'table' => 'pk_name' - public $pk_name_table = array (); - // internal primary key name, for cross calls in async - public $pk_name; - // if we use RETURNING in the INSERT call - private $returning_id = false; - // if a sync is running holds the md5 key of the query - private $async_running; + // set the target encoding to the DEFAULT_ENCODING if it is one of them: EUC, Shift_JIS, UTF-8 + // @ the moment set only from outside - // METHOD __construct - // PARAMS db_config -> array with db, user, password & host - // debug -> turns debugging output on or of (default 0), - // debugging can also be triggerd via DB_DEBUG var on global level - // RETURN nothing - // DESC constructor for db_clss - public function __construct($db_config, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) - { - // start basic class - parent::__construct($debug, $echo, $print); - // sets the names (for connect/reconnect) - $this->db_name = $db_config['db_name']; - $this->db_user = $db_config['db_user']; - $this->db_pwd = $db_config['db_pass']; - $this->db_host = $db_config['db_host']; - $this->db_port = array_key_exists('db_port', $db_config) ? $db_config['db_port'] : '5432'; - $this->db_schema = array_key_exists('db_schema', $db_config) ? $db_config['db_schema'] : ''; // do not set to 'public' if not set, because the default is already public - $this->db_encoding = array_key_exists('db_encoding', $db_config) ? $db_config['db_encoding'] : ''; - $this->db_type = 'db_'.$db_config['db_type']; - $this->db_ssl = array_key_exists('db_ssl', $db_config) ? $db_config['db_ssl'] : 'allow'; + // set loop protection max count + $this->MAX_QUERY_CALL = 20; - // set the target encoding to the DEFAULT_ENCODING if it is one of them: EUC, Shift_JIS, UTF-8 - // @ the moment set only from outside + // error & debug stuff, error & warning ids are the same, its just in which var they get written + $this->error_string['11'] = 'No Querystring given'; + $this->error_string['12'] = 'No Cursor given, no correct query perhaps?'; + $this->error_string['13'] = 'Query could not be executed without errors'; + $this->error_string['14'] = 'Can\'t connect to DB server'; + $this->error_string['15'] = 'Can\'t select DB'; + $this->error_string['16'] = 'No DB Handler found / connect or reconnect failed'; + $this->error_string['17'] = 'All db_return* methods work only with SELECT statements, please use db_exec for everything else'; + $this->error_string['18'] = 'Query not found in cache. Nothing has been reset'; + $this->error_string['19'] = 'Wrong PK name given or no PK name given at all, can\'t get Insert ID'; + $this->error_string['20'] = 'Found given Prepare Statement Name in array, Query not prepared, will use existing one'; + $this->error_string['21'] = 'Query Prepare failed'; + $this->error_string['22'] = 'Query Execute failed'; + $this->error_string['23'] = 'Query Execute failed, data array does not match placeholders'; + $this->error_string['24'] = 'Missing prepared query entry for execute.'; + $this->error_string['25'] = 'Prepare query data is not in array format.'; + $this->error_string['30'] = 'Query call in a possible endless loop. Was called more than '.$this->MAX_QUERY_CALL.' times'; + $this->error_string['31'] = 'Could not fetch PK after query insert'; + $this->error_string['32'] = 'Multiple PK return as array'; + $this->error_string['33'] = 'Returning PK was not found'; + $this->error_string['40'] = 'Query async call failed.'; + $this->error_string['41'] = 'Connection is busy with a different query. Cannot execute.'; + $this->error_string['42'] = 'Cannot check for async query, none has been started yet.'; - // set loop protection max count - $this->MAX_QUERY_CALL = 20; + // set debug, either via global var, or debug var during call + $this->db_debug = $db_debug; + // global overrules local + if (isset($GLOBALS['DB_DEBUG'])) { + $this->db_debug = $GLOBALS['DB_DEBUG']; + } - // error & debug stuff, error & warning ids are the same, its just in which var they get written - $this->error_string['11'] = 'No Querystring given'; - $this->error_string['12'] = 'No Cursor given, no correct query perhaps?'; - $this->error_string['13'] = 'Query could not be executed without errors'; - $this->error_string['14'] = 'Can\'t connect to DB server'; - $this->error_string['15'] = 'Can\'t select DB'; - $this->error_string['16'] = 'No DB Handler found / connect or reconnect failed'; - $this->error_string['17'] = 'All db_return* methods work only with SELECT statements, please use db_exec for everything else'; - $this->error_string['18'] = 'Query not found in cache. Nothing has been reset'; - $this->error_string['19'] = 'Wrong PK name given or no PK name given at all, can\'t get Insert ID'; - $this->error_string['20'] = 'Found given Prepare Statement Name in array, Query not prepared, will use existing one'; - $this->error_string['21'] = 'Query Prepare failed'; - $this->error_string['22'] = 'Query Execute failed'; - $this->error_string['23'] = 'Query Execute failed, data array does not match placeholders'; - $this->error_string['24'] = 'Missing prepared query entry for execute.'; - $this->error_string['25'] = 'Prepare query data is not in array format.'; - $this->error_string['30'] = 'Query call in a possible endless loop. Was called more than '.$this->MAX_QUERY_CALL.' times'; - $this->error_string['31'] = 'Could not fetch PK after query insert'; - $this->error_string['32'] = 'Multiple PK return as array'; - $this->error_string['33'] = 'Returning PK was not found'; - $this->error_string['40'] = 'Query async call failed.'; - $this->error_string['41'] = 'Connection is busy with a different query. Cannot execute.'; - $this->error_string['42'] = 'Cannot check for async query, none has been started yet.'; + // includes sub class for db type + _spl_autoload($this->db_type.'.inc'); + $this->db_functions = new $this->db_type(); - // set debug, either via global var, or debug var during call - $this->db_debug = $db_debug; - // global overrules local - if (isset($GLOBALS['DB_DEBUG'])) - $this->db_debug = $GLOBALS['DB_DEBUG']; + // connect to DB + if (!$this->_connect_to_db()) { + $this->error_id = 16; + $this->_db_error(); + return false; + } - // includes sub class for db type - _spl_autoload($this->db_type.'.inc'); - $this->db_functions = new $this->db_type(); + $this->class_info['db_io']=array( + 'class_name' => 'DB IO', + 'class_version' => '4.1.0', + 'class_created' => '2000-11-23', + 'class_author' => 'Clemens Schwaighofer' + ); + } - // connect to DB - if (!$this->_connect_to_db()) - { + // METHOD: __destruct + // PARAMS: none + // RETURN: none + // DESC: final desctruct method, closes the DB connection + public function __destruct() + { + $this->_close_db(); + parent::__destruct(); + } + + // ************************************************************* + // PRIVATE METHODS + // ************************************************************* + + // METHOD: _connect_to_db + // PARAMS: none + // RETURN: true on successfull connect, false if failed + // DESC: + // internal connection function. Used to connect to the DB if there is no connection done yet. + // Called before any execute + private function _connect_to_db() + { + // generate connect string + $this->dbh = $this->db_functions->_db_connect($this->db_host, $this->db_user, $this->db_pwd, $this->db_name, $this->db_port, $this->db_ssl); + // if no dbh here, we couldn't connect to the DB itself + if (!$this->dbh) { + $this->error_id = 14; + $this->_db_error(); + return false; + } + // 15 error (cant select to DB is not valid in postgres, as connect is different) + // if returns 0 we couldn't select the DB + if ($this->dbh == -1) { + $this->error_id = 15; + $this->_db_error(); + return false; + } + // set search path if needed + if ($this->db_schema) { + $this->db_set_schema(); + } + // set client encoding + if ($this->db_encoding) { + $this->db_set_encoding(); + } + // all okay + return true; + } + + // METHOD: _close_db + // PARAMS: none + // RETURN: none + // DESC : close db connection + // only used by the deconstructor + private function _close_db() + { + if (isset($this->dbh) && $this->dbh) { + $this->db_functions->_db_close(); + unset($this->dbh); + } + } + + // METHOS: _check_query_for_select + // PARAMS: query + // RETURN: true if matching, false if not + // DESC : checks if query is a SELECT, if not error, 0 return + // : NOTE: Query needs to start with SELECT. if starts with "with" it is ignored + private function _check_query_for_select($query) + { + // perhaps allow spaces before select ?!? + if (!preg_match("/^select /i", $query)) { + return false; + } + return true; + } + + // METHOD: _check_query_for_insert + // PARAMS: query, pure flag (boolean) + // RETURN: true if matching, flase if not + // DESC : check for DELETE, INSERT, UPDATE + // : if pure is set to true, only when INSERT is set will return true + // : NOTE: Queries need to start with INSERT, UPDATE, DELETE. Anything else is ignored + private function _check_query_for_insert($query, $pure = false) + { + if (!preg_match("/^insert /i", $query) && !preg_match("/^update /i", $query) && !preg_match("/^delete /i", $query)) { + return false; + } + if (!$pure) { + return true; + } elseif (preg_match("/^insert /i", $query)) { + return true; + } else { + return false; + } + } + + // METHOD: _print_array + // PARAMS: array to print + // RETURN: string with printed and formated array + // DESC : internal funktion that creates the array + // : used in db_dump_data only + private function _print_array($array) + { + while (list($key, $value) = each($array)) { + $string .= $this->nbsp.''.$key.' => '; + if (is_array($value)) { + $this->nbsp .= '   '; + $string .= '
'; + $string .= $this->_print_array($value); + } else { + $string .= $value.'
'; + } + } + $this->nbsp = substr_replace($this->nbsp, '', -18, 18); + return $string; + } + + // METHOD _db_debug + // PARAMS debug_id -> group id for debug + // error_string -> error message or debug data + // id -> db debug group + // type -> query identifiery (Q, I, etc) + // RETURN none + // DESC calls the basic class debug with strip command + private function _db_debug($debug_id, $error_string, $id = '', $type = '') + { + $prefix = ''; + if ($id) { + $prefix .= '['.$id.'] '; + } + if ($type) { + $prefix .= '{'.$type.'} '; + } + if ($prefix) { + $prefix .= '- '; + } + $this->debug($debug_id, $prefix.$error_string, true); + } + + // METHOD _db_error + // PARAMS cursor -> current cursor for pg_result_error, mysql uses dbh, pg_last_error too, + // but pg_result_error is more accurate + // msg -> optional message + // RETURN none + // DESC if error_id set, writes long error string into error_msg + // MARK: needed to make public so it can be called from DB.Array.IO too + public function _db_error($cursor = '', $msg = '') + { + $where_called = $this->get_caller_method(); + if ($cursor) { + $pg_error_string = $this->db_functions->_db_print_error($cursor); + } + if (!$cursor) { + $pg_error_string = $this->db_functions->_db_print_error(); + } + if ($pg_error_string) { + $this->_db_debug('db', $pg_error_string, 'DB_ERROR', $where_called); + } + // okay, an error occured + if ($this->error_id) { + // write error msg ... + $this->_db_debug('db', 'DB-Error '.$this->error_id.': '.$this->error_string[$this->error_id].($msg ? ', '.$msg : '').'', 'DB_ERROR', $where_called); + $this->had_error = $this->error_id; + // write detailed error log + } + if ($this->warning_id) { + $this->_db_debug('db', 'DB-Warning '.$this->warning_id.': '.$this->error_string[$this->warning_id].($msg ? ', '.$msg : '').'', 'DB_ERROR', $where_called); + $this->had_warning = $this->warning_id; + } + // unset the error/warning vars + $this->error_id = 0; + $this->warning_id = 0; + } + + // METHOD _db_convert_encoding + // PARAMS array from fetch_row + // RETURN convert fetch_row array + // DESC if there is the 'to_encoding' var set, and the field is in the wrong encoding converts it to the target + private function _db_convert_encoding($row) + { + if ($this->to_encoding && $this->db_encoding) { + // go through each row and convert the encoding if needed + for ($i = 0; $i < $this->num_fields; $i ++) { + $from_encoding = mb_detect_encoding($row[$i]); + // convert only if encoding doesn't match and source is not pure ASCII + if ($from_encoding != $this->to_encoding && $from_encoding != 'ASCII') { + $row[$i] = mb_convert_encoding($row[$i], $this->to_encoding, $from_encoding); + } + } + } + return $row; + } + + // METHOD _db_debug_prepare + // PARAMS $stm_name, data array + // RETURN query in prepared form + // DESC for debug purpose replaces $1, $2, etc with actual data + private function _db_debug_prepare($stm_name, $data = array()) + { + // get the keys from data array + $keys = array_keys($data); + // because the placeholders start with $ and at 1, we need to increase each key and prefix it with a $ char + for ($i = 0; $i < count($keys); $i ++) { + $keys[$i] = '$'.($keys[$i] + 1); + } + // simply replace the $1, $2, ... with the actual data and return it + return str_replace(array_reverse($keys), array_reverse($data), $this->prepare_cursor[$stm_name]['query']); + } + + // METHOD _db_return_table + // PARAMS insert/select/update/delete query + // RETURN array with schema and table + // DESC extracts schema and table from the query, if no schema returns just empty string + private function _db_return_table($query) + { + if (preg_match("/^SELECT /i", $query)) { + preg_match("/ (FROM) (([\w_]+)\.)?([\w_]+) /i", $query, $matches); + } else { + preg_match("/(INSERT INTO|DELETE FROM|UPDATE) (([\w_]+)\.)?([\w_]+) /i", $query, $matches); + } + return array($matches[3], $matches[4]); + } + + // METHOD _db_prepare_exec + // PARAMS query, primary key [if set to NULL no returning will be added] + // RETURN md5 OR boolean false on error + // DESC sub function for db_exec and db_exec_async + // * checks query is set + // * checks there is a database handler + // * checks that here is no other query executing + // * checks for insert if returning is set/pk name + // * sets internal md5 for query + // * checks multiple call count + private function _db_prepare_exec($query, $pk_name) + { + // to either use the returning method or the guess method for getting primary keys + $this->returning_id = false; + // set the query + if ($query) { + $this->query = $query; + } + if (!$this->query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + // if no DB Handler drop out + if (!$this->dbh) { + // if reconnect fails drop out + if (!$this->_connect_to_db()) { $this->error_id = 16; $this->_db_error(); return false; } - - $this->class_info['db_io']=array( - 'class_name' => 'DB IO', - 'class_version' => '4.1.0', - 'class_created' => '2000-11-23', - 'class_author' => 'Clemens Schwaighofer' - ); } - - // METHOD: __destruct - // PARAMS: none - // RETURN: none - // DESC: final desctruct method, closes the DB connection - public function __destruct() - { - $this->_close_db(); - parent::__destruct(); + // check that no other query is running right now + if ($this->db_functions->_db_connection_busy()) { + $this->error_id = 41; + $this->_db_error(); + return false; } - - // ************************************************************* - // PRIVATE METHODS - // ************************************************************* - - // METHOD: _connect_to_db - // PARAMS: none - // RETURN: true on successfull connect, false if failed - // DESC: - // internal connection function. Used to connect to the DB if there is no connection done yet. - // Called before any execute - private function _connect_to_db() - { - // generate connect string - $this->dbh = $this->db_functions->_db_connect($this->db_host, $this->db_user, $this->db_pwd, $this->db_name, $this->db_port, $this->db_ssl); - // if no dbh here, we couldn't connect to the DB itself - if (!$this->dbh) - { - $this->error_id = 14; + // if we do have an insert, check if there is no RETURNING pk_id, add it if I can get the PK id + if ($this->_check_query_for_insert($this->query, true)) { + $this->pk_name = $pk_name; + if ($this->pk_name != 'NULL') { + if (!$this->pk_name) { + // TODO: get primary key from table name + list($schema, $table) = $this->_db_return_table($this->query); + if (!array_key_exists($table, $this->pk_name_table) || !$this->pk_name_table[$table]) { + $this->pk_name_table[$table] = $this->db_functions->_db_primary_key($table, $schema); + } + $this->pk_name = $this->pk_name_table[$table] ? $this->pk_name_table[$table] : 'NULL'; + } + if (!preg_match("/ returning /i", $this->query) && $this->pk_name && $this->pk_name != 'NULL') { + // check if this query has a ; at the end and remove it + $this->query = preg_replace("/(;\s*)$/", '', $this->query); + $this->query .= " RETURNING ".$this->pk_name; + $this->returning_id = true; + } elseif (preg_match("/ returning (.*)/i", $this->query, $matches) && $this->pk_name && $this->pk_name != 'NULL') { + // add the primary key if it is not in the returning set + if (!preg_match("/$this->pk_name/", $matches[1])) { + $this->query .= " , ".$this->pk_name; + } + $this->returning_id = true; + } + } + } + // for DEBUG, only on first time ;) + if ($this->db_debug) { + $this->_db_debug('db', $this->query, '_db_prepare_exec', 'Q'); + } + // import protection, md5 needed + $md5 = md5($this->query); + // if the array index does not exists set it 0 + if (!array_key_exists($md5, $this->query_called)) { + $this->query_called[$md5] = 0; + } + // if the array index exists, but it is not a numeric one, set it to 0 + if (!is_numeric($this->query_called[$md5])) { + $this->query_called[$md5] = 0; + } + // count up the run, if this is run more than the max_run then exit with error + if ($this->query_called[$md5] > $this->MAX_QUERY_CALL) { + $this->error_id = 30; $this->_db_error(); - return false; - } - // 15 error (cant select to DB is not valid in postgres, as connect is different) - // if returns 0 we couldn't select the DB - if ($this->dbh == -1) - { - $this->error_id = 15; - $this->_db_error(); - return false; - } - // set search path if needed - if ($this->db_schema) - { - $this->db_set_schema(); - } - // set client encoding - if ($this->db_encoding) - { - $this->db_set_encoding(); - } - // all okay - return true; - } - - // METHOD: _close_db - // PARAMS: none - // RETURN: none - // DESC : close db connection - // only used by the deconstructor - private function _close_db() - { - if (isset($this->dbh) && $this->dbh) - { - $this->db_functions->_db_close(); - unset($this->dbh); - } - } - - // METHOS: _check_query_for_select - // PARAMS: query - // RETURN: true if matching, false if not - // DESC : checks if query is a SELECT, if not error, 0 return - // : NOTE: Query needs to start with SELECT. if starts with "with" it is ignored - private function _check_query_for_select($query) - { - // perhaps allow spaces before select ?!? - if (!preg_match("/^select /i", $query)) - { - return false; - } - return true; - } - - // METHOD: _check_query_for_insert - // PARAMS: query, pure flag (boolean) - // RETURN: true if matching, flase if not - // DESC : check for DELETE, INSERT, UPDATE - // : if pure is set to true, only when INSERT is set will return true - // : NOTE: Queries need to start with INSERT, UPDATE, DELETE. Anything else is ignored - private function _check_query_for_insert($query, $pure = FALSE) - { - if (!preg_match("/^insert /i", $query) && !preg_match("/^update /i", $query) && !preg_match("/^delete /i", $query)) - { - return false; - } - if (!$pure) - return true; - elseif (preg_match("/^insert /i", $query)) - return true; - else + $this->_db_debug('db', $this->query, 'db_exec', 'Q[nc]'); return false; } + $this->query_called[$md5] ++; + // return md5 + return $md5; + } - // METHOD: _print_array - // PARAMS: array to print - // RETURN: string with printed and formated array - // DESC : internal funktion that creates the array - // : used in db_dump_data only - private function _print_array($array) - { - while (list($key, $value) = each($array)) - { - $string .= $this->nbsp.''.$key.' => '; - if (is_array($value)) - { - $this->nbsp .= '   '; - $string .= '
'; - $string .= $this->_print_array($value); - } else - { - $string .= $value.'
'; + // METHOD _db_post_exec + // PARAMS none + // RETURN true on success or false if an error occured + // DESC runs post execute for rows affected, field names, inserted primary key, etc + private function _db_post_exec() + { + // if FALSE returned, set error stuff + // if either the cursor is false + if (!$this->cursor || $this->db_functions->_db_last_error_query()) { + // printout Query if debug is turned on + if ($this->db_debug) { + $this->_db_debug('db', $this->query, 'db_exec', 'Q[nc]'); + } + // internal error handling + $this->error_id = 13; + $this->_db_error($this->cursor); + return false; + } else { + // if SELECT do here ... + if ($this->_check_query_for_select($this->query)) { + // count the rows returned (if select) + $this->num_rows = $this->db_functions->_db_num_rows($this->cursor); + // count the fields + $this->num_fields = $this->db_functions->_db_num_fields($this->cursor); + // set field names + unset($this->field_names); + for ($i = 0; $i < $this->num_fields; $i ++) { + $this->field_names[] = $this->db_functions->_db_field_name($this->cursor, $i); } - } - $this->nbsp = substr_replace($this->nbsp, '', -18, 18); - return $string; - } - - // METHOD _db_debug - // PARAMS debug_id -> group id for debug - // error_string -> error message or debug data - // id -> db debug group - // type -> query identifiery (Q, I, etc) - // RETURN none - // DESC calls the basic class debug with strip command - private function _db_debug($debug_id, $error_string, $id = '', $type = '') - { - $prefix = ''; - if ($id) - $prefix .= '['.$id.'] '; - if ($type) - $prefix .= '{'.$type.'} '; - if ($prefix) - $prefix .= '- '; - $this->debug($debug_id, $prefix.$error_string, true); - } - - // METHOD _db_error - // PARAMS cursor -> current cursor for pg_result_error, mysql uses dbh, pg_last_error too, - // but pg_result_error is more accurate - // msg -> optional message - // RETURN none - // DESC if error_id set, writes long error string into error_msg - // MARK: needed to make public so it can be called from DB.Array.IO too - public function _db_error($cursor = '', $msg = '') - { - $where_called = $this->get_caller_method(); - if ($cursor) - $pg_error_string = $this->db_functions->_db_print_error($cursor); - if (!$cursor) - $pg_error_string = $this->db_functions->_db_print_error(); - if ($pg_error_string) - $this->_db_debug('db', $pg_error_string, 'DB_ERROR', $where_called); - // okay, an error occured - if ($this->error_id) - { - // write error msg ... - $this->_db_debug('db', 'DB-Error '.$this->error_id.': '.$this->error_string[$this->error_id].($msg ? ', '.$msg : '').'', 'DB_ERROR', $where_called); - $this->had_error = $this->error_id; - // write detailed error log - } - if ($this->warning_id) - { - $this->_db_debug('db', 'DB-Warning '.$this->warning_id.': '.$this->error_string[$this->warning_id].($msg ? ', '.$msg : '').'', 'DB_ERROR', $where_called); - $this->had_warning = $this->warning_id; - } - // unset the error/warning vars - $this->error_id = 0; - $this->warning_id = 0; - } - - // METHOD _db_convert_encoding - // PARAMS array from fetch_row - // RETURN convert fetch_row array - // DESC if there is the 'to_encoding' var set, and the field is in the wrong encoding converts it to the target - private function _db_convert_encoding($row) - { - if ($this->to_encoding && $this->db_encoding) - { - // go through each row and convert the encoding if needed - for ($i = 0; $i < $this->num_fields; $i ++) - { - $from_encoding = mb_detect_encoding($row[$i]); - // convert only if encoding doesn't match and source is not pure ASCII - if ($from_encoding != $this->to_encoding && $from_encoding != 'ASCII') - { - $row[$i] = mb_convert_encoding($row[$i], $this->to_encoding, $from_encoding); - } - } - } - return $row; - } - - // METHOD _db_debug_prepare - // PARAMS $stm_name, data array - // RETURN query in prepared form - // DESC for debug purpose replaces $1, $2, etc with actual data - private function _db_debug_prepare($stm_name, $data = array()) - { - // get the keys from data array - $keys = array_keys($data); - // because the placeholders start with $ and at 1, we need to increase each key and prefix it with a $ char - for ($i = 0; $i < count($keys); $i ++) - { - $keys[$i] = '$'.($keys[$i] + 1); - } - // simply replace the $1, $2, ... with the actual data and return it - return str_replace(array_reverse($keys), array_reverse($data), $this->prepare_cursor[$stm_name]['query']); - } - - // METHOD _db_return_table - // PARAMS insert/select/update/delete query - // RETURN array with schema and table - // DESC extracts schema and table from the query, if no schema returns just empty string - private function _db_return_table($query) - { - if (preg_match("/^SELECT /i", $query)) - preg_match("/ (FROM) (([\w_]+)\.)?([\w_]+) /i", $query, $matches); - else - preg_match("/(INSERT INTO|DELETE FROM|UPDATE) (([\w_]+)\.)?([\w_]+) /i", $query, $matches); - return array($matches[3], $matches[4]); - } - - // METHOD _db_prepare_exec - // PARAMS query, primary key [if set to NULL no returning will be added] - // RETURN md5 OR boolean false on error - // DESC sub function for db_exec and db_exec_async - // * checks query is set - // * checks there is a database handler - // * checks that here is no other query executing - // * checks for insert if returning is set/pk name - // * sets internal md5 for query - // * checks multiple call count - private function _db_prepare_exec($query, $pk_name) - { - // to either use the returning method or the guess method for getting primary keys - $this->returning_id = false; - // set the query - if ($query) - $this->query = $query; - if (!$this->query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - // if no DB Handler drop out - if (!$this->dbh) - { - // if reconnect fails drop out - if (!$this->_connect_to_db()) - { - $this->error_id = 16; - $this->_db_error(); - return false; - } - } - // check that no other query is running right now - if ($this->db_functions->_db_connection_busy()) - { - $this->error_id = 41; - $this->_db_error(); - return false; - } - // if we do have an insert, check if there is no RETURNING pk_id, add it if I can get the PK id - if ($this->_check_query_for_insert($this->query, true)) - { - $this->pk_name = $pk_name; - if ($this->pk_name != 'NULL') - { - if (!$this->pk_name) - { - // TODO: get primary key from table name - list($schema, $table) = $this->_db_return_table($this->query); - if (!array_key_exists($table, $this->pk_name_table) || !$this->pk_name_table[$table]) - { - $this->pk_name_table[$table] = $this->db_functions->_db_primary_key($table, $schema); - } - $this->pk_name = $this->pk_name_table[$table] ? $this->pk_name_table[$table] : 'NULL'; - } - if (!preg_match("/ returning /i", $this->query) && $this->pk_name && $this->pk_name != 'NULL') - { - // check if this query has a ; at the end and remove it - $this->query = preg_replace("/(;\s*)$/", '', $this->query); - $this->query .= " RETURNING ".$this->pk_name; - $this->returning_id = true; - } - elseif (preg_match("/ returning (.*)/i", $this->query, $matches) && $this->pk_name && $this->pk_name != 'NULL') - { - // add the primary key if it is not in the returning set - if (!preg_match("/$this->pk_name/", $matches[1])) - { - $this->query .= " , ".$this->pk_name; - } - $this->returning_id = true; - } - } - } - // for DEBUG, only on first time ;) - if ($this->db_debug) - $this->_db_debug('db', $this->query, '_db_prepare_exec', 'Q'); - // import protection, md5 needed - $md5 = md5($this->query); - // if the array index does not exists set it 0 - if (!array_key_exists($md5, $this->query_called)) - $this->query_called[$md5] = 0; - // if the array index exists, but it is not a numeric one, set it to 0 - if (!is_numeric($this->query_called[$md5])) - $this->query_called[$md5] = 0; - // count up the run, if this is run more than the max_run then exit with error - if ($this->query_called[$md5] > $this->MAX_QUERY_CALL) - { - $this->error_id = 30; - $this->_db_error(); - $this->_db_debug('db', $this->query, 'db_exec', 'Q[nc]'); - return false; - } - $this->query_called[$md5] ++; - // return md5 - return $md5; - } - - // METHOD _db_post_exec - // PARAMS none - // RETURN true on success or false if an error occured - // DESC runs post execute for rows affected, field names, inserted primary key, etc - private function _db_post_exec() - { - // if FALSE returned, set error stuff - // if either the cursor is false - if (!$this->cursor || $this->db_functions->_db_last_error_query()) - { - // printout Query if debug is turned on - if ($this->db_debug) - $this->_db_debug('db', $this->query, 'db_exec', 'Q[nc]'); - // internal error handling - $this->error_id = 13; - $this->_db_error($this->cursor); - return false; - } - else - { - // if SELECT do here ... - if ($this->_check_query_for_select($this->query)) - { - // count the rows returned (if select) - $this->num_rows = $this->db_functions->_db_num_rows($this->cursor); - // count the fields - $this->num_fields = $this->db_functions->_db_num_fields($this->cursor); - // set field names - unset($this->field_names); - for ($i = 0; $i < $this->num_fields; $i ++) - { - $this->field_names[] = $this->db_functions->_db_field_name($this->cursor, $i); - } - } - else if ($this->_check_query_for_insert($this->query)) - { - // if not select do here - // count affected rows - $this->num_rows = $this->db_functions->_db_affected_rows($this->cursor); - if ($this->_check_query_for_insert($this->query, true) && $this->pk_name != 'NULL') - { - // set insert_id - // if we do not have a returning, we try to get it via the primary key and another select - if (!$this->returning_id) - { - $this->insert_id = $this->db_functions->_db_insert_id($this->query, $this->pk_name); - } - else - { - $this->insert_id = array (); - $this->insert_id_ext = array (); -// echo "** PREPARE RETURNING FOR CURSOR: ".$this->cursor."
"; - // we have returning, now we need to check if we get one or many returned - // we'll need to loop this, if we have multiple insert_id returns - while ($_insert_id = $this->db_functions->_db_fetch_array($this->cursor, PGSQL_ASSOC)) - { -// echo "*** RETURNING: ".print_r($_insert_id, 1)."
"; - $this->insert_id[] = $_insert_id; - } - // if we have only one, revert from array to single - if (count($this->insert_id) == 1) - { -// echo "* SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->pk_name, $this->insert_id[0])."
"; -// echo "* PK DIRECT: ".$this->insert_id[0][$this->pk_name]."
"; - // if this has only the pk_name, then only return this, else array of all data (but without the position) - // example if insert_id[0]['foo'] && insert_id[0]['bar'] it will become insert_id['foo'] & insert_id['bar'] - // if only ['foo_id'] and it is the PK then the PK is directly written to the insert_id - if (count($this->insert_id[0]) > 1 || !array_key_exists($this->pk_name, $this->insert_id[0])) - { - $this->insert_id_ext = $this->insert_id[0]; - $this->insert_id = $this->insert_id[0][$this->pk_name]; - } - elseif ($this->insert_id[0][$this->pk_name]) - { - $this->insert_id = $this->insert_id[0][$this->pk_name]; - } - } - // if we have non -> error - elseif (count($this->insert_id) == 0) - { - // failed to get insert id - $this->insert_id = ''; - $this->warning_id = 33; - $this->_db_error($this->cursor, '[db_exec]'); - } - // if we have multiple, do not set the insert_id different, keep as array - } - // this warning handling is only for pgsql - // we returned an array of PKs instread of a single one - if (is_array($this->insert_id)) - { - $this->warning_id = 32; - $this->_db_error($this->cursor, '[db_exec]'); - } - } - } - return true; - } - } - - // ************************************************************* - // PUBLIC METHODS - // ************************************************************* - - // METHOD db_set_debug - // PARAMS true/false or none - // RETURN new set debug flag - // DESC switches the debug flag on or off - // if none given, then the debug flag auto switches from - // the previous setting to either then on or off - // else override with boolean true/false - public function db_set_debug($debug = '') - { - if ($debug === true) - $this->db_debug = 1; - elseif ($debug === false) - $this->db_debug = 0; - elseif ($this->db_debug) - $this->db_debug = 0; - elseif (!$this->db_debug) - $this->db_debug = 1; - return $this->db_debug; - } - - // METHOD db_reset_query_called - // PARAMS query - // RETURN none - // DESC resets the call times for the max query called to 0 - // USE CAREFULLY: rather make the query prepare -> execute - public function db_reset_query_called($query) - { - $this->query_called[md5($query)] = 0; - } - - // METHOD db_get_query_called - // PARAMS query - // RETURN count of query called - // DESC gets how often a query was called already - public function db_get_query_called($query) - { - $md5 = md5($query); - if ($this->query_called[$md5]) - return $this->query_called[$md5]; - else - return 0; - } - - // METHOD db_close - // PARAMS none - // RETURN none - // DESC closes the db_connection - // normally this is not used, as the class deconstructor closes the connection down - public function db_close() - { - if ($this->dbh) - { - $this->db_functions->_db_close(); - unset($this->dbh); - } - } - - // METHOD db_set_schema - // PARAMS db_schema: if not given tries internal default db schema - // RETURN false on failure to find schema values, true of db exec schema set - // DESC sets new db schema - public function db_set_schema($db_schema = '') - { - if (!$db_schema && $this->db_schema) - $db_schema = $this->db_schema; - if (!$db_schema) - return false; - $q = "SET search_path TO '".$this->db_escape_string($db_schema)."'"; - return $this->db_exec($q); - } - - // METHOD db_get_schema - // PARAMS none - // RETURN db_schema current set - // DESC returns the current set db schema - public function db_get_schema() - { - return $this->db_schema; - } - - // METHOD db_set_encoding - // PARAMS valid encoding name, so the the data gets converted to this encoding - // RETURN false, or true of db exec encoding set - // DESC sets the client encoding in the postgres database - public function db_set_encoding($db_encoding = '') - { - if (!$db_encoding && $this->db_encoding) - $db_encoding = $this->db_encoding; - if (!$db_encoding) - return false; - $q = "SET client_encoding TO '".$this->db_escape_string($db_encoding)."'"; - return $this->db_exec($q); - } - - // METHOD db_info - // PARAMS show, default 1, if set to 0 won't write to error_msg var - // RETURN string with db_connection info - // DESC prints out status info from the connected DB (might be usefull for debug stuff) - public function db_info($show = 1) - { - $string = ''; - $string .= '-DB-info-> Connected to db \''.$this->db_name.'\' with schema \''.$this->db_schema.'\' as user \''.$this->db_user.'\' at host \''.$this->db_host.'\' on port \''.$this->db_port.'\' with ssl mode \''.$this->db_ssl.'\'
'; - $string .= '-DB-info-> DB IO Class debug output: '.(($this->db_debug) ? 'Yes' : 'No').''; - if ($show) - $this->_db_debug('db', '
'.$string, 'db_info'); - else - $string = '
'.$string; - return $string; - } - - // METHOD db_dump_data - // PARAMS query -> if given, only from this quey (if found) - // RETURN formated string with all the data in the array - // DESC dumps ALL data for this query, OR if no query given all in cursor_ext array - public function db_dump_data($query = 0) - { - // set start array - if ($query) - $array = $this->cursor_ext[md5($query)]; - else - $array = $this->cursor_ext; - if (is_array($array)) - { - $this->nbps = ''; - $string .= $this->_print_array($array); - $this->_db_debug('db', $string, 'db_dump_data'); - } - return $string; - } - - // METHOD db_return - // PARAMS query -> the query ... - // reset -> if set to 1, at the end of the query (last row returned), the stored array will be deleted ... - // if set to 2, the data will be read new and cached (wheres 1 reads new AND destroys at end of read) - // -> if set to 3, after EACH row, the data will be reset, no caching is done except for basic (count, etc) - // RETURN res mixed (array/hash) - // DESC single running function, if called creates md5 from - // query string and so can itself call exec/return calls - // caches data, so next time called with IDENTICAL (!!!!) - // [this means 1:1 bit to bit identical query] returns cached - // data, or with reset flag set calls data from DB again - public function db_return($query, $reset = 0) - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - // create MD5 from query ... - $md5 = md5($query); - // pre declare array - if (!isset($this->cursor_ext[$md5])) - { - $this->cursor_ext[$md5] = array ( - 'query' => '', - 'pos' => 0, - 'cursor' => 0, - 'firstcall' => 0, - 'num_rows' => 0, - 'num_fields' => 0, - 'read_rows' => 0 - ); - } - // set the query - $this->cursor_ext[$md5]['query'] = $query; - // before doing ANYTHING check if query is "SELECT ..." everything else does not work - if (!$this->_check_query_for_select($this->cursor_ext[$md5]['query'])) - { - $this->error_id = 17; - $this->_db_error('', $this->cursor_ext[$md5]['query']); - return false; - } - - // if it is a call with reset in it we reset the cursor, so we get an uncached return - // but only for the FIRST call (pos == 0) - if ($reset && !$this->cursor_ext[$md5]['pos']) - { - unset($this->cursor_ext[$md5]['cursor']); - } -// $this->debug('MENU', 'Reset: '.$reset.', Cursor: '.$this->cursor_ext[$md5]['cursor'].', Pos: '.$this->cursor_ext[$md5]['pos'].', Query: '.$query); - - // if no cursor yet, execute - if (!$this->cursor_ext[$md5]['cursor']) - { - // for DEBUG, print out each query executed - if ($this->db_debug) - $this->_db_debug('db', $this->cursor_ext[$md5]['query'], 'db_return', 'Q'); - // if no DB Handler try to reconnect - if (!$this->dbh) - { - // if reconnect fails drop out - if (!$this->_connect_to_db()) - { - $this->error_id = 16; - $this->_db_error(); - return false; - } - } - // check that no other query is running right now - if ($this->db_functions->_db_connection_busy()) - { - $this->error_id = 41; - $this->_db_error(); - return false; - } - $this->cursor_ext[$md5]['cursor'] = $this->db_functions->_db_query($this->cursor_ext[$md5]['query']); - // if still no cursor ... - if (!$this->cursor_ext[$md5]['cursor']) - { - if ($this->db_debug) - $this->_db_debug('db', $this->cursor_ext[$md5]['query'], 'db_return', 'Q'); - // internal error handling - $this->error_id = 13; - $this->_db_error($this->cursor_ext[$md5]['cursor']); - return false; - } - else - { - $this->cursor_ext[$md5]['firstcall'] = 1; - } - } // only go if NO cursor exists - - // if cursor exists ... - if ($this->cursor_ext[$md5]['cursor']) - { - if ($this->cursor_ext[$md5]['firstcall'] == 1) - { - // count the rows returned (if select) - $this->cursor_ext[$md5]['num_rows'] = $this->db_functions->_db_num_rows($this->cursor_ext[$md5]['cursor']); - // count the fields - $this->cursor_ext[$md5]['num_fields'] = $this->db_functions->_db_num_fields($this->cursor_ext[$md5]['cursor']); - // set field names - for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) - { - $this->cursor_ext[$md5]['field_names'][] = $this->db_functions->_db_field_name($this->cursor_ext[$md5]['cursor'], $i); - } - // reset first call vars - $this->cursor_ext[$md5]['firstcall'] = 0; - // reset the internal pos counter - $this->cursor_ext[$md5]['pos'] = 0; - // reset the global (for cache) read counter - $this->cursor_ext[$md5]['read_rows'] = 0; - } - // read data for further work ... but only if necessarry - if ($this->cursor_ext[$md5]['read_rows'] == $this->cursor_ext[$md5]['num_rows']) - $return = 0; - else - $return = $this->_db_convert_encoding($this->db_functions->_db_fetch_array($this->cursor_ext[$md5]['cursor'])); - // check if cached call or reset call ... - if (!$return && !$reset) - { - // check if end of output ... - if ($this->cursor_ext[$md5]['pos'] >= $this->cursor_ext[$md5]['num_rows']) - { - $this->cursor_ext[$md5]['pos'] = 0; - # if not reset given, set the cursor to true, so in a cached call on a different page we don't get problems from DB connection (as those will be LOST) - $this->cursor_ext[$md5]['cursor'] = 1; - $return = 0; - } - else - { - // unset return value ... - unset($return); - for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) - { - // create mixed return array - $field_value = $this->cursor_ext[$md5][$this->cursor_ext[$md5]['pos']][$this->cursor_ext[$md5]['field_names'][$i]]; - $return[$i] = $field_value; - $return[$this->cursor_ext[$md5]['field_names'][$i]] = $field_value; - } - $this->cursor_ext[$md5]['pos'] ++; - } - } - else - { - // return row, if last && reset, then unset the hole md5 array - if (!$return && ($reset == 1 || $reset == 3) && $this->cursor_ext[$md5]['pos']) - { - // unset only the field names here of course - unset($this->cursor_ext[$md5]['field_names']); - $this->cursor_ext[$md5]['pos'] = 0; - } - else if (!$return && $reset == 2 && $this->cursor_ext[$md5]['pos']) - { - // at end of read reset pos & set cursor to 1 (so it does not get lost in session transfer) - $this->cursor_ext[$md5]['pos'] = 0; - $this->cursor_ext[$md5]['cursor'] = 1; - $return = 0; - } - // if something found, write data into hash array - if ($return) - { - // internal position counter - $this->cursor_ext[$md5]['pos'] ++; - $this->cursor_ext[$md5]['read_rows'] ++; - // if reset is <3 caching is done, else no - if ($reset < 3) - { - while (list($field_name, $data) = each($return)) - { - $temp[$field_name] = $data; - } - $this->cursor_ext[$md5][] = $temp; - } - } // cached data if - } // cached or not if - } // cursor exists - return $return; - } - - // METHOD db_cache_reset - // PARAMS $query -> The Query whose cache should be cleaned - // RETURN 0 if failure (eg no query with this md5 found) - // 1 if successfull - // DESC resets all data stored to this query - public function db_cache_reset($query) - { - $md5 = md5($query); - // clears cache for this query - if (!$this->cursor_ext[$md5]['query']) - { - $this->error_id = 18; - $this->_db_error(); - return false; - } - unset($this->cursor_ext[$md5]); - return true; - } - - // METHOD db_exec - // PARAMS query -> the query, if not given, the query class var will be used - // (if this was not set, method will quit with a 0 (failure) - // pk_name -> optional primary key name, for insert id return if the pk name is very different - // if pk name is table name and _id, pk_name is not needed to be set - // if NULL is given here, no RETURNING will be auto added - // RETURN cursor for this query - // DESC executes the query and returns & sets the internal cursor - // fruthermore this functions also sets varios other vars - // like num_rows, num_fields, etc depending on query - // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional - // read from the database for the PK NAME - public function db_exec($query = 0, $pk_name = '') - { - // prepare and check if we can actually run it - if (($md5 = $this->_db_prepare_exec($query, $pk_name)) === false) - // bail if no md5 set - return false; - // ** actual db exec call - $this->cursor = $this->db_functions->_db_query($this->query); - // if FALSE returned, set error stuff - // run the post exec processing - if (!$this->_db_post_exec()) - return false; - else - return $this->cursor; - } - - // METHOD db_exec_async - // PARAMS query -> query to run - // pk_name -> optional primary key name, only used with insert for returning call - // RETURN true if async query was sent ok, false if error happened - // DESC executres the query async so other methods can be run during this - // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional - // read from the database for the PK NAME - // NEEDS db_check_async - public function db_exec_async($query, $pk_name = '') - { - // prepare and check if we can actually run the query - if (($md5 = $this->_db_prepare_exec($query, $pk_name)) === false) - // bail if no md5 set - return false; - // run the async query - if (!$this->db_functions->_db_send_query($this->query)) - { - // if failed, process here - $this->error_id = 40; - $this->_db_error(); - return false; - } - else - { - $this->async_running = $md5; - // all ok, we return true (as would be from the original send query function) - return true; - } - } - - // METHOD db_check_async - // PARAMS none - // RETURN true if the query is still running, false if an error occured or cursor of that query - // DESC checks a previous async query and returns data if finished - // NEEDS db_exec_async - public function db_check_async() - { - // if there is actually a async query there - if ($this->async_running) - { - if ($this->db_functions->_db_connection_busy()) - { - return true; - } - else - { - // get the result/or error - $this->cursor = $this->db_functions->_db_get_result(); - $this->async_running = ''; - // run the post exec processing - if (!$this->_db_post_exec()) - return false; - else - return $this->cursor; - } - } - else - { - // if no async running print error - $this->error_id = 42; - $this->_db_debug('db', 'DB-Error No async query has been started yet.', 'DB_ERROR'); - return false; - } - } - - // METHOD db_fetch_array - // PARAMS cusors -> the cursor from db_exec or pg_query/pg_exec/mysql_query - // if not set will use internal cursor, if not found, stops with 0 (error) - // RETURN a mixed row - // DESC executes a cursor and returns the data, if no more data 0 will be returned - public function db_fetch_array($cursor = 0) - { - // return false if no query or cursor set ... - if (!$cursor) - $cursor = $this->cursor; - if (!$cursor) - { - $this->error_id = 12; - $this->_db_error(); - return false; - } - return $this->_db_convert_encoding($this->db_functions->_db_fetch_array($cursor)); - } - - // METHOD db_return_row - // PARAMS query -> the query to be executed - // RETURN mixed db result - // DESC returns the FIRST row of the given query - public function db_return_row($query) - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - // before doing ANYTHING check if query is "SELECT ..." everything else does not work - if (!$this->_check_query_for_select($query)) - { - $this->error_id = 17; - $this->_db_error('', $query); - return false; - } - $cursor = $this->db_exec($query); - $result = $this->db_fetch_array($cursor); - return $result; - } - - // METHOD db_return_array - // PARAMS query -> the query to be executed, named_only -> if true, only name ref are returned - // RETURN array of hashes (row -> fields) - // DESC createds an array of hashes of the query (all data) - public function db_return_array($query, $named_only = 0) - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - // before doing ANYTHING check if query is "SELECT ..." everything else does not work - if (!$this->_check_query_for_select($query)) - { - $this->error_id = 17; - $this->_db_error('', $query); - return false; - } - $cursor = $this->db_exec($query); - while ($res = $this->db_fetch_array($cursor)) - { - for ($i = 0; $i < $this->num_fields; $i ++) - { - // cereated mixed, first name - $data[$this->field_names[$i]] = $res[$this->field_names[$i]]; - // then number - if (!$named_only) - $data[$i] = $res[$this->field_names[$i]]; - } - $rows[] = $data; - } - return $rows; - } - - // METHOD db_cursor_pos - // PARAMS $query -> query to find in cursor_ext - // RETURN position (int) - // DESC returns the current position the read out - public function db_cursor_pos($query) - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - $md5 = md5($query); - return $this->cursor_ext[$md5]['pos']; - } - - // METHOD db_cursor_num_rows - // PARAMS $query -> query to find in cursor_ext - // RETURN row count (int) - // DESC returns the number of rows for the current select query - public function db_cursor_num_rows($query) - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - $md5 = md5($query); - return $this->cursor_ext[$md5]['num_rows']; - } - - // METHOD db_show_table_meta_data - // PARAMS $table -> table name - // $schema -> optional schema name - // RETURN array of table data - // DESC returns an array of the table with columns and values. FALSE on no table found - public function db_show_table_meta_data($table, $schema = '') - { - $table = ($schema ? $schema.'.' : '').$table; - - $array = $this->db_functions->_db_meta_data($table); - if (!is_array($array)) - $array = FALSE; - return $array; - } - - // METHOD db_prepare - // PARAMS $stm_name, $query, $pk_name: optional - // RETURN false on error - // DESC prepares a query - // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional - // read from the database for the PK NAME - public function db_prepare($stm_name, $query, $pk_name = '') - { - if (!$query) - { - $this->error_id = 11; - $this->_db_error(); - return false; - } - // if no DB Handler drop out - if (!$this->dbh) - { - // if reconnect fails drop out - if (!$this->_connect_to_db()) - { - $this->error_id = 16; - $this->_db_error(); - return false; - } - } - // check that no other query is running right now - if ($this->db_functions->_db_connection_busy()) - { - $this->error_id = 41; - $this->_db_error(); - return false; - } - // check if this was already prepared - if (!array_key_exists($stm_name, $this->prepare_cursor) || !is_array($this->prepare_cursor[$stm_name])) - { - // if this is an insert query, check if we can add a return - if ($this->_check_query_for_insert($query, true)) - { - if ($pk_name != 'NULL') - { - // set primary key name - // current: only via parameter - if (!$pk_name) - { - // read the primary key from the table, if we do not have one, we get nothing in return - list($schema, $table) = $this->_db_return_table($query); - if (!$this->pk_name_table[$table]) - { - $this->pk_name_table[$table] = $this->db_functions->_db_primary_key($table, $schema); - } - $pk_name = $this->pk_name_table[$table]; - } - if ($pk_name) - $this->prepare_cursor[$stm_name]['pk_name'] = $pk_name; - // if no returning, then add it - if (!preg_match("/ returning /i", $query) && $this->prepare_cursor[$stm_name]['pk_name']) - { - $query .= " RETURNING ".$this->prepare_cursor[$stm_name]['pk_name']; - $this->prepare_cursor[$stm_name]['returning_id'] = true; - } - // if returning exists but not pk_name, add it - else if (preg_match("/ returning (.*)/i", $query, $matches) && $this->prepare_cursor[$stm_name]['pk_name']) - { - if (!preg_match("/{$this->prepare_cursor[$stm_name]['pk_name']}/", $matches[1])) - { - $query .= " , ".$this->prepare_cursor[$stm_name]['pk_name']; - } - $this->prepare_cursor[$stm_name]['returning_id'] = true; - } - } - else - { - $this->prepare_cursor[$stm_name]['pk_name'] = $pk_name; - } - } - // search for $1, $2, in the query and push it into the control array - preg_match_all('/(\$[0-9]{1,})/', $query, $match); - $this->prepare_cursor[$stm_name]['count'] = count($match[1]); - $this->prepare_cursor[$stm_name]['query'] = $query; - $result = $this->db_functions->_db_prepare($stm_name, $query); - if ($result) - { - $this->prepare_cursor[$stm_name]['result'] = $result; - return $result; - } - else - { - $this->error_id = 21; - $this->_db_error(); - $this->_db_debug('db', 'DB-Error '.$stm_name.': Prepare field with: '.$stm_name.' | '.$query.'', 'DB_ERROR'); - return $result; - } - } - else - { - // thrown warning - $this->warning_id = 20; - return true; - } - } - - // METHOD db_execute - // PARAMS $stm_name, data array - // RETURN false on error - // DESC runs a prepare query - public function db_execute($stm_name, $data = array()) - { - // if we do not have no prepare cursor array entry for this statement name, abort - if (!is_array($this->prepare_cursor[$stm_name])) - { - $this->error_id = 24; - $this->_db_debug('db', 'DB-Error '.$stm_name.': We do not have a prepared query entry for this statement name.', 'DB_ERROR'); - return FALSE; - } - if (!is_array($data)) - { - $this->error_id = 25; - $this->_db_debug('db', 'DB-Error '.$stm_name.': Prepared query Data has to be given in array form.', 'DB_ERROR'); - return FALSE; - } - if ($this->prepare_cursor[$stm_name]['count'] != count($data)) - { - $this->error_id = 23; - $this->_db_debug('db', 'DB-Error '.$stm_name.': Array data count does not match prepared fields. Need: '.$this->prepare_cursor[$stm_name]['count'].', has: '.count($data).'', 'DB_ERROR'); - return FALSE; - } - else - { - if ($this->db_debug) - $this->_db_debug('db', $this->_db_debug_prepare($stm_name, $data), 'db_exec_prep', 'Q'); - $code = $this->db_functions->_db_execute($stm_name, $data); - if (!$code) - { -$this->debug('ExecuteData', 'ERROR in STM['.$stm_name.'|'.$this->prepare_cursor[$stm_name]['result'].']: '.$this->print_ar($data)); - $this->error_id = 22; - $this->_db_error($this->prepare_cursor[$stm_name]['result']); - $this->_db_debug('db', 'DB-Error '.$stm_name.': Execution failed', 'DB_ERROR'); - } - if ($this->_check_query_for_insert($this->prepare_cursor[$stm_name]['query'], true) && $this->prepare_cursor[$stm_name]['pk_name'] != 'NULL') - { - if (!$this->prepare_cursor[$stm_name]['returning_id']) - { - $this->insert_id = $this->db_functions->_db_insert_id($this->prepare_cursor[$stm_name]['query'], $this->prepare_cursor[$stm_name]['pk_name']); - } - elseif ($code) - { + } elseif ($this->_check_query_for_insert($this->query)) { + // if not select do here + // count affected rows + $this->num_rows = $this->db_functions->_db_affected_rows($this->cursor); + if ($this->_check_query_for_insert($this->query, true) && $this->pk_name != 'NULL') { + // set insert_id + // if we do not have a returning, we try to get it via the primary key and another select + if (!$this->returning_id) { + $this->insert_id = $this->db_functions->_db_insert_id($this->query, $this->pk_name); + } else { $this->insert_id = array (); $this->insert_id_ext = array (); + // echo "** PREPARE RETURNING FOR CURSOR: ".$this->cursor."
"; // we have returning, now we need to check if we get one or many returned // we'll need to loop this, if we have multiple insert_id returns - while ($_insert_id = $this->db_functions->_db_fetch_array($code, PGSQL_ASSOC)) - { + while ($_insert_id = $this->db_functions->_db_fetch_array($this->cursor, PGSQL_ASSOC)) { + // echo "*** RETURNING: ".print_r($_insert_id, 1)."
"; $this->insert_id[] = $_insert_id; } - // if we have only one, revert from arry to single - if (count($this->insert_id) == 1) - { -// echo "+ SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])."
"; -// echo "+ PK DIRECT: ".$this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]."
"; + // if we have only one, revert from array to single + if (count($this->insert_id) == 1) { + // echo "* SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->pk_name, $this->insert_id[0])."
"; + // echo "* PK DIRECT: ".$this->insert_id[0][$this->pk_name]."
"; // if this has only the pk_name, then only return this, else array of all data (but without the position) // example if insert_id[0]['foo'] && insert_id[0]['bar'] it will become insert_id['foo'] & insert_id['bar'] // if only ['foo_id'] and it is the PK then the PK is directly written to the insert_id - if (count($this->insert_id[0]) > 1 || !array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])) - { + if (count($this->insert_id[0]) > 1 || !array_key_exists($this->pk_name, $this->insert_id[0])) { $this->insert_id_ext = $this->insert_id[0]; - $this->insert_id = $this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]; + $this->insert_id = $this->insert_id[0][$this->pk_name]; + } elseif ($this->insert_id[0][$this->pk_name]) { + $this->insert_id = $this->insert_id[0][$this->pk_name]; } - elseif ($this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]) - { - $this->insert_id = $this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]; - } - } - else - { + } elseif (count($this->insert_id) == 0) { + // if we have non -> error // failed to get insert id $this->insert_id = ''; $this->warning_id = 33; - $this->_db_error(); - $this->_db_debug('db', 'DB-Warning '.$stm_name.': insert id returned no data', 'DB_WARNING'); + $this->_db_error($this->cursor, '[db_exec]'); } + // if we have multiple, do not set the insert_id different, keep as array } - // this error handling is only for pgsql - if (is_array($this->insert_id)) - { + // this warning handling is only for pgsql + // we returned an array of PKs instread of a single one + if (is_array($this->insert_id)) { $this->warning_id = 32; - $this->_db_error(); - $this->_db_debug('db', 'DB-Warning '.$stm_name.': insert id data returned as array', 'DB_WARNING'); - } - // NOTE should we keep this inside - elseif (!$this->insert_id) - { - $this->warning_id = 31; - $this->_db_error(); - $this->_db_debug('db', 'DB-Warning '.$stm_name.': Could not get insert id', 'DB_WARNING'); + $this->_db_error($this->cursor, '[db_exec]'); } } - return $code; } + return true; + } + } + + // ************************************************************* + // PUBLIC METHODS + // ************************************************************* + + // METHOD db_set_debug + // PARAMS true/false or none + // RETURN new set debug flag + // DESC switches the debug flag on or off + // if none given, then the debug flag auto switches from + // the previous setting to either then on or off + // else override with boolean true/false + public function db_set_debug($debug = '') + { + if ($debug === true) { + $this->db_debug = 1; + } elseif ($debug === false) { + $this->db_debug = 0; + } elseif ($this->db_debug) { + $this->db_debug = 0; + } elseif (!$this->db_debug) { + $this->db_debug = 1; + } + return $this->db_debug; + } + + // METHOD db_reset_query_called + // PARAMS query + // RETURN none + // DESC resets the call times for the max query called to 0 + // USE CAREFULLY: rather make the query prepare -> execute + public function db_reset_query_called($query) + { + $this->query_called[md5($query)] = 0; + } + + // METHOD db_get_query_called + // PARAMS query + // RETURN count of query called + // DESC gets how often a query was called already + public function db_get_query_called($query) + { + $md5 = md5($query); + if ($this->query_called[$md5]) { + return $this->query_called[$md5]; + } else { + return 0; + } + } + + // METHOD db_close + // PARAMS none + // RETURN none + // DESC closes the db_connection + // normally this is not used, as the class deconstructor closes the connection down + public function db_close() + { + if ($this->dbh) { + $this->db_functions->_db_close(); + unset($this->dbh); + } + } + + // METHOD db_set_schema + // PARAMS db_schema: if not given tries internal default db schema + // RETURN false on failure to find schema values, true of db exec schema set + // DESC sets new db schema + public function db_set_schema($db_schema = '') + { + if (!$db_schema && $this->db_schema) { + $db_schema = $this->db_schema; + } + if (!$db_schema) { + return false; + } + $q = "SET search_path TO '".$this->db_escape_string($db_schema)."'"; + return $this->db_exec($q); + } + + // METHOD db_get_schema + // PARAMS none + // RETURN db_schema current set + // DESC returns the current set db schema + public function db_get_schema() + { + return $this->db_schema; + } + + // METHOD db_set_encoding + // PARAMS valid encoding name, so the the data gets converted to this encoding + // RETURN false, or true of db exec encoding set + // DESC sets the client encoding in the postgres database + public function db_set_encoding($db_encoding = '') + { + if (!$db_encoding && $this->db_encoding) { + $db_encoding = $this->db_encoding; + } + if (!$db_encoding) { + return false; + } + $q = "SET client_encoding TO '".$this->db_escape_string($db_encoding)."'"; + return $this->db_exec($q); + } + + // METHOD db_info + // PARAMS show, default 1, if set to 0 won't write to error_msg var + // RETURN string with db_connection info + // DESC prints out status info from the connected DB (might be usefull for debug stuff) + public function db_info($show = 1) + { + $string = ''; + $string .= '-DB-info-> Connected to db \''.$this->db_name.'\' '; + $string .= 'with schema \''.$this->db_schema.'\' '; + $string .= 'as user \''.$this->db_user.'\' '; + $string .= 'at host \''.$this->db_host.'\' '; + $string .= 'on port \''.$this->db_port.'\' '; + $string .= 'with ssl mode \''.$this->db_ssl.'\'
'; + $string .= '-DB-info-> DB IO Class debug output: '.(($this->db_debug) ? 'Yes' : 'No').''; + if ($show) { + $this->_db_debug('db', '
'.$string, 'db_info'); + } else { + $string = '
'.$string; + } + return $string; + } + + // METHOD db_dump_data + // PARAMS query -> if given, only from this quey (if found) + // RETURN formated string with all the data in the array + // DESC dumps ALL data for this query, OR if no query given all in cursor_ext array + public function db_dump_data($query = 0) + { + // set start array + if ($query) { + $array = $this->cursor_ext[md5($query)]; + } else { + $array = $this->cursor_ext; + } + if (is_array($array)) { + $this->nbps = ''; + $string .= $this->_print_array($array); + $this->_db_debug('db', $string, 'db_dump_data'); + } + return $string; + } + + // METHOD db_return + // PARAMS query -> the query ... + // reset -> if set to 1, at the end of the query (last row returned), the stored array will be deleted ... + // if set to 2, the data will be read new and cached (wheres 1 reads new AND destroys at end of read) + // -> if set to 3, after EACH row, the data will be reset, no caching is done except for basic (count, etc) + // RETURN res mixed (array/hash) + // DESC single running function, if called creates md5 from + // query string and so can itself call exec/return calls + // caches data, so next time called with IDENTICAL (!!!!) + // [this means 1:1 bit to bit identical query] returns cached + // data, or with reset flag set calls data from DB again + public function db_return($query, $reset = 0) + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + // create MD5 from query ... + $md5 = md5($query); + // pre declare array + if (!isset($this->cursor_ext[$md5])) { + $this->cursor_ext[$md5] = array ( + 'query' => '', + 'pos' => 0, + 'cursor' => 0, + 'firstcall' => 0, + 'num_rows' => 0, + 'num_fields' => 0, + 'read_rows' => 0 + ); + } + // set the query + $this->cursor_ext[$md5]['query'] = $query; + // before doing ANYTHING check if query is "SELECT ..." everything else does not work + if (!$this->_check_query_for_select($this->cursor_ext[$md5]['query'])) { + $this->error_id = 17; + $this->_db_error('', $this->cursor_ext[$md5]['query']); + return false; } - // METHOD db_escape_string - // PARAMS $string -> string to escape - // RETURN escaped string - // DESC neutral function to escape a string for DB writing - public function db_escape_string($string) - { - return $this->db_functions->_db_escape_string($string); + // if it is a call with reset in it we reset the cursor, so we get an uncached return + // but only for the FIRST call (pos == 0) + if ($reset && !$this->cursor_ext[$md5]['pos']) { + unset($this->cursor_ext[$md5]['cursor']); } +// $this->debug('MENU', 'Reset: '.$reset.', Cursor: '.$this->cursor_ext[$md5]['cursor'].', Pos: '.$this->cursor_ext[$md5]['pos'].', Query: '.$query); - // METHOD db_escape_bytea - // PARAMS $bytea -> bytea to escape - // RETURN escaped bytea - // DESC neutral function to escape a bytea for DB writing - public function db_escape_bytea($bytea) - { - return $this->db_functions->_db_escape_bytea($bytea); - } - - // METHOD db_version - // PARAMS none - // RETURN database version as string - // DESC return current database version - public function db_version() - { - return $this->db_functions->_db_version(); - } - - // METHOD db_compare_version - // PARAMS string to which the return will return true or false - // =X.Y, >X.Y, , < prefix, and gets stripped, if the rest is not X.Y format then error - preg_match("/^([<>=]{1,2})(\d{1,2})\.(\d{1,2})/", $compare, $matches); - $compare = $matches[1]; - $to_master = $matches[2]; - $to_minor = $matches[3]; - if (!$compare || !$to_master || !$to_minor) - return false; - else - $to_version = $to_master.($to_minor < 10 ? '0' : '').$to_minor; - // db_version can return X.Y.Z - // we only compare the first two - list ($master, $minor, $_other) = explode('.', $this->db_version()); - $version = $master.($minor < 10 ? '0' : '').$minor; - $return = false; - // compare - switch ($compare) - { - case '=': - if ($to_version == $version) - $return = true; - break; - case '<': - if ($version < $to_version) - $return = true; - break; - case '<=': - if ($version <= $to_version) - $return = true; - break; - case '>': - if ($version > $to_version) - $return = true; - break; - case '>=': - if ($version >= $to_version) - $return = true; - break; - default; - $return = false; + // if no cursor yet, execute + if (!$this->cursor_ext[$md5]['cursor']) { + // for DEBUG, print out each query executed + if ($this->db_debug) { + $this->_db_debug('db', $this->cursor_ext[$md5]['query'], 'db_return', 'Q'); } - return $return; - } - - // METHOD db_boolean - // PARAMS 't' / 'f' or any string - // RETURN correct php boolean true/false - // DESC if the input is a single char 't' or 'f' it will return the boolean value instead - public function db_boolean($string, $rev = false) - { - if (!$rev) - { - if ($string == 't' || $string == 'true') - return true; - if ($string == 'f' || $string == 'false') + // if no DB Handler try to reconnect + if (!$this->dbh) { + // if reconnect fails drop out + if (!$this->_connect_to_db()) { + $this->error_id = 16; + $this->_db_error(); return false; + } } - else - { - if ($string) - return 't'; - else - return 'f'; - } - // if neither, just return data as is - return $string; - } - - // ** REMARK ** - // db_write_data is the old without separate update no write list - // db_write_data_ext is the extended with additional array for no write list for update - - // METHOD: db_write_data - // PARAMS: write_array -> list of elements to write - // not_write_array -> list of elements not to write - // primary_key -> id key to decide if we write insert or update - // table -> name for the target table - // RETURN: primary key id - // DESC: writes into one table based on array of table columns - public function db_write_data($write_array, $not_write_array, $primary_key, $table, $data = array ()) - { - if (!is_array($write_array)) - $write_array = array (); - if (!is_array($not_write_array)) - $not_write_array = array (); - if (is_array($table)) + // check that no other query is running right now + if ($this->db_functions->_db_connection_busy()) { + $this->error_id = 41; + $this->_db_error(); return false; - $not_write_update_array = array (); - return $this->db_write_data_ext($write_array, $primary_key, $table, $not_write_array, $not_write_update_array, $data); - } - - // METHOD: db_write_data_ext - // PARAMS: write_array -> list of elements to write - // primary_key -> id key to decide if we write insert or update - // -> alternate the primary key can be an array with 'row' => 'row name', 'value' => 'data' to use a different column as the primary key - // table -> name for the target table - // (optional) - // not_write_array -> list of elements not to write - // not_write_update_array -> list of elements not to write during update - // data -> optional array with data, if not _POST vars are used - // RETURN: primary key id - // DESC: writes into one table based on array of table columns - public function db_write_data_ext($write_array, $primary_key, $table, $not_write_array = array (), $not_write_update_array = array (), $data = array ()) - { - if (!is_array($primary_key)) - { - $primary_key = array ( - 'row' => $table.'_id', - 'value' => $primary_key - ); } - // var set for strings - $q_sub_value = ''; - $q_sub_data = ''; - // get the table layout and row types - $table_data = $this->db_show_table_meta_data(($this->db_schema ? $this->db_schema.'.' : '').$table); - foreach ($write_array as $field) - { - if ((!$primary_key['value'] || ($primary_key['value'] && !in_array($field, $not_write_update_array))) && !in_array($field, $not_write_array)) - { - // data from external or data field - $_data = null; - if (count($data) >= 1 && array_key_exists($field, $data)) - $_data = $data[$field]; - elseif (array_key_exists($field, $GLOBALS)) - $_data = $GLOBALS[$field]; - $has_default = $table_data[$field]['has default']; - $not_null = $table_data[$field]['not null']; - // if not null and string => '', if not null and int or numeric => 0, if bool => skip, all others skip - if ($not_null && !isset($_data)) - { - if (strstr($table_data[$field]['type'], 'int') || strstr($table_data[$field]['type'], 'numeric')) - $_data = 0; - else - $_data = ''; + $this->cursor_ext[$md5]['cursor'] = $this->db_functions->_db_query($this->cursor_ext[$md5]['query']); + // if still no cursor ... + if (!$this->cursor_ext[$md5]['cursor']) { + if ($this->db_debug) { + $this->_db_debug('db', $this->cursor_ext[$md5]['query'], 'db_return', 'Q'); + } + // internal error handling + $this->error_id = 13; + $this->_db_error($this->cursor_ext[$md5]['cursor']); + return false; + } else { + $this->cursor_ext[$md5]['firstcall'] = 1; + } + } // only go if NO cursor exists + + // if cursor exists ... + if ($this->cursor_ext[$md5]['cursor']) { + if ($this->cursor_ext[$md5]['firstcall'] == 1) { + // count the rows returned (if select) + $this->cursor_ext[$md5]['num_rows'] = $this->db_functions->_db_num_rows($this->cursor_ext[$md5]['cursor']); + // count the fields + $this->cursor_ext[$md5]['num_fields'] = $this->db_functions->_db_num_fields($this->cursor_ext[$md5]['cursor']); + // set field names + for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) { + $this->cursor_ext[$md5]['field_names'][] = $this->db_functions->_db_field_name($this->cursor_ext[$md5]['cursor'], $i); + } + // reset first call vars + $this->cursor_ext[$md5]['firstcall'] = 0; + // reset the internal pos counter + $this->cursor_ext[$md5]['pos'] = 0; + // reset the global (for cache) read counter + $this->cursor_ext[$md5]['read_rows'] = 0; + } + // read data for further work ... but only if necessarry + if ($this->cursor_ext[$md5]['read_rows'] == $this->cursor_ext[$md5]['num_rows']) { + $return = 0; + } else { + $return = $this->_db_convert_encoding($this->db_functions->_db_fetch_array($this->cursor_ext[$md5]['cursor'])); + } + // check if cached call or reset call ... + if (!$return && !$reset) { + // check if end of output ... + if ($this->cursor_ext[$md5]['pos'] >= $this->cursor_ext[$md5]['num_rows']) { + $this->cursor_ext[$md5]['pos'] = 0; + # if not reset given, set the cursor to true, so in a cached call on a different page we don't get problems from DB connection (as those will be LOST) + $this->cursor_ext[$md5]['cursor'] = 1; + $return = 0; + } else { + // unset return value ... + unset($return); + for ($i = 0; $i < $this->cursor_ext[$md5]['num_fields']; $i ++) { + // create mixed return array + $field_value = $this->cursor_ext[$md5][$this->cursor_ext[$md5]['pos']][$this->cursor_ext[$md5]['field_names'][$i]]; + $return[$i] = $field_value; + $return[$this->cursor_ext[$md5]['field_names'][$i]] = $field_value; } - // we detect bool, so we can force a write on "false" - $is_bool = $table_data[$field]['type'] == 'bool' ? true : false; - // write if the field has to be not null, or if there is no data and the field has no default values or if there is data or if this is an update and there is no data (set null) - if (($not_null && isset($_data)) || (!$has_default && !isset($_data)) || (is_numeric($_data) && isset($_data)) || ($primary_key['value'] && !isset($_data)) || isset($_data)) - { - if ($q_sub_value && !$primary_key['value']) - $q_sub_value .= ', '; - if ($q_sub_data)// && (!$primary_key || ($primary_key && !in_array($field, $not_write_array)))) - $q_sub_data .= ', '; - if ($primary_key['value']) - $q_sub_data .= $field.' = '; - else - $q_sub_value .= $field; - // if field is "date" and -- -> reset - if ($_data == '--' && strstr($table_data[$field]['type'], 'date')) - $_data = ''; - // write data into sql string - if (strstr($table_data[$field]['type'], 'int')) - $q_sub_data .= (is_numeric($_data) && isset($_data)) ? $_data : 'NULL'; - else - // if bool -> set bool, else write data - $q_sub_data .= isset($_data) ? "'".($is_bool ? $this->db_boolean($_data, true) : $this->db_escape_string($_data))."'" : 'NULL'; + $this->cursor_ext[$md5]['pos'] ++; + } + } else { + // return row, if last && reset, then unset the hole md5 array + if (!$return && ($reset == 1 || $reset == 3) && $this->cursor_ext[$md5]['pos']) { + // unset only the field names here of course + unset($this->cursor_ext[$md5]['field_names']); + $this->cursor_ext[$md5]['pos'] = 0; + } elseif (!$return && $reset == 2 && $this->cursor_ext[$md5]['pos']) { + // at end of read reset pos & set cursor to 1 (so it does not get lost in session transfer) + $this->cursor_ext[$md5]['pos'] = 0; + $this->cursor_ext[$md5]['cursor'] = 1; + $return = 0; + } + // if something found, write data into hash array + if ($return) { + // internal position counter + $this->cursor_ext[$md5]['pos'] ++; + $this->cursor_ext[$md5]['read_rows'] ++; + // if reset is <3 caching is done, else no + if ($reset < 3) { + while (list($field_name, $data) = each($return)) { + $temp[$field_name] = $data; + } + $this->cursor_ext[$md5][] = $temp; + } + } // cached data if + } // cached or not if + } // cursor exists + return $return; + } + + // METHOD db_cache_reset + // PARAMS $query -> The Query whose cache should be cleaned + // RETURN 0 if failure (eg no query with this md5 found) + // 1 if successfull + // DESC resets all data stored to this query + public function db_cache_reset($query) + { + $md5 = md5($query); + // clears cache for this query + if (!$this->cursor_ext[$md5]['query']) { + $this->error_id = 18; + $this->_db_error(); + return false; + } + unset($this->cursor_ext[$md5]); + return true; + } + + // METHOD db_exec + // PARAMS query -> the query, if not given, the query class var will be used + // (if this was not set, method will quit with a 0 (failure) + // pk_name -> optional primary key name, for insert id return if the pk name is very different + // if pk name is table name and _id, pk_name is not needed to be set + // if NULL is given here, no RETURNING will be auto added + // RETURN cursor for this query + // DESC executes the query and returns & sets the internal cursor + // fruthermore this functions also sets varios other vars + // like num_rows, num_fields, etc depending on query + // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional + // read from the database for the PK NAME + public function db_exec($query = 0, $pk_name = '') + { + // prepare and check if we can actually run it + if (($md5 = $this->_db_prepare_exec($query, $pk_name)) === false) { + // bail if no md5 set + return false; + } + // ** actual db exec call + $this->cursor = $this->db_functions->_db_query($this->query); + // if FALSE returned, set error stuff + // run the post exec processing + if (!$this->_db_post_exec()) { + return false; + } else { + return $this->cursor; + } + } + + // METHOD db_exec_async + // PARAMS query -> query to run + // pk_name -> optional primary key name, only used with insert for returning call + // RETURN true if async query was sent ok, false if error happened + // DESC executres the query async so other methods can be run during this + // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional + // read from the database for the PK NAME + // NEEDS db_check_async + public function db_exec_async($query, $pk_name = '') + { + // prepare and check if we can actually run the query + if (($md5 = $this->_db_prepare_exec($query, $pk_name)) === false) { + // bail if no md5 set + return false; + } + // run the async query + if (!$this->db_functions->_db_send_query($this->query)) { + // if failed, process here + $this->error_id = 40; + $this->_db_error(); + return false; + } else { + $this->async_running = $md5; + // all ok, we return true (as would be from the original send query function) + return true; + } + } + + // METHOD db_check_async + // PARAMS none + // RETURN true if the query is still running, false if an error occured or cursor of that query + // DESC checks a previous async query and returns data if finished + // NEEDS db_exec_async + public function db_check_async() + { + // if there is actually a async query there + if ($this->async_running) { + if ($this->db_functions->_db_connection_busy()) { + return true; + } else { + // get the result/or error + $this->cursor = $this->db_functions->_db_get_result(); + $this->async_running = ''; + // run the post exec processing + if (!$this->_db_post_exec()) { + return false; + } else { + return $this->cursor; + } + } + } else { + // if no async running print error + $this->error_id = 42; + $this->_db_debug('db', 'DB-Error No async query has been started yet.', 'DB_ERROR'); + return false; + } + } + + // METHOD db_fetch_array + // PARAMS cusors -> the cursor from db_exec or pg_query/pg_exec/mysql_query + // if not set will use internal cursor, if not found, stops with 0 (error) + // RETURN a mixed row + // DESC executes a cursor and returns the data, if no more data 0 will be returned + public function db_fetch_array($cursor = 0) + { + // return false if no query or cursor set ... + if (!$cursor) { + $cursor = $this->cursor; + } + if (!$cursor) { + $this->error_id = 12; + $this->_db_error(); + return false; + } + return $this->_db_convert_encoding($this->db_functions->_db_fetch_array($cursor)); + } + + // METHOD db_return_row + // PARAMS query -> the query to be executed + // RETURN mixed db result + // DESC returns the FIRST row of the given query + public function db_return_row($query) + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + // before doing ANYTHING check if query is "SELECT ..." everything else does not work + if (!$this->_check_query_for_select($query)) { + $this->error_id = 17; + $this->_db_error('', $query); + return false; + } + $cursor = $this->db_exec($query); + $result = $this->db_fetch_array($cursor); + return $result; + } + + // METHOD db_return_array + // PARAMS query -> the query to be executed, named_only -> if true, only name ref are returned + // RETURN array of hashes (row -> fields) + // DESC createds an array of hashes of the query (all data) + public function db_return_array($query, $named_only = 0) + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + // before doing ANYTHING check if query is "SELECT ..." everything else does not work + if (!$this->_check_query_for_select($query)) { + $this->error_id = 17; + $this->_db_error('', $query); + return false; + } + $cursor = $this->db_exec($query); + while ($res = $this->db_fetch_array($cursor)) { + for ($i = 0; $i < $this->num_fields; $i ++) { + // cereated mixed, first name + $data[$this->field_names[$i]] = $res[$this->field_names[$i]]; + // then number + if (!$named_only) { + $data[$i] = $res[$this->field_names[$i]]; + } + } + $rows[] = $data; + } + return $rows; + } + + // METHOD db_cursor_pos + // PARAMS $query -> query to find in cursor_ext + // RETURN position (int) + // DESC returns the current position the read out + public function db_cursor_pos($query) + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + $md5 = md5($query); + return $this->cursor_ext[$md5]['pos']; + } + + // METHOD db_cursor_num_rows + // PARAMS $query -> query to find in cursor_ext + // RETURN row count (int) + // DESC returns the number of rows for the current select query + public function db_cursor_num_rows($query) + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + $md5 = md5($query); + return $this->cursor_ext[$md5]['num_rows']; + } + + // METHOD db_show_table_meta_data + // PARAMS $table -> table name + // $schema -> optional schema name + // RETURN array of table data + // DESC returns an array of the table with columns and values. FALSE on no table found + public function db_show_table_meta_data($table, $schema = '') + { + $table = ($schema ? $schema.'.' : '').$table; + + $array = $this->db_functions->_db_meta_data($table); + if (!is_array($array)) { + $array = false; + } + return $array; + } + + // METHOD db_prepare + // PARAMS $stm_name, $query, $pk_name: optional + // RETURN false on error + // DESC prepares a query + // for INSERT INTO queries it is highly recommended to set the pk_name to avoid an additional + // read from the database for the PK NAME + public function db_prepare($stm_name, $query, $pk_name = '') + { + if (!$query) { + $this->error_id = 11; + $this->_db_error(); + return false; + } + // if no DB Handler drop out + if (!$this->dbh) { + // if reconnect fails drop out + if (!$this->_connect_to_db()) { + $this->error_id = 16; + $this->_db_error(); + return false; + } + } + // check that no other query is running right now + if ($this->db_functions->_db_connection_busy()) { + $this->error_id = 41; + $this->_db_error(); + return false; + } + // check if this was already prepared + if (!array_key_exists($stm_name, $this->prepare_cursor) || !is_array($this->prepare_cursor[$stm_name])) { + // if this is an insert query, check if we can add a return + if ($this->_check_query_for_insert($query, true)) { + if ($pk_name != 'NULL') { + // set primary key name + // current: only via parameter + if (!$pk_name) { + // read the primary key from the table, if we do not have one, we get nothing in return + list($schema, $table) = $this->_db_return_table($query); + if (!$this->pk_name_table[$table]) { + $this->pk_name_table[$table] = $this->db_functions->_db_primary_key($table, $schema); + } + $pk_name = $this->pk_name_table[$table]; + } + if ($pk_name) { + $this->prepare_cursor[$stm_name]['pk_name'] = $pk_name; + } + // if no returning, then add it + if (!preg_match("/ returning /i", $query) && $this->prepare_cursor[$stm_name]['pk_name']) { + $query .= " RETURNING ".$this->prepare_cursor[$stm_name]['pk_name']; + $this->prepare_cursor[$stm_name]['returning_id'] = true; + } elseif (preg_match("/ returning (.*)/i", $query, $matches) && $this->prepare_cursor[$stm_name]['pk_name']) { + // if returning exists but not pk_name, add it + if (!preg_match("/{$this->prepare_cursor[$stm_name]['pk_name']}/", $matches[1])) { + $query .= " , ".$this->prepare_cursor[$stm_name]['pk_name']; + } + $this->prepare_cursor[$stm_name]['returning_id'] = true; + } + } else { + $this->prepare_cursor[$stm_name]['pk_name'] = $pk_name; + } + } + // search for $1, $2, in the query and push it into the control array + preg_match_all('/(\$[0-9]{1,})/', $query, $match); + $this->prepare_cursor[$stm_name]['count'] = count($match[1]); + $this->prepare_cursor[$stm_name]['query'] = $query; + $result = $this->db_functions->_db_prepare($stm_name, $query); + if ($result) { + $this->prepare_cursor[$stm_name]['result'] = $result; + return $result; + } else { + $this->error_id = 21; + $this->_db_error(); + $this->_db_debug('db', 'DB-Error '.$stm_name.': Prepare field with: '.$stm_name.' | '.$query.'', 'DB_ERROR'); + return $result; + } + } else { + // thrown warning + $this->warning_id = 20; + return true; + } + } + + // METHOD db_execute + // PARAMS $stm_name, data array + // RETURN false on error + // DESC runs a prepare query + public function db_execute($stm_name, $data = array()) + { + // if we do not have no prepare cursor array entry for this statement name, abort + if (!is_array($this->prepare_cursor[$stm_name])) { + $this->error_id = 24; + $this->_db_debug('db', 'DB-Error '.$stm_name.': We do not have a prepared query entry for this statement name.', 'DB_ERROR'); + return false; + } + if (!is_array($data)) { + $this->error_id = 25; + $this->_db_debug('db', 'DB-Error '.$stm_name.': Prepared query Data has to be given in array form.', 'DB_ERROR'); + return false; + } + if ($this->prepare_cursor[$stm_name]['count'] != count($data)) { + $this->error_id = 23; + $this->_db_debug('db', 'DB-Error '.$stm_name.': Array data count does not match prepared fields. Need: '.$this->prepare_cursor[$stm_name]['count'].', has: '.count($data).'', 'DB_ERROR'); + return false; + } else { + if ($this->db_debug) { + $this->_db_debug('db', $this->_db_debug_prepare($stm_name, $data), 'db_exec_prep', 'Q'); + } + $code = $this->db_functions->_db_execute($stm_name, $data); + if (!$code) { + $this->debug('ExecuteData', 'ERROR in STM['.$stm_name.'|'.$this->prepare_cursor[$stm_name]['result'].']: '.$this->print_ar($data)); + $this->error_id = 22; + $this->_db_error($this->prepare_cursor[$stm_name]['result']); + $this->_db_debug('db', 'DB-Error '.$stm_name.': Execution failed', 'DB_ERROR'); + } + if ($this->_check_query_for_insert($this->prepare_cursor[$stm_name]['query'], true) && $this->prepare_cursor[$stm_name]['pk_name'] != 'NULL') { + if (!$this->prepare_cursor[$stm_name]['returning_id']) { + $this->insert_id = $this->db_functions->_db_insert_id($this->prepare_cursor[$stm_name]['query'], $this->prepare_cursor[$stm_name]['pk_name']); + } elseif ($code) { + $this->insert_id = array (); + $this->insert_id_ext = array (); + // we have returning, now we need to check if we get one or many returned + // we'll need to loop this, if we have multiple insert_id returns + while ($_insert_id = $this->db_functions->_db_fetch_array($code, PGSQL_ASSOC)) { + $this->insert_id[] = $_insert_id; + } + // if we have only one, revert from arry to single + if (count($this->insert_id) == 1) { + // echo "+ SINGLE DATA CONVERT: ".count($this->insert_id[0])." => ".array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])."
"; + // echo "+ PK DIRECT: ".$this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]."
"; + // if this has only the pk_name, then only return this, else array of all data (but without the position) + // example if insert_id[0]['foo'] && insert_id[0]['bar'] it will become insert_id['foo'] & insert_id['bar'] + // if only ['foo_id'] and it is the PK then the PK is directly written to the insert_id + if (count($this->insert_id[0]) > 1 || !array_key_exists($this->prepare_cursor[$stm_name]['pk_name'], $this->insert_id[0])) { + $this->insert_id_ext = $this->insert_id[0]; + $this->insert_id = $this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]; + } elseif ($this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]) { + $this->insert_id = $this->insert_id[0][$this->prepare_cursor[$stm_name]['pk_name']]; + } + } else { + // failed to get insert id + $this->insert_id = ''; + $this->warning_id = 33; + $this->_db_error(); + $this->_db_debug('db', 'DB-Warning '.$stm_name.': insert id returned no data', 'DB_WARNING'); + } + } + // this error handling is only for pgsql + if (is_array($this->insert_id)) { + $this->warning_id = 32; + $this->_db_error(); + $this->_db_debug('db', 'DB-Warning '.$stm_name.': insert id data returned as array', 'DB_WARNING'); + } elseif (!$this->insert_id) { + // NOTE should we keep this inside + $this->warning_id = 31; + $this->_db_error(); + $this->_db_debug('db', 'DB-Warning '.$stm_name.': Could not get insert id', 'DB_WARNING'); + } + } + return $code; + } + } + + // METHOD db_escape_string + // PARAMS $string -> string to escape + // RETURN escaped string + // DESC neutral function to escape a string for DB writing + public function db_escape_string($string) + { + return $this->db_functions->_db_escape_string($string); + } + + // METHOD db_escape_bytea + // PARAMS $bytea -> bytea to escape + // RETURN escaped bytea + // DESC neutral function to escape a bytea for DB writing + public function db_escape_bytea($bytea) + { + return $this->db_functions->_db_escape_bytea($bytea); + } + + // METHOD db_version + // PARAMS none + // RETURN database version as string + // DESC return current database version + public function db_version() + { + return $this->db_functions->_db_version(); + } + + // METHOD db_compare_version + // PARAMS string to which the return will return true or false + // =X.Y, >X.Y, , < prefix, and gets stripped, if the rest is not X.Y format then error + preg_match("/^([<>=]{1,2})(\d{1,2})\.(\d{1,2})/", $compare, $matches); + $compare = $matches[1]; + $to_master = $matches[2]; + $to_minor = $matches[3]; + if (!$compare || !$to_master || !$to_minor) { + return false; + } else { + $to_version = $to_master.($to_minor < 10 ? '0' : '').$to_minor; + } + // db_version can return X.Y.Z + // we only compare the first two + list ($master, $minor, $_other) = explode('.', $this->db_version()); + $version = $master.($minor < 10 ? '0' : '').$minor; + $return = false; + // compare + switch ($compare) { + case '=': + if ($to_version == $version) { + $return = true; + } + break; + case '<': + if ($version < $to_version) { + $return = true; + } + break; + case '<=': + if ($version <= $to_version) { + $return = true; + } + break; + case '>': + if ($version > $to_version) { + $return = true; + } + break; + case '>=': + if ($version >= $to_version) { + $return = true; + } + break; + default: + $return = false; + } + return $return; + } + + // METHOD db_boolean + // PARAMS 't' / 'f' or any string + // RETURN correct php boolean true/false + // DESC if the input is a single char 't' or 'f' it will return the boolean value instead + public function db_boolean($string, $rev = false) + { + if (!$rev) { + if ($string == 't' || $string == 'true') { + return true; + } + if ($string == 'f' || $string == 'false') { + return false; + } + } else { + if ($string) { + return 't'; + } else { + return 'f'; + } + } + // if neither, just return data as is + return $string; + } + + // ** REMARK ** + // db_write_data is the old without separate update no write list + // db_write_data_ext is the extended with additional array for no write list for update + + // METHOD: db_write_data + // PARAMS: write_array -> list of elements to write + // not_write_array -> list of elements not to write + // primary_key -> id key to decide if we write insert or update + // table -> name for the target table + // RETURN: primary key id + // DESC: writes into one table based on array of table columns + public function db_write_data($write_array, $not_write_array, $primary_key, $table, $data = array ()) + { + if (!is_array($write_array)) { + $write_array = array (); + } + if (!is_array($not_write_array)) { + $not_write_array = array (); + } + if (is_array($table)) { + return false; + } + $not_write_update_array = array (); + return $this->db_write_data_ext($write_array, $primary_key, $table, $not_write_array, $not_write_update_array, $data); + } + + // METHOD: db_write_data_ext + // PARAMS: write_array -> list of elements to write + // primary_key -> id key to decide if we write insert or update + // -> alternate the primary key can be an array with 'row' => 'row name', 'value' => 'data' to use a different column as the primary key + // table -> name for the target table + // (optional) + // not_write_array -> list of elements not to write + // not_write_update_array -> list of elements not to write during update + // data -> optional array with data, if not _POST vars are used + // RETURN: primary key id + // DESC: writes into one table based on array of table columns + public function db_write_data_ext($write_array, $primary_key, $table, $not_write_array = array (), $not_write_update_array = array (), $data = array ()) + { + if (!is_array($primary_key)) { + $primary_key = array ( + 'row' => $table.'_id', + 'value' => $primary_key + ); + } + // var set for strings + $q_sub_value = ''; + $q_sub_data = ''; + // get the table layout and row types + $table_data = $this->db_show_table_meta_data(($this->db_schema ? $this->db_schema.'.' : '').$table); + foreach ($write_array as $field) { + if ((!$primary_key['value'] || ($primary_key['value'] && !in_array($field, $not_write_update_array))) && !in_array($field, $not_write_array)) { + // data from external or data field + $_data = null; + if (count($data) >= 1 && array_key_exists($field, $data)) { + $_data = $data[$field]; + } elseif (array_key_exists($field, $GLOBALS)) { + $_data = $GLOBALS[$field]; + } + $has_default = $table_data[$field]['has default']; + $not_null = $table_data[$field]['not null']; + // if not null and string => '', if not null and int or numeric => 0, if bool => skip, all others skip + if ($not_null && !isset($_data)) { + if (strstr($table_data[$field]['type'], 'int') || strstr($table_data[$field]['type'], 'numeric')) { + $_data = 0; + } else { + $_data = ''; + } + } + // we detect bool, so we can force a write on "false" + $is_bool = $table_data[$field]['type'] == 'bool' ? true : false; + // write if the field has to be not null, or if there is no data and the field has no default values or if there is data or if this is an update and there is no data (set null) + if (($not_null && isset($_data)) || (!$has_default && !isset($_data)) || (is_numeric($_data) && isset($_data)) || ($primary_key['value'] && !isset($_data)) || isset($_data)) { + if ($q_sub_value && !$primary_key['value']) { + $q_sub_value .= ', '; + } + if ($q_sub_data) { // && (!$primary_key || ($primary_key && !in_array($field, $not_write_array)))) + $q_sub_data .= ', '; + } + if ($primary_key['value']) { + $q_sub_data .= $field.' = '; + } else { + $q_sub_value .= $field; + } + // if field is "date" and -- -> reset + if ($_data == '--' && strstr($table_data[$field]['type'], 'date')) { + $_data = ''; + } + // write data into sql string + if (strstr($table_data[$field]['type'], 'int')) { + $q_sub_data .= (is_numeric($_data) && isset($_data)) ? $_data : 'NULL'; + } else { + // if bool -> set bool, else write data + $q_sub_data .= isset($_data) ? "'".($is_bool ? $this->db_boolean($_data, true) : $this->db_escape_string($_data))."'" : 'NULL'; } } } - - // first work contact itself (we need contact id for everything else) - if ($primary_key['value']) - { - $q = 'UPDATE '.$table.' SET '; - $q .= $q_sub_data.' '; - $q .= 'WHERE '.$primary_key['row'].' = '.$primary_key['value']; - $this->temp_sql = $q_sub_data; - } - else - { - $q = 'INSERT INTO '.$table.' ('; - $q .= $q_sub_value; - $q .= ') VALUES ('; - $q .= $q_sub_data; - $q .= ')'; - $this->temp_sql = $q; - } - if (!$this->db_exec($q)) - return false; - if (!$primary_key['value']) - $primary_key['value'] = $this->insert_id; - - return $primary_key['value']; } - // METHOD: db_time_format - // PARAMS: age or datetime difference - // micro on off (default false) - // RETURN: Y/M/D/h/m/s formatted string (like TimeStringFormat - // DESC: only for postgres. pretty formats an age or datetime difference string - public function db_time_format($age, $show_micro = false) - { - // in string (datetime diff): 1786 days 22:11:52.87418 - // or (age): 4 years 10 mons 21 days 12:31:11.87418 - // also -09:43:54.781021 or without - prefix - - preg_match("/(.*)?(\d{2}):(\d{2}):(\d{2})(\.(\d+))/", $age, $matches); - - $prefix = $matches[1] != '-' ? $matches[1] : ''; - $hour = $matches[2] != '00' ? preg_replace('/^0/', '', $matches[2]) : ''; - $minutes = $matches[3] != '00' ? preg_replace('/^0/', '', $matches[3]) : ''; - $seconds = $matches[4] != '00' ? preg_replace('/^0/', '', $matches[4]) : ''; - $milliseconds = $matches[6]; - - return $prefix.($hour ? $hour.'h ' : '').($minutes ? $minutes.'m ' : '').($seconds ? $seconds.'s' : '').($show_micro && $milliseconds? ' '.$milliseconds.'ms' : ''); + // first work contact itself (we need contact id for everything else) + if ($primary_key['value']) { + $q = 'UPDATE '.$table.' SET '; + $q .= $q_sub_data.' '; + $q .= 'WHERE '.$primary_key['row'].' = '.$primary_key['value']; + $this->temp_sql = $q_sub_data; + } else { + $q = 'INSERT INTO '.$table.' ('; + $q .= $q_sub_value; + $q .= ') VALUES ('; + $q .= $q_sub_data; + $q .= ')'; + $this->temp_sql = $q; + } + if (!$this->db_exec($q)) { + return false; + } + if (!$primary_key['value']) { + $primary_key['value'] = $this->insert_id; } - // METHOD: db_array_parse - // PARAMS: text: input text to parse to an array - // RETURN: PHP array of the parsed data - // DESC: this is only needed for Postgresql. Converts postgresql arrays to PHP - public function db_array_parse($text) - { - return $this->db_functions->_db_array_parse($text, $output); - } + return $primary_key['value']; + } - // METHOD: db_sql_escape - // PARAMS: value -> to escape data - // kbn -> escape trigger type - // RETURN: escaped value - // DESC : clear up any data for valid DB insert - public function db_sql_escape($value, $kbn = "") - { - switch ($kbn) - { - case "i": - $value = (!isset($value) || $value === "") ? "NULL" : intval($value); - break; - case "f": - $value = (!isset($value) || $value === "") ? "NULL" : floatval($value); - break; - case "t": - $value = (!isset($value) || $value === "") ? "NULL" : "'".$this->db_escape_string($value)."'"; - break; - case "d": - $value = (!isset($value) || $value === "") ? "NULL" : "'".$this->db_escape_string($value)."'"; - break; - case "i2": - $value = (!isset($value) || $value === "") ? 0 : intval($value); - break; - } - return $value; + // METHOD: db_time_format + // PARAMS: age or datetime difference + // micro on off (default false) + // RETURN: Y/M/D/h/m/s formatted string (like TimeStringFormat + // DESC: only for postgres. pretty formats an age or datetime difference string + public function db_time_format($age, $show_micro = false) + { + // in string (datetime diff): 1786 days 22:11:52.87418 + // or (age): 4 years 10 mons 21 days 12:31:11.87418 + // also -09:43:54.781021 or without - prefix + + preg_match("/(.*)?(\d{2}):(\d{2}):(\d{2})(\.(\d+))/", $age, $matches); + + $prefix = $matches[1] != '-' ? $matches[1] : ''; + $hour = $matches[2] != '00' ? preg_replace('/^0/', '', $matches[2]) : ''; + $minutes = $matches[3] != '00' ? preg_replace('/^0/', '', $matches[3]) : ''; + $seconds = $matches[4] != '00' ? preg_replace('/^0/', '', $matches[4]) : ''; + $milliseconds = $matches[6]; + + return $prefix.($hour ? $hour.'h ' : '').($minutes ? $minutes.'m ' : '').($seconds ? $seconds.'s' : '').($show_micro && $milliseconds? ' '.$milliseconds.'ms' : ''); + } + + // METHOD: db_array_parse + // PARAMS: text: input text to parse to an array + // RETURN: PHP array of the parsed data + // DESC: this is only needed for Postgresql. Converts postgresql arrays to PHP + public function db_array_parse($text) + { + return $this->db_functions->_db_array_parse($text, $output); + } + + // METHOD: db_sql_escape + // PARAMS: value -> to escape data + // kbn -> escape trigger type + // RETURN: escaped value + // DESC : clear up any data for valid DB insert + public function db_sql_escape($value, $kbn = "") + { + switch ($kbn) { + case "i": + $value = (!isset($value) || $value === "") ? "NULL" : intval($value); + break; + case "f": + $value = (!isset($value) || $value === "") ? "NULL" : floatval($value); + break; + case "t": + $value = (!isset($value) || $value === "") ? "NULL" : "'".$this->db_escape_string($value)."'"; + break; + case "d": + $value = (!isset($value) || $value === "") ? "NULL" : "'".$this->db_escape_string($value)."'"; + break; + case "i2": + $value = (!isset($value) || $value === "") ? 0 : intval($value); + break; } - } // end if db class -?> + return $value; + } +} // end if db class diff --git a/www/libs/Class.Form.Generate.inc b/www/libs/Class.Form.Generate.inc index 19c0f866..00eed11c 100644 --- a/www/libs/Class.Form.Generate.inc +++ b/www/libs/Class.Form.Generate.inc @@ -1,1801 +1,1707 @@ array( - * "name_of_col_in_table" => array( - * "value" => $name_of_col_in_table", - * "pk" => 1/0 - sets the primary key (only one) - * "fk" => 1/0 - sets the foreign key (do not use at the moment ... buggy ;) - * "mandatory" => 1/0 - triggers * in output, but nor error check - * "output_name" => "text" - text put as label for the element - * "type" => "view/text/textarea/date/drop_down_db/drop_down_array/drop_down_db_input/drop_down_db_same_db/radio_array/binary/hidden/file/password" - * View is special, it just prints out the data as is, will not be saved - * 1) more will come - * 2) keep in mind that binary will not be checked, as it is always set to a value (default is "no") - * ---- the next four fields are only NECESSARY (!!!) for drop_down_db_input - * "table_name" => the name of the table for the drop down - * "pk_name" => the pk_name of the table for the drop down - * "input_name" => the text field name in the table for the drop down - * "input_value" => the $name of input_name (must be same) - * "order_by" => "order bY" string for drop_down_db(_input) if no query given but fields set - * "query" => for drop_down_db/array if no outer query given - * "preset" => value to preset when array is unset (available for all types) - * "element_list" => array ( "true", "false") - MUST (!) be set for binary - * "length" => "nr" - only available for "text" (maxlength) - * "size" => "nr" - only available for "text" (size of input field) - * "rows" => "nr" - only available for "textarea" - * "cols" => "nr" - only available for "textarea" - * "error_check" => "custom/email/date/number/unique" - 1) more will come - * "error_regex" => "regex" - if error_check is custom regex here - * "error_example" => "text" - example input text for error_check (only custom right now) - * "empty" => "value/text" - ONLY for view. If no data found, set this value - * --- file: - * "save_dir" => "directory where it should be saved to - * "accept_type" => "mime types accepted (mime/text,mime/jpeg ... etc)" - * ), - * ... - * ), - * # all reference tables (n<->n) - * "reference_array" => array( - * "name_u_choose" => array( - * "table_name" => "table_u_choose_for_n_to_n_table", - * "other_table_pk" => "primary_key_name_of_reference_table", - * "output_name" => "Printed out next to multiple select field", - * "mandatory" => 1/0 for must be selected, - * "select_size" => size of multiple select field, - * "query" => "the query to load the multiple select field - * (select id, concat_ws(" ",name_a, name_b) from reference_table)", - * "selected" => $var_name for name="xx" in multiple select - * ), - * ... - * ), - * # fields that should be shown from the load_query and with what aditions - * "show_fields" => array( - * array( - * "name" => "name_of_col_in_query" - col from the query that should be shown - * "before_value" => "text" - if set this text will be put in FRONT of the value from the col - * "binary" => array ("true","false") - for 1/0 fields in DB changes it int human readable format - * ), - * ... - * ), - * # the laod query - * "load_query" => "query", - query for generting the list in "load" function - * # the name of the main table - * "table_name" => "table_name" - the exakt name of the table ... - * # security levels for load ... usefull is delete with a low number and load with a high - * "security_level" => - * "load" => ... for load to appear - * "new" => 1... - security level minimum required for new part to appear (goes in hadn with save) - * "save" => ... - should be same level as new [or its a bit useless] - * "delete" => ... - for delete - * - * example for a page: - * - * $form->form_procedure_load(${$form->archive_pk_name}); - * $form->form_procedure_new(); - * $form->form_procedure_save(); - * $form->form_procedure_delete(); - * - * $form->form_create_load(); - * $form->form_create_new(); - * if ($form->yes) - * { - * $from->form_create_element("element_name"); - * $from->form_create_hidden_fields(); - * $form->form_creae_save_delete(); - * } - * $form->_form(); - * - * - * list_of_functions: - * form_get_col_name_from_key($want_key) - * returns the value for the key (out of table_array) - * form_get_col_name_array_from_key($want_key) - * returns array of values for the searched key ... - * form_print_msg () [form_error_msg()] - * returns the HTML formated part with the error msg, if one exists - * form_procedure_load($id) - * starts the loading procedure - * form_procedure_new() - * starts the new procedure - * form_procedure_save() - * starts the save procedure - * form_procedure_delete() - * starts the delete procedure - * form_create_load () [form_load()] - * returns the HTML part for loading a table row, load_query & field_array have to be set for this!!!!!! - * form_create_new () [form_new()] - * returns the HTML part for creating a new table_row - * form_create_save_delete () [form_delete_save()] - * returns the HTML part for saveing and deleteing one table_row - * form_create_element ($element_name, $query="") - * creates and HTML element based on the description in the table_array array, second parameter is for drop_down fields, either a query for _db or an array for _array - * form_error_check() - * checks on errors after submit based on the settings in the table_array array - * form_set_order() - * if it finds the order flag set in the table_array sets the order for the current element to MAX+1 from the DB - * form_unset_table_array() - * unsets the table_array value fields for new entries - * form_create_hidden_fields($hidden_array) - * outputs a string with the HTML hidden fields (array must be $name["hidden_name"]=$hidden_value) - * form_create_element_reference_table($table_name) [form_show_reference_table()] - * creates and table tr part for the reference table name given - * form_load_table_array($pk_id=0) - * loads the table_array and the reference tables for the pk_id set in the class or given via parameter - * form_save_table_array($addslashes=0) - * save table array & reference tables - * form_delete_table_array() - * deletes table array & reference tables - * - * // debug methods - * form_dump_table_array() - * returns a formatted string with alle table_array vars - * - * HISTORY: - * 2005/07/14 (cs) fixed the insert for reference tables, prepared drop down text insert to be correct [untested] - * 2005/07/08 (cs) added int set for integer insert values - * 2005/07/07 (cs) bug with protected data, error got triggered even if no delete was pressed - * 2005/06/30 (cs) changed color settings, they get set from CSS file now - * 2005/06/29 (cs) finished full support for element_lists - * 2005/06/24 (cs) added full support for a list in a form, a list is written to an other table and the other table has this forms PK as a FK - * 2005/06/23 (cs) changed all HTML to Smarty Template Type - * 2005/06/22 (cs) you can put more than one error check into the error field; alphanumeric check and unique in same table are new - * 2005/06/21 (cs) changed the error_msg writings to debug - * 2005/03/31 (cs) fixed the class call with all debug vars - * 2004/11/10 (cs) fix bug with preset: don't check if set, check if variable is set at all - * 2004/09/30 (cs) layout change - * 2003-06-13: error with "protected" flag, fixed and added error msg, if protected flag is detected during - * delete - * 2003-06-12: adapted class to register_global_vars off - * 2003-06-10: in procedure_delete function I added "protected" variable clause, so if this field exists - * in the DB and is set, you are not able to delete [at the moment used for admin edit user - * in DB] - * 2003-05-30: _temp for drop_down_db was added always and not only for same_db - * 2003-05-28: added drop_down_db_same_db for drop down/input combinations going into the same DB. - * WARNING!!! please be careful that input_value var name MUST have the ending _temp - * This might get change in future - * added a "where" field to the field list, this is only used for the drop_down for selecting - * only a certain field list. If where is filled out and used in combination with insert (not same_db) - * then this key will be SET when inserted into the DB !!! - * 2003-04-09: added open_dir for download of file (URL), save_dir is only for upload (absolute path) - * added require once for class_db_array_io.inc - * 2003-03-31: added a file upload module (type==file) - * 2003-03-20: added form_procedure_new, etc functions so for default calls it is easier to write - * also added security levels to all functions where it is needed - * 2003-03-14: changed the static error msgs to dynamic ones - * 2003-03-13: very bad bug with getting key function. fixed it (set first array value always) - * reason was that in second if I forgot to check if the second method field was really - * set, so I compared to empty which was always right. - * 2003-03-11: started renaming some functions: - * form_load, form_new, form_delete_save -> form_create_... (and _save_delete) - * .._show_reference_table -> create_element_reference_table - * added language array - * - kept old var names/function names for backward compatbile - * 2003-03-10: added flag for form_delete_save, first flag hides delete part, second flag - * hides checkbox for delete, both are set 0 default - * added drop_down_db_input element type. - * next to a drop down with elements froma db, there is an input field, - * if something is input there and not yet in the DB it will be inserted into - * the db first and then selected in the drop down, if already in db, the element - * in the drop down will be selected - * 2003-03-07: form_create_hidden_fields() has to be called mandatory - * 2003-03-06: if nothing selected for reference table, do not write - * a wrong return in form_delete_table_array quit the function to early - * 2003-03-04: drop_down_array value for option was left from array and - * not right - * 2003-02-27: added another check in unset if reference array exists - * 2003-02-26: change form to extend db_array_io and created load, save, - * delete functions removed all reference table functions, - * except show function rewrite config array - * re-wrote the class info vars into array - * 2003-02-25: added reference table functions - * 2002-10-22: create this class so creating basic and medium form pages - * can be handled easy. - * with a given config file the class handles error checks, - * save data, loads data, etc - *********************************************************************/ +/******************************************************************** +* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) +* CREATED: 2002/10/22 +* VERSION: 2.4.9 +* RELEASED LICENSE: GNU GPL 3 +* SHORT DESCRIPTION: +* ~ 2003/02/26: decided to move away from single class and change this +* to extend db_array_io which extends db_io. this is much more efficient +* in use of vars and use of methods of other classes +* +* ~ 2002/10/20: this class contains a set of functions that helps in creating +* more or less default forms, or supports u in handling normal +* form data +* +* description of the variables && arrays that have to be set ... +* $name_u_choose=array( +* # this is the description of ALL fields in the main table +* "table_array" => array( +* "name_of_col_in_table" => array( +* "value" => $name_of_col_in_table", +* "pk" => 1/0 - sets the primary key (only one) +* "fk" => 1/0 - sets the foreign key (do not use at the moment ... buggy ;) +* "mandatory" => 1/0 - triggers * in output, but nor error check +* "output_name" => "text" - text put as label for the element +* "type" => "view/text/textarea/date/drop_down_db/drop_down_array/drop_down_db_input/drop_down_db_same_db/radio_array/binary/hidden/file/password" +* View is special, it just prints out the data as is, will not be saved +* 1) more will come +* 2) keep in mind that binary will not be checked, as it is always set to a value (default is "no") +* ---- the next four fields are only NECESSARY (!!!) for drop_down_db_input +* "table_name" => the name of the table for the drop down +* "pk_name" => the pk_name of the table for the drop down +* "input_name" => the text field name in the table for the drop down +* "input_value" => the $name of input_name (must be same) +* "order_by" => "order bY" string for drop_down_db(_input) if no query given but fields set +* "query" => for drop_down_db/array if no outer query given +* "preset" => value to preset when array is unset (available for all types) +* "element_list" => array ( "true", "false") - MUST (!) be set for binary +* "length" => "nr" - only available for "text" (maxlength) +* "size" => "nr" - only available for "text" (size of input field) +* "rows" => "nr" - only available for "textarea" +* "cols" => "nr" - only available for "textarea" +* "error_check" => "custom/email/date/number/unique" - 1) more will come +* "error_regex" => "regex" - if error_check is custom regex here +* "error_example" => "text" - example input text for error_check (only custom right now) +* "empty" => "value/text" - ONLY for view. If no data found, set this value +* --- file: +* "save_dir" => "directory where it should be saved to +* "accept_type" => "mime types accepted (mime/text,mime/jpeg ... etc)" +* ), +* ... +* ), +* # all reference tables (n<->n) +* "reference_array" => array( +* "name_u_choose" => array( +* "table_name" => "table_u_choose_for_n_to_n_table", +* "other_table_pk" => "primary_key_name_of_reference_table", +* "output_name" => "Printed out next to multiple select field", +* "mandatory" => 1/0 for must be selected, +* "select_size" => size of multiple select field, +* "query" => "the query to load the multiple select field +* (select id, concat_ws(" ",name_a, name_b) from reference_table)", +* "selected" => $var_name for name="xx" in multiple select +* ), +* ... +* ), +* # fields that should be shown from the load_query and with what aditions +* "show_fields" => array( +* array( +* "name" => "name_of_col_in_query" - col from the query that should be shown +* "before_value" => "text" - if set this text will be put in FRONT of the value from the col +* "binary" => array ("true","false") - for 1/0 fields in DB changes it int human readable format +* ), +* ... +* ), +* # the laod query +* "load_query" => "query", - query for generting the list in "load" function +* # the name of the main table +* "table_name" => "table_name" - the exakt name of the table ... +* # security levels for load ... usefull is delete with a low number and load with a high +* "security_level" => +* "load" => ... for load to appear +* "new" => 1... - security level minimum required for new part to appear (goes in hadn with save) +* "save" => ... - should be same level as new [or its a bit useless] +* "delete" => ... - for delete +* +* example for a page: +* +* $form->form_procedure_load(${$form->archive_pk_name}); +* $form->form_procedure_new(); +* $form->form_procedure_save(); +* $form->form_procedure_delete(); +* +* $form->form_create_load(); +* $form->form_create_new(); +* if ($form->yes) +* { +* $from->form_create_element("element_name"); +* $from->form_create_hidden_fields(); +* $form->form_creae_save_delete(); +* } +* $form->_form(); +* +* +* list_of_functions: +* form_get_col_name_from_key($want_key) +* returns the value for the key (out of table_array) +* form_get_col_name_array_from_key($want_key) +* returns array of values for the searched key ... +* form_print_msg () [form_error_msg()] +* returns the HTML formated part with the error msg, if one exists +* form_procedure_load($id) +* starts the loading procedure +* form_procedure_new() +* starts the new procedure +* form_procedure_save() +* starts the save procedure +* form_procedure_delete() +* starts the delete procedure +* form_create_load () [form_load()] +* returns the HTML part for loading a table row, load_query & field_array have to be set for this!!!!!! +* form_create_new () [form_new()] +* returns the HTML part for creating a new table_row +* form_create_save_delete () [form_delete_save()] +* returns the HTML part for saveing and deleteing one table_row +* form_create_element ($element_name, $query="") +* creates and HTML element based on the description in the table_array array, second parameter is for drop_down fields, either a query for _db or an array for _array +* form_error_check() +* checks on errors after submit based on the settings in the table_array array +* form_set_order() +* if it finds the order flag set in the table_array sets the order for the current element to MAX+1 from the DB +* form_unset_table_array() +* unsets the table_array value fields for new entries +* form_create_hidden_fields($hidden_array) +* outputs a string with the HTML hidden fields (array must be $name["hidden_name"]=$hidden_value) +* form_create_element_reference_table($table_name) [form_show_reference_table()] +* creates and table tr part for the reference table name given +* form_load_table_array($pk_id=0) +* loads the table_array and the reference tables for the pk_id set in the class or given via parameter +* form_save_table_array($addslashes=0) +* save table array & reference tables +* form_delete_table_array() +* deletes table array & reference tables +* +* // debug methods +* form_dump_table_array() +* returns a formatted string with alle table_array vars +* +* HISTORY: +* 2005/07/14 (cs) fixed the insert for reference tables, prepared drop down text insert to be correct [untested] +* 2005/07/08 (cs) added int set for integer insert values +* 2005/07/07 (cs) bug with protected data, error got triggered even if no delete was pressed +* 2005/06/30 (cs) changed color settings, they get set from CSS file now +* 2005/06/29 (cs) finished full support for element_lists +* 2005/06/24 (cs) added full support for a list in a form, a list is written to an other table and the other table has this forms PK as a FK +* 2005/06/23 (cs) changed all HTML to Smarty Template Type +* 2005/06/22 (cs) you can put more than one error check into the error field; alphanumeric check and unique in same table are new +* 2005/06/21 (cs) changed the error_msg writings to debug +* 2005/03/31 (cs) fixed the class call with all debug vars +* 2004/11/10 (cs) fix bug with preset: don't check if set, check if variable is set at all +* 2004/09/30 (cs) layout change +* 2003-06-13: error with "protected" flag, fixed and added error msg, if protected flag is detected during +* delete +* 2003-06-12: adapted class to register_global_vars off +* 2003-06-10: in procedure_delete function I added "protected" variable clause, so if this field exists +* in the DB and is set, you are not able to delete [at the moment used for admin edit user +* in DB] +* 2003-05-30: _temp for drop_down_db was added always and not only for same_db +* 2003-05-28: added drop_down_db_same_db for drop down/input combinations going into the same DB. +* WARNING!!! please be careful that input_value var name MUST have the ending _temp +* This might get change in future +* added a "where" field to the field list, this is only used for the drop_down for selecting +* only a certain field list. If where is filled out and used in combination with insert (not same_db) +* then this key will be SET when inserted into the DB !!! +* 2003-04-09: added open_dir for download of file (URL), save_dir is only for upload (absolute path) +* added require once for class_db_array_io.inc +* 2003-03-31: added a file upload module (type==file) +* 2003-03-20: added form_procedure_new, etc functions so for default calls it is easier to write +* also added security levels to all functions where it is needed +* 2003-03-14: changed the static error msgs to dynamic ones +* 2003-03-13: very bad bug with getting key function. fixed it (set first array value always) +* reason was that in second if I forgot to check if the second method field was really +* set, so I compared to empty which was always right. +* 2003-03-11: started renaming some functions: +* form_load, form_new, form_delete_save -> form_create_... (and _save_delete) +* .._show_reference_table -> create_element_reference_table +* added language array +* - kept old var names/function names for backward compatbile +* 2003-03-10: added flag for form_delete_save, first flag hides delete part, second flag +* hides checkbox for delete, both are set 0 default +* added drop_down_db_input element type. +* next to a drop down with elements froma db, there is an input field, +* if something is input there and not yet in the DB it will be inserted into +* the db first and then selected in the drop down, if already in db, the element +* in the drop down will be selected +* 2003-03-07: form_create_hidden_fields() has to be called mandatory +* 2003-03-06: if nothing selected for reference table, do not write +* a wrong return in form_delete_table_array quit the function to early +* 2003-03-04: drop_down_array value for option was left from array and +* not right +* 2003-02-27: added another check in unset if reference array exists +* 2003-02-26: change form to extend db_array_io and created load, save, +* delete functions removed all reference table functions, +* except show function rewrite config array +* re-wrote the class info vars into array +* 2003-02-25: added reference table functions +* 2002-10-22: create this class so creating basic and medium form pages +* can be handled easy. +* with a given config file the class handles error checks, +* save data, loads data, etc +*********************************************************************/ - // try to include file from LIBS path, or from normal path - _spl_autoload('Class.DB.Array.IO.inc'); +// try to include file from LIBS path, or from normal path +_spl_autoload('Class.DB.Array.IO.inc'); - class form extends db_array_io +class form extends db_array_io +{ + // rest + public $field_array = array (); // for the load statetment describes which elements from the load query should be shown and i which format + public $load_query; // the query needed for loading a data set (one row in the table) + public $col_name; // the name of the columen (before _) [used for order button] + public $yes; // the yes flag that triggers the template to show ALL and not only new/load + public $msg; // the error msg + public $error; // the error flag set for printing red error msg + public $warning; // warning flag, for information (saved, loaded, etc) + public $archive_pk_name; // the pk name for the load select form + private $int_pk_name; // primary key, only internal usage + public $reference_array = array (); // reference arrays -> stored in $this->reference_array[$table_name]=>array(); + public $element_list; // element list for elements next to each other as a special sub group + public $my_page_name; // the name of the page without .php extension + // buttons and checkboxes + public $archive; + public $new; + public $really_new; + public $delete; + public $really_delete; + public $save; + // security publics + public $group_level_user; + public $security_levels; + // layout publics + public $table_width; + + // now some default error msgs (english) + public $language_array = array (); + + // METHOD constructor + // PARAMS $db_config -> connect to DB + // $lang -> language code ("en", "ja", etc) + // $table_width -> width of table + // $db_debug -> turns db_io debug on/off (DB_DEBUG as global var does the same) + public function __construct($db_config, $lang, $table_width = 750, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) { - // rest - public $field_array = array (); // for the load statetment describes which elements from the load query should be shown and i which format - public $load_query; // the query needed for loading a data set (one row in the table) - public $col_name; // the name of the columen (before _) [used for order button] - public $yes; // the yes flag that triggers the template to show ALL and not only new/load - public $msg; // the error msg - public $error; // the error flag set for printing red error msg - public $warning; // warning flag, for information (saved, loaded, etc) - public $archive_pk_name; // the pk name for the load select form - private $int_pk_name; // primary key, only internal usage - public $reference_array = array (); // reference arrays -> stored in $this->reference_array[$table_name]=>array(); - public $element_list; // element list for elements next to each other as a special sub group - public $my_page_name; // the name of the page without .php extension - // buttons and checkboxes - public $archive; - public $new; - public $really_new; - public $delete; - public $really_delete; - public $save; - // security publics - public $group_level_user; - public $security_levels; - // layout publics - public $table_width; - - // now some default error msgs (english) - public $language_array = array (); - - // METHOD constructor - // PARAMS $db_config -> connect to DB - // $lang -> language code ("en", "ja", etc) - // $table_width -> width of table - // $db_debug -> turns db_io debug on/off (DB_DEBUG as global var does the same) - public function __construct($db_config, $lang, $table_width = 750, $debug = 0, $db_debug = 0, $echo = 1, $print = 0) - { - $this->my_page_name = $this->get_page_name(1); - // init the language class - _spl_autoload('Class.l10n.inc'); - $this->l = new l10n($lang); - // load config array - // get table array definitions for current page name - // WARNING: auto spl load does not work with this as it is an array and not a function/object + $this->my_page_name = $this->get_page_name(1); + // init the language class + _spl_autoload('Class.l10n.inc'); + $this->l = new l10n($lang); + // load config array + // get table array definitions for current page name + // WARNING: auto spl load does not work with this as it is an array and not a function/object // $flag = _spl_autoload('array_'.$this->my_page_name.'.inc'); - include(TABLE_ARRAYS."array_".$this->my_page_name.".inc"); + include(TABLE_ARRAYS."array_".$this->my_page_name.".inc"); - $config_array = ${$this->my_page_name}; + $config_array = ${$this->my_page_name}; - // start the array_io class which will start db_io ... - parent::__construct($db_config, $config_array["table_array"], $config_array["table_name"], $debug, $db_debug, $echo, $print); - // here should be a check if the config_array is correct ... - // - $this->field_array = $config_array["show_fields"]; - $this->load_query = $config_array["load_query"]; - $this->archive_pk_name = "a_".$this->pk_name; - $this->col_name = str_replace("_id", "", $this->pk_name); - $this->int_pk_name = $this->pk_name; - // check if reference_arrays are given and proceed them - if (is_array($config_array["reference_arrays"])) - { - while (list($key, $value) = each($config_array["reference_arrays"])) - { - $this->reference_array[$key] = $value; - } + // start the array_io class which will start db_io ... + parent::__construct($db_config, $config_array["table_array"], $config_array["table_name"], $debug, $db_debug, $echo, $print); + // here should be a check if the config_array is correct ... + // + $this->field_array = $config_array["show_fields"]; + $this->load_query = $config_array["load_query"]; + $this->archive_pk_name = "a_".$this->pk_name; + $this->col_name = str_replace("_id", "", $this->pk_name); + $this->int_pk_name = $this->pk_name; + // check if reference_arrays are given and proceed them + if (is_array($config_array["reference_arrays"])) { + while (list($key, $value) = each($config_array["reference_arrays"])) { + $this->reference_array[$key] = $value; } - if (is_array($config_array["element_list"])) - { - while (list($key, $value) = each($config_array["element_list"])) - { - $this->element_list[$key] = $value; - } - } - - // layout - $this->table_width = $table_width; - - // set button vars - $this->archive = $_POST["archive"]; - $this->new = $_POST["new"]; - $this->really_new = $_POST["really_new"]; - $this->delete = $_POST["delete"]; - $this->really_delete = $_POST["really_delete"]; - $this->save = $_POST["save"]; - $this->remove_button = $_POST["remove_button"]; - - // security settings - $this->group_level_user = $_SESSION["GROUP_LEVEL"]; - // security levels for buttons/actions - // if array does not exists create basic - if (!is_array($config_array["security_level"]) || count($config_array["security_level"]) < 4) - $config_array["security_level"] = array("load" => 100, "new" => 100, "save" => 100, "delete" => 100); - // write array to class var - $this->security_level = $config_array["security_level"]; - - // internal - $this->class_info["form"] = array( - "class_name" => "Form create", - "class_version" => "2.4.9", - "class_created" => "2002-10-22", - "class_author" => "cs/gullevek/at" - ); } - - // dumps all values into output (for error msg) - public function form_dump_table_array() - { - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - $string .= "TABLE ARRAY DUMP: ".$this->table_name."
"; - while (list($key, $value) = each($this->table_array)) - { - $string .= "$key: ".$value["value"]."
"; - } - return $string; - } - - // dekonstruktor - // writes out error msg to global var - // closes db connection - public function __destruct() - { - // close DB connection - parent::__destruct(); - } - - /***************************************************** - Along here are wrapper functions for the former, old names - */ - - public function form_load() - { - return $this->form_create_load(); - } - - public function form_new($hide_new_checkbox = 0) - { - return $this->form_create_new($hide_new_checkbox); - } - - public function form_delete_save($hide_delete = 0, $hide_delete_checkbox = 0) - { - return $this->form_create_save_delete($hide_delete, $hide_delete_checkbox); - } - - public function form_error_msg() - { - return $this->form_print_msg(); - } - - public function form_show_reference_table($table_name) - { - return $this->form_create_element_reference_table($table_name); - } - - public function form_show_list_table($table_name) - { - return $this->form_create_element_list_table($table_name); - } - - // END wrapper - - // METHOD form_get_col_name_from_key - // PARAMS $want_key: the key where u want the data from - // $key_value: if set searches for special right value - // RETURN the value of the $want_key array field - // works only with fields that appear only ONCE - // if multiple gets only FIRST - public function form_get_col_name_from_key($want_key, $key_value = "") - { - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - if ($value[$want_key] && !$key_value) - return $key; - else if ($value[$want_key] == $key_value && $key_value) - return $key; + if (is_array($config_array["element_list"])) { + while (list($key, $value) = each($config_array["element_list"])) { + $this->element_list[$key] = $value; } } - // METHOD form_get_col_name_array_from_key - // PARAMS $want_key: the key where u want the data from - // $key_value: if set searches for special right value - // RETURN array of fields - public function form_get_col_name_array_from_key($want_key, $key_value = "") - { - $key_array = array(); - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - if ($value[$want_key] && !$key_value) - array_push($key_array, $key); - if ($value[$want_key] == $key_value) - array_push($key_array, $key); - } - return $key_array; - } + // layout + $this->table_width = $table_width; - // METHOD form_print_msg - // PARAMS none - // RETURN formated output for the error && warning msg - public function form_print_msg() - { - if ($this->error) - { - $class = "error"; - } - if ($this->warning) - { - $class = "warning"; - } - return array('msg' => $this->msg, 'width' => $this->table_width, 'class' => $class); - } + // set button vars + $this->archive = $_POST["archive"]; + $this->new = $_POST["new"]; + $this->really_new = $_POST["really_new"]; + $this->delete = $_POST["delete"]; + $this->really_delete = $_POST["really_delete"]; + $this->save = $_POST["save"]; + $this->remove_button = $_POST["remove_button"]; - // next for functions are pre_test fkts for easier default new,load, etc handling - // METHOD form_procedure_load - // PARAMS archive_id - which ID should be loaded - // RETURN none - // DESC default load procedure - public function form_procedure_load($archive_id) - { - if ($this->archive && $archive_id && $this->group_level_user <= $this->security_level["load"]) - { - $this->form_load_table_array($archive_id); + // security settings + $this->group_level_user = $_SESSION["GROUP_LEVEL"]; + // security levels for buttons/actions + // if array does not exists create basic + if (!is_array($config_array["security_level"]) || count($config_array["security_level"]) < 4) { + $config_array["security_level"] = array("load" => 100, "new" => 100, "save" => 100, "delete" => 100); + } + // write array to class var + $this->security_level = $config_array["security_level"]; + + // internal + $this->class_info["form"] = array( + "class_name" => "Form create", + "class_version" => "2.4.9", + "class_created" => "2002-10-22", + "class_author" => "cs/gullevek/at" + ); + } + + // dumps all values into output (for error msg) + public function form_dump_table_array() + { + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + $string .= "TABLE ARRAY DUMP: ".$this->table_name."
"; + while (list($key, $value) = each($this->table_array)) { + $string .= "$key: ".$value["value"]."
"; + } + return $string; + } + + // dekonstruktor + // writes out error msg to global var + // closes db connection + public function __destruct() + { + // close DB connection + parent::__destruct(); + } + + /***************************************************** + Along here are wrapper functions for the former, old names + */ + + public function form_load() + { + return $this->form_create_load(); + } + + public function form_new($hide_new_checkbox = 0) + { + return $this->form_create_new($hide_new_checkbox); + } + + public function form_delete_save($hide_delete = 0, $hide_delete_checkbox = 0) + { + return $this->form_create_save_delete($hide_delete, $hide_delete_checkbox); + } + + public function form_error_msg() + { + return $this->form_print_msg(); + } + + public function form_show_reference_table($table_name) + { + return $this->form_create_element_reference_table($table_name); + } + + public function form_show_list_table($table_name) + { + return $this->form_create_element_list_table($table_name); + } + + // END wrapper + + // METHOD form_get_col_name_from_key + // PARAMS $want_key: the key where u want the data from + // $key_value: if set searches for special right value + // RETURN the value of the $want_key array field + // works only with fields that appear only ONCE + // if multiple gets only FIRST + public function form_get_col_name_from_key($want_key, $key_value = "") + { + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + if ($value[$want_key] && !$key_value) { + return $key; + } elseif ($value[$want_key] == $key_value && $key_value) { + return $key; + } + } + } + + // METHOD form_get_col_name_array_from_key + // PARAMS $want_key: the key where u want the data from + // $key_value: if set searches for special right value + // RETURN array of fields + public function form_get_col_name_array_from_key($want_key, $key_value = "") + { + $key_array = array(); + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + if ($value[$want_key] && !$key_value) { + array_push($key_array, $key); + } + if ($value[$want_key] == $key_value) { + array_push($key_array, $key); + } + } + return $key_array; + } + + // METHOD form_print_msg + // PARAMS none + // RETURN formated output for the error && warning msg + public function form_print_msg() + { + if ($this->error) { + $class = "error"; + } + if ($this->warning) { + $class = "warning"; + } + return array('msg' => $this->msg, 'width' => $this->table_width, 'class' => $class); + } + + // next for functions are pre_test fkts for easier default new,load, etc handling + // METHOD form_procedure_load + // PARAMS archive_id - which ID should be loaded + // RETURN none + // DESC default load procedure + public function form_procedure_load($archive_id) + { + if ($this->archive && $archive_id && $this->group_level_user <= $this->security_level["load"]) { + $this->form_load_table_array($archive_id); + $this->yes = 1; + } + } + + // METHOD form_procedure_new + // PARAMS none + // RETURN none + // DESC default new procedure + public function form_procedure_new() + { + if ($this->new && $this->group_level_user <= $this->security_level["new"]) { + if ($this->really_new == "yes") { + $this->form_unset_table_array(); + } else { + $this->msg .= $this->l->__("You have to select the Checkbox for New!
"); + $this->error = 2; + } + $this->yes = 1; + } + } + + // METHOD form_procedure_save + // PARAMS none + // RETURN none + // DESC default save procedure + public function form_procedure_save() + { + if ($this->save && $this->group_level_user <= $this->security_level["save"]) { + $this->form_error_check(); + if (!$this->error) { + $this->form_save_table_array(); + } + $this->yes = 1; + } + } + + // METHOD form_procedure_delete + // PARAMS none + // RETURN none + // DESC default delete procedure + public function form_procedure_delete() + { + // delete is also by "protected" + if ($this->delete && $this->group_level_user <= $this->security_level["delete"] && !$this->table_array["protected"]["value"]) { + if ($this->table_array["protected"]["value"]) { + $this->msg .= $this->l->__("Cannot delete this Dataset, because it is internaly protected!"); + $this->error = 2; + } + if ($this->really_delete == "yes") { + $this->form_delete_table_array(); + } else { + $this->msg .= $this->l->__("You have to select the Checkbox for Delete!
"); + $this->error = 2; $this->yes = 1; } } + } - // METHOD form_procedure_new - // PARAMS none - // RETURN none - // DESC default new procedure - public function form_procedure_new() - { - if ($this->new && $this->group_level_user <= $this->security_level["new"]) - { - if ($this->really_new == "yes") - { - $this->form_unset_table_array(); - } else - { - $this->msg .= $this->l->__("You have to select the Checkbox for New!
"); - $this->error = 2; - } - $this->yes = 1; - } - } - - // METHOD form_procedure_save - // PARAMS none - // RETURN none - // DESC default save procedure - public function form_procedure_save() - { - if ($this->save && $this->group_level_user <= $this->security_level["save"]) - { - $this->form_error_check(); - if (!$this->error) - { - $this->form_save_table_array(); - } - $this->yes = 1; - } - } - - // METHOD form_procedure_delete - // PARAMS none - // RETURN none - // DESC default delete procedure - public function form_procedure_delete() - { - // delete is also by "protected" - if ($this->delete && $this->group_level_user <= $this->security_level["delete"] && !$this->table_array["protected"]["value"]) - { - if ($this->table_array["protected"]["value"]) - { - $this->msg .= $this->l->__("Cannot delete this Dataset, because it is internaly protected!"); - $this->error = 2; - } - if ($this->really_delete == "yes") - { - $this->form_delete_table_array(); - } - else - { - $this->msg .= $this->l->__("You have to select the Checkbox for Delete!
"); - $this->error = 2; - $this->yes = 1; - } - } - } - - // METHOD form_procedure_delete_from_element_list - // PARAMS none - // RETURN none - // DESC default delete procedure - public function form_procedure_delete_from_element_list($element_list, $remove_name) - { - // only do if the user is allowed to delete - if ($this->group_level_user <= $this->security_level["delete"] && !$this->table_array["protected"]["value"] && !$this->error) - { - for ($i = 0; $i < count($element_list); $i ++) - { + // METHOD form_procedure_delete_from_element_list + // PARAMS none + // RETURN none + // DESC default delete procedure + public function form_procedure_delete_from_element_list($element_list, $remove_name) + { + // only do if the user is allowed to delete + if ($this->group_level_user <= $this->security_level["delete"] && !$this->table_array["protected"]["value"] && !$this->error) { + for ($i = 0; $i < count($element_list); $i ++) { //$this->debug('form_error', "Array: ".is_array($this->element_list[$element_list[$i]]["read_data"])." | ".$this->element_list[$element_list[$i]]["delete"]); - // if prefix, set it - $prfx = ($this->element_list[$element_list[$i]]["prefix"]) ? $this->element_list[$element_list[$i]]["prefix"]."_" : ''; - // get the primary key - while (list($el_name, $data) = each($this->element_list[$element_list[$i]]["elements"])) - { - if ($data["pk_id"]) - $pk_name = $el_name; + // if prefix, set it + $prfx = ($this->element_list[$element_list[$i]]["prefix"]) ? $this->element_list[$element_list[$i]]["prefix"]."_" : ''; + // get the primary key + while (list($el_name, $data) = each($this->element_list[$element_list[$i]]["elements"])) { + if ($data["pk_id"]) { + $pk_name = $el_name; } - // which key should be deleted - $id = $remove_name[$i]; - if (($this->element_list[$element_list[$i]]["delete_name"] || $this->element_list[$element_list[$i]]["delete"]) && !$this->element_list[$element_list[$i]]["enable_name"]) - { - // flag var name - $flag = $remove_name[$i]."_flag"; + } + // which key should be deleted + $id = $remove_name[$i]; + if (($this->element_list[$element_list[$i]]["delete_name"] || $this->element_list[$element_list[$i]]["delete"]) && !$this->element_list[$element_list[$i]]["enable_name"]) { + // flag var name + $flag = $remove_name[$i]."_flag"; - if ($_POST[$flag] == "true") - { - $q = "DELETE FROM ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$id]; - $this->db_exec($q); - $this->msg .= $this->l->__("Removed entry from list
"); + if ($_POST[$flag] == "true") { + $q = "DELETE FROM ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$id]; + $this->db_exec($q); + $this->msg .= $this->l->__("Removed entry from list
"); + $this->warning = 1; + } // post okay true -> delete + } elseif (is_array($this->element_list[$element_list[$i]]["read_data"]) && !$this->element_list[$element_list[$i]]["delete"]) { + for ($j = 0; $j < count($_POST[$id]); $j ++) { + // if it is not activated + if (!$_POST[$remove_name[$i]][$j]) { + $q = "UPDATE ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$prfx.$pk_name][$j]; + // $this->debug('edit_db', "UP: $q"); + // $this->db_exec($q); + $this->msg .= $this->l->__("Disabled deselected entries from list
"); $this->warning = 1; - } // post okay true -> delete - } - elseif (is_array($this->element_list[$element_list[$i]]["read_data"]) && !$this->element_list[$element_list[$i]]["delete"]) - { - for ($j = 0; $j < count($_POST[$id]); $j ++) - { - // if it is not activated - if (!$_POST[$remove_name[$i]][$j]) - { - $q = "UPDATE ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$prfx.$pk_name][$j]; -// $this->debug('edit_db', "UP: $q"); - // $this->db_exec($q); - $this->msg .= $this->l->__("Disabled deselected entries from list
"); - $this->warning = 1; - } } } - elseif (is_array($this->element_list[$element_list[$i]]["read_data"]) && $this->element_list[$element_list[$i]]["delete"]) - { + } elseif (is_array($this->element_list[$element_list[$i]]["read_data"]) && $this->element_list[$element_list[$i]]["delete"]) { //$this->debug('form_clean', "ID [$id] [$prfx.$pk_name]"); //$this->debug('form_clean', "ID arr: ".$this->print_ar($_POST[$id])); //$this->debug('form_clean', "PK arr: ".$this->print_ar($_POST[$prfx.$pk_name])); - for ($j = 0; $j < count($_POST[$prfx.$pk_name]); $j ++) - { - if (!$_POST[$remove_name[$i]][$j] && $_POST[$prfx.$pk_name][$j]) - { - $q = "DELETE FROM ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$prfx.$pk_name][$j]; + for ($j = 0; $j < count($_POST[$prfx.$pk_name]); $j ++) { + if (!$_POST[$remove_name[$i]][$j] && $_POST[$prfx.$pk_name][$j]) { + $q = "DELETE FROM ".$element_list[$i]." WHERE ".$pk_name." = ".$_POST[$prfx.$pk_name][$j]; // $this->debug('edit_db', "DEL: $q"); - $this->db_exec($q); - $this->msg .= $this->l->__("Deleted deselected entries from list
"); - $this->warning = 1; - } + $this->db_exec($q); + $this->msg .= $this->l->__("Deleted deselected entries from list
"); + $this->warning = 1; } } - } // for each element group - } - if ($this->remove_button) - $this->yes = 1; + } + } // for each element group } + if ($this->remove_button) { + $this->yes = 1; + } + } - // METHOD form_create_load - // PARAMS none - // RETURN string from "load" part of form ... - public function form_create_load() - { - // when security leve is okay ... - if ($this->group_level_user <= $this->security_level["load"]) - { - $t_pk_name = $this->archive_pk_name; + // METHOD form_create_load + // PARAMS none + // RETURN string from "load" part of form ... + public function form_create_load() + { + // when security leve is okay ... + if ($this->group_level_user <= $this->security_level["load"]) { + $t_pk_name = $this->archive_pk_name; - // lade liste - $this->db_exec($this->load_query); - while ($res = $this->db_fetch_array()) - { - $pk_ids[] = $res[$this->int_pk_name]; - if ($res[$this->int_pk_name] == $this->table_array[$this->int_pk_name]["value"]) - { - $pk_selected = $res[$this->int_pk_name]; + // lade liste + $this->db_exec($this->load_query); + while ($res = $this->db_fetch_array()) { + $pk_ids[] = $res[$this->int_pk_name]; + if ($res[$this->int_pk_name] == $this->table_array[$this->int_pk_name]["value"]) { + $pk_selected = $res[$this->int_pk_name]; + } + unset($t_string); + for ($i = 0; $i < count($this->field_array); $i ++) { + if ($t_string) { + $t_string .= ", "; } - unset($t_string); - for ($i = 0; $i < count($this->field_array); $i ++) - { - if ($t_string) - $t_string .= ", "; - if ($this->field_array[$i]["before_value"]) - $t_string .= $this->field_array[$i]["before_value"]; - if ($this->field_array[$i]["binary"]) - $t_string .= ($res[$this->field_array[$i]["name"]]) ? $this->field_array[$i]["binary"][0] : $this->field_array[$i]["binary"][1]; - else - $t_string .= $res[$this->field_array[$i]["name"]]; + if ($this->field_array[$i]["before_value"]) { + $t_string .= $this->field_array[$i]["before_value"]; } + if ($this->field_array[$i]["binary"]) { + $t_string .= ($res[$this->field_array[$i]["name"]]) ? $this->field_array[$i]["binary"][0] : $this->field_array[$i]["binary"][1]; + } else { + $t_string .= $res[$this->field_array[$i]["name"]]; + } + } /* // */ - $pk_names[] = $t_string; + $pk_names[] = $t_string; + } + } // show it at all + return array('t_pk_name' => $t_pk_name, 'pk_ids' => $pk_ids, 'pk_names' => $pk_names, 'pk_selected' => $pk_selected); + } + + // METHOD form_create_new + // PARAMS none + // RETURN part for new + public function form_create_new($hide_new_checkbox = 0) + { + // when security level is okay + if ($this->group_level_user <= $this->security_level["new"]) { + if ($this->yes && !$hide_new_checkbox) { + $show_checkbox = 1; + } + // set type of new name + if ($this->yes) { + $new_name = $this->l->__("Clear all and create new"); + } else { + $new_name = $this->l->__("New"); + } + } // security level okay + return array('new_name' => $new_name, 'show_checkbox' => $show_checkbox); + } + + // METHOD form_create_save_delete + // PARAMS none + // RETURN string for delete / save part + public function form_create_save_delete($hide_delete = 0, $hide_delete_checkbox = 0) + { + if ($this->group_level_user <= $this->security_level["save"] || $this->group_level_user <= $this->security_level["delete"]) { + $old_school_hidden = 0; + if ($this->group_level_user <= $this->security_level["save"]) { + $seclevel_okay = 1; + if (!$this->table_array[$this->int_pk_name]["value"]) { + $save = $this->l->__("Save"); + } else { + $save = $this->l->__("Update"); } - } // show it at all - return array('t_pk_name' => $t_pk_name, 'pk_ids' => $pk_ids, 'pk_names' => $pk_names, 'pk_selected' => $pk_selected); + // print the old_school hidden if requestet + if ($old_school_hidden) { + $pk_name = $this->int_pk_name; + $pk_value = $this->table_array[$this->int_pk_name]["value"]; + } + } // show save part + // show delete part only if pk is set && we want to see the delete + if ($this->table_array[$this->int_pk_name]["value"] && !$hide_delete && $this->group_level_user <= $this->security_level["delete"]) { + $show_delete = 1; + } + } // print save/delete row at all$ + return array('seclevel_okay' => $seclevel_okay, 'save' => $save, 'pk_name' => $pk_name, 'pk_value' => $pk_value, 'show_delete' => $show_delete, 'hide_delete_checkbox' => $hide_delete_checkbox); + } // end of function + + // METHOD form_create_element + // PARAMS $element_name: the name from the array, you want to have build + // $query: can overrule internal query data, + // for drop down, as data comes from a reference table + // for drop_down_text it has to be an array with $key->$value + // RETURN element in HTML + public function form_create_element($element_name, $query = "") + { + // special 2nd color for "binary" attribut + if ($this->table_array[$element_name]["type"] == "binary" && !$this->table_array[$element_name]["value"]) { + $EDIT_FGCOLOR_T = 'edit_fgcolor_no'; + } else { + $EDIT_FGCOLOR_T = 'edit_fgcolor'; } - - // METHOD form_create_new - // PARAMS none - // RETURN part for new - public function form_create_new($hide_new_checkbox = 0) - { - // when security level is okay - if ($this->group_level_user <= $this->security_level["new"]) - { - if ($this->yes && !$hide_new_checkbox) - { - $show_checkbox = 1; - } - // set type of new name - if ($this->yes) - $new_name = $this->l->__("Clear all and create new"); - else - $new_name = $this->l->__("New"); - } // security level okay - return array('new_name' => $new_name, 'show_checkbox' => $show_checkbox); + $output_name = $this->table_array[$element_name]["output_name"]; + if ($this->table_array[$element_name]["mandatory"]) { + $output_name .= ' *'; } + // create right side depending on "definiton" in table_array + $type = $this->table_array[$element_name]["type"]; + // view only output + if ($this->table_array[$element_name]["type"] == "view") { + $data['value'] = !$this->table_array[$element_name]["value"] ? $this->table_array[$element_name]['empty'] : $this->table_array[$element_name]["value"]; + } + // binary true/false element + if ($this->table_array[$element_name]["type"] == "binary") { + for ($i = (count($this->table_array[$element_name]["element_list"]) - 1); $i >= 0; $i --) { + $data['value'][] = $i; + $data['output'][] = $this->table_array[$element_name]["element_list"][$i]; + $data['name'] = $element_name; + if (($i && $this->table_array[$element_name]["value"]) || (!$i && !$this->table_array[$element_name]["value"])) { + $data['checked'] = $this->table_array[$element_name]["value"]; + } - // METHOD form_create_save_delete - // PARAMS none - // RETURN string for delete / save part - public function form_create_save_delete($hide_delete = 0, $hide_delete_checkbox = 0) - { - if ($this->group_level_user <= $this->security_level["save"] || $this->group_level_user <= $this->security_level["delete"]) - { - $old_school_hidden = 0; - if ($this->group_level_user <= $this->security_level["save"]) - { - $seclevel_okay = 1; - if (!$this->table_array[$this->int_pk_name]["value"]) - { - $save = $this->l->__("Save"); - } - else - { - $save = $this->l->__("Update"); - } - // print the old_school hidden if requestet - if ($old_school_hidden) - { - $pk_name = $this->int_pk_name; - $pk_value = $this->table_array[$this->int_pk_name]["value"]; - } - } // show save part - // show delete part only if pk is set && we want to see the delete - if ($this->table_array[$this->int_pk_name]["value"] && !$hide_delete && $this->group_level_user <= $this->security_level["delete"]) - { - $show_delete = 1; - } - } // print save/delete row at all$ - return array('seclevel_okay' => $seclevel_okay, 'save' => $save, 'pk_name' => $pk_name, 'pk_value' => $pk_value, 'show_delete' => $show_delete, 'hide_delete_checkbox' => $hide_delete_checkbox); - } // end of function - - // METHOD form_create_element - // PARAMS $element_name: the name from the array, you want to have build - // $query: can overrule internal query data, - // for drop down, as data comes from a reference table - // for drop_down_text it has to be an array with $key->$value - // RETURN element in HTML - public function form_create_element($element_name, $query = "") - { - // special 2nd color for "binary" attribut - if ($this->table_array[$element_name]["type"] == "binary" && !$this->table_array[$element_name]["value"]) - $EDIT_FGCOLOR_T = 'edit_fgcolor_no'; - else - $EDIT_FGCOLOR_T = 'edit_fgcolor'; - $output_name = $this->table_array[$element_name]["output_name"]; - if ($this->table_array[$element_name]["mandatory"]) - $output_name .= ' *'; - // create right side depending on "definiton" in table_array - $type = $this->table_array[$element_name]["type"]; - // view only output - if ($this->table_array[$element_name]["type"] == "view") - { - $data['value'] = !$this->table_array[$element_name]["value"] ? $this->table_array[$element_name]['empty'] : $this->table_array[$element_name]["value"]; - } - // binary true/false element - if ($this->table_array[$element_name]["type"] == "binary") - { - for ($i = (count($this->table_array[$element_name]["element_list"]) - 1); $i >= 0; $i --) - { - $data['value'][] = $i; - $data['output'][] = $this->table_array[$element_name]["element_list"][$i]; - $data['name'] = $element_name; - if (($i && $this->table_array[$element_name]["value"]) || (!$i && !$this->table_array[$element_name]["value"])) - $data['checked'] = $this->table_array[$element_name]["value"]; - - if ($i) - $data['separator'] = ''; - } - } - // checkbox element - if ($this->table_array[$element_name]["type"] == "checkbox") - { - $data['name'] = $element_name; - $data['value'][] = $this->table_array[$element_name]["element_list"]; - $data['checked'] = $this->table_array[$element_name]["value"]; - } - // normal text element - if ($this->table_array[$element_name]["type"] == "text") - { - $data['name'] = $element_name; - $data['value'] = $this->table_array[$element_name]["value"]; - $data['size'] = $this->table_array[$element_name]["size"]; - $data['length'] = $this->table_array[$element_name]["length"]; - } - // password element, does not write back the value - if ($this->table_array[$element_name]["type"] == "password") - { - $data['name'] = $element_name; - $data['HIDDEN_value'] = $this->table_array[$element_name]["HIDDEN_value"]; - $data['size'] = $this->table_array[$element_name]["size"]; - $data['length'] = $this->table_array[$element_name]["length"]; - } - // date (YYYY-MM-DD) - if ($this->table_array[$element_name]["type"] == "date") - { - if (!$this->table_array[$element_name]["value"]) - $this->table_array[$element_name]["value"] = "YYYY-MM-DD"; - $data['name'] = $element_name; - $data['value'] = $this->table_array[$element_name]["value"]; - } - // textarea - if ($this->table_array[$element_name]["type"] == "textarea") - { - $data['name'] = $element_name; - $data['value'] = $this->table_array[$element_name]["value"]; - $data['rows'] = $this->table_array[$element_name]["rows"]; - $data['cols'] = $this->table_array[$element_name]["cols"]; - } - // for drop_down_* - if (preg_match("/^drop_down_/", $this->table_array[$element_name]["type"])) - { - $type = 'drop_down'; - // outer query overrules inner - if (!$query) - $query = $this->table_array[$element_name]["query"]; - } - // for drop_down_db* - if (preg_match("/^drop_down_db/", $this->table_array[$element_name]["type"])) - { - // if still NO query - if (!$query) - { - // select pk_name, input_name from table_name (order by order_by) - $query = "SELECT DISTINCT ".$this->table_array[$element_name]["pk_name"].", ".$this->table_array[$element_name]["input_name"]." FROM ".$this->table_array[$element_name]["table_name"]; - // possible where statements - if ($this->table_array[$element_name]["where"]) - $query .= " WHERE ".$this->table_array[$element_name]["where"]; - // possible order statements - if ($this->table_array[$element_name]["order_by"]) - $query .= " ORDER BY ".$this->table_array[$element_name]["order_by"]; - } - // set output data - $data['name'] = $element_name; - $data['value'][] = ""; - $data['output'][] = $this->l->__("Please choose ..."); - while ($res = $this->db_return($query)) - { - $data['value'][] = $res[0]; - $data['output'][] = $res[1]; - if ($this->table_array[$element_name]["value"] == $res[0]) - $data['selected'] = $this->table_array[$element_name]["value"]; - } - // for _input put additional field next to drop down - if (preg_match("/^drop_down_db_input/", $this->table_array[$element_name]["type"])) - { - $data['drop_down_input'] = 1; - // pre fill the temp if empty and other side is selected, only for same_db - if ($this->table_array[$element_name]["type"] == "drop_down_db_input_same_db" && !$this->table_array[$element_name]["input_value"] && $this->table_array[$element_name]["value"]) - $this->table_array[$element_name]["input_value"] = $this->table_array[$element_name]["value"]; - $data['input_value'] = $this->table_array[$element_name]["input_value"]; - $data['input_name'] = $this->table_array[$element_name]["input_name"].(($this->table_array[$element_name]["type"] == "drop_down_db_input_same_db") ? '_temp' : ''); - $data['input_size'] = $this->table_array[$element_name]["size"]; - $data['input_length'] = $this->table_array[$element_name]["length"]; - } - } - // drop down array - if ($this->table_array[$element_name]["type"] == "drop_down_array") - { - $data['name'] = $element_name; - $data['value'][] = ""; - $data['output'][] = $this->l->__("Please choose ..."); - // outer query overrules inner - while (list($key, $value) = each($query)) - { - $data['value'][] = $key; - $data['output'][] = $value; - if ($this->table_array[$element_name]["value"] == $key) - $data['selected'] = $this->table_array[$element_name]["value"]; - } - } - // radio array - if ($this->table_array[$element_name]["type"] == "radio_array") - { - if (!$query) - $query = $this->table_array[$element_name]["query"]; - $data['name'] = $element_name; - while (list($key, $value) = each($query)) - { - $data['value'][] = $key; - $data['output'][] = $value; - if ($this->table_array[$element_name]["value"] == $key) - $data['checked'] = $this->table_array[$element_name]["value"]; + if ($i) { $data['separator'] = ''; } } - // for media / not yet implemented - if ($this->table_array[$element_name]["type"] == "media") - { - //media::insert_file($element_name,$this->table_array[$element_name]["value"],$query); - } - // order button - if ($this->table_array[$element_name]["type"] == "order") - { - $data['output_name'] = $this->table_array[$element_name]["output_name"]; - $data['name'] = $element_name; - $data['value'] = $this->table_array[$element_name]["value"]; - $data['col_name'] = $this->col_name; - $data['table_name'] = $this->table_name; - $data['query'] = urlencode($query); - } - // file upload - if ($this->table_array[$element_name]["type"] == "file") - { - $data['name'] = $element_name; - // if file for this exsists, print "delete, view stuff" - if ($this->table_array[$element_name]["value"]) - { - $data['content'] = 1; - $data['url'] = $this->table_array[$element_name]["open_dir"].$this->table_array[$element_name]["value"]; - $data['output'] = $this->table_array[$element_name]["value"]; - $data['value'] = $this->table_array[$element_name]["value"]; - } - } - return array('output_name' => $output_name, 'color' => $EDIT_FGCOLOR_T, 'type' => $type, 'data' => $data); } - - // METHOD form_error_check - // PARAMS none - // RETURNS full error message string for output - // should be cought like this ... - // if ($msg=$form->form_error_check()) - // $error=1; - public function form_error_check() - { - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - //if ($value["mandatory"] && $value["error_check"]) - // if error value set && somethign input, check if input okay - if ($value["error_check"] && $this->table_array[$key]["value"]) - { - // each error check can be a piped seperated value, lets split it -//$this->debug('edit', $value["error_check"]); - foreach (explode('|', $value["error_check"]) as $error_check) - { - switch ($error_check) - { - case "number": - if (!preg_match("/^[0-9]+(['\,','.']?[0-9]+)*$/", $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a vailid Number for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - case "date": // YYYY-MM-DD - if (!check_date($this->table_array[$key]["value"], 1)) - $this->msg .= sprintf($this->l->__("Please enter a vailid date (YYYY-MM-DD) for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - case "time": // HH:MM[:SS] - if (!check_time($this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a vailid time (HH:MM[:SS]) for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - case "datetime": // YYYY-MM-DD HH:MM[:SS] - break; - case "intervalshort": // ony interval n [Y/M/D] only - if (preg_match("/^\d{1,3}\ ?[YMDymd]{1}$/", $this->table_array[$key]['value'])) - $this->msg .= sprintf($this->l->__('Please enter a valid time interval in the format Y|M|D for the %s Field!
'), $this->table[$key]['output_name']); - case "email": - if (!preg_match("/$this->email_regex/", $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a valid E-Mail Address for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - // check unique, check if field in table is not yet exist - case "unique": - $q = "SELECT ".$key." FROM ".$this->table_name." WHERE ".$key." = '".$this->db_escape_string($this->table_array[$key]["value"])."'"; - if ($this->table_array[$this->int_pk_name]["value"]) - $q .= " AND ".$this->int_pk_name." <> ".$this->table_array[$this->int_pk_name]["value"]; - list($$key) = $this->db_return_row($q); - if ($$key) - $this->msg .= sprintf($this->l->__("The field %s can be used only once!
"), $this->table_array[$key]["output_name"]); - break; - case "custom": - if (!preg_match($this->table_array[$key]["error_regex"], $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a valid (%s) input for the %s Field!
"), $this->table_array[$key]["error_example"], $this->table_array[$key]["output_name"]); - break; - case "alphanumericspace": -//$this->debug('edit', 'IN Alphanumericspace'); - if (!preg_match("/^[0-9A-Za-z\ ]+$/", $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters, spaces allowed) value for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - case "alphanumeric": -//$this->debug('edit', 'IN Alphanumeric'); - if (!preg_match("/^[0-9A-Za-z_\-]+$/", $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters only also - and _, no spaces) value for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - // this one also allows @ and . - case "alphanumericextended": -//$this->debug('edit', 'IN Alphanumericextended'); - if (!preg_match("/^[0-9A-Za-z_\-@\.]+$/", $this->table_array[$key]["value"])) - $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric extended (Numbers, Letters, -, _, @ and . only, no spaces) value for the %s Field!
"), $this->table_array[$key]["output_name"]); - break; - case "password": - // password can only be alphanumeric + special chars - // password and CONFIRM_password need to be the same - if ($this->table_array[$key]["value"] != $this->table_array[$key]["CONFIRM_value"]) - { - // error - } - break; - } // switch - } // for each error to check + // checkbox element + if ($this->table_array[$element_name]["type"] == "checkbox") { + $data['name'] = $element_name; + $data['value'][] = $this->table_array[$element_name]["element_list"]; + $data['checked'] = $this->table_array[$element_name]["value"]; + } + // normal text element + if ($this->table_array[$element_name]["type"] == "text") { + $data['name'] = $element_name; + $data['value'] = $this->table_array[$element_name]["value"]; + $data['size'] = $this->table_array[$element_name]["size"]; + $data['length'] = $this->table_array[$element_name]["length"]; + } + // password element, does not write back the value + if ($this->table_array[$element_name]["type"] == "password") { + $data['name'] = $element_name; + $data['HIDDEN_value'] = $this->table_array[$element_name]["HIDDEN_value"]; + $data['size'] = $this->table_array[$element_name]["size"]; + $data['length'] = $this->table_array[$element_name]["length"]; + } + // date (YYYY-MM-DD) + if ($this->table_array[$element_name]["type"] == "date") { + if (!$this->table_array[$element_name]["value"]) { + $this->table_array[$element_name]["value"] = "YYYY-MM-DD"; + } + $data['name'] = $element_name; + $data['value'] = $this->table_array[$element_name]["value"]; + } + // textarea + if ($this->table_array[$element_name]["type"] == "textarea") { + $data['name'] = $element_name; + $data['value'] = $this->table_array[$element_name]["value"]; + $data['rows'] = $this->table_array[$element_name]["rows"]; + $data['cols'] = $this->table_array[$element_name]["cols"]; + } + // for drop_down_* + if (preg_match("/^drop_down_/", $this->table_array[$element_name]["type"])) { + $type = 'drop_down'; + // outer query overrules inner + if (!$query) { + $query = $this->table_array[$element_name]["query"]; + } + } + // for drop_down_db* + if (preg_match("/^drop_down_db/", $this->table_array[$element_name]["type"])) { + // if still NO query + if (!$query) { + // select pk_name, input_name from table_name (order by order_by) + $query = "SELECT DISTINCT ".$this->table_array[$element_name]["pk_name"].", ".$this->table_array[$element_name]["input_name"]." FROM ".$this->table_array[$element_name]["table_name"]; + // possible where statements + if ($this->table_array[$element_name]["where"]) { + $query .= " WHERE ".$this->table_array[$element_name]["where"]; } - // if mandatory && no input - else if ($value["mandatory"] && - ( - // for all "normal" fields - ($this->table_array[$key]["type"] != "password" && $this->table_array[$key]["type"] != "drop_down_db_input" && !$this->table_array[$key]["value"]) || - // for drop_down_db_input check if one of both fields filled - ($this->table_array[$key]["type"] == "drop_down_db_input" && !$this->table_array[$key]["input_value"] && !$this->table_array[$key]["value"]) || - // for password - ($this->table_array[$key]["type"] == "password" && !$this->table_array[$key]["value"] && !$this->table_array[$key]["HIDDEN_value"]) - ) - ) // main if end - { -//$this->debug('form', "A: ".$this->table_array[$key]["type"]." -- ".$this->table_array[$key]["input_value"]." -- ".$this->table_array[$key]["value"]); - if (!$this->table_array[$key]["value"] && $this->table_array[$key]["type"] != "binary") - $this->msg .= sprintf($this->l->__("Please enter something into the %s field!
"), $this->table_array[$key]["output_name"]); - } // mandatory - // check file upload - if ($this->table_array[$key]["type"] == "file" && $GLOBALS["_FILES"][$key."_file"]['name'] && is_array($this->table_array[$key]["accept_type"])) - { - // check against allowed types - $mime_okay = 0; - foreach ($this->table_array[$key]["accept_type"] as $mime_type) - { - if ($GLOBALS["_FILES"][$key."_file"]['type'] == $mime_type) - $mime_okay = 1; - } - if (!$mime_okay) - { - $this->msg .= sprintf($this->l->__("Uploaded File %s has MIME Type %s which is not in theallowed MIME List for Upload Field %s!
"), $GLOBALS["_FILES"][$key."_file"]['name'], $GLOBALS["_FILES"][$key."_file"]['type'], $this->table_array[$key]["output_name"]); - } - } - } // while - if (is_array($this->reference_array)) - { - // do check for reference tables - if (!is_array($this->reference_array)) - $this->reference_array = array (); - reset($this->reference_array); - while (list($key, $value) = each($this->reference_array)) - { - if ($this->reference_array[$key]["mandatory"] && !$this->reference_array[$key]["selected"][0]) - $this->msg .= sprintf($this->l->__("Please select at least one Element from field %s!
"), $this->reference_array[$key]["output_name"]); + // possible order statements + if ($this->table_array[$element_name]["order_by"]) { + $query .= " ORDER BY ".$this->table_array[$element_name]["order_by"]; } } -//$this->debug('edit_error', "QS:
".print_r($_POST, 1)."
"); - if (is_array($this->element_list)) - { - // check the mandatory stuff - // if mandatory, check that at least on pk exists or if at least the mandatory field is filled - while (list($table_name, $reference_array) = each($this->element_list)) - { - // set pk/fk id for this - foreach ($reference_array['elements'] as $_name => $_data) - { - if ($_data['pk_id']) - $_pk_name = $_name; - if ($_data['fk_id']) - $_fk_name = $_name; + // set output data + $data['name'] = $element_name; + $data['value'][] = ""; + $data['output'][] = $this->l->__("Please choose ..."); + while ($res = $this->db_return($query)) { + $data['value'][] = $res[0]; + $data['output'][] = $res[1]; + if ($this->table_array[$element_name]["value"] == $res[0]) { + $data['selected'] = $this->table_array[$element_name]["value"]; + } + } + // for _input put additional field next to drop down + if (preg_match("/^drop_down_db_input/", $this->table_array[$element_name]["type"])) { + $data['drop_down_input'] = 1; + // pre fill the temp if empty and other side is selected, only for same_db + if ($this->table_array[$element_name]["type"] == "drop_down_db_input_same_db" && !$this->table_array[$element_name]["input_value"] && $this->table_array[$element_name]["value"]) { + $this->table_array[$element_name]["input_value"] = $this->table_array[$element_name]["value"]; + } + $data['input_value'] = $this->table_array[$element_name]["input_value"]; + $data['input_name'] = $this->table_array[$element_name]["input_name"].(($this->table_array[$element_name]["type"] == "drop_down_db_input_same_db") ? '_temp' : ''); + $data['input_size'] = $this->table_array[$element_name]["size"]; + $data['input_length'] = $this->table_array[$element_name]["length"]; + } + } + // drop down array + if ($this->table_array[$element_name]["type"] == "drop_down_array") { + $data['name'] = $element_name; + $data['value'][] = ""; + $data['output'][] = $this->l->__("Please choose ..."); + // outer query overrules inner + while (list($key, $value) = each($query)) { + $data['value'][] = $key; + $data['output'][] = $value; + if ($this->table_array[$element_name]["value"] == $key) { + $data['selected'] = $this->table_array[$element_name]["value"]; + } + } + } + // radio array + if ($this->table_array[$element_name]["type"] == "radio_array") { + if (!$query) { + $query = $this->table_array[$element_name]["query"]; + } + $data['name'] = $element_name; + while (list($key, $value) = each($query)) { + $data['value'][] = $key; + $data['output'][] = $value; + if ($this->table_array[$element_name]["value"] == $key) { + $data['checked'] = $this->table_array[$element_name]["value"]; + } + $data['separator'] = ''; + } + } + // for media / not yet implemented + if ($this->table_array[$element_name]["type"] == "media") { + //media::insert_file($element_name,$this->table_array[$element_name]["value"],$query); + } + // order button + if ($this->table_array[$element_name]["type"] == "order") { + $data['output_name'] = $this->table_array[$element_name]["output_name"]; + $data['name'] = $element_name; + $data['value'] = $this->table_array[$element_name]["value"]; + $data['col_name'] = $this->col_name; + $data['table_name'] = $this->table_name; + $data['query'] = urlencode($query); + } + // file upload + if ($this->table_array[$element_name]["type"] == "file") { + $data['name'] = $element_name; + // if file for this exsists, print "delete, view stuff" + if ($this->table_array[$element_name]["value"]) { + $data['content'] = 1; + $data['url'] = $this->table_array[$element_name]["open_dir"].$this->table_array[$element_name]["value"]; + $data['output'] = $this->table_array[$element_name]["value"]; + $data['value'] = $this->table_array[$element_name]["value"]; + } + } + return array('output_name' => $output_name, 'color' => $EDIT_FGCOLOR_T, 'type' => $type, 'data' => $data); + } + + // METHOD form_error_check + // PARAMS none + // RETURNS full error message string for output + // should be cought like this ... + // if ($msg=$form->form_error_check()) + // $error=1; + public function form_error_check() + { + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + //if ($value["mandatory"] && $value["error_check"]) + // if error value set && somethign input, check if input okay + if ($value["error_check"] && $this->table_array[$key]["value"]) { + // each error check can be a piped seperated value, lets split it +//$this->debug('edit', $value["error_check"]); + foreach (explode('|', $value["error_check"]) as $error_check) { + switch ($error_check) { + case "number": + if (!preg_match("/^[0-9]+(['\,','.']?[0-9]+)*$/", $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a vailid Number for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + case "date": // YYYY-MM-DD + if (!check_date($this->table_array[$key]["value"], 1)) { + $this->msg .= sprintf($this->l->__("Please enter a vailid date (YYYY-MM-DD) for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + case "time": // HH:MM[:SS] + if (!check_time($this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a vailid time (HH:MM[:SS]) for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + case "datetime": // YYYY-MM-DD HH:MM[:SS] + // not implemented + break; + case "intervalshort": // ony interval n [Y/M/D] only + if (preg_match("/^\d{1,3}\ ?[YMDymd]{1}$/", $this->table_array[$key]['value'])) { + $this->msg .= sprintf($this->l->__('Please enter a valid time interval in the format Y|M|D for the %s Field!
'), $this->table[$key]['output_name']); + } + break; + case "email": + if (!preg_match("/$this->email_regex/", $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a valid E-Mail Address for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + // check unique, check if field in table is not yet exist + case "unique": + $q = "SELECT ".$key." FROM ".$this->table_name." WHERE ".$key." = '".$this->db_escape_string($this->table_array[$key]["value"])."'"; + if ($this->table_array[$this->int_pk_name]["value"]) { + $q .= " AND ".$this->int_pk_name." <> ".$this->table_array[$this->int_pk_name]["value"]; + } + list($$key) = $this->db_return_row($q); + if ($$key) { + $this->msg .= sprintf($this->l->__("The field %s can be used only once!
"), $this->table_array[$key]["output_name"]); + } + break; + case "custom": + if (!preg_match($this->table_array[$key]["error_regex"], $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a valid (%s) input for the %s Field!
"), $this->table_array[$key]["error_example"], $this->table_array[$key]["output_name"]); + } + break; + case "alphanumericspace": +//$this->debug('edit', 'IN Alphanumericspace'); + if (!preg_match("/^[0-9A-Za-z\ ]+$/", $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters, spaces allowed) value for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + case "alphanumeric": +//$this->debug('edit', 'IN Alphanumeric'); + if (!preg_match("/^[0-9A-Za-z_\-]+$/", $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters only also - and _, no spaces) value for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + // this one also allows @ and . + case "alphanumericextended": +//$this->debug('edit', 'IN Alphanumericextended'); + if (!preg_match("/^[0-9A-Za-z_\-@\.]+$/", $this->table_array[$key]["value"])) { + $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric extended (Numbers, Letters, -, _, @ and . only, no spaces) value for the %s Field!
"), $this->table_array[$key]["output_name"]); + } + break; + case "password": + // password can only be alphanumeric + special chars + // password and CONFIRM_password need to be the same + if ($this->table_array[$key]["value"] != $this->table_array[$key]["CONFIRM_value"]) { + // error + } + break; + } // switch + } // for each error to check + } elseif ($value["mandatory"] && + ( + // for all "normal" fields + ($this->table_array[$key]["type"] != "password" && $this->table_array[$key]["type"] != "drop_down_db_input" && !$this->table_array[$key]["value"]) || + // for drop_down_db_input check if one of both fields filled + ($this->table_array[$key]["type"] == "drop_down_db_input" && !$this->table_array[$key]["input_value"] && !$this->table_array[$key]["value"]) || + // for password + ($this->table_array[$key]["type"] == "password" && !$this->table_array[$key]["value"] && !$this->table_array[$key]["HIDDEN_value"]) + ) + // main if end + ) { + // if mandatory && no input +//$this->debug('form', "A: ".$this->table_array[$key]["type"]." -- ".$this->table_array[$key]["input_value"]." -- ".$this->table_array[$key]["value"]); + if (!$this->table_array[$key]["value"] && $this->table_array[$key]["type"] != "binary") { + $this->msg .= sprintf($this->l->__("Please enter something into the %s field!
"), $this->table_array[$key]["output_name"]); + } + } // mandatory + // check file upload + if ($this->table_array[$key]["type"] == "file" && $GLOBALS["_FILES"][$key."_file"]['name'] && is_array($this->table_array[$key]["accept_type"])) { + // check against allowed types + $mime_okay = 0; + foreach ($this->table_array[$key]["accept_type"] as $mime_type) { + if ($GLOBALS["_FILES"][$key."_file"]['type'] == $mime_type) { + $mime_okay = 1; + } + } + if (!$mime_okay) { + $this->msg .= sprintf( + $this->l->__("Uploaded File %s has MIME Type %s which is not in theallowed MIME List for Upload Field %s!
"), + $GLOBALS["_FILES"][$key."_file"]['name'], + $GLOBALS["_FILES"][$key."_file"]['type'], + $this->table_array[$key]["output_name"] + ); + } + } + } // while + if (is_array($this->reference_array)) { + // do check for reference tables + if (!is_array($this->reference_array)) { + $this->reference_array = array (); + } + reset($this->reference_array); + while (list($key, $value) = each($this->reference_array)) { + if ($this->reference_array[$key]["mandatory"] && !$this->reference_array[$key]["selected"][0]) { + $this->msg .= sprintf($this->l->__("Please select at least one Element from field %s!
"), $this->reference_array[$key]["output_name"]); + } + } + } +//$this->debug('edit_error', "QS:
".print_r($_POST, 1)."
"); + if (is_array($this->element_list)) { + // check the mandatory stuff + // if mandatory, check that at least on pk exists or if at least the mandatory field is filled + while (list($table_name, $reference_array) = each($this->element_list)) { + // set pk/fk id for this + foreach ($reference_array['elements'] as $_name => $_data) { + if ($_data['pk_id']) { + $_pk_name = $_name; + } + if ($_data['fk_id']) { + $_fk_name = $_name; + } + } + // get the leasy of keys from the elements array + $keys = array_keys($reference_array["elements"]); + // prefix + $prfx = ($reference_array["prefix"]) ? $reference_array["prefix"]."_" : ''; + // get max elements + $max = 0; + foreach ($keys as $key) { + if (count($_POST[$prfx.$key]) > $max) { + $max = count($_POST[$prfx.$key]); } - // get the leasy of keys from the elements array - $keys = array_keys($reference_array["elements"]); - // prefix - $prfx = ($reference_array["prefix"]) ? $reference_array["prefix"]."_" : ''; - // get max elements - $max = 0; - foreach ($keys as $key) - { - if (count($_POST[$prfx.$key]) > $max) - $max = count($_POST[$prfx.$key]); //$this->debug('edit_error_chk', "KEY: $prfx$key | count: ".count($_POST[$prfx.$key])." | M: $max"); //$this->debug('edit_error_chk', "K: ".$_POST[$prfx.$key]." | ".$_POST[$prfx.$key][0]); - } + } //$this->debug('post_array', $this->print_ar($_POST)); - # check each row - for ($i = 0; $i < $max; $i ++) - { - // either one of the post pks is set, or the mandatory - while (list($el_name, $data_array) = each($reference_array["elements"])) - { - if ($data_array["mandatory"]) - $mand_name = $data_array["output_name"]; - // check if there is a primary ket inside, so it is okay - if ($data_array["pk_id"] && count($_POST[$prfx.$el_name]) && $reference_array["mandatory"]) - { - $mand_okay = 1; - } - // we found a mandatory field. check now if one is set to satisfy the main mandatory - // also check, if this field is mandatory and its not set, but any other, throw an error + # check each row + for ($i = 0; $i < $max; $i ++) { + // either one of the post pks is set, or the mandatory + while (list($el_name, $data_array) = each($reference_array["elements"])) { + if ($data_array["mandatory"]) { + $mand_name = $data_array["output_name"]; + } + // check if there is a primary ket inside, so it is okay + if ($data_array["pk_id"] && count($_POST[$prfx.$el_name]) && $reference_array["mandatory"]) { + $mand_okay = 1; + } + // we found a mandatory field. check now if one is set to satisfy the main mandatory + // also check, if this field is mandatory and its not set, but any other, throw an error //$this->debug('edit_error_chk', "RG error - Data[".$prfx.$el_name.": ".$_POST[$prfx.$el_name][$i]." | ".$_POST[$prfx.$el_name]." - ".$reference_array['enable_name']." - ".$_POST[$reference_array['enable_name']][$_POST[$prfx.$el_name][$i]]); - if ($data_array["mandatory"] && $_POST[$prfx.$el_name][$i]) - { - $mand_okay = 1; - $row_okay[$i] = 1; - } + if ($data_array["mandatory"] && $_POST[$prfx.$el_name][$i]) { + $mand_okay = 1; + $row_okay[$i] = 1; + } elseif ($data_array['type'] == 'radio_group' && !isset($_POST[$prfx.$el_name])) { // radio group and set where one not active - elseif ($data_array['type'] == 'radio_group' && !isset($_POST[$prfx.$el_name])) - { //$this->debug('edit_error_chk', "RADIO GROUP"); - $row_okay[$_POST[$prfx.$el_name][$i]] = 0; - $default_wrong[$_POST[$prfx.$el_name][$i]] = 1; - $error[$_POST[$prfx.$el_name][$i]] = 1; - } - elseif ($_POST[$prfx.$el_name][$i] && !$error[$i]) - { + $row_okay[$_POST[$prfx.$el_name][$i]] = 0; + $default_wrong[$_POST[$prfx.$el_name][$i]] = 1; + $error[$_POST[$prfx.$el_name][$i]] = 1; + } elseif ($_POST[$prfx.$el_name][$i] && !$error[$i]) { //$this->debug('edit_error_chk', "[$i]"); - $element_set[$i] = 1; - $row_okay[$i] = 1; - } - elseif ($data_array["mandatory"] && !$_POST[$prfx.$el_name][$i]) - { - $row_okay[$i] = 0; - } - // do optional error checks like for normal fields - // currently active: unique/alphanumeric - if ($data_rray['error_check']) - { - foreach (explode('|', $value["error_check"]) as $error_check) - { - switch ($error_check) - { - // check unique, check if field in table is not yet exist - case "unique": - $q = "SELECT ".$_pk_name." FROM ".$table_name." WHERE ".$el_name." = '".$this->db_escape_string($_POST[$prfx.$el_name][$i])."'"; - if ($this->table_array[$this->int_pk_name]["value"]) - $q .= " AND ".$this->int_pk_name." <> ".$this->table_array[$this->int_pk_name]["value"]; - list($$key) = $this->db_return_row($q); - if ($$key) - $this->msg .= sprintf($this->l->__("The field %s in row %s can be used only once!
"), $reference_array["output_name"], $i); - break; - case "alphanumericspace": - if (!preg_match("/^[0-9A-Za-z\ ]+$/", $_POST[$prfx.$el_name][$i])) - $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters, spaces allowed) value for the %s Field and row %s!
"), $reference_array["output_name"], $i); - break; - } + $element_set[$i] = 1; + $row_okay[$i] = 1; + } elseif ($data_array["mandatory"] && !$_POST[$prfx.$el_name][$i]) { + $row_okay[$i] = 0; + } + // do optional error checks like for normal fields + // currently active: unique/alphanumeric + if ($data_rray['error_check']) { + foreach (explode('|', $value["error_check"]) as $error_check) { + switch ($error_check) { + // check unique, check if field in table is not yet exist + case "unique": + $q = "SELECT ".$_pk_name." FROM ".$table_name." WHERE ".$el_name." = '".$this->db_escape_string($_POST[$prfx.$el_name][$i])."'"; + if ($this->table_array[$this->int_pk_name]["value"]) { + $q .= " AND ".$this->int_pk_name." <> ".$this->table_array[$this->int_pk_name]["value"]; + } + list($$key) = $this->db_return_row($q); + if ($$key) { + $this->msg .= sprintf($this->l->__("The field %s in row %s can be used only once!
"), $reference_array["output_name"], $i); + } + break; + case "alphanumericspace": + if (!preg_match("/^[0-9A-Za-z\ ]+$/", $_POST[$prfx.$el_name][$i])) { + $this->msg .= sprintf($this->l->__("Please enter a valid alphanumeric (Numbers and Letters, spaces allowed) value for the %s Field and row %s!
"), $reference_array["output_name"], $i); + } + break; } } - } // if main mandatory - } - - // main mandatory is met -> error msg - if (!$mand_okay && $reference_array["mandatory"]) - { - $this->msg .= sprintf($this->l->__("You need to enter at least one data set for field %s!
"), $reference_array["output_name"]); - } - for ($i = 0; $i < $max; $i ++) - { - if (!$row_okay[$i] && $element_set[$i]) - { - $this->msg .= sprintf($this->l->__("The row %s has %s set as mandatory, please fill at least this field out
"), $i, $mand_name); - } - if (!$row_okay[$i] && $default_wrong[$i]) - { - $this->msg .= sprintf($this->l->__("The row %s would have a default setting, but it would be disabled. Please change the default setting and save again
"), $i); } + } // if main mandatory + } + + // main mandatory is met -> error msg + if (!$mand_okay && $reference_array["mandatory"]) { + $this->msg .= sprintf($this->l->__("You need to enter at least one data set for field %s!
"), $reference_array["output_name"]); + } + for ($i = 0; $i < $max; $i ++) { + if (!$row_okay[$i] && $element_set[$i]) { + $this->msg .= sprintf($this->l->__("The row %s has %s set as mandatory, please fill at least this field out
"), $i, $mand_name); } - } // each element list + if (!$row_okay[$i] && $default_wrong[$i]) { + $this->msg .= sprintf($this->l->__("The row %s would have a default setting, but it would be disabled. Please change the default setting and save again
"), $i); + } + } + } // each element list + } + if ($this->msg) { + $this->error = 1; + } + } + + // METHOD form_set_order + // PARAMS none + // RETURN the table array + // DOES sets the order to the maximum, if order flag is set in array + public function form_set_order() + { + // get order name + $order_name = $this->form_get_col_name_from_key("order"); + if ($order_name) { + // first check out of order ... + + if (!$this->table_array[$order_name]["value"]) { + // set order (read max) + $q = "SELECT MAX(".$order_name.") + 1 AS max_page_order FROM ".$this->table_name; + list($this->table_array[$order_name]["value"]) = $this->db_return_row($q); + // frist element is 0 because NULL gets returned, set to 1 + if (!$this->table_array[$order_name]["value"]) { + $this->table_array[$order_name]["value"] = 1; + } + } elseif ($this->table_array[$this->int_pk_name]["value"]) { + $q = "SELECT $order_name FROM ".$this->table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; + list($this->table_array[$order_name]["value"]) = $this->db_return_row($q); } - if ($this->msg) - $this->error = 1; + } + return $this->table_array; + } + + // METHOD form_unsert_table_array + // PARAMS none + // RETURN none + // DOES resets all values in table_array and in the reference tables + public function form_unset_table_array() + { + unset($this->pk_id); + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + unset($this->table_array[$key]["value"]); + unset($this->table_array[$key]["input_value"]); + // if preset var present preset + if (isset($this->table_array[$key]["preset"])) { + $this->table_array[$key]["value"] = $this->table_array[$key]["preset"]; + } + } + if (is_array($this->reference_array)) { + if (!is_array($this->reference_array)) { + $this->reference_array = array (); + } + reset($this->reference_array); + while (list($key, $value) = each($this->reference_array)) { + unset($this->reference_array[$key]["selected"]); + } + } + $this->warning = 1; + $this->msg = $this->l->__("Cleared for new Dataset!"); + } + + // METHOD form_load_table_array + // PARAMS pk_id - overrule pk_id + // RETURN none + // DESC load a table & reference + public function form_load_table_array($pk_id = 0) + { + if ($pk_id) { + $this->pk_id = $pk_id; + } + $this->table_array = $this->db_read(1); + + // reset all temp fields + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + unset($this->table_array[$key]["input_value"]); } - // METHOD form_set_order - // PARAMS none - // RETURN the table array - // DOES sets the order to the maximum, if order flag is set in array - public function form_set_order() - { - // get order name - $order_name = $this->form_get_col_name_from_key("order"); - if ($order_name) - { - // first check out of order ... - - if (!$this->table_array[$order_name]["value"]) - { - // set order (read max) - $q = "SELECT MAX(".$order_name.") + 1 AS max_page_order FROM ".$this->table_name; - list($this->table_array[$order_name]["value"]) = $this->db_return_row($q); - // frist element is 0 because NULL gets returned, set to 1 - if (!$this->table_array[$order_name]["value"]) - $this->table_array[$order_name]["value"] = 1; - } - else if ($this->table_array[$this->int_pk_name]["value"]) - { - $q = "SELECT $order_name FROM ".$this->table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; - list($this->table_array[$order_name]["value"]) = $this->db_return_row($q); + if (is_array($this->reference_array)) { + // load each reference_table + if (!is_array($this->reference_array)) { + $this->reference_array = array (); + } + reset($this->reference_array); + while (list($key, $value) = each($this->reference_array)) { + unset($this->reference_array[$key]["selected"]); + $q = "SELECT ".$this->reference_array[$key]["other_table_pk"]." FROM ".$this->reference_array[$key]["table_name"]." WHERE ".$this->int_pk_name."=".$this->table_array[$this->int_pk_name]["value"]; + while ($res = $this->db_return($q)) { + $this->reference_array[$key]["selected"][] = $res[$this->reference_array[$key]["other_table_pk"]]; } } - return $this->table_array; } + $this->warning = 1; + $this->msg = $this->l->__("Dataset has been loaded!
"); + } - // METHOD form_unsert_table_array - // PARAMS none - // RETURN none - // DOES resets all values in table_array and in the reference tables - public function form_unset_table_array() - { - unset($this->pk_id); - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - unset($this->table_array[$key]["value"]); - unset($this->table_array[$key]["input_value"]); - // if preset var present preset - if (isset($this->table_array[$key]["preset"])) - $this->table_array[$key]["value"] = $this->table_array[$key]["preset"]; - } - if (is_array($this->reference_array)) - { - if (!is_array($this->reference_array)) - $this->reference_array = array (); - reset($this->reference_array); - while (list($key, $value) = each($this->reference_array)) - { - unset($this->reference_array[$key]["selected"]); - } - } - $this->warning = 1; - $this->msg = $this->l->__("Cleared for new Dataset!"); - } - - // METHOD form_load_table_array - // PARAMS pk_id - overrule pk_id - // RETURN none - // DESC load a table & reference - public function form_load_table_array($pk_id = 0) - { - if ($pk_id) - $this->pk_id = $pk_id; - $this->table_array = $this->db_read(1); - - // reset all temp fields - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - unset($this->table_array[$key]["input_value"]); - - if (is_array($this->reference_array)) - { - // load each reference_table - if (!is_array($this->reference_array)) - $this->reference_array = array (); - reset($this->reference_array); - while (list($key, $value) = each($this->reference_array)) - { - unset($this->reference_array[$key]["selected"]); - $q = "SELECT ".$this->reference_array[$key]["other_table_pk"]." FROM ".$this->reference_array[$key]["table_name"]." WHERE ".$this->int_pk_name."=".$this->table_array[$this->int_pk_name]["value"]; - while ($res = $this->db_return($q)) - $this->reference_array[$key]["selected"][] = $res[$this->reference_array[$key]["other_table_pk"]]; - } - } - $this->warning = 1; - $this->msg = $this->l->__("Dataset has been loaded!
"); - } - - // METHOD form_save_table_array - // PARAMS addslashes - if one, passes 1 to the db_write function - // RETURN none - // DESC save a table, reference and all input fields - public function form_save_table_array($addslashes = 0) - { + // METHOD form_save_table_array + // PARAMS addslashes - if one, passes 1 to the db_write function + // RETURN none + // DESC save a table, reference and all input fields + public function form_save_table_array($addslashes = 0) + { // global $_FILES; - // for drop_down_db_input check if text field is filled and if, if not yet in db ... - // and upload files - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - // drop_down_db with input + reference table + // for drop_down_db_input check if text field is filled and if, if not yet in db ... + // and upload files + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + // drop_down_db with input + reference table //$this->debug('form', "A: ".$this->table_array[$key]["type"]." --- ".$this->table_array[$key]["input_value"]); - if ($this->table_array[$key]["type"] == "drop_down_db_input" && $this->table_array[$key]["input_value"]) - { + if ($this->table_array[$key]["type"] == "drop_down_db_input" && $this->table_array[$key]["input_value"]) { //$this->debug('form', "HERE"); - // check if this text name already exists (lowercase compare) - $q = "SELECT ".$this->table_array[$key]["pk_name"]." FROM ".$this->table_array[$key]["table_name"]." WHERE LCASE(".$this->table_array[$key]["input_name"].") = '".$this->db_escape_string(strtolower($this->table_array[$key]["input_value"]))."'"; - // if a where was given, add here - if ($this->table_array[$key]["where"]) - $q .= " AND ".$this->table_array[$key]["where"]; - list($pk_name_temp) = $this->db_return_row($q); - if ($this->num_rows >= 1) - { - $this->table_array[$key]["value"] = $pk_name_temp; - } - else - { - // if a where was given, set this key also [dangerous!] - // postgreSQL compatible insert - $q = "INSERT INTO ".$this->table_array[$key]["table_name"]." (".$this->table_array[$key]["input_name"].") VALUES ('".$this->db_escape_string($this->table_array[$key]["input_value"])."')"; + // check if this text name already exists (lowercase compare) + $q = "SELECT ".$this->table_array[$key]["pk_name"]." FROM ".$this->table_array[$key]["table_name"]." WHERE LCASE(".$this->table_array[$key]["input_name"].") = '".$this->db_escape_string(strtolower($this->table_array[$key]["input_value"]))."'"; + // if a where was given, add here + if ($this->table_array[$key]["where"]) { + $q .= " AND ".$this->table_array[$key]["where"]; + } + list($pk_name_temp) = $this->db_return_row($q); + if ($this->num_rows >= 1) { + $this->table_array[$key]["value"] = $pk_name_temp; + } else { + // if a where was given, set this key also [dangerous!] + // postgreSQL compatible insert + $q = "INSERT INTO ".$this->table_array[$key]["table_name"]." (".$this->table_array[$key]["input_name"].") VALUES ('".$this->db_escape_string($this->table_array[$key]["input_value"])."')"; + $this->db_exec($q); + if ($this->table_array[$key]["where"]) { + // make an update on the just inseted data with the where data als update values + $q = "UPDATE ".$this->table_array[$key]["table_name"]." SET "; + $q .= $this->table_array[$key]["where"]." "; + $q .= "WHERE ".$this->table_array[$key]["pk_name"]." = ".$this->insert_id; $this->db_exec($q); - if ($this->table_array[$key]["where"]) - { - // make an update on the just inseted data with the where data als update values - $q = "UPDATE ".$this->table_array[$key]["table_name"]." SET "; - $q .= $this->table_array[$key]["where"]." "; - $q .= "WHERE ".$this->table_array[$key]["pk_name"]." = ".$this->insert_id; - $this->db_exec($q); - } - $this->table_array[$key]["value"] = $this->insert_id; - } // set value from DB through select or insert - unset($this->table_array[$key]["input_value"]); - } // if it is certain field type && if there is something in the temp field - // drop_down_db with input and in same table - if ($this->table_array[$key]["type"] == "drop_down_db_input_same_db" && $this->table_array[$key]["input_value"]) - { - // if drop down & input are different - if ($this->table_array[$key]["input_value"] != $this->table_array[$key]["value"]) - { - // check if "right input" is in DB - $q = "SELECT ".$this->table_array[$key]["input_name"]." FROM ".$this->table_array[$key]["table_name"]." WHERE LCASE(".$this->table_array[$key]["input_name"].") = '".strtolower($this->db_escape_string($this->table_array[$key]["input_value"]))."'"; - // if a where was given, add here - if ($this->table_array[$key]["where"]) - $q .= " AND ".$this->table_array[$key]["where"]; - list($temp) = $this->db_return_row($q); - // nothing found in table, use new inserted key - if (!$temp) - { - $this->table_array[$key]["value"] = $this->table_array[$key]["input_value"]; - } else // found in DB - { - $this->table_array[$key]["input_value"] = $this->table_array[$key]["value"]; - } - } // key difference ? - } // for same_db drop down + } + $this->table_array[$key]["value"] = $this->insert_id; + } // set value from DB through select or insert + unset($this->table_array[$key]["input_value"]); + } // if it is certain field type && if there is something in the temp field + // drop_down_db with input and in same table + if ($this->table_array[$key]["type"] == "drop_down_db_input_same_db" && $this->table_array[$key]["input_value"]) { + // if drop down & input are different + if ($this->table_array[$key]["input_value"] != $this->table_array[$key]["value"]) { + // check if "right input" is in DB + $q = "SELECT ".$this->table_array[$key]["input_name"]." FROM ".$this->table_array[$key]["table_name"]." WHERE LCASE(".$this->table_array[$key]["input_name"].") = '".strtolower($this->db_escape_string($this->table_array[$key]["input_value"]))."'"; + // if a where was given, add here + if ($this->table_array[$key]["where"]) { + $q .= " AND ".$this->table_array[$key]["where"]; + } + list($temp) = $this->db_return_row($q); + // nothing found in table, use new inserted key + if (!$temp) { + $this->table_array[$key]["value"] = $this->table_array[$key]["input_value"]; + } else { + // found in DB + $this->table_array[$key]["input_value"] = $this->table_array[$key]["value"]; + } + } // key difference ? + } // for same_db drop down - // upload & save files to locations - if ($this->table_array[$key]["type"] == "file") - { - // if smth in $$key_file -> save or overwrite - // if smth in $key && $$key_delete && !$$key_file-> delte - // if smth in $key, keep as is + // upload & save files to locations + if ($this->table_array[$key]["type"] == "file") { + // if smth in $$key_file -> save or overwrite + // if smth in $key && $$key_delete && !$$key_file-> delte + // if smth in $key, keep as is // $_file=$key."_file"; // $_delete=$key."_delete"; //$this->debug('form', "UF: ".$GLOBALS["_FILES"][$key."_file"]['name']); //$this->debug('form', "delete: ".$key."_delete => ".$GLOBALS[$key.'_delete']); - if ($GLOBALS["_FILES"][$key."_file"]['name']) - { - // check if dir exists - if (is_dir($this->table_array[$key]["save_dir"])) - { - //if a slash at the end (if not add slash) - if (!preg_match("|/$|", $this->table_array[$key]["save_dir"])) - $this->table_array[$key]["save_dir"] .= "/"; - if (move_uploaded_file($GLOBALS["_FILES"][$key."_file"]['tmp_name'], $this->table_array[$key]["save_dir"].$GLOBALS["_FILES"][$key."_file"]['name'])) - { - // make it unique with a unique number at the beginning - $this->table_array[$key]["value"] = uniqid(rand(), 1)."_".$GLOBALS["_FILES"][$key."_file"]['name']; - } - else - { - $this->msg .= $this->l->__("File could not be copied to target directory! Perhaps wrong directory permissions."); - $this->error = 1; - } // could not move file (dir permissions?) + if ($GLOBALS["_FILES"][$key."_file"]['name']) { + // check if dir exists + if (is_dir($this->table_array[$key]["save_dir"])) { + //if a slash at the end (if not add slash) + if (!preg_match("|/$|", $this->table_array[$key]["save_dir"])) { + $this->table_array[$key]["save_dir"] .= "/"; } - else - { - $this->msg .= sprintf($this->l->__("Target Directory \"%s\" is not a vaild directory!"), $this->table_array[$key]["save_dir"]); + if (move_uploaded_file($GLOBALS["_FILES"][$key."_file"]['tmp_name'], $this->table_array[$key]["save_dir"].$GLOBALS["_FILES"][$key."_file"]['name'])) { + // make it unique with a unique number at the beginning + $this->table_array[$key]["value"] = uniqid(rand(), 1)."_".$GLOBALS["_FILES"][$key."_file"]['name']; + } else { + $this->msg .= $this->l->__("File could not be copied to target directory! Perhaps wrong directory permissions."); $this->error = 1; - } // could not dir check (dir wrong??) - } - if ($GLOBALS[$key.'_delete'] && $this->table_array[$key]["value"] && !$GLOBALS["_FILES"][$key."_file"]['name']) - { - unlink($this->table_array[$key]["save_dir"].$this->table_array[$key]["value"]); - unset($this->table_array[$key]["value"]); - } + } // could not move file (dir permissions?) + } else { + $this->msg .= sprintf($this->l->__("Target Directory \"%s\" is not a vaild directory!"), $this->table_array[$key]["save_dir"]); + $this->error = 1; + } // could not dir check (dir wrong??) } + if ($GLOBALS[$key.'_delete'] && $this->table_array[$key]["value"] && !$GLOBALS["_FILES"][$key."_file"]['name']) { + unlink($this->table_array[$key]["save_dir"].$this->table_array[$key]["value"]); + unset($this->table_array[$key]["value"]); + } + } - // for password crypt it as blowfish, or if not available MD5 - if ($this->table_array[$key]['type'] == 'password') - { - if ($this->table_array[$key]["value"]) - { - // password is stored in blowfish format, or in the format supported by this PHP version - $this->table_array[$key]["value"] = $this->cryptString($this->table_array[$key]["value"]); - $this->table_array[$key]["HIDDEN_value"] = $this->table_array[$key]["value"]; - } - else - { + // for password crypt it as blowfish, or if not available MD5 + if ($this->table_array[$key]['type'] == 'password') { + if ($this->table_array[$key]["value"]) { + // password is stored in blowfish format, or in the format supported by this PHP version + $this->table_array[$key]["value"] = $this->cryptString($this->table_array[$key]["value"]); + $this->table_array[$key]["HIDDEN_value"] = $this->table_array[$key]["value"]; + } else { // $this->table_array[$key]["HIDDEN_value"] = + } + } + } // go through each field + + // set object order (if necessary) + $this->form_set_order(); + // write the object + $this->db_write($addslashes); + // write reference array(s) if necessary + if (is_array($this->reference_array)) { + if (!is_array($this->reference_array)) { + $this->reference_array = array (); + } + reset($this->reference_array); + foreach ($this->reference_array as $reference_array) { + $q = "DELETE FROM ".$reference_array["table_name"]." WHERE ".$this->int_pk_name."=".$this->table_array[$this->int_pk_name]["value"]; + $this->db_exec($q); + $q = "INSERT INTO ".$reference_array["table_name"]." (".$reference_array["other_table_pk"].", ".$this->int_pk_name.") VALUES "; + for ($i = 0; $i < count($reference_array["selected"]); $i ++) { + $t_q = "(".$reference_array["selected"][$i].", ".$this->table_array[$this->int_pk_name]["value"].")"; + $this->db_exec($q.$t_q); + } + } // foreach reference arrays + } // if reference arrays + // write element list + if (is_array($this->element_list)) { + if (!is_array($this->element_list)) { + $this->element_list = array (); + } + reset($this->element_list); + while (list($table_name, $reference_array) = each($this->element_list)) { + // get the number of keys from the elements array + $keys = array_keys($reference_array["elements"]); + // element prefix name + $prfx = ($reference_array["prefix"]) ? $reference_array["prefix"]."_" : ''; + // get max elements + $max = 0; + foreach ($keys as $key) { + if (count($_POST[$prfx.$key]) > $max) { + $max = count($_POST[$prfx.$key]); } } - } // go through each field - - // set object order (if necessary) - $this->form_set_order(); - // write the object - $this->db_write($addslashes); - // write reference array(s) if necessary - if (is_array($this->reference_array)) - { - if (!is_array($this->reference_array)) - $this->reference_array = array (); - reset($this->reference_array); - foreach ($this->reference_array AS $reference_array) - { - $q = "DELETE FROM ".$reference_array["table_name"]." WHERE ".$this->int_pk_name."=".$this->table_array[$this->int_pk_name]["value"]; - $this->db_exec($q); - $q = "INSERT INTO ".$reference_array["table_name"]." (".$reference_array["other_table_pk"].", ".$this->int_pk_name.") VALUES "; - for ($i = 0; $i < count($reference_array["selected"]); $i ++) - { - $t_q = "(".$reference_array["selected"][$i].", ".$this->table_array[$this->int_pk_name]["value"].")"; - $this->db_exec($q.$t_q); - } - } // foreach reference arrays - } // if reference arrays - // write element list - if (is_array($this->element_list)) - { - if (!is_array($this->element_list)) - $this->element_list = array (); - reset($this->element_list); - while (list($table_name, $reference_array) = each($this->element_list)) - { - // get the number of keys from the elements array - $keys = array_keys($reference_array["elements"]); - // element prefix name - $prfx = ($reference_array["prefix"]) ? $reference_array["prefix"]."_" : ''; - // get max elements - $max = 0; - foreach ($keys as $key) - { - if (count($_POST[$prfx.$key]) > $max) - $max = count($_POST[$prfx.$key]); - } //$this->debug('edit_error', "MAX: $max"); - // check if there is a hidden key, update, else insert - while (list($el_name, $data_array) = each($reference_array["elements"])) - { - // this is only for reference_data part, at least one of the text fields need to be set for writing - $blow_write = array (); + // check if there is a hidden key, update, else insert + while (list($el_name, $data_array) = each($reference_array["elements"])) { + // this is only for reference_data part, at least one of the text fields need to be set for writing + $blow_write = array (); //$this->debug('edit_error_query', "QUERY: ".$this->print_ar($_POST)); - // go through all submitted data + // go through all submitted data // for ($i = 0; $i < count($_POST[$el_name]); $i ++) - for ($i = 0; $i < $max; $i ++) - { - // if we have enable name & delete set, then only insert/update those which are flagged as active - // check if mandatory field is set, if not set "do not write flag" - if ($data_array["mandatory"] && !$_POST[$prfx.$el_name][$i]) - { - $no_write[$i] = 1; - } - if ($reference_array['enable_name'] && $reference_array['delete'] && !$_POST[$reference_array['enable_name']][$i]) - { - $no_write[$i] = 1; - } - // flag if data is in the text field and we are in a reference data set - if ($reference_array['type'] == 'reference_data' ) - { - if ($data_array['type'] == 'text' && $_POST[$prfx.$el_name][$i]) - $block_write[$i] = 1; - } - else - { + for ($i = 0; $i < $max; $i ++) { + // if we have enable name & delete set, then only insert/update those which are flagged as active + // check if mandatory field is set, if not set "do not write flag" + if ($data_array["mandatory"] && !$_POST[$prfx.$el_name][$i]) { + $no_write[$i] = 1; + } + if ($reference_array['enable_name'] && $reference_array['delete'] && !$_POST[$reference_array['enable_name']][$i]) { + $no_write[$i] = 1; + } + // flag if data is in the text field and we are in a reference data set + if ($reference_array['type'] == 'reference_data') { + if ($data_array['type'] == 'text' && $_POST[$prfx.$el_name][$i]) { $block_write[$i] = 1; } - // set type and boundaries for insert/update - if ($data_array["pk_id"] && $_POST[$prfx.$el_name][$i]) - { - $q_begin[$i] = "UPDATE $table_name SET "; - $q_end[$i] = " WHERE $el_name = ".$_POST[$prfx.$el_name][$i]; - $type[$i] = "update"; - } - elseif ($data_array["pk_id"] && !$_POST[$prfx.$el_name][$i]) - { - $q_begin[$i] = "INSERT INTO $table_name ("; - $q_middle[$i] = ") VALUES ("; - $q_end[$i] = ")"; - $type[$i] = "insert"; - } - // write all data (insert/update) because I don't know until all are processed if it is insert or update - // don't write primary key backup for update - // for reference_data type, only write if at least one text type field is set + } else { + $block_write[$i] = 1; + } + // set type and boundaries for insert/update + if ($data_array["pk_id"] && $_POST[$prfx.$el_name][$i]) { + $q_begin[$i] = "UPDATE $table_name SET "; + $q_end[$i] = " WHERE $el_name = ".$_POST[$prfx.$el_name][$i]; + $type[$i] = "update"; + } elseif ($data_array["pk_id"] && !$_POST[$prfx.$el_name][$i]) { + $q_begin[$i] = "INSERT INTO $table_name ("; + $q_middle[$i] = ") VALUES ("; + $q_end[$i] = ")"; + $type[$i] = "insert"; + } + // write all data (insert/update) because I don't know until all are processed if it is insert or update + // don't write primary key backup for update + // for reference_data type, only write if at least one text type field is set //$this->debug('edit_error', "I: $i | EL Name: $prfx$el_name | Data: ".$_POST[$prfx.$el_name][$i]." | Type: ".$type[$i]." | PK: ".$data_array["pk_id"].", Block write: ".$block_write[$i]); - // only add elements that are not PK or FK flaged - if (!$data_array['pk_id'] && !$data_array['fk_id']) - { - // update data list - if (strlen($q_data[$i])) - $q_data[$i] .= ", "; - // insert name part list - if ($q_names[$i]) - $q_names[$i] .= ", "; - // insert value part list - if (strlen($q_values[$i])) - $q_values[$i] .= ", "; - // insert column name add - $q_names[$i] .= $el_name; - // data part, read from where [POST] - // radio group selections (only one can be active) - if ($data_array['type'] == 'radio_group') - { - if ($i == $_POST[$prfx.$el_name]) - $_value = $i + 1; - else - $_value = 'NULL'; + // only add elements that are not PK or FK flaged + if (!$data_array['pk_id'] && !$data_array['fk_id']) { + // update data list + if (strlen($q_data[$i])) { + $q_data[$i] .= ", "; + } + // insert name part list + if ($q_names[$i]) { + $q_names[$i] .= ", "; + } + // insert value part list + if (strlen($q_values[$i])) { + $q_values[$i] .= ", "; + } + // insert column name add + $q_names[$i] .= $el_name; + // data part, read from where [POST] + // radio group selections (only one can be active) + if ($data_array['type'] == 'radio_group') { + if ($i == $_POST[$prfx.$el_name]) { + $_value = $i + 1; + } else { + $_value = 'NULL'; } - else - { - $_value = $_POST[$prfx.$el_name][$i]; - } - // pre write data set. if int value, unset flagged need to be set null or 0 depending on settings - if ($data_array['int'] || $data_array['int_null']) - { - if (!$_value && $data_array['int_null']) - $_value = 'NULL'; - elseif (!isset($_value)) - $_value = 0; - $q_data[$i] .= $el_name." = ".$_value; - $q_values[$i] .= $_value; - } - else - { - // normal data gets escaped - $q_data[$i] .= $el_name." = '".$this->db_escape_string($_value)."'"; - $q_values[$i] .= "'".$this->db_escape_string($_value)."'"; + } else { + $_value = $_POST[$prfx.$el_name][$i]; + } + // pre write data set. if int value, unset flagged need to be set null or 0 depending on settings + if ($data_array['int'] || $data_array['int_null']) { + if (!$_value && $data_array['int_null']) { + $_value = 'NULL'; + } elseif (!isset($_value)) { + $_value = 0; } + $q_data[$i] .= $el_name." = ".$_value; + $q_values[$i] .= $_value; + } else { + // normal data gets escaped + $q_data[$i] .= $el_name." = '".$this->db_escape_string($_value)."'"; + $q_values[$i] .= "'".$this->db_escape_string($_value)."'"; } } - } // eche table elements - // finalize the queries, add FK key reference for inserts and run the query - for ($i = 0; $i < count($type); $i ++) - { - $q = ''; - if (!$no_write[$i]) - { - if ($type[$i] == "update") - { - $q = $q_begin[$i].$q_data[$i].$q_end[$i]; - } - elseif ($block_write[$i]) - { - $q = $q_begin[$i].$q_names[$i].", ".$this->int_pk_name.$q_middle[$i].$q_values[$i].", ".$this->table_array[$this->int_pk_name]["value"].$q_end[$i]; - } -$this->debug('edit', "Pos[$i] => ".$type[$i]." Q: ".$q."
"); - // write the dataset - if ($q) - $this->db_exec($q); - } - } // for each created query - } // each element list - } - $this->warning = 1; - $this->msg = $this->l->__("Dataset has been saved!
"); - } - - // METHOD form_delete_table_array - // PARAMS none - // RETURN none - // DESC delete a table and reference fields - public function form_delete_table_array() - { - // remove any reference arrays - if (is_array($this->reference_array)) - { - if (!is_array($this->reference_array)) - $this->reference_array = array (); - reset($this->reference_array); - foreach ($this->reference_array AS $reference_array) - { - $q = "DELETE FROM ".$reference_array["table_name"]." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; - $this->db_exec($q); - } - } - // remove any element list references - if (is_array($this->element_list)) - { - if (!is_array($this->element_list)) - $this->element_list = array (); - reset($this->element_list); - while (list($table_name, $data_array) = each($this->element_list)) - { - $q = "DELETE FROM ".$table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; - $this->db_exec($q); - } - } - // unlink ALL files - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - if ($this->table_array[$key]["type"] == "file") - unlink($this->table_array[$key]["save_dir"].$this->table_array[$key]["value"]); - } - $this->db_delete(); - $this->warning = 1; - $this->msg = $this->l->__("Dataset has been deleted!"); - } - - // METHOD form_create_hidden_fields - // PARAMS $hidden_array - // RETURNS the input fields (html) - // creates HTML hidden input fields out of an hash array - public function form_create_hidden_fields($hidden_array = "") - { - $hidden = array (); - if (!is_array($this->table_array)) - $this->table_array = array (); - reset($this->table_array); - while (list($key, $value) = each($this->table_array)) - { - if ($this->table_array[$key]["type"] == "hidden") - { - $hidden_array[$key] = $this->table_array[$key]["value"]; - } - } - if (is_array($hidden_array)) - { - reset($hidden_array); - while (list($key, $value) = each($hidden_array)) - { - $hidden[] = array('key' => $key, 'value' => $value); - } - } - return $hidden; - } - - // METHOD form_create_element_reference_table - // PARAMS show which reference table - // RETURN array for output - // DESC creates the multiple select part for a reference_table - public function form_create_element_reference_table($table_name) - { - $output_name = $this->reference_array[$table_name]["output_name"]; - if ($this->reference_array[$table_name]["mandatory"]) - $output_name .= ' *'; - $data['name'] = $this->reference_array[$table_name]["other_table_pk"]; - $data['size'] = $this->reference_array[$table_name]["select_size"]; - while ($res = $this->db_return($this->reference_array[$table_name]["query"])) - { - $data['value'][] = $res[0]; - $data['output'][] = $res[1]; - $data['selected'][] = ($this->checked($this->reference_array[$table_name]["selected"], $res[0])) ? $res[0] : ''; - } - $type = 'reference_table'; - return array('output_name' => $output_name, 'type' => $type, 'color' => 'edit_fgcolor', 'data' => $data); - } - - // METHOD form_create_element_list - // PARAMS show which element list - // RETURN array for output - // DESC create list of elements next to each other for a group of data in an input field - // this currently only works for a list that is filled from a sub table and creates only a connection to this one - // new version will allow a sub list with free input fields to directly fill a sub table to a master table - public function form_create_element_list_table($table_name) - { - // output name for the viewable left table td box, prefixed with * if mandatory - $output_name = $this->element_list[$table_name]["output_name"]; - if ($this->element_list[$table_name]["mandatory"]) - $output_name .= ' *'; - // delete button name, if there is one set - if ($this->element_list[$table_name]["delete_name"]) - $data['delete_name'] = $this->element_list[$table_name]["delete_name"]; - // set the enable checkbox for delete, if the delete flag is given if there is one - if ($this->element_list[$table_name]["enable_name"]) - { - $data['enable_name'] = $this->element_list[$table_name]["enable_name"]; - if ($this->element_list[$table_name]["delete"]) - $data['delete'] = 1; - } - // prefix for the elements, to not collide with names in the master set - if ($this->element_list[$table_name]["prefix"]) - $data["prefix"] = $this->element_list[$table_name]["prefix"]."_"; - // the sub data table name - $data['table_name'] = $table_name; - - // build the select part - if (!is_array($this->element_list[$table_name]["elements"])) - $this->element_list[$table_name]["elements"] = array (); - reset($this->element_list[$table_name]["elements"]); - // generic data read in (counts for all rows) - // visible list data output - while (list($el_name, $data_array) = each($this->element_list[$table_name]["elements"])) - { -// $this->debug('CFG', 'El: '.$el_name.' -> '.$this->print_ar($data_array)); - // if the element name matches the read array, then set the table as a name prefix - $q_select[] = $el_name; // this is for reading the data - // prefix the name for any further data parts - $el_name = $data["prefix"].$el_name; - $data['output_name'][$el_name] = $data_array["output_name"]; // this are the output names (if given) - $data['type'][$el_name] = $data_array["type"]; /// this is the type of the field - // set the primary key name - if ($data_array['pk_id']) - $data['pk_name'] = $el_name; - if ($data_array['fk_id']) - $data['fk_name'] = $el_name; - // if drop down db read data for element list from the given sub table as from the query - // only two elements are allowed: pos 0 is key, pso 1 is visible output name - if ($data_array['type'] == 'drop_down_db') - { - $md_q = md5($data_array['query']); - while ($res = $this->db_return($data_array['query'])) - { -//$this->debug('edit', "Q[$md_q] pos: ".$this->cursor_ext[$md_q]["pos"]." | want: ".$data_array["preset"]." | set: ".$data['preset'][$el_name]); - // first is default for this element - if (!$data['preset'][$el_name] && ($this->cursor_ext[$md_q]["pos"] == $data_array['preset'])) - $data['preset'][$el_name] = $res[0]; - // split up data, 0 is id, 1 name - $data['element_list'][$el_name][] = $res[0]; - $data['output_data'][$el_name][] = $res[1]; } - } - elseif ($data_array["element_list"]) - { - $data['element_list'][$el_name] = $data_array["element_list"]; // this is for the checkboxes - } - $proto[$el_name] = ($this->error) ? $_POST[$el_name][(count($_POST[$el_name]) - 1)] : ''; // this is for the new line + } // eche table elements + // finalize the queries, add FK key reference for inserts and run the query + for ($i = 0; $i < count($type); $i ++) { + $q = ''; + if (!$no_write[$i]) { + if ($type[$i] == "update") { + $q = $q_begin[$i].$q_data[$i].$q_end[$i]; + } elseif ($block_write[$i]) { + $q = $q_begin[$i].$q_names[$i].", ".$this->int_pk_name.$q_middle[$i].$q_values[$i].", ".$this->table_array[$this->int_pk_name]["value"].$q_end[$i]; + } + $this->debug('edit', "Pos[$i] => ".$type[$i]." Q: ".$q."
"); + // write the dataset + if ($q) { + $this->db_exec($q); + } + } + } // for each created query + } // each element list + } + $this->warning = 1; + $this->msg = $this->l->__("Dataset has been saved!
"); + } + + // METHOD form_delete_table_array + // PARAMS none + // RETURN none + // DESC delete a table and reference fields + public function form_delete_table_array() + { + // remove any reference arrays + if (is_array($this->reference_array)) { + if (!is_array($this->reference_array)) { + $this->reference_array = array (); } + reset($this->reference_array); + foreach ($this->reference_array as $reference_array) { + $q = "DELETE FROM ".$reference_array["table_name"]." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; + $this->db_exec($q); + } + } + // remove any element list references + if (is_array($this->element_list)) { + if (!is_array($this->element_list)) { + $this->element_list = array (); + } + reset($this->element_list); + while (list($table_name, $data_array) = each($this->element_list)) { + $q = "DELETE FROM ".$table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; + $this->db_exec($q); + } + } + // unlink ALL files + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + if ($this->table_array[$key]["type"] == "file") { + unlink($this->table_array[$key]["save_dir"].$this->table_array[$key]["value"]); + } + } + $this->db_delete(); + $this->warning = 1; + $this->msg = $this->l->__("Dataset has been deleted!"); + } + + // METHOD form_create_hidden_fields + // PARAMS $hidden_array + // RETURNS the input fields (html) + // creates HTML hidden input fields out of an hash array + public function form_create_hidden_fields($hidden_array = "") + { + $hidden = array (); + if (!is_array($this->table_array)) { + $this->table_array = array (); + } + reset($this->table_array); + while (list($key, $value) = each($this->table_array)) { + if ($this->table_array[$key]["type"] == "hidden") { + $hidden_array[$key] = $this->table_array[$key]["value"]; + } + } + if (is_array($hidden_array)) { + reset($hidden_array); + while (list($key, $value) = each($hidden_array)) { + $hidden[] = array('key' => $key, 'value' => $value); + } + } + return $hidden; + } + + // METHOD form_create_element_reference_table + // PARAMS show which reference table + // RETURN array for output + // DESC creates the multiple select part for a reference_table + public function form_create_element_reference_table($table_name) + { + $output_name = $this->reference_array[$table_name]["output_name"]; + if ($this->reference_array[$table_name]["mandatory"]) { + $output_name .= ' *'; + } + $data['name'] = $this->reference_array[$table_name]["other_table_pk"]; + $data['size'] = $this->reference_array[$table_name]["select_size"]; + while ($res = $this->db_return($this->reference_array[$table_name]["query"])) { + $data['value'][] = $res[0]; + $data['output'][] = $res[1]; + $data['selected'][] = ($this->checked($this->reference_array[$table_name]["selected"], $res[0])) ? $res[0] : ''; + } + $type = 'reference_table'; + return array('output_name' => $output_name, 'type' => $type, 'color' => 'edit_fgcolor', 'data' => $data); + } + + // METHOD form_create_element_list + // PARAMS show which element list + // RETURN array for output + // DESC create list of elements next to each other for a group of data in an input field + // this currently only works for a list that is filled from a sub table and creates only a connection to this one + // new version will allow a sub list with free input fields to directly fill a sub table to a master table + public function form_create_element_list_table($table_name) + { + // output name for the viewable left table td box, prefixed with * if mandatory + $output_name = $this->element_list[$table_name]["output_name"]; + if ($this->element_list[$table_name]["mandatory"]) { + $output_name .= ' *'; + } + // delete button name, if there is one set + if ($this->element_list[$table_name]["delete_name"]) { + $data['delete_name'] = $this->element_list[$table_name]["delete_name"]; + } + // set the enable checkbox for delete, if the delete flag is given if there is one + if ($this->element_list[$table_name]["enable_name"]) { + $data['enable_name'] = $this->element_list[$table_name]["enable_name"]; + if ($this->element_list[$table_name]["delete"]) { + $data['delete'] = 1; + } + } + // prefix for the elements, to not collide with names in the master set + if ($this->element_list[$table_name]["prefix"]) { + $data["prefix"] = $this->element_list[$table_name]["prefix"]."_"; + } + // the sub data table name + $data['table_name'] = $table_name; + + // build the select part + if (!is_array($this->element_list[$table_name]["elements"])) { + $this->element_list[$table_name]["elements"] = array (); + } + reset($this->element_list[$table_name]["elements"]); + // generic data read in (counts for all rows) + // visible list data output + while (list($el_name, $data_array) = each($this->element_list[$table_name]["elements"])) { +// $this->debug('CFG', 'El: '.$el_name.' -> '.$this->print_ar($data_array)); + // if the element name matches the read array, then set the table as a name prefix + $q_select[] = $el_name; // this is for reading the data + // prefix the name for any further data parts + $el_name = $data["prefix"].$el_name; + $data['output_name'][$el_name] = $data_array["output_name"]; // this are the output names (if given) + $data['type'][$el_name] = $data_array["type"]; /// this is the type of the field + // set the primary key name + if ($data_array['pk_id']) { + $data['pk_name'] = $el_name; + } + if ($data_array['fk_id']) { + $data['fk_name'] = $el_name; + } + // if drop down db read data for element list from the given sub table as from the query + // only two elements are allowed: pos 0 is key, pso 1 is visible output name + if ($data_array['type'] == 'drop_down_db') { + $md_q = md5($data_array['query']); + while ($res = $this->db_return($data_array['query'])) { +//$this->debug('edit', "Q[$md_q] pos: ".$this->cursor_ext[$md_q]["pos"]." | want: ".$data_array["preset"]." | set: ".$data['preset'][$el_name]); + // first is default for this element + if (!$data['preset'][$el_name] && ($this->cursor_ext[$md_q]["pos"] == $data_array['preset'])) { + $data['preset'][$el_name] = $res[0]; + } + // split up data, 0 is id, 1 name + $data['element_list'][$el_name][] = $res[0]; + $data['output_data'][$el_name][] = $res[1]; + } + } elseif ($data_array["element_list"]) { + $data['element_list'][$el_name] = $data_array["element_list"]; // this is for the checkboxes + } + $proto[$el_name] = ($this->error) ? $_POST[$el_name][(count($_POST[$el_name]) - 1)] : ''; // this is for the new line + } // $this->debug('CFG DATA', 'Data: '.$this->print_ar($data)); // $this->debug('CFG PROTO', 'Proto: '.$this->print_ar($proto)); // $this->debug('CFG SELECT', 'Proto: '.$this->print_ar($q_select)); - // query for reading in the data + // query for reading in the data //$this->debug('edit_error', "ERR: ".$this->error); - // if we got a read data, build the read select for the read, and read out the "selected" data - if ($this->element_list[$table_name]["read_data"]) - { - // we need a second one for the query build only - // prefix all elements with the $table name - foreach ($q_select as $_pos => $element) - { - $_q_select[$_pos] = $table_name.'.'.$element; + // if we got a read data, build the read select for the read, and read out the "selected" data + if ($this->element_list[$table_name]["read_data"]) { + // we need a second one for the query build only + // prefix all elements with the $table name + foreach ($q_select as $_pos => $element) { + $_q_select[$_pos] = $table_name.'.'.$element; + } + // add the read names in here, prefix them with the table name + // earch to read part is split by | + if ($this->element_list[$table_name]["read_data"]["name"]) { + foreach (explode('|', $this->element_list[$table_name]["read_data"]["name"]) as $read_name) { + array_unshift($_q_select, $this->element_list[$table_name]["read_data"]["table_name"].'.'.$read_name); + array_unshift($q_select, $read_name); } - // add the read names in here, prefix them with the table name - // earch to read part is split by | - if ($this->element_list[$table_name]["read_data"]["name"]) - { - foreach (explode('|', $this->element_list[$table_name]["read_data"]["name"]) as $read_name) - { - array_unshift($_q_select, $this->element_list[$table_name]["read_data"]["table_name"].'.'.$read_name); - array_unshift($q_select, $read_name); - } - } - // set the rest of the data so we can print something out - $data['type'][$data["prefix"].$this->element_list[$table_name]["read_data"]["name"]] = 'string'; - // build the read query - $q = "SELECT "; + } + // set the rest of the data so we can print something out + $data['type'][$data["prefix"].$this->element_list[$table_name]["read_data"]["name"]] = 'string'; + // build the read query + $q = "SELECT "; // if (!$this->table_array[$this->int_pk_name]["value"]) // $q .= "DISTINCT "; - // prefix join key with table name, and implode the query select part - $q .= str_replace($table_name.'.'.$this->element_list[$table_name]["read_data"]["pk_id"], $this->element_list[$table_name]["read_data"]["table_name"].'.'.$this->element_list[$table_name]["read_data"]["pk_id"], implode(', ', $_q_select)).' '; + // prefix join key with table name, and implode the query select part + $q .= str_replace($table_name.'.'.$this->element_list[$table_name]["read_data"]["pk_id"], $this->element_list[$table_name]["read_data"]["table_name"].'.'.$this->element_list[$table_name]["read_data"]["pk_id"], implode(', ', $_q_select)).' '; // if (!$this->table_array[$this->int_pk_name]["value"] && $this->element_list[$table_name]["read_data"]["order"]) // $q .= ", ".$this->element_list[$table_name]["read_data"]["order"]." "; - // read from the read table as main, and left join to the sub table to read the actual data - $q .= "FROM ".$this->element_list[$table_name]["read_data"]["table_name"]." "; - $q .= "LEFT JOIN ".$table_name." "; - $q .= "ON ("; - $q .= $this->element_list[$table_name]["read_data"]["table_name"].".".$this->element_list[$table_name]["read_data"]["pk_id"]." = ".$table_name.".".$this->element_list[$table_name]["read_data"]["pk_id"]." "; + // read from the read table as main, and left join to the sub table to read the actual data + $q .= "FROM ".$this->element_list[$table_name]["read_data"]["table_name"]." "; + $q .= "LEFT JOIN ".$table_name." "; + $q .= "ON ("; + $q .= $this->element_list[$table_name]["read_data"]["table_name"].".".$this->element_list[$table_name]["read_data"]["pk_id"]." = ".$table_name.".".$this->element_list[$table_name]["read_data"]["pk_id"]." "; // if ($this->table_array[$this->int_pk_name]["value"]) - $q .= "AND ".$table_name.".".$this->int_pk_name." = ".(($this->table_array[$this->int_pk_name]["value"]) ? $this->table_array[$this->int_pk_name]["value"] : 'NULL')." "; - $q .= ") "; - if ($this->element_list[$table_name]["read_data"]["order"]) - $q .= " ORDER BY ".$this->element_list[$table_name]["read_data"]["table_name"].'.'.$this->element_list[$table_name]["read_data"]["order"]; + $q .= "AND ".$table_name.".".$this->int_pk_name." = ".(($this->table_array[$this->int_pk_name]["value"]) ? $this->table_array[$this->int_pk_name]["value"] : 'NULL')." "; + $q .= ") "; + if ($this->element_list[$table_name]["read_data"]["order"]) { + $q .= " ORDER BY ".$this->element_list[$table_name]["read_data"]["table_name"].'.'.$this->element_list[$table_name]["read_data"]["order"]; } - else - { - // only create query if we have a primary key - // reads directly from the reference table - if ($this->table_array[$this->int_pk_name]["value"]) - $q = "SELECT ".implode(", ", $q_select)." FROM ".$table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; + } else { + // only create query if we have a primary key + // reads directly from the reference table + if ($this->table_array[$this->int_pk_name]["value"]) { + $q = "SELECT ".implode(", ", $q_select)." FROM ".$table_name." WHERE ".$this->int_pk_name." = ".$this->table_array[$this->int_pk_name]["value"]; } + } // $this->debug('CFG QUERY', 'Q: '.$q); - // only run if we have query strnig - if ($q) - { - $pos = 0; // position in while for overwrite if needed - // read out the list and add the selected data if needed - while ($res = $this->db_return($q)) - { - $_data = array (); - $prfx = $data["prefix"]; // short - // go through each res - for ($i = 0; $i < count($q_select); $i ++) - { - // query select part, set to the element name - $el_name = $q_select[$i]; + // only run if we have query strnig + if ($q) { + $pos = 0; // position in while for overwrite if needed + // read out the list and add the selected data if needed + while ($res = $this->db_return($q)) { + $_data = array (); + $prfx = $data["prefix"]; // short + // go through each res + for ($i = 0; $i < count($q_select); $i ++) { + // query select part, set to the element name + $el_name = $q_select[$i]; //$this->debug('edit_error', "[$i] ELNAME: $el_name | POS[$prfx$el_name]: ".$_POST[$prfx.$el_name][$pos]." | RES: ".$res[$el_name]); - // if we have an error, we take what we have in the vars, if not we take the data from the db - if ($this->error) - { - // if we have a radio group, set a bit different - if ($data['element_list'][$prfx.$el_name] == 'radio_group') - $_data[$prfx.$el_name] = ($res[$el_name]) ? ($res[$el_name] - 1) : 0; - else - $_data[$prfx.$el_name] = $_POST[$prfx.$el_name][$pos]; + // if we have an error, we take what we have in the vars, if not we take the data from the db + if ($this->error) { + // if we have a radio group, set a bit different + if ($data['element_list'][$prfx.$el_name] == 'radio_group') { + $_data[$prfx.$el_name] = ($res[$el_name]) ? ($res[$el_name] - 1) : 0; + } else { + $_data[$prfx.$el_name] = $_POST[$prfx.$el_name][$pos]; } - else - { - if ($data["preset"][$prfx.$el_name] && !$res[$el_name]) - $_data[$prfx.$el_name] = $data["preset"][$el_name]; - else - $_data[$prfx.$el_name] = $res[$el_name]; + } else { + if ($data["preset"][$prfx.$el_name] && !$res[$el_name]) { + $_data[$prfx.$el_name] = $data["preset"][$el_name]; + } else { + $_data[$prfx.$el_name] = $res[$el_name]; + } + } + } + $data['content'][] = $_data; + $data['pos'][] = array(0 => $pos); // this is for the checkboxes + $pos ++; // move up one + // reset and unset before next run + unset($_data); + } + } + // if this is normal single reference data check the content on the element count + // if there is a max_empty is set, then fill up new elements (unfilled) until we reach max empty + if ($this->element_list[$table_name]['type'] == 'reference_data' && is_numeric($this->element_list[$table_name]['max_empty']) && $this->element_list[$table_name]['max_empty'] > 0) { + // if the max empty is bigger than 10, just cut it to ten at the moment + if ($this->element_list[$table_name]['max_empty'] > 10) { + $this->element_list[$table_name]['max_empty'] = 10; + } + // check if we need to fill fields + $element_count = count($data['content']); + $missing_empty_count = $this->element_list[$table_name]['max_empty'] - count($data['content']); + $this->debug('CFG MAX', 'Max empty: '.$this->element_list[$table_name]['max_empty'].', Missing: '.$missing_empty_count.', Has: '.$element_count); + // set if we need more open entries or if we do not have any entries yet + if (($missing_empty_count < $this->element_list[$table_name]['max_empty']) || $element_count == 0) { + for ($pos = count($data['content']); $pos <= ($this->element_list[$table_name]['max_empty'] + $element_count); $pos ++) { + $_data = array (); + + // the fields that need to be filled are in data->type array: + // pk fields are unfilled + // fk fields are filled with the fk_id "int_pk_name" value + foreach ($data['type'] as $el_name => $type) { + $_data[$el_name] = ''; + if ($el_name == $data['pk_name']) { + } elseif ($el_name == $data['fk_name']) { + $_data[$el_name] = $this->table_array[$this->int_pk_name]["value"]; } } $data['content'][] = $_data; $data['pos'][] = array(0 => $pos); // this is for the checkboxes - $pos ++; // move up one - // reset and unset before next run - unset($_data); } } - // if this is normal single reference data check the content on the element count - // if there is a max_empty is set, then fill up new elements (unfilled) until we reach max empty - if ($this->element_list[$table_name]['type'] == 'reference_data' && is_numeric($this->element_list[$table_name]['max_empty']) && $this->element_list[$table_name]['max_empty'] > 0) - { - // if the max empty is bigger than 10, just cut it to ten at the moment - if ($this->element_list[$table_name]['max_empty'] > 10) - $this->element_list[$table_name]['max_empty'] = 10; - // check if we need to fill fields - $element_count = count($data['content']); - $missing_empty_count = $this->element_list[$table_name]['max_empty'] - count($data['content']); - $this->debug('CFG MAX', 'Max empty: '.$this->element_list[$table_name]['max_empty'].', Missing: '.$missing_empty_count.', Has: '.$element_count); - // set if we need more open entries or if we do not have any entries yet - if (($missing_empty_count < $this->element_list[$table_name]['max_empty']) || $element_count == 0) - { - for ($pos = count($data['content']); $pos <= ($this->element_list[$table_name]['max_empty'] + $element_count); $pos ++) - { - $_data = array (); - - // the fields that need to be filled are in data->type array: - // pk fields are unfilled - // fk fields are filled with the fk_id "int_pk_name" value - foreach ($data['type'] as $el_name => $type) - { - $_data[$el_name] = ''; - if ($el_name == $data['pk_name']) - { - } - elseif ($el_name == $data['fk_name']) - { - $_data[$el_name] = $this->table_array[$this->int_pk_name]["value"]; - } - } - $data['content'][] = $_data; - $data['pos'][] = array(0 => $pos); // this is for the checkboxes - } - } - } - - // push in an empty line of this type, but only if we have a delete key - if ($data['delete_name']) - $data['content'][] = $proto; -//$this->debug('edit', "A:
".print_r($data, 1)."
"); - $type = 'element_list'; - return array('output_name' => $output_name, 'type' => $type, 'color' => 'edit_fgcolor', 'data' => $data); } - } // end of class -?> + + // push in an empty line of this type, but only if we have a delete key + if ($data['delete_name']) { + $data['content'][] = $proto; + } +//$this->debug('edit', "A:
".print_r($data, 1)."
"); + $type = 'element_list'; + return array('output_name' => $output_name, 'type' => $type, 'color' => 'edit_fgcolor', 'data' => $data); + } +} // end of class diff --git a/www/libs/Class.Login.inc b/www/libs/Class.Login.inc index b0e53b0e..d19c20dd 100644 --- a/www/libs/Class.Login.inc +++ b/www/libs/Class.Login.inc @@ -1,874 +1,815 @@ width - * popup_y - if popup -> height - * online - page is online (user can access) - * query_string - string to paste for popup (will change) - * - * HISTORY: - * 2010/12/21 (cs) merge back password change interface - * 2010/12/17 (cs) change that password can be blowfish encrypted, auto detects if other encryption is used (md5, std des) and tries to use them - * 2007/05/29 (cs) BUG with assign query and visible sub arrays to pages - * 2005/09/21 (cs) if error -> unset the session vars - * 2005/07/04 (cs) add a function to write into the edit log file - * 2005/07/01 (cs) start adepting login class to new edit interface layout - * 2005/03/31 (cs) fixed the class call with all debug vars - * 2004/11/17 (cs) unused var cleanup - * 2004/11/16 (cs) rewrite login so it uses a template and not just plain html. prepare it, so it will be able to use external stuff later (some interface has to be designed for that - * 2004/11/16 (cs) removed the mobile html part from login * 2004/09/30 (cs) layout fix - * 2003-11-11: if user has debug 1 unset memlimit, because there can be serious problems with the query logging - * 2003-06-12: added flag to PAGES array - * changed the get vars from GLOBALS to _POST - * changed the session registration. no more GLOBAL vars are registered - * only _SESSION["..."] - * 2003-06-09: added mobile phone login possibility - * 2003-03-04: droped ADMIN and added GROUP_LEVEL - * 2003-03-03: started to change the include file function collection - * to become a class - * 2003-02-28: various advances and changes, but far from perfect - * decided to change it into a class for easier handling - * add also possibility to change what will stored in the - * login session ? - * 2000-06-01: created basic idea and functions - *********************************************************************/ +/********************************************************************* +* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) +* CREATED: 2000/06/01 +* VERSION: 4.0.0 +* RELEASED LICENSE: GNU GPL 3 +* SHORT DESCRIPTON: +* ~ 2003/03/03: change the whole include file into one class +* advantages are a) can include before actuall call, can control it +* easer (login db, etc), etc etc etc +* +* a login lib that should stand out of all others +* will be a class one day +* +* descrption of session_vars +* DEBUG_ALL - set to one, prints out error_msg var at end of php execution +* DB_DEBUG - prints out database debugs (query, etc) +* GROUP_LEVEL - the level he can access (numeric) +* USER_NAME - login name from user +* LANG - lang to show edit interface (not yet used) +* DEFAULT_CHARSET - in connection with LANG (not yet used) +* PAGES - array of hashes +* edit_page_id - ID from the edit_pages table +* filename - name of the file +* page_name - name in menu +* menu - appears in menu +* popup - is a popup +* popup_x - if popup -> width +* popup_y - if popup -> height +* online - page is online (user can access) +* query_string - string to paste for popup (will change) +* +* HISTORY: +* 2010/12/21 (cs) merge back password change interface +* 2010/12/17 (cs) change that password can be blowfish encrypted, auto detects if other encryption is used (md5, std des) and tries to use them +* 2007/05/29 (cs) BUG with assign query and visible sub arrays to pages +* 2005/09/21 (cs) if error -> unset the session vars +* 2005/07/04 (cs) add a function to write into the edit log file +* 2005/07/01 (cs) start adepting login class to new edit interface layout +* 2005/03/31 (cs) fixed the class call with all debug vars +* 2004/11/17 (cs) unused var cleanup +* 2004/11/16 (cs) rewrite login so it uses a template and not just plain html. prepare it, so it will be able to use external stuff later (some interface has to be designed for that +* 2004/11/16 (cs) removed the mobile html part from login * 2004/09/30 (cs) layout fix +* 2003-11-11: if user has debug 1 unset memlimit, because there can be serious problems with the query logging +* 2003-06-12: added flag to PAGES array +* changed the get vars from GLOBALS to _POST +* changed the session registration. no more GLOBAL vars are registered +* only _SESSION["..."] +* 2003-06-09: added mobile phone login possibility +* 2003-03-04: droped ADMIN and added GROUP_LEVEL +* 2003-03-03: started to change the include file function collection +* to become a class +* 2003-02-28: various advances and changes, but far from perfect +* decided to change it into a class for easier handling +* add also possibility to change what will stored in the +* login session ? +* 2000-06-01: created basic idea and functions +*********************************************************************/ - // try to include file from LIBS path, or from normal path - _spl_autoload('Class.DB.IO.inc'); +// try to include file from LIBS path, or from normal path +_spl_autoload('Class.DB.IO.inc'); - class login extends db_io +class login extends db_io +{ + private $euid; // the user id var + private $permission_okay = 0; // is set to one if login okay, or EUID is set and user is okay to access this page + public $login; // pressed login + private $username; // login name + private $password; // login password + private $logout; // logout button + private $login_error; // login error code, can be matched to the array login_error_msg, which holds the string + private $password_change = false; // if this is set to true, the user can change passwords + private $pw_change_deny_users = array (); // array of users for which the password change is forbidden + + // all possible login error conditions + private $login_error_msg = array (); + // this is an array holding all strings & templates passed from the outside (translation) + private $login_template = array ('strings' => array (), 'password_change' => '', 'template' => ''); + + // acl vars + public $acl = array (); + public $default_acl_list = array (); + + // METHOD: login + // PARAMS: db_config -> array for logging in to DB where edit_users tables are + // db_debug -> sets debug output for db_io (can be overruled with DB_DEBUG) + // RETURN: none + // DESC : cunstroctuor, does ALL, opens db, works through connection checks, closes itself + public function __construct($db_config, $lang = 'en_utf8', $debug = 0, $db_debug = 0, $echo = 1, $print = 0) { - private $euid; // the user id var - private $permission_okay = 0; // is set to one if login okay, or EUID is set and user is okay to access this page - public $login; // pressed login - private $username; // login name - private $password; // login password - private $logout; // logout button - private $login_error; // login error code, can be matched to the array login_error_msg, which holds the string - private $password_change = false; // if this is set to true, the user can change passwords - private $pw_change_deny_users = array (); // array of users for which the password change is forbidden + // log login data for this class only + $this->log_per_class = 1; - // all possible login error conditions - private $login_error_msg = array (); - // this is an array holding all strings & templates passed from the outside (translation) - private $login_template = array ('strings' => array (), 'password_change' => '', 'template' => ''); + // create db connection and init base class + parent::__construct($db_config, $debug, $db_debug, $echo, $print); - // acl vars - public $acl = array (); - public $default_acl_list = array (); + // no session could be found at all + if (!session_id()) { + echo "Session not started!
Use 'session_start();'.
For less problems with other session, you can set a session name with 'session_name(\"name\");'.
"; + exit; + } - // METHOD: login - // PARAMS: db_config -> array for logging in to DB where edit_users tables are - // db_debug -> sets debug output for db_io (can be overruled with DB_DEBUG) - // RETURN: none - // DESC : cunstroctuor, does ALL, opens db, works through connection checks, closes itself - public function __construct($db_config, $lang = 'en_utf8', $debug = 0, $db_debug = 0, $echo = 1, $print = 0) - { - // log login data for this class only - $this->log_per_class = 1; + // get the language sub class & init it + _spl_autoload('Class.l10n.inc'); + $this->l = new l10n($lang); - // create db connection and init base class - parent::__construct($db_config, $debug, $db_debug, $echo, $print); + // if we have a search path we need to set it, to use the correct DB to login + // check what schema to use. if there is a login schema use this, else check if there is a schema set in the config, or fall back to DB_SCHEMA if this exists, if this also does not exists use public schema + $SCHEMA = defined('LOGIN_DB_SCHEMA') ? LOGIN_DB_SCHEMA : ($db_config['db_schema'] ? $db_config['db_schema'] : (defined('DB_SCHEMA') ? DB_SCHEMA : 'public')); + $this->db_exec("SET search_path TO ".$SCHEMA); + $this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check + // get login vars, are so, can't be changed + // prepare + if (!isset($_POST['login_login'])) { + $_POST['login_login'] = ''; + } + if (!isset($_POST['login_username'])) { + $_POST['login_username'] = ''; + } + if (!isset($_POST['login_password'])) { + $_POST['login_password'] = ''; + } + if (!isset($_POST['login_logout'])) { + $_POST['login_logout'] = ''; + } + if (!isset($_POST['change_password'])) { + $_POST['change_password'] = ''; + } + if (!isset($_POST['pw_username'])) { + $_POST['pw_username'] = ''; + } + if (!isset($_POST['pw_old_password'])) { + $_POST['pw_old_password'] = ''; + } + if (!isset($_POST['pw_new_password'])) { + $_POST['pw_new_password'] = ''; + } + if (!isset($_POST['pw_new_password_confirm'])) { + $_POST['pw_new_password_confirm'] = ''; + } + // pass on vars to Object vars + $this->login = $_POST["login_login"]; + $this->username = $_POST["login_username"]; + $this->password = $_POST["login_password"]; + $this->logout = $_POST["login_logout"]; + // password change vars + $this->change_password = $_POST["change_password"]; + $this->pw_username = $_POST['pw_username']; + $this->pw_old_password = $_POST['pw_old_password']; + $this->pw_new_password = $_POST['pw_new_password']; + $this->pw_new_password_confirm = $_POST['pw_new_password_confirm']; + // logout target (from config) + $this->logout_target = LOGOUT_TARGET; + // disallow user list for password change + $this->pw_change_deny_users = array ('admin'); + // set flag if password change is okay + if (defined('PASSWORD_CHANGE')) { + $this->password_change = PASSWORD_CHANGE; + } + // max login counts before error reporting + $this->max_login_error_count = 10; + // users that never get locked, even if they are set strict + $this->lock_deny_users = array ('admin'); - // no session could be found at all - if (!session_id()) - { - echo "Session not started!
Use 'session_start();'.
For less problems with other session, you can set a session name with 'session_name(\"name\");'.
"; - exit; - } + // internal + $this->class_info["login"] = array( + "class_name" => "Login", + "class_version" => "4.0.0", + "class_created" => "2000-06-01", + "class_author" => "cs/gullevek/at" + ); - // get the language sub class & init it - _spl_autoload('Class.l10n.inc'); - $this->l = new l10n($lang); - - // if we have a search path we need to set it, to use the correct DB to login - // check what schema to use. if there is a login schema use this, else check if there is a schema set in the config, or fall back to DB_SCHEMA if this exists, if this also does not exists use public schema - $SCHEMA = defined('LOGIN_DB_SCHEMA') ? LOGIN_DB_SCHEMA : ($db_config['db_schema'] ? $db_config['db_schema'] : (defined('DB_SCHEMA') ? DB_SCHEMA : 'public')); - $this->db_exec("SET search_path TO ".$SCHEMA); - $this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check - // get login vars, are so, can't be changed - // prepare - if (!isset($_POST['login_login'])) - $_POST['login_login'] = ''; - if (!isset($_POST['login_username'])) - $_POST['login_username'] = ''; - if (!isset($_POST['login_password'])) - $_POST['login_password'] = ''; - if (!isset($_POST['login_logout'])) - $_POST['login_logout'] = ''; - if (!isset($_POST['change_password'])) - $_POST['change_password'] = ''; - if (!isset($_POST['pw_username'])) - $_POST['pw_username'] = ''; - if (!isset($_POST['pw_old_password'])) - $_POST['pw_old_password'] = ''; - if (!isset($_POST['pw_new_password'])) - $_POST['pw_new_password'] = ''; - if (!isset($_POST['pw_new_password_confirm'])) - $_POST['pw_new_password_confirm'] = ''; - // pass on vars to Object vars - $this->login = $_POST["login_login"]; - $this->username = $_POST["login_username"]; - $this->password = $_POST["login_password"]; - $this->logout = $_POST["login_logout"]; - // password change vars - $this->change_password = $_POST["change_password"]; - $this->pw_username = $_POST['pw_username']; - $this->pw_old_password = $_POST['pw_old_password']; - $this->pw_new_password = $_POST['pw_new_password']; - $this->pw_new_password_confirm = $_POST['pw_new_password_confirm']; - // logout target (from config) - $this->logout_target = LOGOUT_TARGET; - // disallow user list for password change - $this->pw_change_deny_users = array ('admin'); - // set flag if password change is okay - if (defined('PASSWORD_CHANGE')) - $this->password_change = PASSWORD_CHANGE; - // max login counts before error reporting - $this->max_login_error_count = 10; - // users that never get locked, even if they are set strict - $this->lock_deny_users = array ('admin'); - - // internal - $this->class_info["login"] = array( - "class_name" => "Login", - "class_version" => "4.0.0", - "class_created" => "2000-06-01", - "class_author" => "cs/gullevek/at" + // init default ACL list array + $_SESSION['DEFAULT_ACL_LIST'] = array (); + // read the current edit_access_right list into an array + $q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level"; + while ($res = $this->db_return($q)) { + // level to description format (numeric) + $this->default_acl_list[$res['level']] = array ( + 'type' => $res['type'], + 'name' => $res['name'] ); - - // init default ACL list array - $_SESSION['DEFAULT_ACL_LIST'] = array (); - // read the current edit_access_right list into an array - $q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level"; - while ($res = $this->db_return($q)) - { - // level to description format (numeric) - $this->default_acl_list[$res['level']] = array ( - 'type' => $res['type'], - 'name' => $res['name'] - ); - } - // write that into the session - $_SESSION['DEFAULT_ACL_LIST'] = $this->default_acl_list; - - // if username & password & !$euid start login - $this->login_login_user(); - // checks if $euid given check if user is okay for that side - $this->login_check_permissions(); - // logsout user - $this->login_logout_user(); - // if the password change flag is okay, run the password change method - if ($this->password_change) - $this->login_password_change(); - // if !$euid || permission not okay, print login screan - echo $this->login_print_login(); - // closing all connections, depending on error status, exit - if (!$this->login_close_class()) - { - // do not go anywhere, quit processing here - // do something with possible debug data? - if (TARGET == 'live' || TARGET == 'remote') - { - // login - $this->debug_output_all = DEBUG ? 1 : 0; - $this->echo_output_all = 0; - $this->print_output_all = DEBUG ? 1 : 0; - } - $status_msg = $this->print_error_msg(); - if ($this->echo_output_all) - echo $status_msg; - exit; - } - // set acls for this user/group and this page - $this->login_set_acl(); } + // write that into the session + $_SESSION['DEFAULT_ACL_LIST'] = $this->default_acl_list; - // METHOD: _login - // PARAMS: none - // RETURN: none - // DESC : deconstructory, called with the last function to close DB connection - public function __destruct() - { - parent::__destruct(); + // if username & password & !$euid start login + $this->login_login_user(); + // checks if $euid given check if user is okay for that side + $this->login_check_permissions(); + // logsout user + $this->login_logout_user(); + // if the password change flag is okay, run the password change method + if ($this->password_change) { + $this->login_password_change(); } + // if !$euid || permission not okay, print login screan + echo $this->login_print_login(); + // closing all connections, depending on error status, exit + if (!$this->login_close_class()) { + // do not go anywhere, quit processing here + // do something with possible debug data? + if (TARGET == 'live' || TARGET == 'remote') { + // login + $this->debug_output_all = DEBUG ? 1 : 0; + $this->echo_output_all = 0; + $this->print_output_all = DEBUG ? 1 : 0; + } + $status_msg = $this->print_error_msg(); + if ($this->echo_output_all) { + echo $status_msg; + } + exit; + } + // set acls for this user/group and this page + $this->login_set_acl(); + } - // METHOD: login_login_user - // PARAMS: none - // RETURN: none - // DESC : if user pressed login button this script is called, but only if there is no preview euid set - private function login_login_user() - { - // have to get the global stuff here for setting it later - if (!$this->euid && $this->login) - { - if (!($this->password && $this->username)) - { - $this->login_error = 102; - } - else - { - // we have to get the themes in here too - $q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, eg.name AS edit_group_name, admin, eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, "; - $q .= "debug, db_debug, "; - $q .= "eareu.level AS user_level, eareu.type AS user_type, "; - $q .= "eareg.level AS group_level, eareg.type AS group_type, "; - $q .= "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, first.header_color AS first_header_color, second.header_color AS second_header_color, second.template "; - $q .= "FROM edit_user eu "; - $q .= "LEFT JOIN edit_scheme second ON (second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), "; - $q .= "edit_language el, edit_group eg, "; - $q .= "edit_access_right eareu, "; - $q .= "edit_access_right eareg, "; - $q .= "edit_scheme first "; - $q .= "WHERE first.edit_scheme_id = eg.edit_scheme_id AND eu.edit_group_id = eg.edit_group_id AND eu.edit_language_id = el.edit_language_id AND "; - $q .= "eu.edit_access_right_id = eareu.edit_access_right_id AND "; - $q .= "eg.edit_access_right_id = eareg.edit_access_right_id AND "; - // password match is done in script, against old plain or new blowfish encypted - $q .= "(LOWER(username) = '".strtolower($this->username)."') "; - $res = $this->db_return($q); - // username is wrong, but we throw for wrong username and wrong password the same error - if (!$this->cursor_ext[md5($q)]["num_rows"]) - { - $this->login_error = 1010; - } - else - { - // if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try + // METHOD: _login + // PARAMS: none + // RETURN: none + // DESC : deconstructory, called with the last function to close DB connection + public function __destruct() + { + parent::__destruct(); + } - // check with what kind of prefix the password begins: - // $2a$ or $2y$: BLOWFISCH - // $1$: MD5 - // $ and one alphanumeric letter, 13 chars long, but nor $ at the end: STD_DESC - // if no $ => normal password - // NOW, if we have a password encoded, but not the correct encoder available, throw special error + // METHOD: login_login_user + // PARAMS: none + // RETURN: none + // DESC : if user pressed login button this script is called, but only if there is no preview euid set + private function login_login_user() + { + // have to get the global stuff here for setting it later + if (!$this->euid && $this->login) { + if (!($this->password && $this->username)) { + $this->login_error = 102; + } else { + // we have to get the themes in here too + $q = "SELECT eu.edit_user_id, username, password, eu.edit_group_id, eg.name AS edit_group_name, admin, eu.login_error_count, eu.login_error_date_last, eu.login_error_date_first, eu.strict, eu.locked, "; + $q .= "debug, db_debug, "; + $q .= "eareu.level AS user_level, eareu.type AS user_type, "; + $q .= "eareg.level AS group_level, eareg.type AS group_type, "; + $q .= "eu.enabled, el.short_name AS lang_short, el.iso_name AS lang_iso, first.header_color AS first_header_color, second.header_color AS second_header_color, second.template "; + $q .= "FROM edit_user eu "; + $q .= "LEFT JOIN edit_scheme second ON (second.edit_scheme_id = eu.edit_scheme_id AND second.enabled = 1), "; + $q .= "edit_language el, edit_group eg, "; + $q .= "edit_access_right eareu, "; + $q .= "edit_access_right eareg, "; + $q .= "edit_scheme first "; + $q .= "WHERE first.edit_scheme_id = eg.edit_scheme_id AND eu.edit_group_id = eg.edit_group_id AND eu.edit_language_id = el.edit_language_id AND "; + $q .= "eu.edit_access_right_id = eareu.edit_access_right_id AND "; + $q .= "eg.edit_access_right_id = eareg.edit_access_right_id AND "; + // password match is done in script, against old plain or new blowfish encypted + $q .= "(LOWER(username) = '".strtolower($this->username)."') "; + $res = $this->db_return($q); + // username is wrong, but we throw for wrong username and wrong password the same error + if (!$this->cursor_ext[md5($q)]["num_rows"]) { + $this->login_error = 1010; + } else { + // if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try - // check flow - // - user is enabled - // - user is not locked - // - password is readable - // - encrypted password matches - // - plain password matches + // check with what kind of prefix the password begins: + // $2a$ or $2y$: BLOWFISCH + // $1$: MD5 + // $ and one alphanumeric letter, 13 chars long, but nor $ at the end: STD_DESC + // if no $ => normal password + // NOW, if we have a password encoded, but not the correct encoder available, throw special error + // check flow + // - user is enabled + // - user is not locked + // - password is readable + // - encrypted password matches + // - plain password matches + + if (!$res["enabled"]) { // user is enabled - if (!$res["enabled"]) - { - $this->login_error = 104; - } + $this->login_error = 104; + } elseif ($res['locked']) { // user is locked, either set or auto set - elseif ($res['locked']) - { - $this->login_error = 105; - } - elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) && CRYPT_BLOWFISH != 1) || (preg_match("/^\\$1\\$/", $res['password']) && CRYPT_MD5 != 1) || (preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && CRYPT_STD_DES != 1)) - { - $this->login_error = 9999; // this means password cannot be decrypted because of missing crypt methods - } + $this->login_error = 105; + } elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) && CRYPT_BLOWFISH != 1) || (preg_match("/^\\$1\\$/", $res['password']) && CRYPT_MD5 != 1) || (preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && CRYPT_STD_DES != 1)) { + // this means password cannot be decrypted because of missing crypt methods + $this->login_error = 9999; + } elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) || preg_match("/^\\$1\\$/", $res['password']) || preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password'])) && !$this->verifyCryptString($this->password, $res['password'])) { // check passwword as crypted, $2a$ or $2y$ is blowfish start, $1$ is MD5 start, $\w{12} is standard DES - elseif ((preg_match("/^\\$2(a|y)\\$/", $res['password']) || preg_match("/^\\$1\\$/", $res['password']) || preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password'])) && !$this->verifyCryptString($this->password, $res['password'])) - { - $this->login_error = 1011; - } + $this->login_error = 1011; + } elseif (!preg_match("/^\\$2(a|y)\\$/", $res['password']) && !preg_match("/^\\$1\\$/", $res['password']) && !preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && $res['password'] != $this->password) { // check old plain password, non case sensitive - elseif (!preg_match("/^\\$2(a|y)\\$/", $res['password']) && !preg_match("/^\\$1\\$/", $res['password']) && !preg_match("/^\\$[0-9A-Za-z.]{12}$/", $res['password']) && $res['password'] != $this->password) - { - $this->login_error = 1012; + $this->login_error = 1012; + } else { + // normal user processing + // set class var and session var + $_SESSION["EUID"] = $this->euid = $res["edit_user_id"]; + // check if user is okay + $this->login_check_permissions(); + if (!$this->login_error) { + // now set all session vars and read page permissions + $GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"]; + $GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"]; + $_SESSION["USER_NAME"] = $res["username"]; + $_SESSION["ADMIN"] = $res["admin"]; + $_SESSION["GROUP_NAME"] = $res["edit_group_name"]; + $_SESSION["USER_ACL_LEVEL"] = $res["user_level"]; + $_SESSION["USER_ACL_TYPE"] = $res["user_type"]; + $_SESSION["GROUP_ACL_LEVEL"] = $res["group_level"]; + $_SESSION["GROUP_ACL_TYPE"] = $res["group_type"]; + $_SESSION["TEMPLATE"] = ($res["template"]) ? $res["template"] : DEFAULT_TEMPLATE; + $_SESSION["HEADER_COLOR"] = ($res["second_header_color"]) ? $res["second_header_color"] : $res["first_header_color"]; + $_SESSION["LANG"] = $res["lang_short"]; + $_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"]; + $_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"])); + // reset any login error count for this user + if ($res['login_error_count'] > 0) { + $q = "UPDATE edit_user SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL WHERE edit_user_id = ".$res['edit_user_id']; + $this->db_exec($q); + } + $pages = array(); + $edit_page_ids = array(); + // set pages access + $q = "SELECT ep.edit_page_id, filename, ep.name AS edit_page_name, ep.order_number AS edit_page_order, menu, popup, popup_x, popup_y, online, ear.level, ear.type "; + $q .= "FROM edit_page ep, edit_page_access epa, edit_access_right ear "; + $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id "; + $q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." "; + $q .= "ORDER BY ep.order_number"; + while ($res = $this->db_return($q)) { + // page id array for sub data readout + $edit_page_ids[] = $res['edit_page_id']; + // create the array for pages + array_push($pages, array ( + "edit_page_id" => $res["edit_page_id"], + "filename" => $res["filename"], + "page_name" => $res["edit_page_name"], + "order" => $res['edit_page_order'], + "menu" => $res["menu"], + "popup" => $res["popup"], + "popup_x" => $res["popup_x"], + "popup_y" => $res["popup_y"], + "online" => $res["online"], + "acl_level" => $res["level"], + "acl_type" => $res["type"], + "query" => array (), + "visible" => array () + )); + // make reference filename -> level + $pages_acl[$res["filename"]] = $res["level"]; + } // for each page + // get the visible groups for all pages and write them to the pages + $_edit_page_id = 0; + $q = "SELECT epvg.edit_page_id, name, flag FROM edit_visible_group evp, edit_page_visible_group epvg WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id AND epvg.edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY epvg.edit_page_id"; + while ($res = $this->db_return($q)) { + if ($res['edit_page_id'] != $_edit_page_id) { + // search the pos in the array push + $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); + $_edit_page_id = $res['edit_page_id']; + } + $pages[$pos[0]]['visible'][$res['name']] = $res['flag']; + } + // get the same for the query strings + $_edit_page_id = 0; + $q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs WHERE enabled = 1 AND edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY eqs.edit_page_id"; + while ($res = $this->db_return($q)) { + if ($res['edit_page_id'] != $_edit_page_id) { + // search the pos in the array push + $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); + $_edit_page_id = $res['edit_page_id']; + } + $pages[$pos[0]]['query'][] = array ( + "name" => $res['name'], + "value" => $res['value'], + "dynamic" => $res['dynamic'] + ); + } + + $_SESSION["PAGES"] = $pages; + $_SESSION["PAGES_ACL_LEVEL"] = $pages_acl; + // load the edit_access user rights + $q = "SELECT ea.edit_access_id, level, type, ea.name, ea.color, ea.uid, edit_default "; + $q .= "FROM edit_access_user eau, edit_access_right ear, edit_access ea "; + $q .= "WHERE eau.edit_access_id = ea.edit_access_id AND eau.edit_access_right_id = ear.edit_access_right_id AND eau.enabled = 1 AND edit_user_id = ".$this->euid." "; + $q .= "ORDER BY ea.name"; + $unit_access = array(); + $eauid = array(); + $unit_acl = array(); + while ($res = $this->db_return($q)) { + // read edit access data fields and drop them into the unit access array + $q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id']; + $ea_data = array (); + while ($res_sub = $this->db_return($q_sub)) { + $ea_data[$res_sub['name']] = $res_sub['value']; + } + // build master unit array + $unit_access[$res['edit_access_id']] = array ( + "id" => $res['edit_access_id'], + "acl_level" => $res["level"], + "acl_type" => $res["type"], + "name" => $res["name"], + "uid" => $res['uid'], + "color" => $res["color"], + "default" => $res["edit_default"], + 'data' => $ea_data + ); + // set the default unit + if ($res['edit_default']) { + $_SESSION["UNIT_DEFAULT"] = $res['edit_access_id']; + } + // sub arrays for simple access + array_push($eauid, $res['edit_access_id']); + $unit_acl[$res['edit_access_id']] = $res['level']; + } + $_SESSION["UNIT"] = $unit_access; + $_SESSION["UNIT_ACL_LEVEL"] = $unit_acl; + $_SESSION['EAID'] = $eauid; + } // user has permission to THIS page + } // user was not enabled or other login error + if ($this->login_error) { + if ($res['login_error_count'] == 0) { + $login_error_date_first = ', login_error_date_first = NOW()'; } - // nromal user processing - else - { - // set class var and session var - $_SESSION["EUID"] = $this->euid = $res["edit_user_id"]; - // check if user is okay - $this->login_check_permissions(); - if (!$this->login_error) - { - // now set all session vars and read page permissions - $GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"]; - $GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"]; - $_SESSION["USER_NAME"] = $res["username"]; - $_SESSION["ADMIN"] = $res["admin"]; - $_SESSION["GROUP_NAME"] = $res["edit_group_name"]; - $_SESSION["USER_ACL_LEVEL"] = $res["user_level"]; - $_SESSION["USER_ACL_TYPE"] = $res["user_type"]; - $_SESSION["GROUP_ACL_LEVEL"] = $res["group_level"]; - $_SESSION["GROUP_ACL_TYPE"] = $res["group_type"]; - $_SESSION["TEMPLATE"] = ($res["template"]) ? $res["template"] : DEFAULT_TEMPLATE; - $_SESSION["HEADER_COLOR"] = ($res["second_header_color"]) ? $res["second_header_color"] : $res["first_header_color"]; - $_SESSION["LANG"] = $res["lang_short"]; - $_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"]; - $_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"])); - // reset any login error count for this user - if ($res['login_error_count'] > 0) - { - $q = "UPDATE edit_user SET login_error_count = 0, login_error_date_last = NULL, login_error_date_first = NULL WHERE edit_user_id = ".$res['edit_user_id']; - $this->db_exec($q); - } - $pages = array(); - $edit_page_ids = array(); - // set pages access - $q = "SELECT ep.edit_page_id, filename, ep.name AS edit_page_name, ep.order_number AS edit_page_order, menu, popup, popup_x, popup_y, online, ear.level, ear.type "; - $q .= "FROM edit_page ep, edit_page_access epa, edit_access_right ear "; - $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id "; - $q .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." "; - $q .= "ORDER BY ep.order_number"; - while ($res = $this->db_return($q)) - { - // page id array for sub data readout - $edit_page_ids[] = $res['edit_page_id']; - // create the array for pages - array_push($pages, array ( - "edit_page_id" => $res["edit_page_id"], - "filename" => $res["filename"], - "page_name" => $res["edit_page_name"], - "order" => $res['edit_page_order'], - "menu" => $res["menu"], - "popup" => $res["popup"], - "popup_x" => $res["popup_x"], - "popup_y" => $res["popup_y"], - "online" => $res["online"], - "acl_level" => $res["level"], - "acl_type" => $res["type"], - "query" => array (), - "visible" => array () - )); - // make reference filename -> level - $pages_acl[$res["filename"]] = $res["level"]; - - } // for each page - // get the visible groups for all pages and write them to the pages - $_edit_page_id = 0; - $q = "SELECT epvg.edit_page_id, name, flag FROM edit_visible_group evp, edit_page_visible_group epvg WHERE evp.edit_visible_group_id = epvg.edit_visible_group_id AND epvg.edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY epvg.edit_page_id"; - while ($res = $this->db_return($q)) - { - if ($res['edit_page_id'] != $_edit_page_id) - { - // search the pos in the array push - $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); - $_edit_page_id = $res['edit_page_id']; - } - $pages[$pos[0]]['visible'][$res['name']] = $res['flag']; - } - // get the same for the query strings - $_edit_page_id = 0; - $q = "SELECT eqs.edit_page_id, name, value, dynamic FROM edit_query_string eqs WHERE enabled = 1 AND edit_page_id IN (".join(', ', $edit_page_ids).") ORDER BY eqs.edit_page_id"; - while ($res = $this->db_return($q)) - { - if ($res['edit_page_id'] != $_edit_page_id) - { - // search the pos in the array push - $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); - $_edit_page_id = $res['edit_page_id']; - } - $pages[$pos[0]]['query'][] = array ( - "name" => $res['name'], - "value" => $res['value'], - "dynamic" => $res['dynamic'] - ); - } - - $_SESSION["PAGES"] = $pages; - $_SESSION["PAGES_ACL_LEVEL"] = $pages_acl; - // load the edit_access user rights - $q = "SELECT ea.edit_access_id, level, type, ea.name, ea.color, ea.uid, edit_default "; - $q .= "FROM edit_access_user eau, edit_access_right ear, edit_access ea "; - $q .= "WHERE eau.edit_access_id = ea.edit_access_id AND eau.edit_access_right_id = ear.edit_access_right_id AND eau.enabled = 1 AND edit_user_id = ".$this->euid." "; - $q .= "ORDER BY ea.name"; - $unit_access = array(); - $eauid = array(); - $unit_acl = array(); - while ($res = $this->db_return($q)) - { - // read edit access data fields and drop them into the unit access array - $q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id']; - $ea_data = array (); - while ($res_sub = $this->db_return($q_sub)) - { - $ea_data[$res_sub['name']] = $res_sub['value']; - } - // build master unit array - $unit_access[$res['edit_access_id']] = array ( - "id" => $res['edit_access_id'], - "acl_level" => $res["level"], - "acl_type" => $res["type"], - "name" => $res["name"], - "uid" => $res['uid'], - "color" => $res["color"], - "default" => $res["edit_default"], - 'data' => $ea_data - ); - // set the default unit - if ($res['edit_default']) - $_SESSION["UNIT_DEFAULT"] = $res['edit_access_id']; - // sub arrays for simple access - array_push($eauid, $res['edit_access_id']); - $unit_acl[$res['edit_access_id']] = $res['level']; - } - $_SESSION["UNIT"] = $unit_access; - $_SESSION["UNIT_ACL_LEVEL"] = $unit_acl; - $_SESSION['EAID'] = $eauid; - } // user has permission to THIS page - } // user was not enabled or other login error - if ($this->login_error) - { - if ($res['login_error_count'] == 0) - $login_error_date_first = ', login_error_date_first = NOW()'; - // update login error count for this user - $q = "UPDATE edit_user SET login_error_count = login_error_count + 1, login_error_date_last = NOW() $login_error_date_first WHERE edit_user_id = ".$res['edit_user_id']; - $this->db_exec($q); - // totally lock the user if error max is reached - if ($res['login_error_count'] + 1 > $this->max_login_error_count) - { - // do some alert reporting in case this error is too big - // if strict is set, lock this user - // this needs manual unlocking by an admin user - if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) - { - $q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id']; - } + // update login error count for this user + $q = "UPDATE edit_user SET login_error_count = login_error_count + 1, login_error_date_last = NOW() $login_error_date_first WHERE edit_user_id = ".$res['edit_user_id']; + $this->db_exec($q); + // totally lock the user if error max is reached + if ($res['login_error_count'] + 1 > $this->max_login_error_count) { + // do some alert reporting in case this error is too big + // if strict is set, lock this user + // this needs manual unlocking by an admin user + if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) { + $q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id']; } } - } // user was not found - } // if not username AND password where given - // if there was an login error, show login screen - if ($this->login_error) - { - // reset the perm var, to confirm logout - $this->permission_okay = 0; - } - } // if he pressed login at least and is not yet loggined in - } + } + } // user was not found + } // if not username AND password where given + // if there was an login error, show login screen + if ($this->login_error) { + // reset the perm var, to confirm logout + $this->permission_okay = 0; + } + } // if he pressed login at least and is not yet loggined in + } - // METHOD: login_check_permission - // PARAMS: none - // RETUNR none - // DESC : for every page the user access this script checks if he is allowed to do so - public function login_check_permissions() - { - if ($this->euid && $this->login_error != 103) - { - $q = "SELECT filename "; - $q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "; - $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND eg.edit_group_id = epa.edit_group_id AND eg.edit_group_id = eu.edit_group_id "; - $q .= "AND eu.edit_user_id = ".$this->euid." AND filename = '".$this->page_name."' AND eg.enabled = 1 AND epa.enabled = 1"; - $res = $this->db_return_row($q); - // unset mem limit if debug is set to 1 + // METHOD: login_check_permission + // PARAMS: none + // RETUNR none + // DESC : for every page the user access this script checks if he is allowed to do so + public function login_check_permissions() + { + if ($this->euid && $this->login_error != 103) { + $q = "SELECT filename "; + $q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "; + $q .= "WHERE ep.edit_page_id = epa.edit_page_id AND eg.edit_group_id = epa.edit_group_id AND eg.edit_group_id = eu.edit_group_id "; + $q .= "AND eu.edit_user_id = ".$this->euid." AND filename = '".$this->page_name."' AND eg.enabled = 1 AND epa.enabled = 1"; + $res = $this->db_return_row($q); + // unset mem limit if debug is set to 1 // if (($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] || $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) && ini_get('memory_limit') != -1) // ini_set('memory_limit', -1); - if ($res["filename"] == $this->page_name) - { - $this->permission_okay = 1; - } - else - { - $this->login_error = 103; - $this->permission_okay = 0; - } - } - // if called from public, so we can check if the permissions are ok - return $this->permission_okay; - } - - // METHOD: login_logout_user - // PARAMS: none - // RETURN: none - // DESC : if a user pressed on logout, destroyes session and unsets all global vars - public function login_logout_user() - { - if ($this->logout || $this->login_error) - { - // unregister and destroy session vars - unset($_SESSION["EUID"]); - unset($_SESSION["GROUP_LEVEL"]); - unset($_SESSION["PAGES"]); - unset($_SESSION["USER_NAME"]); - unset($_SESSION["UNIT"]); - unset($_SESSION["DEBUG_ALL"]); - unset($_SESSION["DB_DEBUG"]); - unset($GLOBALS["DEBUG_ALL"]); - unset($GLOBALS["DB_DEBUG"]); - unset($_SESSION["LANG"]); - unset($_SESSION["DEFAULT_CHARSET"]); - unset($_SESSION["DEFAULT_LANG"]); - unset($_SESSION["GROUP_NAME"]); - unset($_SESSION["HEADER_COLOR"]); - session_destroy(); - // he prints the login screen again + if ($res["filename"] == $this->page_name) { + $this->permission_okay = 1; + } else { + $this->login_error = 103; $this->permission_okay = 0; } } + // if called from public, so we can check if the permissions are ok + return $this->permission_okay; + } - // METHOD: login_set_acl - // PARAMS: none - // RETURN: none - // DESC : sets all the basic ACLs - // init set the basic acl the user has, based on the following rules - // * init set from config DEFAULT ACL - // * if page ACL is set, it overrides the default ACL - // * if group ACL is set, it overrides the page ACL - // * if user ACL is set, it overrides the group ACL - // set the page ACL - // * default ACL set - // * set group ACL if not default overrides default ACL - // * set page ACL if not default overrides group ACL - // set edit access ACL and set default edit access group - // * if an account ACL is set, set this parallel, account ACL overrides user ACL if it applies - // * if edit access ACL level is set, use this, else use page - // set all base ACL levels as a list keyword -> ACL number - public function login_set_acl() - { - // we start with the default acl - $this->acl['base'] = DEFAULT_ACL_LEVEL; + // METHOD: login_logout_user + // PARAMS: none + // RETURN: none + // DESC : if a user pressed on logout, destroyes session and unsets all global vars + public function login_logout_user() + { + if ($this->logout || $this->login_error) { + // unregister and destroy session vars + unset($_SESSION["EUID"]); + unset($_SESSION["GROUP_LEVEL"]); + unset($_SESSION["PAGES"]); + unset($_SESSION["USER_NAME"]); + unset($_SESSION["UNIT"]); + unset($_SESSION["DEBUG_ALL"]); + unset($_SESSION["DB_DEBUG"]); + unset($GLOBALS["DEBUG_ALL"]); + unset($GLOBALS["DB_DEBUG"]); + unset($_SESSION["LANG"]); + unset($_SESSION["DEFAULT_CHARSET"]); + unset($_SESSION["DEFAULT_LANG"]); + unset($_SESSION["GROUP_NAME"]); + unset($_SESSION["HEADER_COLOR"]); + session_destroy(); + // he prints the login screen again + $this->permission_okay = 0; + } + } - // set admin flag and base to 100 - if ($_SESSION['ADMIN']) - { - $this->acl['admin'] = 1; - $this->acl['base'] = 100; - } - else - { - // now go throw the flow and set the correct ACL - // user > page > group - // group ACL 0 - if ($_SESSION['GROUP_ACL_LEVEL'] != -1) - { - $this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL']; - } - // page ACL 1 - if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) - { - $this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; - } - // user ACL 2 - if ($_SESSION['USER_ACL_LEVEL'] != -1) - { - $this->acl['base'] = $_SESSION['USER_ACL_LEVEL']; - } - } + // METHOD: login_set_acl + // PARAMS: none + // RETURN: none + // DESC : sets all the basic ACLs + // init set the basic acl the user has, based on the following rules + // * init set from config DEFAULT ACL + // * if page ACL is set, it overrides the default ACL + // * if group ACL is set, it overrides the page ACL + // * if user ACL is set, it overrides the group ACL + // set the page ACL + // * default ACL set + // * set group ACL if not default overrides default ACL + // * set page ACL if not default overrides group ACL + // set edit access ACL and set default edit access group + // * if an account ACL is set, set this parallel, account ACL overrides user ACL if it applies + // * if edit access ACL level is set, use this, else use page + // set all base ACL levels as a list keyword -> ACL number + public function login_set_acl() + { + // we start with the default acl + $this->acl['base'] = DEFAULT_ACL_LEVEL; - // set the current page acl - // start with default acl - // set group if not -1, overrides default - // set page if not -1, overrides group set - $this->acl['page'] = DEFAULT_ACL_LEVEL; - if ($_SESSION['GROUP_ACL_LEVEL'] != -1) - { - $this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL']; + // set admin flag and base to 100 + if ($_SESSION['ADMIN']) { + $this->acl['admin'] = 1; + $this->acl['base'] = 100; + } else { + // now go throw the flow and set the correct ACL + // user > page > group + // group ACL 0 + if ($_SESSION['GROUP_ACL_LEVEL'] != -1) { + $this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL']; } - if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) - { - $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; + // page ACL 1 + if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) { + $this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; } + // user ACL 2 + if ($_SESSION['USER_ACL_LEVEL'] != -1) { + $this->acl['base'] = $_SESSION['USER_ACL_LEVEL']; + } + } - // PER ACCOUNT (UNIT/edit access)-> - foreach ($_SESSION['UNIT'] as $ea_id => $unit) - { - // if admin flag is set, all units are set to 100 - if ($this->acl['admin']) - { + // set the current page acl + // start with default acl + // set group if not -1, overrides default + // set page if not -1, overrides group set + $this->acl['page'] = DEFAULT_ACL_LEVEL; + if ($_SESSION['GROUP_ACL_LEVEL'] != -1) { + $this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL']; + } + if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) { + $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; + } + + // PER ACCOUNT (UNIT/edit access)-> + foreach ($_SESSION['UNIT'] as $ea_id => $unit) { + // if admin flag is set, all units are set to 100 + if ($this->acl['admin']) { + $this->acl['unit'][$ea_id] = $this->acl['base']; + } else { + if ($unit['acl_level'] != -1) { + $this->acl['unit'][$ea_id] = $unit['acl_level']; + } else { $this->acl['unit'][$ea_id] = $this->acl['base']; } - else - { - if ($unit['acl_level'] != -1) - $this->acl['unit'][$ea_id] = $unit['acl_level']; - else - $this->acl['unit'][$ea_id] = $this->acl['base']; - } - // detail name/level set - $this->acl['unit_detail'][$ea_id] = array ( - 'name' => $unit['name'], - 'uid' => $unit['uid'], - 'level' => $this->default_acl_list[$this->acl['unit'][$ea_id]]['name'], - 'default' => $unit['default'], - 'data' => $unit['data'] - ); - // set default - if ($unit['default']) - { - $this->acl['unit_id'] = $unit['id']; - $this->acl['unit_name'] = $unit['name']; - $this->acl['unit_uid'] = $unit['uid']; - } } - // flag if to show extra edit access drop downs (because user has multiple groups assigned) - if (count($_SESSION['UNIT']) > 1) - $this->acl['show_ea_extra'] = 1; - else - $this->acl['show_ea_extra'] = 0; - // set the default edit access - $this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT']; - // integrate the type acl list, but only for the keyword -> level - foreach ($this->default_acl_list as $level => $data) - { - $this->acl['min'][$data['type']] = $level; + // detail name/level set + $this->acl['unit_detail'][$ea_id] = array ( + 'name' => $unit['name'], + 'uid' => $unit['uid'], + 'level' => $this->default_acl_list[$this->acl['unit'][$ea_id]]['name'], + 'default' => $unit['default'], + 'data' => $unit['data'] + ); + // set default + if ($unit['default']) { + $this->acl['unit_id'] = $unit['id']; + $this->acl['unit_name'] = $unit['name']; + $this->acl['unit_uid'] = $unit['uid']; } - // set the full acl list too - $this->acl['acl_list'] = $_SESSION['DEFAULT_ACL_LIST']; - // debug + } + // flag if to show extra edit access drop downs (because user has multiple groups assigned) + if (count($_SESSION['UNIT']) > 1) { + $this->acl['show_ea_extra'] = 1; + } else { + $this->acl['show_ea_extra'] = 0; + } + // set the default edit access + $this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT']; + // integrate the type acl list, but only for the keyword -> level + foreach ($this->default_acl_list as $level => $data) { + $this->acl['min'][$data['type']] = $level; + } + // set the full acl list too + $this->acl['acl_list'] = $_SESSION['DEFAULT_ACL_LIST']; + // debug // $this->debug('ACL', $this->print_ar($this->acl)); + } + + // METHOD: login_check_edit_access + // PARAMS: edit_access_id to check + // RETURN: true/false: if the edit access is not in the valid list: false + // DESC : checks if this edit access id is valid + public function login_check_edit_access($edit_access_id) + { + if (array_key_exists($edit_access_id, $this->acl['unit'])) { + return true; + } else { + return false; } + } - // METHOD: login_check_edit_access - // PARAMS: edit_access_id to check - // RETURN: true/false: if the edit access is not in the valid list: false - // DESC : checks if this edit access id is valid - public function login_check_edit_access($edit_access_id) - { - if (array_key_exists($edit_access_id, $this->acl['unit'])) - return true; - else - return false; - } - - // METHOD: login_password_change - // PARAMS: none - // RETURN: none - // DESC : changes a user password - private function login_password_change() - { - if ($this->change_password) - { - $event = 'Password Change'; - // check that given username is NOT in the deny list, else silent skip (with error log) - if (!in_array($this->pw_username, $this->pw_change_deny_users)) - { - if (!$this->pw_username || !$this->pw_password) - { - $this->login_error = 200; - $data = 'Missing username or old password.'; - } - // check user exist, if not -> error - if (!$this->login_error) - { - $q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."'"; - list ($edit_user_id) = $this->db_return_row($q); - if (!$edit_user_id) - { - // username wrong - $this->login_error = 201; - $data = 'User could not be found'; - } - } - // check old passwords match -> error - if (!$this->login_error) - { - $q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."' AND password = '".$this->db_escape_string($this->pw_old_password)."'"; - list ($edit_user_id) = $this->db_return_row($q); - if (!$edit_user_id) - { - // old password wrong - $this->login_error = 202; - $data = 'The old password does not match'; - } - } - // check if new passwords were filled out -> error - if (!$this->login_error) - { - if (!$this->pw_new_password || !$this->pw_new_password_confirm) - { - $this->login_error = 203; - $data = 'Missing new password or new password confirm.'; - } - } - // check new passwords both match -> error - if (!$this->login_error) - { - if ($this->pw_new_password != $this->pw_new_password_confirm) - { - $this->login_error = 204; - $data = 'The new passwords do not match: '.$this->pw_new_password.' == '.$this->pw_new_password_confirm; - } - } - // no error change this users password - if (!$this->login_error) - { - // update the user (edit_user_id) with the new password - $q = "UPDATE edit_user SET password = '".$this->db_escape_string($this->cryptString($this->pw_new_password))."' WHERE edit_user_id = ".$edit_user_id; - $this->db_exec($q); - $data = 'Password change for user "'.$this->pw_username.'" from "'.$this->pw_old_password.'" to "'.$this->pw_new_password.'"'; + // METHOD: login_password_change + // PARAMS: none + // RETURN: none + // DESC : changes a user password + private function login_password_change() + { + if ($this->change_password) { + $event = 'Password Change'; + // check that given username is NOT in the deny list, else silent skip (with error log) + if (!in_array($this->pw_username, $this->pw_change_deny_users)) { + if (!$this->pw_username || !$this->pw_password) { + $this->login_error = 200; + $data = 'Missing username or old password.'; + } + // check user exist, if not -> error + if (!$this->login_error) { + $q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."'"; + list ($edit_user_id) = $this->db_return_row($q); + if (!$edit_user_id) { + // username wrong + $this->login_error = 201; + $data = 'User could not be found'; } } - else - { - // illegal user error - $this->login_error = '220'; - $data = 'Illegal user for password change: '.$this->pw_username; - } - // log this password change attempt - $this->write_log($event, $data, $this->login_error, $pw_username, $pw_old_password); - } // button pressed - } - - // METHOD: login_print_login - // PARAMS: none - // RETURN: none - // DESC : prints out login html part if no permission (error) is set - private function login_print_login() - { - if (!$this->permission_okay) - { - // set the templates now - $this->login_set_templates(); - // if there is a global logout target ... - if (file_exists($this->logout_target) && $this->logout_target) - { - $LOGOUT_TARGET = $this->logout_target; - } else - { - $LOGOUT_TARGET = ""; - } - - $html_string = $this->login_template['template']; - - // if password change is okay - if ($this->password_change) - { - $html_string_password_change = $this->login_template['password_change']; - - // pre change the data in the PASSWORD_CHANGE_DIV first - foreach ($this->login_template['strings'] as $string => $data) - { - if ($data) - $html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change); + // check old passwords match -> error + if (!$this->login_error) { + $q = "SELECT edit_user_id FROM edit_user WHERE enabled = 1 AND username = '".$this->db_escape_string($this->pw_username)."' AND password = '".$this->db_escape_string($this->pw_old_password)."'"; + list ($edit_user_id) = $this->db_return_row($q); + if (!$edit_user_id) { + // old password wrong + $this->login_error = 202; + $data = 'The old password does not match'; } - $this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change; } - - // put in the logout redirect string - if ($this->logout && $LOGOUT_TARGET) - $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); - else - $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); - - // print error messagae - if ($this->login_error) - $html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."
", $html_string); - else - $html_string = str_replace("{ERROR_MSG}", "
", $html_string); - - // create the replace array context - foreach ($this->login_template['strings'] as $string => $data) - { - $html_string = str_replace("{".$string."}", $data, $html_string); + // check if new passwords were filled out -> error + if (!$this->login_error) { + if (!$this->pw_new_password || !$this->pw_new_password_confirm) { + $this->login_error = 203; + $data = 'Missing new password or new password confirm.'; + } } - - // return the created HTML here - return $html_string; - } // if permission is 0 then print out login - } - - // METHOD: login_close_class - // PARAMS: none - // RETURN: none - // DESC : last function called, writes log and prints out error msg and exists script if permission 0 - private function login_close_class() - { - // write to LOG table ... - if ($this->login_error || $this->login || $this->logout) - { - $username = ''; - $password = ''; - // set event - if ($this->login) - $event = "Login"; - else if ($this->logout) - $event = "Logout"; - else - $event = "No Permission"; - // prepare for log - if ($this->euid) - { - // get user from user table - $q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid; - list($username, $password) = $this->db_return_row($q); - } // if euid is set, get username (or try) - $this->write_log($event, '', $this->login_error, $username, $password); - } // write log under certain settings - // now close DB connection -// $this->error_msg = $this->_login(); - if (!$this->permission_okay) - { - return false; + // check new passwords both match -> error + if (!$this->login_error) { + if ($this->pw_new_password != $this->pw_new_password_confirm) { + $this->login_error = 204; + $data = 'The new passwords do not match: '.$this->pw_new_password.' == '.$this->pw_new_password_confirm; + } + } + // no error change this users password + if (!$this->login_error) { + // update the user (edit_user_id) with the new password + $q = "UPDATE edit_user SET password = '".$this->db_escape_string($this->cryptString($this->pw_new_password))."' WHERE edit_user_id = ".$edit_user_id; + $this->db_exec($q); + $data = 'Password change for user "'.$this->pw_username.'" from "'.$this->pw_old_password.'" to "'.$this->pw_new_password.'"'; + } + } else { + // illegal user error + $this->login_error = '220'; + $data = 'Illegal user for password change: '.$this->pw_username; } - else - { - return true; + // log this password change attempt + $this->write_log($event, $data, $this->login_error, $pw_username, $pw_old_password); + } // button pressed + } + + // METHOD: login_print_login + // PARAMS: none + // RETURN: none + // DESC : prints out login html part if no permission (error) is set + private function login_print_login() + { + if (!$this->permission_okay) { + // set the templates now + $this->login_set_templates(); + // if there is a global logout target ... + if (file_exists($this->logout_target) && $this->logout_target) { + $LOGOUT_TARGET = $this->logout_target; + } else { + $LOGOUT_TARGET = ""; } - } - // METHOD: login_set_templates - // PARAMS: - // RETURN: none - // DESC : checks if there are external templates, if not uses internal fallback ones - private function login_set_templates() - { - $strings = array ( - 'HTML_TITLE' => $this->l->__("LOGIN"), - 'TITLE' => $this->l->__("LOGIN"), - 'USERNAME' => $this->l->__("Username"), - 'PASSWORD' => $this->l->__("Password"), - 'LOGIN' => $this->l->__("Login"), - 'ERROR_MSG' => '', - 'LOGOUT_TARGET' => '', - 'PASSWORD_CHANGE_BUTTON_VALUE' => $this->l->__('Change Password') - ); - - $error_msgs = array ( - "100" => $this->l->__("Fatal Error: [EUID] came in as GET/POST!"), // actually obsolete - "1010" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // user not found - "1011" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // blowfish password wrong - "1012" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // fallback md5 password wrong - "102" => $this->l->__("Fatal Error: Login Failed - Please enter username and password"), - "103" => $this->l->__("Fatal Error: You do not have the rights to access this Page"), - "104" => $this->l->__("Fatal Error: Login Failed - User not enabled"), - "105" => $this->l->__("Fatal Error: Login Failed - User is locked"), - "220" => $this->l->__("Fatal Error: Password change - The user could not be found"), // actually this is an illegal user, but I mask it - '200' => $this->l->__("Fatal Error: Password change - Please enter username and old password"), - "201" => $this->l->__("Fatal Error: Password change - The user could not be found"), - "202" => $this->l->__("Fatal Error: Password change - The old password is not correct"), - "203" => $this->l->__("Fatal Error: Password change - Please fill out both new password fields"), - "204" => $this->l->__("Fatal Error: Password change - The new passwords do not match"), - "9999" => $this->l->__("Fatal Error: necessary crypt engine could not be found. Login is impossible") // this is bad bad error - ); + $html_string = $this->login_template['template']; // if password change is okay - if ($this->password_change) - { - $strings = array_merge($strings, array ( - 'TITLE_PASSWORD_CHANGE' => 'Change Password for User', - 'OLD_PASSWORD' => $this->l->__("Old Password"), - 'NEW_PASSWORD' => $this->l->__("New Password"), - 'NEW_PASSWORD_CONFIRM' => $this->l->__("New Password confirm"), - 'CLOSE' => $this->l->__('Close'), - 'JS_SHOW_HIDE' => "function ShowHideDiv(id) { element = document.getElementById(id); if (element.className == 'visible' || !element.className) element.className = 'hidden'; else element.className = 'visible'; }", - 'PASSWORD_CHANGE_BUTTON' => '' - )); - $this->login_template['password_change'] = <<password_change) { + $html_string_password_change = $this->login_template['password_change']; + + // pre change the data in the PASSWORD_CHANGE_DIV first + foreach ($this->login_template['strings'] as $string => $data) { + if ($data) { + $html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change); + } + } + $this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change; + } + + // put in the logout redirect string + if ($this->logout && $LOGOUT_TARGET) { + $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); + } else { + $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); + } + + // print error messagae + if ($this->login_error) { + $html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."
", $html_string); + } else { + $html_string = str_replace("{ERROR_MSG}", "
", $html_string); + } + + // create the replace array context + foreach ($this->login_template['strings'] as $string => $data) { + $html_string = str_replace("{".$string."}", $data, $html_string); + } + + // return the created HTML here + return $html_string; + } // if permission is 0 then print out login + } + + // METHOD: login_close_class + // PARAMS: none + // RETURN: none + // DESC : last function called, writes log and prints out error msg and exists script if permission 0 + private function login_close_class() + { + // write to LOG table ... + if ($this->login_error || $this->login || $this->logout) { + $username = ''; + $password = ''; + // set event + if ($this->login) { + $event = "Login"; + } elseif ($this->logout) { + $event = "Logout"; + } else { + $event = "No Permission"; + } + // prepare for log + if ($this->euid) { + // get user from user table + $q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid; + list($username, $password) = $this->db_return_row($q); + } // if euid is set, get username (or try) + $this->write_log($event, '', $this->login_error, $username, $password); + } // write log under certain settings + // now close DB connection +// $this->error_msg = $this->_login(); + if (!$this->permission_okay) { + return false; + } else { + return true; + } + } + + // METHOD: login_set_templates + // PARAMS: + // RETURN: none + // DESC : checks if there are external templates, if not uses internal fallback ones + private function login_set_templates() + { + $strings = array ( + 'HTML_TITLE' => $this->l->__("LOGIN"), + 'TITLE' => $this->l->__("LOGIN"), + 'USERNAME' => $this->l->__("Username"), + 'PASSWORD' => $this->l->__("Password"), + 'LOGIN' => $this->l->__("Login"), + 'ERROR_MSG' => '', + 'LOGOUT_TARGET' => '', + 'PASSWORD_CHANGE_BUTTON_VALUE' => $this->l->__('Change Password') + ); + + $error_msgs = array ( + "100" => $this->l->__("Fatal Error: [EUID] came in as GET/POST!"), // actually obsolete + "1010" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // user not found + "1011" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // blowfish password wrong + "1012" => $this->l->__("Fatal Error: Login Failed - Wrong Username or Password"), // fallback md5 password wrong + "102" => $this->l->__("Fatal Error: Login Failed - Please enter username and password"), + "103" => $this->l->__("Fatal Error: You do not have the rights to access this Page"), + "104" => $this->l->__("Fatal Error: Login Failed - User not enabled"), + "105" => $this->l->__("Fatal Error: Login Failed - User is locked"), + "220" => $this->l->__("Fatal Error: Password change - The user could not be found"), // actually this is an illegal user, but I mask it + '200' => $this->l->__("Fatal Error: Password change - Please enter username and old password"), + "201" => $this->l->__("Fatal Error: Password change - The user could not be found"), + "202" => $this->l->__("Fatal Error: Password change - The old password is not correct"), + "203" => $this->l->__("Fatal Error: Password change - Please fill out both new password fields"), + "204" => $this->l->__("Fatal Error: Password change - The new passwords do not match"), + "9999" => $this->l->__("Fatal Error: necessary crypt engine could not be found. Login is impossible") // this is bad bad error + ); + + // if password change is okay + if ($this->password_change) { + $strings = array_merge($strings, array ( + 'TITLE_PASSWORD_CHANGE' => 'Change Password for User', + 'OLD_PASSWORD' => $this->l->__("Old Password"), + 'NEW_PASSWORD' => $this->l->__("New Password"), + 'NEW_PASSWORD_CONFIRM' => $this->l->__("New Password confirm"), + 'CLOSE' => $this->l->__('Close'), + 'JS_SHOW_HIDE' => "function ShowHideDiv(id) { element = document.getElementById(id); if (element.className == 'visible' || !element.className) element.className = 'hidden'; else element.className = 'visible'; }", + 'PASSWORD_CHANGE_BUTTON' => '' + )); + $this->login_template['password_change'] = <<