Compare commits

...

15 Commits

Author SHA1 Message Date
Clemens Schwaighofer 484444b97a tmp folder in 4dev 2018-03-28 14:31:14 +09:00
clemens 6dc6a58765 Fix impossible lang translate call in basic lib 2018-03-28 10:40:27 +09:00
clemens ca8da46a58 Merge branch 'master' of git.tokyo.tequila.jp:/var/lib/git/php_core 2018-03-28 10:02:27 +09:00
clemens a28e5244ab Fixes & code style changes 2018-03-28 10:02:19 +09:00
Clemens Schwaighofer 31acfd1ee4 Update to Smarty 3.1.30
Keep old 3.1.27 around for testing
2018-03-22 10:22:37 +09:00
Clemens Schwaighofer f1155ad824 Rename wrong named (extension) translation files 2018-03-20 17:09:42 +09:00
Clemens Schwaighofer eef3a81be7 Minor update for DB psql class include 2018-03-20 14:10:06 +09:00
Clemens Schwaighofer bf60e9fcbf Readme update 2018-03-20 14:05:37 +09:00
clemens 7d42256a30 PHP CodeStandard update
- all if/while/for/etc blocks have brackets on same line
- functions have brackets on new line
- no blocks without brackets
- all code starts on col 0 and there are no tab intends anymore

off: came case for classes and class methods
ignore: _ prefix functions (we can't change that anymore)
2018-03-15 17:38:33 +09:00
Clemens Schwaighofer 5226fbcfc3 error reporting test 2018-03-14 15:36:42 +09:00
Clemens Schwaighofer 87b9af9786 PHP Notice warning fixes 2018-03-13 18:37:04 +09:00
Clemens Schwaighofer 7981e3ab51 Fix Class DB not init for dbh check on close db handler 2018-03-13 13:42:25 +09:00
Clemens Schwaighofer 21b9b99197 Minor white space clean up in login class and DB Array IO 2018-02-19 10:44:25 +09:00
Clemens Schwaighofer d9df0d64b8 Class DB IO, fix for trailing ; with RETURNING
If an INSERT query has no RETURNING but ; at the end, the RETURNING was
added after the ;

The ; is now stripped before adding RETURNING
2018-02-08 10:58:53 +09:00
Clemens Schwaighofer 73cdbe27c0 Fix JavaScript SetCenter 2018-02-08 10:45:48 +09:00
252 changed files with 43128 additions and 12041 deletions
+2
View File
@@ -0,0 +1,2 @@
*
!.gitignore
+23 -8
View File
@@ -1,10 +1,25 @@
PHP Core Library # PHP Core Library
================
Base PHP class files to setup any project Base PHP class files to setup any project
* login * login
* database wrapper * database wrapper
* basic helper class for debugging and other features * basic helper class for debugging and other features
* admin/frontend split * admin/frontend split
* domain controlled database/settings split * domain controlled database/settings split
* dynamic layout groups * dynamic layout groups
## NOTE
There are three branches:
### master
This is currently the legacy branch set live. This will change to the namespace branch once development is finished
### legacy
The old non namepsace format layout. This will only get bug fixes and no new development
### namespace
The new namespace branch. Once development is finished this branch will be removed or renamed to development only branch
+1 -1
View File
@@ -1 +1 @@
smarty-3.1.27/ smarty-3.1.30
+136 -132
View File
@@ -1,118 +1,123 @@
<? <?
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
$DB_DEBUG = 1; $DB_DEBUG = 1;
if ($DEBUG_ALL) if ($DEBUG_ALL) {
error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR); error_reporting(E_ALL | E_STRICT | E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
}
define('USE_DATABASE', true); define('USE_DATABASE', true);
// sample config // sample config
require("config.inc"); require("config.inc");
// set session name // set session name
DEFINE('SET_SESSION_NAME', EDIT_SESSION_NAME); DEFINE('SET_SESSION_NAME', EDIT_SESSION_NAME);
// session_name(EDIT_SESSION_NAME); // session_name(EDIT_SESSION_NAME);
// session_start(); // session_start();
// basic class test file // basic class test file
foreach (array ('Login', 'Admin.Backend') as $class) foreach (array ('Login', 'Admin.Backend') as $class) {
_spl_autoload('Class.'.$class.'.inc'); _spl_autoload('Class.'.$class.'.inc');
}
$lang = 'en_utf8'; $lang = 'en_utf8';
DEFINE('LOG_FILE_ID', 'classTest'); DEFINE('LOG_FILE_ID', 'classTest');
$login = new login($DB_CONFIG[LOGIN_DB], $lang); $login = new login($DB_CONFIG[LOGIN_DB], $lang);
// init with standard // init with standard
// $basic = new db_io($DB_CONFIG[MAIN_DB]); // $basic = new db_io($DB_CONFIG[MAIN_DB]);
$basic = new AdminBackend($DB_CONFIG[MAIN_DB], $lang); $basic = new AdminBackend($DB_CONFIG[MAIN_DB], $lang);
$basic->db_info(1); $basic->db_info(1);
// set + check edit access id // set + check edit access id
$edit_access_id = 3; $edit_access_id = 3;
print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."<br>"; print "ACL UNIT: ".print_r(array_keys($login->acl['unit']), 1)."<br>";
print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."<br>"; print "ACCESS CHECK: ".$login->login_check_edit_access($edit_access_id)."<br>";
if ($login->login_check_edit_access($edit_access_id)) if ($login->login_check_edit_access($edit_access_id)) {
$basic->edit_access_id = $edit_access_id; $basic->edit_access_id = $edit_access_id;
else } else {
$basic->edit_access_id = $login->acl['unit_id']; $basic->edit_access_id = $login->acl['unit_id'];
}
// $basic->debug('SESSION', $basic->print_ar($_SESSION)); // $basic->debug('SESSION', $basic->print_ar($_SESSION));
print "<html><head><title>TEST CLASS</title><head>"; print "<html><head><title>TEST CLASS</title><head>";
print "<body>"; print "<body>";
print '<form method="post" name="loginlogout">'; print '<form method="post" name="loginlogout">';
print '<a href="javascript:document.loginlogout.login_logout.value=\'Logou\';document.loginlogout.submit();">Logout</a>'; print '<a href="javascript:document.loginlogout.login_logout.value=\'Logou\';document.loginlogout.submit();">Logout</a>';
print '<input type="hidden" name="login_logout" value="">'; print '<input type="hidden" name="login_logout" value="">';
print '</form>'; print '</form>';
// print the debug core vars // print the debug core vars
print "DEBUG OUT: ".$basic->debug_output."<br>"; print "DEBUG OUT: ".$basic->debug_output."<br>";
print "ECHO OUT: ".$basic->echo_output."<br>"; print "ECHO OUT: ".$basic->echo_output."<br>";
print "PRINT OUT: ".$basic->print_output."<br>"; print "PRINT OUT: ".$basic->print_output."<br>";
print "NOT DEBUG OUT: ".$basic->debug_output_not."<br>"; print "NOT DEBUG OUT: ".$basic->debug_output_not."<br>";
print "NOT ECHO OUT: ".$basic->echo_output_not."<br>"; print "NOT ECHO OUT: ".$basic->echo_output_not."<br>";
print "NOT PRINT OUT: ".$basic->print_output_not."<br>"; print "NOT PRINT OUT: ".$basic->print_output_not."<br>";
print "DEBUG OUT ALL: ".$basic->debug_output_all."<br>"; print "DEBUG OUT ALL: ".$basic->debug_output_all."<br>";
print "ECHO OUT ALL: ".$basic->echo_output_all."<br>"; print "ECHO OUT ALL: ".$basic->echo_output_all."<br>";
print "PRINT OUT ALL: ".$basic->print_output_all."<br>"; print "PRINT OUT ALL: ".$basic->print_output_all."<br>";
print "CALLER BACKTRACE: ".$basic->get_caller_method()."<br>"; print "CALLER BACKTRACE: ".$basic->get_caller_method()."<br>";
$basic->debug('SOME MARK', 'Some error output'); $basic->debug('SOME MARK', 'Some error output');
print "EDIT ACCESS ID: ".$basic->edit_access_id."<br>"; print "EDIT ACCESS ID: ".$basic->edit_access_id."<br>";
// print "ACL: <br>".$basic->print_ar($login->acl)."<br>"; // print "ACL: <br>".$basic->print_ar($login->acl)."<br>";
$basic->debug('ACL', "ACL: ".$basic->print_ar($login->acl)); $basic->debug('ACL', "ACL: ".$basic->print_ar($login->acl));
// print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>"; // print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>";
// print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>"; // print "DEFAULT ACL: <br>".$basic->print_ar($login->default_acl_list)."<br>";
// $result = array_flip(array_filter(array_flip($login->default_acl_list), function ($key) { if (is_numeric($key)) return $key; })); // $result = array_flip(array_filter(array_flip($login->default_acl_list), function ($key) { if (is_numeric($key)) return $key; }));
// print "DEFAULT ACL: <br>".$basic->print_ar($result)."<br>"; // print "DEFAULT ACL: <br>".$basic->print_ar($result)."<br>";
// DEPRICATED CALL // DEPRICATED CALL
// $basic->adbSetACL($login->acl); // $basic->adbSetACL($login->acl);
while ($res = $basic->db_return("SELECT * FROM max_test")) while ($res = $basic->db_return("SELECT * FROM max_test")) {
{
print "TIME: ".$res['time']."<br>"; print "TIME: ".$res['time']."<br>";
} }
$status = $basic->db_exec("INSERT INTO foo (test) VALUES ('FOO TEST ".time()."') RETURNING test"); $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)."<br>"; print "DIRECT INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>";
print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>"; print "DIRECT INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>";
$basic->db_prepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)"); $basic->db_prepare("ins_foo", "INSERT INTO foo (test) VALUES ($1)");
$status = $basic->db_execute("ins_foo", array('BAR TEST '.time())); $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)."<br>"; print "PREPARE INSERT STATUS: $status | PRIMARY KEY: ".$basic->insert_id." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>";
print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>"; print "PREPARE INSERT PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>";
// returning test with multiple entries // 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");
$status = $basic->db_exec("INSERT INTO foo (test) values ('BAR 1 ".time()."'), ('BAR 2 ".time()."'), ('BAR 3 ".time()."') RETURNING foo_id, test"); $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)."<br>"; print "DIRECT MULTIPLE INSERT STATUS: $status | PRIMARY KEYS: ".print_r($basic->insert_id, 1)." | PRIMARY KEY EXT: ".print_r($basic->insert_id_ext, 1)."<br>";
// 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)."<br>";
# db write class test # db write class test
$table = 'foo'; $table = 'foo';
print "TABLE META DATA: ".$basic->print_ar($basic->db_show_table_meta_data($table))."<br>"; print "TABLE META DATA: ".$basic->print_ar($basic->db_show_table_meta_data($table))."<br>";
$primary_key = ''; # unset $primary_key = ''; # unset
$db_write_table = array ('test', 'string_a', 'number_a', 'some_bool'); $db_write_table = array ('test', 'string_a', 'number_a', 'some_bool');
// $db_write_table = array ('test'); // $db_write_table = array ('test');
$object_fields_not_touch = array (); $object_fields_not_touch = array ();
$object_fields_not_update = array (); $object_fields_not_update = array ();
$data = array ('test' => 'BOOL TEST SOMETHING '.time(), 'string_a' => 'SOME TEXT', 'number_a' => 5); $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); $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<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array ('test' => 'BOOL TEST ON '.time(), 'string_a' => '', 'number_a' => 0, 'some_bool' => 1); $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); $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<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array ('test' => 'BOOL TEST OFF '.time(), 'string_a' => null, 'number_a' => null, 'some_bool' => 0); $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); $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<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
$data = array ('test' => 'BOOL TEST UNSET '.time()); $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); $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<br>"; print "Wrote to DB tabel $table and got primary key $primary_key<br>";
# 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)"); /* $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: "; echo "WAITING FOR ASYNC: ";
$chars = array('|', '/', '-', '\\'); $chars = array('|', '/', '-', '\\');
while (($ret = $basic->db_check_async()) === true) while (($ret = $basic->db_check_async()) === true)
{ {
if ((list($_, $char) = each($chars)) === FALSE) if ((list($_, $char) = each($chars)) === FALSE)
{ {
reset($chars); reset($chars);
@@ -121,71 +126,70 @@
print $char; print $char;
sleep(1); sleep(1);
flush(); flush();
} }
print "<br>END STATUS: ".$ret."<br>"; print "<br>END STATUS: ".$ret."<br>";
// while ($res = $basic->db_fetch_array($ret)) // while ($res = $basic->db_fetch_array($ret))
while ($res = $basic->db_fetch_array()) while ($res = $basic->db_fetch_array())
{ {
echo "RES: ".$res['test']."<br>"; echo "RES: ".$res['test']."<br>";
} }
# test async insert # test async insert
$basic->db_exec_async("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')"); $basic->db_exec_async("INSERT INTO foo (Test) VALUES ('ASYNC TEST ".time()."')");
echo "WAITING FOR ASYNC INSERT: "; echo "WAITING FOR ASYNC INSERT: ";
while (($ret = $basic->db_check_async()) === true) while (($ret = $basic->db_check_async()) === true)
{ {
print "."; print ".";
sleep(1); sleep(1);
flush(); flush();
} }
print "<br>END STATUS: ".$ret." | PK: ".$basic->insert_id."<br>"; print "<br>END STATUS: ".$ret." | PK: ".$basic->insert_id."<br>";
print "ASYNC PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>"; */ print "ASYNC PREVIOUS INSERTED: ".print_r($basic->db_return_row("SELECT foo_id, test FROM foo WHERE foo_id = ".$basic->insert_id), 1)."<br>"; */
$to_db_version = '9.1.9'; $to_db_version = '9.1.9';
print "VERSION DB: ".$basic->db_version()."<br>"; print "VERSION DB: ".$basic->db_version()."<br>";
print "DB Version smaller $to_db_version: ".$basic->db_compare_version('<'.$to_db_version)."<br>"; print "DB Version smaller $to_db_version: ".$basic->db_compare_version('<'.$to_db_version)."<br>";
print "DB Version smaller than $to_db_version: ".$basic->db_compare_version('<='.$to_db_version)."<br>"; print "DB Version smaller than $to_db_version: ".$basic->db_compare_version('<='.$to_db_version)."<br>";
print "DB Version equal $to_db_version: ".$basic->db_compare_version('='.$to_db_version)."<br>"; print "DB Version equal $to_db_version: ".$basic->db_compare_version('='.$to_db_version)."<br>";
print "DB Version bigger than $to_db_version: ".$basic->db_compare_version('>='.$to_db_version)."<br>"; print "DB Version bigger than $to_db_version: ".$basic->db_compare_version('>='.$to_db_version)."<br>";
print "DB Version bigger $to_db_version: ".$basic->db_compare_version('>'.$to_db_version)."<br>"; print "DB Version bigger $to_db_version: ".$basic->db_compare_version('>'.$to_db_version)."<br>";
/* $q = "SELECT FOO FRO BAR"; /* $q = "SELECT FOO FRO BAR";
// $q = "Select * from foo"; // $q = "Select * from foo";
$foo = $basic->db_exec_async($q); $foo = $basic->db_exec_async($q);
print "[ERR] Query: ".$q."<br>"; print "[ERR] Query: ".$q."<br>";
print "[ERR] RESOURCE: $foo<br>"; print "[ERR] RESOURCE: $foo<br>";
while (($ret = $basic->db_check_async()) === true) while (($ret = $basic->db_check_async()) === true)
{ {
print "[ERR]: $ret<br>"; print "[ERR]: $ret<br>";
// sleep(5); // sleep(5);
} */ } */
// search path check // search path check
$q = "SHOW search_path"; $q = "SHOW search_path";
$cursor = $basic->db_exec($q); $cursor = $basic->db_exec($q);
$data = $basic->db_fetch_array($cursor)['search_path']; $data = $basic->db_fetch_array($cursor)['search_path'];
print "RETURN DATA FOR search_path: ".$data."<br>"; print "RETURN DATA FOR search_path: ".$data."<br>";
// print "RETURN DATA FOR search_path: ".$basic->print_ar($data)."<br>"; // print "RETURN DATA FOR search_path: ".$basic->print_ar($data)."<br>";
// insert something into test.schema_test and see if we get the PK back // 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).")"); $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."<br>"; print "OTHER SCHEMA INSERT STATUS: ".$status." | PK NAME: ".$basic->pk_name.", PRIMARY KEY: ".$basic->insert_id."<br>";
// time string thest // time string thest
$timestamp = 5887998.33445; $timestamp = 5887998.33445;
$time_string = $basic->TimeStringFormat($timestamp); $time_string = $basic->TimeStringFormat($timestamp);
print "TIME STRING TEST: ".$time_string."<br>"; print "TIME STRING TEST: ".$time_string."<br>";
print "REVERSE TIME STRING: ".$basic->StringToTime($time_string); print "REVERSE TIME STRING: ".$basic->StringToTime($time_string);
// magic links test // magic links test
print $basic->magic_links('user@bubu.at').'<br>'; print $basic->magic_links('user@bubu.at').'<br>';
print $basic->magic_links('http://test.com/foo/bar.php?foo=1').'<br>'; print $basic->magic_links('http://test.com/foo/bar.php?foo=1').'<br>';
// compare date // compare date
$date_1 = '2017/1/5'; $date_1 = '2017/1/5';
$date_2 = '2017-01-05'; $date_2 = '2017-01-05';
print "COMPARE DATE: ".$basic->CompareDate($date_1, $date_2)."<br>"; print "COMPARE DATE: ".$basic->CompareDate($date_1, $date_2)."<br>";
// print error messages // print error messages
print $basic->print_error_msg(); print $basic->print_error_msg();
print "</body></html>"; print "</body></html>";
?>
+148 -169
View File
@@ -1,72 +1,70 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/06/10 * CREATED: 2003/06/10
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* central include for all edit_pages * central include for all edit_pages
* - edit_groups.php * - edit_groups.php
* - edit_languages.php * - edit_languages.php
* - edit_pages.php * - edit_pages.php
* - edit_schemes.php * - edit_schemes.php
* - edit_users.php * - edit_users.php
* - edit_visible_group.php * - edit_visible_group.php
* HISTORY: * HISTORY:
* 2005/06/30 (cs) remove color settings, they are in CSS File now * 2005/06/30 (cs) remove color settings, they are in CSS File now
* 2005/06/22 (cs) moved load of config array into form class, set lang and lang is must set var for form class; removed the page name setting, moved it into the form class, remove all HTML from main page * 2005/06/22 (cs) moved load of config array into form class, set lang and lang is must set var for form class; removed the page name setting, moved it into the form class, remove all HTML from main page
* 2004/09/30 (cs) changed layout to fit default layout & changed LIBS, etc * 2004/09/30 (cs) changed layout to fit default layout & changed LIBS, etc
* 2003-06-10: creation of this page * 2003-06-10: creation of this page
*********************************************************************/ *********************************************************************/
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$DB_DEBUG = 1; $DB_DEBUG = 1;
extract($_POST, EXTR_SKIP); extract($_POST, EXTR_SKIP);
$table_width = 750; $table_width = 750;
// this is for certain CMS modules that set a relative path // this is for certain CMS modules that set a relative path
define(REL_PATH, ''); define(REL_PATH, '');
ob_start(); ob_start();
include("config.inc"); include("config.inc");
// overrride debug flags // overrride debug flags
if (!DEBUG) if (!DEBUG) {
{
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
$DB_DEBUG = 0; $DB_DEBUG = 0;
$ECHO_ALL = 0; $ECHO_ALL = 0;
// $DEBUG_TMPL = 0; // $DEBUG_TMPL = 0;
} }
// set session name here // set session name here
define('SET_SESSION_NAME', EDIT_SESSION_NAME); define('SET_SESSION_NAME', EDIT_SESSION_NAME);
// login class // login class
require(LIBS."Class.Login.inc"); require(LIBS."Class.Login.inc");
// form generate for edit interface // form generate for edit interface
require(LIBS."Class.Form.Generate.inc"); require(LIBS."Class.Form.Generate.inc");
// Smarty: and the small extend for l10n calls // Smarty: and the small extend for l10n calls
require(LIBS.'Class.Smarty.Extend.inc'); require(LIBS.'Class.Smarty.Extend.inc');
// set default lang if not set otherwise // set default lang if not set otherwise
if (!$lang) if (!$lang) {
$lang = DEFAULT_LANG; $lang = DEFAULT_LANG;
// should be utf8 }
header("Content-type: text/html; charset=".DEFAULT_ENCODING); // should be utf8
ob_end_flush(); header("Content-type: text/html; charset=".DEFAULT_ENCODING);
$login = new login($DB_CONFIG[LOGIN_DB], $lang); ob_end_flush();
$login = new login($DB_CONFIG[LOGIN_DB], $lang);
// create form class // create form class
$form = new form($DB_CONFIG[MAIN_DB], $lang); $form = new form($DB_CONFIG[MAIN_DB], $lang);
$form->db_exec("SET search_path TO ".LOGIN_DB_SCHEMA); $form->db_exec("SET search_path TO ".LOGIN_DB_SCHEMA);
if ($form->mobile_phone) if ($form->mobile_phone) {
{
echo "I am sorry, but this page cannot be viewed by a mobile phone"; echo "I am sorry, but this page cannot be viewed by a mobile phone";
exit; exit;
} }
// smarty template engine (extended Translation version) // smarty template engine (extended Translation version)
$smarty = new SmartyML($lang); $smarty = new SmartyML($lang);
if (TARGET == 'live' || TARGET == 'remote') if (TARGET == 'live' || TARGET == 'remote') {
{
// login // login
$login->debug_output_all = DEBUG ? 1 : 0; $login->debug_output_all = DEBUG ? 1 : 0;
$login->echo_output_all = 0; $login->echo_output_all = 0;
@@ -75,152 +73,139 @@
$form->debug_output_all = DEBUG ? 1 : 0; $form->debug_output_all = DEBUG ? 1 : 0;
$form->echo_output_all = 0; $form->echo_output_all = 0;
$form->print_output_all = DEBUG ? 1 : 0; $form->print_output_all = DEBUG ? 1 : 0;
} }
// set the template dir // set the template dir
// WARNING: this has a special check for the mailing tool layout (old layout) // WARNING: this has a special check for the mailing tool layout (old layout)
if (defined('LAYOUT')) if (defined('LAYOUT')) {
{
$smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS; $DATA['css'] = LAYOUT.DEFAULT_TEMPLATE.CSS;
$DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS; $DATA['js'] = LAYOUT.DEFAULT_TEMPLATE.JS;
} } else {
else
{
$smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE); $smarty->setTemplateDir(TEMPLATES.DEFAULT_TEMPLATE);
$DATA['css'] = CSS.DEFAULT_TEMPLATE; $DATA['css'] = CSS.DEFAULT_TEMPLATE;
$DATA['js'] = JS.DEFAULT_TEMPLATE; $DATA['js'] = JS.DEFAULT_TEMPLATE;
} }
// space for setting special debug flags // space for setting special debug flags
$login->debug_output_all = 1; $login->debug_output_all = 1;
// define edit logging function. should be in a special edit interface class later // define edit logging function. should be in a special edit interface class later
// METHOD: EditLog() // METHOD: EditLog()
// PARAMS: event -> any kind of event description, data -> any kind of data related to that event // PARAMS: event -> any kind of event description, data -> any kind of data related to that event
// RETURN: none // RETURN: none
// DESC: writes all action vars plus other info into edit_log table // DESC: writes all action vars plus other info into edit_log table
function EditLog($event = '', $data = '') function EditLog($event = '', $data = '')
{ {
$q = "INSERT INTO edit_log "; $q = "INSERT INTO edit_log ";
$q .= "(euid, event_date, ip, event, data, page) "; $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()."')"; $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 // log backend data
// data part creation // data part creation
$data = array ( $data = array (
'_SESSION' => $_SESSION, '_SESSION' => $_SESSION,
'_GET' => $_GET, '_GET' => $_GET,
'_POST' => $_POST, '_POST' => $_POST,
'_FILES' => $_FILES '_FILES' => $_FILES
); );
// log action // log action
EditLog('Edit Submit', serialize($data)); EditLog('Edit Submit', serialize($data));
$form->form_procedure_load(${$form->archive_pk_name}); $form->form_procedure_load(${$form->archive_pk_name});
$form->form_procedure_new(); $form->form_procedure_new();
$form->form_procedure_save(); $form->form_procedure_save();
$form->form_procedure_delete(); $form->form_procedure_delete();
$form->form_procedure_delete_from_element_list($element_list, $remove_name); $form->form_procedure_delete_from_element_list($element_list, $remove_name);
// define all needed smarty stuff for the general HTML/page building // define all needed smarty stuff for the general HTML/page building
$HEADER['CSS'] = CSS; $HEADER['CSS'] = CSS;
$HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; $HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING;
$HEADER['JS'] = JS; $HEADER['JS'] = JS;
$HEADER['STYLESHEET'] = $EDIT_STYLESHEET; $HEADER['STYLESHEET'] = $EDIT_STYLESHEET;
$HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; $HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT;
$DATA['table_width'] = $table_width; $DATA['table_width'] = $table_width;
// write out error / status messages // write out error / status messages
$messages[] = $form->form_error_msg(); $messages[] = $form->form_error_msg();
$DATA['form_error_msg'] = $messages; $DATA['form_error_msg'] = $messages;
// MENU START // MENU START
// request some session vars // request some session vars
if (!$HEADER_COLOR) if (!$HEADER_COLOR) {
$DATA['HEADER_COLOR'] = "#E0E2FF"; $DATA['HEADER_COLOR'] = "#E0E2FF";
else } else {
$DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR']; $DATA['HEADER_COLOR'] = $_SESSION['HEADER_COLOR'];
$DATA['USER_NAME'] = $_SESSION["USER_NAME"]; }
$DATA['EUID'] = $_SESSION["EUID"]; $DATA['USER_NAME'] = $_SESSION["USER_NAME"];
$DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"]; $DATA['EUID'] = $_SESSION["EUID"];
$DATA['GROUP_LEVEL'] = $_SESSION["GROUP_LEVEL"]; $DATA['GROUP_NAME'] = $_SESSION["GROUP_NAME"];
$PAGES = $_SESSION["PAGES"]; $DATA['GROUP_LEVEL'] = $_SESSION["GROUP_LEVEL"];
$PAGES = $_SESSION["PAGES"];
//$form->debug('menu', $form->print_ar($PAGES)); //$form->debug('menu', $form->print_ar($PAGES));
// baue nav aus $PAGES ... // baue nav aus $PAGES ...
for ($i = 0; $i < count($PAGES); $i ++) for ($i = 0; $i < count($PAGES); $i ++) {
{ if ($PAGES[$i]["menu"] && $PAGES[$i]["online"]) {
if ($PAGES[$i]["menu"] && $PAGES[$i]["online"])
{
$menuarray[] = $PAGES[$i]; $menuarray[] = $PAGES[$i];
} }
} }
// split point for nav points // split point for nav points
$COUNT_NAV_POINTS = count($menuarray); $COUNT_NAV_POINTS = count($menuarray);
$SPLIT_FACTOR = 3; $SPLIT_FACTOR = 3;
$START_SPLIT_COUNT = 3; $START_SPLIT_COUNT = 3;
// WTF ?? I dunno what I am doing here ... // WTF ?? I dunno what I am doing here ...
for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) for ($i = 9; $i < $COUNT_NAV_POINTS; $i += $START_SPLIT_COUNT) {
{ if ($COUNT_NAV_POINTS > $i) {
if ($COUNT_NAV_POINTS > $i)
$SPLIT_FACTOR += 1; $SPLIT_FACTOR += 1;
} }
}
for ($i = 1; $i <= count($menuarray); $i ++) for ($i = 1; $i <= count($menuarray); $i ++) {
{
// do that for new array // do that for new array
$j = $i - 1; $j = $i - 1;
$menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]); $menu_data[$j]['pagename'] = htmlentities($menuarray[($i-1)]["page_name"]);
$menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"]; $menu_data[$j]['filename'] = $menuarray[($i-1)]["filename"].$menuarray[($i-1)]["query_string"];
if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) if ($i == 1 || !(($i - 1) % $SPLIT_FACTOR)) {
{
$menu_data[$j]['splitfactor_in'] = 1; $menu_data[$j]['splitfactor_in'] = 1;
} }
if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) if ($menuarray[($i - 1)]["filename"] == $form->get_page_name()) {
{
$position = $i - 1; $position = $i - 1;
$menu_data[$j]['position'] = 1; $menu_data[$j]['position'] = 1;
} } else {
else
{
// add query stuff // add query stuff
// HAS TO DONE LATER ... set urlencode, etc ... // HAS TO DONE LATER ... set urlencode, etc ...
// check if popup needed // check if popup needed
if ($menuarray[($i - 1)]["popup"]) if ($menuarray[($i - 1)]["popup"]) {
{
$menu_data[$j]['popup'] = 1; $menu_data[$j]['popup'] = 1;
$menu_data[$j]['rand'] = uniqid(rand()); $menu_data[$j]['rand'] = uniqid(rand());
$menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"]; $menu_data[$j]['width'] = $menuarray[($i-1)]["popup_x"];
$menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"]; $menu_data[$j]['height'] = $menuarray[($i-1)]["popup_y"];
} // popup or not } // popup or not
} // highlight or not } // highlight or not
if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) if (!($i % $SPLIT_FACTOR) || (($i + 1) > count($menuarray))) {
{
$menu_data[$j]['splitfactor_out'] = 1; $menu_data[$j]['splitfactor_out'] = 1;
} // split } // split
} // for } // for
$DATA['menu_data'] = $menu_data; $DATA['menu_data'] = $menu_data;
$DATA['page_name'] = $menuarray[$position]["page_name"]; $DATA['page_name'] = $menuarray[$position]["page_name"];
$L_TITLE = $DATA['page_name']; $L_TITLE = $DATA['page_name'];
// html title // html title
$HEADER['HTML_TITLE'] = ((!$L_TITLE) ? $form->l->__($G_TITLE) : $form->l->__($L_TITLE)); $HEADER['HTML_TITLE'] = ((!$L_TITLE) ? $form->l->__($G_TITLE) : $form->l->__($L_TITLE));
// END MENU // END MENU
// LOAD AND NEW // LOAD AND NEW
$DATA['load'] = $form->form_create_load(); $DATA['load'] = $form->form_create_load();
$DATA['new'] = $form->form_create_new(); $DATA['new'] = $form->form_create_new();
// SHOW DATA PART // SHOW DATA PART
if ($form->yes) if ($form->yes) {
{
$DATA['form_yes'] = $form->yes; $DATA['form_yes'] = $form->yes;
$DATA['form_my_page_name'] = $form->my_page_name; $DATA['form_my_page_name'] = $form->my_page_name;
// depending on the "get_page_name()" I show different stuff // depending on the "get_page_name()" I show different stuff
switch ($form->my_page_name) switch ($form->my_page_name) {
{
case "edit_users": case "edit_users":
$elements[] = $form->form_create_element("login_error_count"); $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_last");
@@ -250,30 +235,27 @@
$elements[] = $form->form_create_element("template"); $elements[] = $form->form_create_element("template");
break; break;
case "edit_pages": case "edit_pages":
if (!$form->table_array["edit_page_id"]["value"]) if (!$form->table_array["edit_page_id"]["value"]) {
{
$q = "DELETE FROM temp_files"; $q = "DELETE FROM temp_files";
$form->db_exec($q); $form->db_exec($q);
// gets all files in the current dir ending with .php // gets all files in the current dir ending with .php
$crap = exec("ls *.php", $output, $status); $crap = exec("ls *.php", $output, $status);
// now get all that are NOT in de DB // now get all that are NOT in de DB
$q = "INSERT INTO temp_files VALUES "; $q = "INSERT INTO temp_files VALUES ";
for ($i = 0; $i < count($output); $i ++) for ($i = 0; $i < count($output); $i ++) {
{
$t_q = "('".$form->db_escape_string($output[$i])."')"; $t_q = "('".$form->db_escape_string($output[$i])."')";
$form->db_exec($q.$t_q, 'NULL'); $form->db_exec($q.$t_q, 'NULL');
} }
$elements[] = $form->form_create_element("filename"); $elements[] = $form->form_create_element("filename");
} } else {
else // show file menu // show file menu
{
// just show name of file ... // just show name of file ...
$DATA['filename_exist'] = 1; $DATA['filename_exist'] = 1;
$DATA['filename'] = $form->table_array["filename"]["value"]; $DATA['filename'] = $form->table_array["filename"]["value"];
} // File Name View IF } // File Name View IF
$elements[] = $form->form_create_element("name"); $elements[] = $form->form_create_element("name");
// $elements[] = $form->form_create_element("tag"); // $elements[] = $form->form_create_element("tag");
// $elements[] = $form->form_create_element("min_acl"); // $elements[] = $form->form_create_element("min_acl");
$elements[] = $form->form_create_element("order_number"); $elements[] = $form->form_create_element("order_number");
$elements[] = $form->form_create_element("online"); $elements[] = $form->form_create_element("online");
$elements[] = $form->form_create_element("menu"); $elements[] = $form->form_create_element("menu");
@@ -313,33 +295,30 @@
// add name/value list here // add name/value list here
$elements[] = $form->form_show_list_table("edit_access_data"); $elements[] = $form->form_show_list_table("edit_access_data");
break; break;
break;
default: default:
print "NO NO NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO!"; print "[No valid page definition given]";
break; break;
} }
// $form->debug('edit', "Elements: <pre>".$form->print_ar($elements)); // $form->debug('edit', "Elements: <pre>".$form->print_ar($elements));
$DATA['elements'] = $elements; $DATA['elements'] = $elements;
$DATA['hidden'] = $form->form_create_hidden_fields(); $DATA['hidden'] = $form->form_create_hidden_fields();
$DATA['save_delete'] = $form->form_create_save_delete(); $DATA['save_delete'] = $form->form_create_save_delete();
} }
// debug data, if DEBUG flag is on, this data is print out // debug data, if DEBUG flag is on, this data is print out
$DEBUG_DATA['DEBUG'] = $DEBUG_TMPL; $DEBUG_DATA['DEBUG'] = $DEBUG_TMPL;
// create main data array // create main data array
$CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA); $CONTENT_DATA = array_merge($HEADER, $DATA, $DEBUG_DATA);
// data is 1:1 mapping (all vars, values, etc) // data is 1:1 mapping (all vars, values, etc)
while (list($key, $value) = each($CONTENT_DATA)) while (list($key, $value) = each($CONTENT_DATA)) {
{
$smarty->assign($key, $value); $smarty->assign($key, $value);
} }
// $smarty->assign('popup_page', 'mt_popup_'.$body_part.'.tpl'); // $smarty->assign('popup_page', 'mt_popup_'.$body_part.'.tpl');
$smarty->display('edit_body.tpl'); $smarty->display('edit_body.tpl');
// debug output // debug output
echo $login->print_error_msg(); echo $login->print_error_msg();
echo $form->print_error_msg(); echo $form->print_error_msg();
?>
+18
View File
@@ -0,0 +1,18 @@
<?php
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1;
$PRINT_ALL = 1;
$DB_DEBUG = 1;
if ($DEBUG_ALL) {
error_reporting(E_ALL);
}
// sample config
require("config.inc");
require(LIBS."Error.Handling.inc");
if ($var) {
echo "OUT<br>";
}
+213 -243
View File
@@ -1,208 +1,198 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/13 * CREATED: 2005/07/13
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* Create categories for CMS * Create categories for CMS
* HISTORY: * HISTORY:
* 2005/08/19 (cs) changed the mime type get from the _FILE to mime get fkt * 2005/08/19 (cs) changed the mime type get from the _FILE to mime get fkt
*********************************************************************/ *********************************************************************/
// DEBUG vars here // DEBUG vars here
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$DB_DEBUG = 1; $DB_DEBUG = 1;
$DEBUG_TMPL = 1; $DEBUG_TMPL = 1;
//------------------------------ header //------------------------------ header
require("header.inc"); require("header.inc");
$MASTER_TEMPLATE_NAME = 'cms_popup.tpl'; $MASTER_TEMPLATE_NAME = 'cms_popup.tpl';
$TEMPLATE_NAME = 'cms_files.tpl'; $TEMPLATE_NAME = 'cms_files.tpl';
$PAGE_WIDTH = 750; $PAGE_WIDTH = 750;
require("set_paths.inc"); require("set_paths.inc");
//------------------------------ header //------------------------------ header
//------------------------------ processing data start //------------------------------ processing data start
$form_name = $_GET['form']; $form_name = $_GET['form'];
$value_name = $_GET['name']; $value_name = $_GET['name'];
$data_id = $_GET['id']; $data_id = $_GET['id'];
$show_type = $_GET['type']; // P (pic), F (flash), V (video), D (document: word), A (document: pdf), B (binary); , separated string $show_type = $_GET['type']; // P (pic), F (flash), V (video), D (document: word), A (document: pdf), B (binary); , separated string
// default view is list // default view is list
if (!$view && !$data_id) if (!$view && !$data_id) {
$view = 'list'; $view = 'list';
elseif (!$view && $data_id) } elseif (!$view && $data_id) {
$view = 'list'; $view = 'list';
// default is online }
if (!isset($online)) // default is online
if (!isset($online)) {
$online = 't'; $online = 't';
// if not set, it is a fresh load }
if (!$show_amount) // if not set, it is a fresh load
if (!$show_amount) {
$fresh_load = 1; $fresh_load = 1;
// the next two are for page view }
if (!$start_row) // the next two are for page view
if (!$start_row) {
$start_row = 0; $start_row = 0;
if (!$show_amount) }
if (!$show_amount) {
$show_amount = 12; $show_amount = 12;
if (!$show_type) }
if (!$show_type) {
$show_type = 'P'; $show_type = 'P';
}
// yes no list (online) // yes no list (online)
$yesno_list['f'] = 'No'; $yesno_list['f'] = 'No';
$yesno_list['t'] = 'Yes'; $yesno_list['t'] = 'Yes';
// order list // order list
$sort_order_list['date_created'] = 'ID / Insert time'; // default $sort_order_list['date_created'] = 'ID / Insert time'; // default
$sort_order_list['file_name'] = 'File Name'; $sort_order_list['file_name'] = 'File Name';
$sort_order_list['file_size'] = 'File Size'; $sort_order_list['file_size'] = 'File Size';
$sort_order_list['mime_type'] = 'Mime Type'; $sort_order_list['mime_type'] = 'Mime Type';
$sort_order_list['name_en'] = 'Alt Name English'; $sort_order_list['name_en'] = 'Alt Name English';
$sort_order_list['name_ja'] = 'Alt Name Japanese'; $sort_order_list['name_ja'] = 'Alt Name Japanese';
$sort_order_list['date_updated'] = 'Updated'; $sort_order_list['date_updated'] = 'Updated';
if (!$sort_order) if (!$sort_order) {
$sort_order = 'date_created'; $sort_order = 'date_created';
$sort_direction_list['ASC'] = 'Normal'; }
$sort_direction_list['DESC'] = 'Reverse'; $sort_direction_list['ASC'] = 'Normal';
if (!$sort_direction) $sort_direction_list['DESC'] = 'Reverse';
if (!$sort_direction) {
$sort_direction = 'ASC'; $sort_direction = 'ASC';
// set if we need to write to any of the set live queues }
// a) on page save with set_live // set if we need to write to any of the set live queues
// b) global page with live_queue // a) on page save with set_live
// set via QUEUE variable // b) global page with live_queue
// set via QUEUE variable
// create 0 entries for: templates, menu, data_group? // create 0 entries for: templates, menu, data_group?
if ($cms->action == 'new' && $cms->action_yes == 'true') if ($cms->action == 'new' && $cms->action_yes == 'true') {
{
unset($file_uid); unset($file_uid);
unset($file_id); unset($file_id);
unset($file_type); unset($file_type);
$new_okay = 1; $new_okay = 1;
} }
// file type: P picture, M mouse over picutre, F flash, V video, B binary // file type: P picture, M mouse over picutre, F flash, V video, B binary
if ($cms->action == 'save') if ($cms->action == 'save') {
{ if (!$file_type) {
if (!$file_type)
$file_type = 'B'; $file_type = 'B';
}
$file_ok = false; $file_ok = false;
if (!$_FILES['file_up']['name'] && !$file_uid) if (!$_FILES['file_up']['name'] && !$file_uid) {
{
$cms->messages[] = array('msg' => 'No file name given', 'class' => 'error'); $cms->messages[] = array('msg' => 'No file name given', 'class' => 'error');
$error = 1; $error = 1;
} }
if (!$_FILES['file_up']['name'] && $file_uid) if (!$_FILES['file_up']['name'] && $file_uid) {
$file_ok = true; $file_ok = true;
// echo "FILE TYPE: ".$_FILES['file_up']['type']."<br>"; }
foreach (split(',', $show_type) as $_show_type) // echo "FILE TYPE: ".$_FILES['file_up']['type']."<br>";
{ foreach (split(',', $show_type) as $_show_type) {
// check if the uploaded filename matches to the given 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)) if ($_FILES['file_up']['name'] && preg_match("/jpeg|png|gif/", $_FILES['file_up']['type']) && preg_match("/P/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/swf/", $_FILES['file_up']['type']) && preg_match("/F/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/video/", $_FILES['file_up']['type']) && preg_match("/V/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/msword|vnd.oasis.opendocument.text/", $_FILES['file_up']['type']) && preg_match("/D/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/pdf/", $_FILES['file_up']['type']) && preg_match("/A/", $show_type)) {
{
$file_ok = true; $file_ok = true;
} }
if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) if ($_FILES['file_up']['name'] && preg_match("/B/", $show_type)) {
$file_ok = true; $file_ok = true;
} }
}
// write out error messages according to show type // write out error messages according to show type
if (!$file_ok) if (!$file_ok) {
{ if (preg_match("/P/", $show_type)) {
if (preg_match("/P/", $show_type))
{
$cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a JPEG/PNG/GIF file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/F/", $show_type)) if (preg_match("/F/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a Flash File', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/V/", $show_type)) if (preg_match("/V/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a Video', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/D/", $show_type)) if (preg_match("/D/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a DOC/ODT file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/A/", $show_type)) if (preg_match("/A/", $show_type)) {
{
$cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error'); $cms->messages[] = array('msg' => 'File is not a PDF file', 'class' => 'error');
$error = 1; $error = 1;
} }
if (preg_match("/B/", $show_type)) if (preg_match("/B/", $show_type)) {
{
$cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error'); $cms->messages[] = array('msg' => 'No valid file was given', 'class' => 'error');
$error = 1; $error = 1;
} }
} }
// binary: all okay // binary: all okay
// if no error, save data // if no error, save data
if (!$error) if (!$error) {
{ if ($_FILES['file_up']['name']) {
if ($_FILES['file_up']['name'])
{
$mime_type = $_FILES['file_up']['type']; $mime_type = $_FILES['file_up']['type'];
$file_size = $_FILES['file_up']['size']; $file_size = $_FILES['file_up']['size'];
$file_name = $_FILES['file_up']['name']; $file_name = $_FILES['file_up']['name'];
// get picture size // get picture size
list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']); list($width, $height) = getimagesize($_FILES['file_up']['tmp_name']);
$cms->debug('upload', "Width: $width X Height: $height"); $cms->debug('upload', "Width: $width X Height: $height");
// set the file type and the target folder // set the file type and the target folder
if (preg_match("/jpeg|png|gif/", $mime_type)) if (preg_match("/jpeg|png|gif/", $mime_type)) {
$file_type = 'P'; $file_type = 'P';
elseif (preg_match("/swf/", $mime_type)) } elseif (preg_match("/swf/", $mime_type)) {
$file_type = 'F'; $file_type = 'F';
elseif (preg_match("/video/", $mime_type)) } elseif (preg_match("/video/", $mime_type)) {
$file_type = 'V'; $file_type = 'V';
elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) } elseif (preg_match("/msword|vnd.oasis.opendocument.text/", $mime_type)) {
$file_type = 'D'; $file_type = 'D';
elseif (preg_match("/pdf/", $mime_type)) } elseif (preg_match("/pdf/", $mime_type)) {
$file_type = 'A'; $file_type = 'A';
elseif ($mime_type) } elseif ($mime_type) {
$file_type = 'B'; $file_type = 'B';
} }
}
// if we have an id -> updated // if we have an id -> updated
if ($file_uid) if ($file_uid) {
{
$q = "UPDATE file SET"; $q = "UPDATE file SET";
$q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' "; $q_set = " name_en = '".addslashes($name_en)."', name_ja = '".addslashes($name_ja)."', file_name = '".addslashes($file_name)."', online = '".$online."' ";
if ($_FILES['file_up']['name']) 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_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."'"; $q .= $q_set."WHERE file_uid = '".$file_uid."'";
$cms->db_exec($q); $cms->db_exec($q);
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$sql_action = 'UPDATE'; $sql_action = 'UPDATE';
$sql_data = $q_set; $sql_data = $q_set;
} }
} } else {
// insert new data // insert new data
else
{
$file_uid = md5(uniqid(rand(), true)); $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."')"; $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); $cms->db_exec($q);
$file_id = $cms->insert_id; $file_id = $cms->insert_id;
// if queue // if queue
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$sql_data = $q; $sql_data = $q;
$sql_action = 'INSERT'; $sql_action = 'INSERT';
} }
@@ -211,37 +201,33 @@ $cms->debug('upload', "Width: $width X Height: $height");
$size_y = $height; $size_y = $height;
$file = DEV_SCHEMA."_".$file_uid; $file = DEV_SCHEMA."_".$file_uid;
// now upload the file // now upload the file
if ($_FILES['file_up']['name']) if ($_FILES['file_up']['name']) {
{
$upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file; $upload_file = ROOT.MEDIA.$cms->data_path[$file_type].$file;
// wipe out any old tmp data for this new upload // wipe out any old tmp data for this new upload
if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) if (is_array(glob(ROOT.TMP."thumb_".$file."*"))) {
{ foreach (glob(ROOT.TMP."thumb_".$file."*") as $filename) {
foreach (glob(ROOT.TMP."thumb_".$file."*") AS $filename)
@unlink($filename); @unlink($filename);
} }
}
# copy file to correct path # copy file to correct path
$error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file); $error = move_uploaded_file($_FILES['file_up']['tmp_name'], $upload_file);
$cms->debug('file_upload', "UP: $upload_file"); $cms->debug('file_upload', "UP: $upload_file");
$cms->debug('file_upload', "Orig: ".$cms->print_ar($_FILES['file_up'])); $cms->debug('file_upload', "Orig: ".$cms->print_ar($_FILES['file_up']));
// because I get bogus error info from move_uploaded_file ... // because I get bogus error info from move_uploaded_file ...
$error = 0; $error = 0;
if ($error) if ($error) {
{ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize"));
$cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_filesize"));
$cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error'); $cms->messages[] = array('msg' => 'File upload failed', 'class' => 'error');
$q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'";
$cms->db_exec($q); $cms->db_exec($q);
unset($file_id); unset($file_id);
unset($file_uid); unset($file_uid);
$view = 'list'; $view = 'list';
} } else {
else
{
$cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning'); $cms->messages[] = array('msg' => 'File upload successful', 'class' => 'warning');
// $vew = 'list'; // $view = 'list';
} }
} // if file upload } // if file upload
// create thumbs + file size // create thumbs + file size
@@ -249,44 +235,42 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$picture_small = $cms->cache_pictures.$cms->adbCreateThumbnail($file, 80, 60, $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); $file_size = $cms->adbByteStringFormat($file_size);
// for live queue this is here needed // for live queue this is here needed
if (QUEUE == 'live_queue') if (QUEUE == 'live_queue') {
{
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (queue_key, key_value, key_name, type, target, data, group_key, action"; $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']) if ($_FILES['file_up']['name']) {
$q .= ", file"; $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."'"; $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']) 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 .= ", '".ROOT.MEDIA.$cms->data_path[$file_type].$file."#".ROOT.MEDIA.$cms->data_path[$file_type].PUBLIC_SCHEMA."_".$file_uid."'";
}
$q .= ")"; $q .= ")";
$cms->db_exec($q); $cms->db_exec($q);
} }
} // if not error } // if not error
} }
if ($cms->action == 'delete' && $cms->action_yes == 'true') if ($cms->action == 'delete' && $cms->action_yes == 'true') {
{
$file_uid = $cms->action_id; $file_uid = $cms->action_id;
$q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'"; $q = "SELECT type FROM file WHERE file_uid = '".$file_uid."'";
list ($file_type) = $cms->db_return_row($q); list ($file_type) = $cms->db_return_row($q);
// get the file type for the file path // get the file type for the file path
$q = "DELETE FROM file WHERE file_uid = '".$file_uid."'"; $q = "DELETE FROM file WHERE file_uid = '".$file_uid."'";
$cms->db_exec($q); $cms->db_exec($q);
if (QUEUE == 'set_live') if (QUEUE == 'set_live') {
{
$q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')"; $q = "INSERT INTO ".GLOBAL_DB_SCHEMA.".set_live (table_name, pkid, delete_flag) VALUES ('".$cms->page_name."', ".$file_uid.", 't')";
$cms->db_exec($q); $cms->db_exec($q);
} }
if (QUEUE == 'live_queue') 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 = "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."')"; $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."')";
} }
@unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid); @unlink(ROOT.MEDIA.$cms->data_path[$file_type].DEV_SCHEMA."_".$file_uid);
unset($file_uid); unset($file_uid);
unset($file_id); unset($file_id);
$delete_done = 1; $delete_done = 1;
$view = 'list'; $view = 'list';
} }
if ($cms->action == 'load') if ($cms->action == 'load') {
{
$file_uid = $cms->action_id; $file_uid = $cms->action_id;
// load the data // 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."'"; $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."'";
@@ -299,53 +283,44 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$file_size = $cms->adbByteStringFormat($file_size); $file_size = $cms->adbByteStringFormat($file_size);
// view to edit // view to edit
$view = 'edit'; $view = 'edit';
} }
if ($cms->action == 'add_new') if ($cms->action == 'add_new') {
{
$view = 'edit'; $view = 'edit';
} }
if ($cms->action == 'view_files' && $cms->action_yes == 'true') if ($cms->action == 'view_files' && $cms->action_yes == 'true') {
{
$view = 'list'; $view = 'list';
} }
// set delete live // set delete live
if ($cms->action_flag == 'set_live' && $cms->action = 'set_delete') 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'"; $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)) while ($res = $cms->db_return($q)) {
{
$q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"'; $q_del = "DELETE FROM ".PUBLIC_SCHEMA.".file WHERE file_uid = '".$res['pkid'].'"';
$cms->db_exec($q_del); $cms->db_exec($q_del);
@unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']); @unlink(ROOT.MEDIA.$cms->data_path[$res['type']].PUBLIC_SCHEMA."_".$res['file_uid']);
} }
$q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'"; $q = "DELETE FROM ".LOGIN_DB_SCHEMA.".set_live WHERE table_name = '".$cms->page_name."' AND delete_flag = 't'";
$cms->db_exec($q); $cms->db_exec($q);
} }
if (DEV_SCHEMA != PUBLIC_SCHEMA) if (DEV_SCHEMA != PUBLIC_SCHEMA) {
{
// read out possible deleted, to add "delete from live" // 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'"; $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)) while ($res = $cms->db_return($q, 3)) {
{
$cms->DATA['set_delete'][]['pkid'] = $res['pkid']; $cms->DATA['set_delete'][]['pkid'] = $res['pkid'];
} }
} }
// get th max entries // get th max entries
$q = "SELECT COUNT(file_uid) FROM file "; $q = "SELECT COUNT(file_uid) FROM file ";
$q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') "; $q_search_where = "WHERE type in ('".str_replace(',', "','", $show_type)."') ";
if ($search_what) 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_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; $q .= $q_search_where;
// get selection from show_type // get selection from show_type
list ($file_count) = $cms->db_return_row($q); list ($file_count) = $cms->db_return_row($q);
if ($cms->action == 'browse') if ($cms->action == 'browse') {
{
// browse in the list of data // browse in the list of data
switch ($cms->action_id) switch ($cms->action_id) {
{
case "<<<<": case "<<<<":
$start_row = 0; $start_row = 0;
break; break;
@@ -364,59 +339,56 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$current_page = $cms->action_value; $current_page = $cms->action_value;
break; break;
} }
} }
// check overflow // check overflow
if ($start_row < 0) if ($start_row < 0) {
$start_row = 0; $start_row = 0;
if ($start_row > $file_count) }
if ($start_row > $file_count) {
$start_row = $file_count - $show_amount; $start_row = $file_count - $show_amount;
}
// if we have a "fresh_load" // if we have a "fresh_load"
if ($fresh_load) if ($fresh_load) {
{
$count = 1; $count = 1;
$q = "SELECT file_uid FROM file "; $q = "SELECT file_uid FROM file ";
if ($q_search_where) if ($q_search_where) {
$q .= $q_search_where; $q .= $q_search_where;
}
$q .= "ORDER BY ".$sort_order." ".$sort_direction." "; $q .= "ORDER BY ".$sort_order." ".$sort_direction." ";
while ($res = $cms->db_return($q)) 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 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'])) if ($data_id && ($data_id == $res['file_uid'])) {
{
$current_page = floor(($count / $show_amount)); $current_page = floor(($count / $show_amount));
$start_row = $current_page * $show_amount; $start_row = $current_page * $show_amount;
$current_page ++; $current_page ++;
} }
$count ++; $count ++;
} }
} }
// page forward/back buttons settings // page forward/back buttons settings
if ($start_row > 0) if ($start_row > 0) {
{
$cms->DATA['show_back'] = 1; $cms->DATA['show_back'] = 1;
} }
$cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1; $cms->DATA['page_number'] = ceil($start_row / $show_amount) + 1;
$cms->DATA['page_count'] = ceil($file_count / $show_amount); $cms->DATA['page_count'] = ceil($file_count / $show_amount);
if ($cms->DATA['page_count'] > 2 && !$current_page) if ($cms->DATA['page_count'] > 2 && !$current_page) {
{
$current_page = 1; $current_page = 1;
} }
if (($start_row + $show_amount) < $file_count) if (($start_row + $show_amount) < $file_count) {
{
$cms->DATA['show_forward'] = 1; $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 "; $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 search what, search in name_en, name_ja, file_name for the string
if ($q_search_where) if ($q_search_where) {
$q .= $q_search_where; $q .= $q_search_where;
$q .= "ORDER BY ".$sort_order." ".$sort_direction." "; }
$q .= "LIMIT ".$show_amount." OFFSET ".$start_row; $q .= "ORDER BY ".$sort_order." ".$sort_direction." ";
while ($res = $cms->db_return($q)) $q .= "LIMIT ".$show_amount." OFFSET ".$start_row;
{ while ($res = $cms->db_return($q)) {
$data_files[] = array ( $data_files[] = array (
'id' => $res['file_id'], 'id' => $res['file_id'],
'name_en' => $res['name_en'], 'name_en' => $res['name_en'],
@@ -431,21 +403,20 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
'file_type' => $res['type'], 'file_type' => $res['type'],
'picture' => $cms->cache_pictures.$cms->adbCreateThumbnail(DEV_SCHEMA.'_'.$res['file_uid'], 80, 60, $res['type'], '', $cms->cache_pictures_root) 'picture' => $cms->cache_pictures.$cms->adbCreateThumbnail(DEV_SCHEMA.'_'.$res['file_uid'], 80, 60, $res['type'], '', $cms->cache_pictures_root)
); );
} }
$cms->DATA['show_type'] = $show_type; $cms->DATA['show_type'] = $show_type;
$cms->DATA['data_files'] = $data_files; $cms->DATA['data_files'] = $data_files;
$cms->DATA['view'] = $view; $cms->DATA['view'] = $view;
$cms->DATA['images_path'] = MEDIA.$cms->data_path[$file_type]; $cms->DATA['images_path'] = MEDIA.$cms->data_path[$file_type];
// get vars for position (only when) // get vars for position (only when)
$cms->DATA['form_name'] = $form_name; $cms->DATA['form_name'] = $form_name;
$cms->DATA['value_name'] = $value_name; $cms->DATA['value_name'] = $value_name;
$cms->DATA['file_id'] = $file_id; $cms->DATA['file_id'] = $file_id;
$cms->DATA['file_uid'] = $file_uid; $cms->DATA['file_uid'] = $file_uid;
// write back all the other vars // write back all the other vars
if (!($delete_done || $new_okay)) if (!($delete_done || $new_okay)) {
{
// data name // data name
$cms->DATA['file_name'] = $file_name; $cms->DATA['file_name'] = $file_name;
$cms->DATA['name_en'] = $name_en; $cms->DATA['name_en'] = $name_en;
@@ -458,29 +429,28 @@ $cms->debug('file_upload', "ERROR: $error | INI FSize: ".ini_get("upload_max_fil
$cms->DATA['picture'] = $picture; $cms->DATA['picture'] = $picture;
$cms->DATA['picture_small'] = $picture_small; $cms->DATA['picture_small'] = $picture_small;
$cms->DATA['file_type'] = $file_type; $cms->DATA['file_type'] = $file_type;
} }
$cms->DATA['sort_order_list'] = $sort_order_list; $cms->DATA['sort_order_list'] = $sort_order_list;
$cms->DATA['sort_order'] = $sort_order; $cms->DATA['sort_order'] = $sort_order;
$cms->DATA['sort_direction_list'] = $sort_direction_list; $cms->DATA['sort_direction_list'] = $sort_direction_list;
$cms->DATA['sort_direction'] = $sort_direction; $cms->DATA['sort_direction'] = $sort_direction;
$cms->DATA['search_what'] = $search_what; $cms->DATA['search_what'] = $search_what;
$cms->DATA['current_page'] = $current_page; $cms->DATA['current_page'] = $current_page;
$cms->DATA['yesno_list'] = $yesno_list; $cms->DATA['yesno_list'] = $yesno_list;
$cms->DATA['start_row'] = $start_row; $cms->DATA['start_row'] = $start_row;
$cms->DATA['show_amount'] = $show_amount; $cms->DATA['show_amount'] = $show_amount;
if ($data_id) if ($data_id) {
$cms->DATA['data_id'] = $data_id; $cms->DATA['data_id'] = $data_id;
$cms->DATA['top'] = 0; }
$cms->DATA['left'] = 0; $cms->DATA['top'] = 0;
$cms->DATA['left'] = 0;
//------------------------------ processing data end //------------------------------ processing data end
//------------------------------ smarty start //------------------------------ smarty start
require("smarty.inc"); require("smarty.inc");
//------------------------------ smarty end //------------------------------ smarty end
//------------------------------ footer //------------------------------ footer
require("footer.inc"); require("footer.inc");
//------------------------------ footer //------------------------------ footer
?>
+10 -11
View File
@@ -1,13 +1,12 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2008/08/14 * CREATED: 2008/08/14
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* URL redirect header * URL redirect header
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
// print debug messages // print debug messages
echo $login->print_error_msg(); echo $login->print_error_msg();
echo $cms->print_error_msg(); echo $cms->print_error_msg();
?>
+77 -75
View File
@@ -1,102 +1,104 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2008/08/01 * CREATED: 2008/08/01
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* URL redirect header * URL redirect header
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
//------------------------------ variable init start //------------------------------ variable init start
// for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-<day>.log // for dev test we set full error reporting; writes everything, except E_ERROR into logs/php_error-<day>.log
if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) if ($DEBUG_ALL && $ENABLE_ERROR_HANDLING) {
include("libs/Error.Handling.inc"); include("libs/Error.Handling.inc");
// predefine vars }
$lang = ''; // predefine vars
$messages = array (); $lang = '';
// import all POST vars $messages = array ();
extract($_POST, EXTR_SKIP); // import all POST vars
//------------------------------ variable init end extract($_POST, EXTR_SKIP);
//------------------------------ variable init end
//------------------------------ library include start //------------------------------ library include start
// set output to quiet for load of classes & session settings // set output to quiet for load of classes & session settings
ob_start(); ob_start();
require("config.inc"); require("config.inc");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME); // login class, DB connections & Admin class, Smarty extension
// login class, DB connections & Admin class, Smarty extension foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class) {
foreach (array ('Login', 'Admin.Backend', 'Smarty.Extend') as $class)
_spl_autoload('Class.'.$class.'.inc'); _spl_autoload('Class.'.$class.'.inc');
//------------------------------ library include end }
//------------------------------ library include end
//------------------------------ basic variable settings start //------------------------------ basic variable settings start
// set encoding // set encoding
if (!isset($encoding)) if (!isset($encoding)) {
$encoding = DEFAULT_ENCODING; $encoding = DEFAULT_ENCODING;
// set the default lang, if not given }
if (session_id() && $_SESSION['DEFAULT_LANG']) // set the default lang, if not given
if (session_id() && $_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
elseif (!$lang) } elseif (!$lang) {
$lang = DEFAULT_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') // 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); header("Content-type: text/html; charset=".$encoding);
ob_end_flush(); ob_end_flush();
} }
//------------------------------ basic variable settings start //------------------------------ basic variable settings start
//------------------------------ class init start //------------------------------ class init start
// login & page access check // login & page access check
$login = new login($DB_CONFIG[LOGIN_DB], $lang); $login = new login($DB_CONFIG[LOGIN_DB], $lang);
// post login lang check // post login lang check
if ($_SESSION['DEFAULT_LANG']) if ($_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
// create smarty object }
$smarty = new SmartyML($lang); // create smarty object
// create new DB class $smarty = new SmartyML($lang);
$cms = new AdminBackend($DB_CONFIG[MAIN_DB], $lang); // create new DB class
// set search path to the default DB schema $cms = new AdminBackend($DB_CONFIG[MAIN_DB], $lang);
$cms->db_exec("SET search_path TO ".DB_SCHEMA); // set search path to the default DB schema
// the menu show flag (what menu to show) $cms->db_exec("SET search_path TO ".DB_SCHEMA);
$cms->menu_show_flag = 'main'; // the menu show flag (what menu to show)
// db nfo $cms->menu_show_flag = 'main';
$cms->db_info(); // db nfo
// set acl $cms->db_info();
$cms->acl = $login->acl; // set acl
//------------------------------ class init end $cms->acl = $login->acl;
//------------------------------ class init end
//------------------------------ logging start //------------------------------ logging start
// log backend data // log backend data
// data part creation // data part creation
$data = array ( $data = array (
'_SESSION' => $_SESSION, '_SESSION' => $_SESSION,
'_GET' => $_GET, '_GET' => $_GET,
'_POST' => $_POST, '_POST' => $_POST,
'_FILES' => $_FILES '_FILES' => $_FILES
); );
// log action // log action
// no log if login // no log if login
if (!$login->login) if (!$login->login) {
$cms->adbEditLog('Submit', $data, 'BINARY'); $cms->adbEditLog('Submit', $data, 'BINARY');
//------------------------------ logging end }
//------------------------------ logging end
//------------------------------ page rights start //------------------------------ page rights start
// flag if to show the edit access id drop down list // flag if to show the edit access id drop down list
// check if we have more than one EA ID // check if we have more than one EA ID
$cms->DATA['show_ea_extra'] = $login->acl['acl']['show_ea_extra']; $cms->DATA['show_ea_extra'] = $login->acl['acl']['show_ea_extra'];
//------------------------------ page rights ned //------------------------------ page rights ned
// automatic hide for DEBUG messages on live server // 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) // 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) if ((TARGET == 'live' || TARGET == 'remote') && !$DEBUG_ALL_OVERRIDE) {
{
$login->debug_output_all = 0; $login->debug_output_all = 0;
$login->echo_output_all = 0; $login->echo_output_all = 0;
$login->print_output_all = 0; $login->print_output_all = 0;
$cms->debug_output_all = 0; $cms->debug_output_all = 0;
$cms->echo_output_all = 0; $cms->echo_output_all = 0;
$cms->print_output_all = 0; $cms->print_output_all = 0;
} }
$cms->DATA['JS_DEBUG'] = DEBUG; $cms->DATA['JS_DEBUG'] = DEBUG;
?>
+46 -48
View File
@@ -1,53 +1,51 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/19 * CREATED: 2005/07/19
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* preset date variables * preset date variables
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
$day_short[1] = "Mon"; $day_short[1] = "Mon";
$day_short[2] = "Tue"; $day_short[2] = "Tue";
$day_short[3] = "Wed"; $day_short[3] = "Wed";
$day_short[4] = "Thu"; $day_short[4] = "Thu";
$day_short[5] = "Fri"; $day_short[5] = "Fri";
$day_short[6] = "Sat"; $day_short[6] = "Sat";
$day_short[7] = "Sun"; $day_short[7] = "Sun";
$day_long[1] = "Monday"; $day_long[1] = "Monday";
$day_long[2] = "Tuesday"; $day_long[2] = "Tuesday";
$day_long[3] = "Wednesday"; $day_long[3] = "Wednesday";
$day_long[4] = "Thursday"; $day_long[4] = "Thursday";
$day_long[5] = "Friday"; $day_long[5] = "Friday";
$day_long[6] = "Saturday"; $day_long[6] = "Saturday";
$day_long[7] = "Sunday"; $day_long[7] = "Sunday";
// monate // monate
$month_long[1] = "January"; $month_long[1] = "January";
$month_long[2] = "February"; $month_long[2] = "February";
$month_long[3] = "March"; $month_long[3] = "March";
$month_long[4] = "April"; $month_long[4] = "April";
$month_long[5] = "May"; $month_long[5] = "May";
$month_long[6] = "June"; $month_long[6] = "June";
$month_long[7] = "July"; $month_long[7] = "July";
$month_long[8] = "August"; $month_long[8] = "August";
$month_long[9] = "September"; $month_long[9] = "September";
$month_long[10] = "October"; $month_long[10] = "October";
$month_long[11] = "November"; $month_long[11] = "November";
$month_long[12] = "December"; $month_long[12] = "December";
$month_short[1] = "Jan"; $month_short[1] = "Jan";
$month_short[2] = "Feb"; $month_short[2] = "Feb";
$month_short[3] = "Mar"; $month_short[3] = "Mar";
$month_short[4] = "Apr"; $month_short[4] = "Apr";
$month_short[5] = "May"; $month_short[5] = "May";
$month_short[6] = "Jun"; $month_short[6] = "Jun";
$month_short[7] = "Jul"; $month_short[7] = "Jul";
$month_short[8] = "Aug"; $month_short[8] = "Aug";
$month_short[9] = "Sep"; $month_short[9] = "Sep";
$month_short[10] = "Oct"; $month_short[10] = "Oct";
$month_short[11] = "Nov"; $month_short[11] = "Nov";
$month_short[12] = "Dec"; $month_short[12] = "Dec";
?>
+85 -79
View File
@@ -1,113 +1,119 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2007/09/03 * CREATED: 2007/09/03
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* set paths & language variables * set paths & language variables
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
// template path // template path
if ($_SESSION['TEMPLATE']) if ($_SESSION['TEMPLATE']) {
$TEMPLATE = $_SESSION['TEMPLATE']; $TEMPLATE = $_SESSION['TEMPLATE'];
elseif ($LOCAL_TEMPLATE) } elseif ($LOCAL_TEMPLATE) {
$TEMPLATE = $LOCAL_TEMPLATE; $TEMPLATE = $LOCAL_TEMPLATE;
else } else {
$TEMPLATE = DEFAULT_TEMPLATE; $TEMPLATE = DEFAULT_TEMPLATE;
$TEMPLATE_DIR = $TEMPLATE.'/'; }
// master template $TEMPLATE_DIR = $TEMPLATE.'/';
if (!$MASTER_TEMPLATE_NAME) // master template
if (!$MASTER_TEMPLATE_NAME) {
$MASTER_TEMPLATE_NAME = MASTER_TEMPLATE_NAME; $MASTER_TEMPLATE_NAME = MASTER_TEMPLATE_NAME;
}
// just emergency fallback for language // just emergency fallback for language
// set encoding // set encoding
if ($_SESSION['DEFAULT_CHARSET']) if ($_SESSION['DEFAULT_CHARSET']) {
$encoding = $_SESSION['DEFAULT_CHARSET']; $encoding = $_SESSION['DEFAULT_CHARSET'];
elseif (!$encoding) } elseif (!$encoding) {
$encoding = DEFAULT_ENCODING; $encoding = DEFAULT_ENCODING;
// just emergency fallback for language }
if ($_SESSION['DEFAULT_LANG']) // just emergency fallback for language
if ($_SESSION['DEFAULT_LANG']) {
$lang = $_SESSION['DEFAULT_LANG']; $lang = $_SESSION['DEFAULT_LANG'];
elseif (!$lang) } elseif (!$lang) {
$lang = DEFAULT_LANG; $lang = DEFAULT_LANG;
// create the char lang encoding }
$lang_short = substr($lang, 0, 2); // create the char lang encoding
$lang_short = substr($lang, 0, 2);
// set include & template names // set include & template names
$CONTENT_INCLUDE = str_replace(".php", ".tpl", $cms->page_name); $CONTENT_INCLUDE = str_replace(".php", ".tpl", $cms->page_name);
$FORM_NAME = !isset($FORM_NAME) || !$FORM_NAME ? str_replace(".php", "", $cms->page_name) : $FORM_NAME; $FORM_NAME = !isset($FORM_NAME) || !$FORM_NAME ? str_replace(".php", "", $cms->page_name) : $FORM_NAME;
// set local page title // set local page title
$L_TITLE = ucfirst(str_replace('_', ' ', $cms->get_page_name(1))).' - '.$G_TITLE; $L_TITLE = ucfirst(str_replace('_', ' ', $cms->get_page_name(1))).' - '.$G_TITLE;
// strip tpl and replace it with inc // strip tpl and replace it with inc
// php include file per page // php include file per page
$cms->INC_TEMPLATE_NAME = str_replace(".tpl", ".inc", $CONTENT_INCLUDE); $cms->INC_TEMPLATE_NAME = str_replace(".tpl", ".inc", $CONTENT_INCLUDE);
// javascript include per page // javascript include per page
$cms->JS_TEMPLATE_NAME = str_replace(".tpl", ".js", $CONTENT_INCLUDE); $cms->JS_TEMPLATE_NAME = str_replace(".tpl", ".js", $CONTENT_INCLUDE);
// css per page // css per page
$cms->CSS_TEMPLATE_NAME = str_replace(".tpl", ".css", $CONTENT_INCLUDE); $cms->CSS_TEMPLATE_NAME = str_replace(".tpl", ".css", $CONTENT_INCLUDE);
// special CSS file // special CSS file
$cms->CSS_SPECIAL_TEMPLATE_NAME = @$CSS_NAME; $cms->CSS_SPECIAL_TEMPLATE_NAME = @$CSS_NAME;
// special JS file // special JS file
$cms->JS_SPECIAL_TEMPLATE_NAME = @$JS_NAME; $cms->JS_SPECIAL_TEMPLATE_NAME = @$JS_NAME;
// set basic template path (tmp) // set basic template path (tmp)
$smarty->setTemplateDir(LAYOUT.$TEMPLATE_DIR.TEMPLATES.'/'); $smarty->setTemplateDir(LAYOUT.$TEMPLATE_DIR.TEMPLATES.'/');
$cms->lang_dir = LAYOUT.$TEMPLATE_DIR.LANG."/"; $cms->lang_dir = LAYOUT.$TEMPLATE_DIR.LANG."/";
$cms->includes = LAYOUT.$TEMPLATE_DIR.INCLUDES."/"; $cms->includes = LAYOUT.$TEMPLATE_DIR.INCLUDES."/";
$cms->javascript = LAYOUT.$TEMPLATE_DIR.JS."/"; $cms->javascript = LAYOUT.$TEMPLATE_DIR.JS."/";
$cms->css = LAYOUT.$TEMPLATE_DIR.CSS."/"; $cms->css = LAYOUT.$TEMPLATE_DIR.CSS."/";
$cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/"; $cms->pictures = LAYOUT.$TEMPLATE_DIR.IMAGES."/";
$cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/'; $cms->cache_pictures = LAYOUT.$TEMPLATE_DIR.CACHE.IMAGES.'/';
$cms->cache_pictures_root = ROOT.$cms->cache_pictures; $cms->cache_pictures_root = ROOT.$cms->cache_pictures;
if (!is_dir($cms->cache_pictures_root)) if (!is_dir($cms->cache_pictures_root)) {
mkdir($cms->cache_pictures_root); mkdir($cms->cache_pictures_root);
$template_set = $TEMPLATE; }
$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 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]."/".MASTER_TEMPLATE_NAME)) {
{ if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME)) {
if (file_exists(ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME))
$TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME; $TEMPLATE_NAME = ROOT.$smarty->getTemplateDir()[0]."/".$TEMPLATE_NAME;
}
$smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$template_set = DEFAULT_TEMPLATE; $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 // 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); $smarty->setTemplateDir(LAYOUT.DEFAULT_TEMPLATE.TEMPLATES);
$template_set = DEFAULT_TEMPLATE; $template_set = DEFAULT_TEMPLATE;
} }
// loop to check if dir exists // loop to check if dir exists
// check if file exists, if not reset to default path // 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 // check if the javascript folder exists in the template path, if not fall back to default
if (!is_dir($cms->javascript)) if (!is_dir($cms->javascript)) {
$cms->javascript = LAYOUT.DEFAULT_TEMPLATE.JS."/"; $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)) // 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."/"; $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)) // 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."/"; $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)) // 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."/"; $cms->css = LAYOUT.DEFAULT_TEMPLATE.CSS."/";
if (!is_dir($cms->pictures)) }
if (!is_dir($cms->pictures)) {
$cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/'; $cms->pictures = LAYOUT.DEFAULT_TEMPLATE.PICTURES.'/';
if (!is_dir($cms->cache_pictures)) }
if (!is_dir($cms->cache_pictures)) {
$cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/'; $cms->cache_pictures = LAYOUT.DEFAULT_TEMPLATE.CACHE.IMAGES.'/';
}
// if the template_dir is != DEFAULT_TEMPLATE, then try to make a lang switch // 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 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)) 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->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); $cms->l->l10nReloadMOfile($lang, $cms->lang_dir);
$smarty->l10n->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", "L: $lang | ".$cms->lang_dir." | MO File: ".$cms->l->mofile);
$cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']); $cms->debug("LANGUAGE", "SL: ".$_SESSION['DEFAULT_CHARSET']." | ".$_SESSION['LANG']." | ".$_SESSION['DEFAULT_LANG']);
$cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]); $cms->debug("TEMPLATE", "P: ".$smarty->getTemplateDir()[0]);
?>
+79 -86
View File
@@ -1,103 +1,96 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2005/07/12 * CREATED: 2005/07/12
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* default smarty vars, and create output template for smarty * default smarty vars, and create output template for smarty
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
// trigger flags // trigger flags
$cms->HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE; $cms->HEADER['USE_PROTOTYPE'] = USE_PROTOTYPE;
// scriptacolous, can only be used with prototype // scriptacolous, can only be used with prototype
if (USE_PROTOTYPE) if (USE_PROTOTYPE) {
$cms->HEADER['USE_SCRIPTACULOUS'] = USE_SCRIPTACULOUS; $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 // 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) // set basic template path (tmp)
// paths are set in the 'set_paths.inc' file // paths are set in the 'set_paths.inc' file
// check if we have an external file with the 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)) if (file_exists($cms->includes.$cms->INC_TEMPLATE_NAME) && is_file($cms->includes.$cms->INC_TEMPLATE_NAME)) {
{
include($cms->includes.$cms->INC_TEMPLATE_NAME); include($cms->includes.$cms->INC_TEMPLATE_NAME);
} }
// additional per page Javascript include // additional per page Javascript include
$cms->JS_INCLUDE = ''; $cms->JS_INCLUDE = '';
if (file_exists($cms->javascript.$cms->JS_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_TEMPLATE_NAME)) 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; $cms->JS_INCLUDE = $cms->javascript.$cms->JS_TEMPLATE_NAME;
} }
// per page css file // per page css file
$cms->CSS_INCLUDE = ''; $cms->CSS_INCLUDE = '';
if (file_exists($cms->css.$cms->CSS_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_TEMPLATE_NAME)) 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; $cms->CSS_INCLUDE = $cms->css.$cms->CSS_TEMPLATE_NAME;
} }
// optional CSS file // optional CSS file
$cms->CSS_SPECIAL_INCLUDE = ''; $cms->CSS_SPECIAL_INCLUDE = '';
if (file_exists($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME) && is_file($cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME)) 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; $cms->CSS_SPECIAL_INCLUDE = $cms->css.$cms->CSS_SPECIAL_TEMPLATE_NAME;
} }
// optional JS file // optional JS file
$cms->JS_SPECIAL_INCLUDE = ''; $cms->JS_SPECIAL_INCLUDE = '';
if (file_exists($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME) && is_file($cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME)) 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; $cms->JS_SPECIAL_INCLUDE = $cms->javascript.$cms->JS_SPECIAL_TEMPLATE_NAME;
} }
// the actual include files for javascript (per page) // the actual include files for javascript (per page)
$cms->HEADER['JS_INCLUDE'] = $cms->JS_INCLUDE; $cms->HEADER['JS_INCLUDE'] = $cms->JS_INCLUDE;
$cms->HEADER['CSS_INCLUDE'] = $cms->CSS_INCLUDE; $cms->HEADER['CSS_INCLUDE'] = $cms->CSS_INCLUDE;
$cms->HEADER['CSS_SPECIAL_INCLUDE'] = $cms->CSS_SPECIAL_INCLUDE; $cms->HEADER['CSS_SPECIAL_INCLUDE'] = $cms->CSS_SPECIAL_INCLUDE;
$cms->HEADER['JS_SPECIAL_INCLUDE'] = $cms->JS_SPECIAL_INCLUDE; $cms->HEADER['JS_SPECIAL_INCLUDE'] = $cms->JS_SPECIAL_INCLUDE;
// paths to the files // paths to the files
$cms->DATA['includes'] = $cms->includes; $cms->DATA['includes'] = $cms->includes;
$cms->DATA['js'] = $cms->javascript; $cms->DATA['js'] = $cms->javascript;
$cms->DATA['css'] = $cms->css; $cms->DATA['css'] = $cms->css;
$cms->DATA['pictures'] = $cms->pictures; $cms->DATA['pictures'] = $cms->pictures;
// default CMS settings // default CMS settings
// define all needed smarty stuff for the general HTML/page building // define all needed smarty stuff for the general HTML/page building
$cms->HEADER['CSS'] = CSS; $cms->HEADER['CSS'] = CSS;
$cms->HEADER['JS'] = JS; $cms->HEADER['JS'] = JS;
$cms->HEADER['ENCODING'] = $encoding; $cms->HEADER['ENCODING'] = $encoding;
$cms->HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING; $cms->HEADER['DEFAULT_ENCODING'] = DEFAULT_ENCODING;
$cms->HEADER['STYLESHEET'] = $EDIT_STYLESHEET; $cms->HEADER['STYLESHEET'] = $EDIT_STYLESHEET;
$cms->HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT; $cms->HEADER['JAVASCRIPT'] = $EDIT_JAVASCRIPT;
// html title // html title
$cms->HEADER['HTML_TITLE'] = (!isset($L_TITLE) || !$L_TITLE) ? $cms->l->__($G_TITLE) : $cms->l->__($L_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; $cms->DATA['table_width'] = $PAGE_WIDTH ? $PAGE_WIDTH : PAGE_WIDTH;
// messages = array('msg' =>, 'class' => 'error/warning/...') // messages = array('msg' =>, 'class' => 'error/warning/...')
$cms->DATA['messages'] = $cms->messages; $cms->DATA['messages'] = $cms->messages;
// top menu // top menu
$cms->DATA['nav_menu'] = $cms->adbTopMenu(); $cms->DATA['nav_menu'] = $cms->adbTopMenu();
// the page name // the page name
$cms->DATA['page_name'] = $cms->page_name; $cms->DATA['page_name'] = $cms->page_name;
// user name // user name
$cms->DATA['USER_NAME'] = $_SESSION['USER_NAME']; $cms->DATA['USER_NAME'] = $_SESSION['USER_NAME'];
// the template part to include into the body // the template part to include into the body
$cms->DATA['TEMPLATE_NAME'] = $TEMPLATE_NAME; $cms->DATA['TEMPLATE_NAME'] = $TEMPLATE_NAME;
$cms->DATA['CONTENT_INCLUDE'] = $CONTENT_INCLUDE; $cms->DATA['CONTENT_INCLUDE'] = $CONTENT_INCLUDE;
// LANG // LANG
$cms->DATA['LANG'] = $lang; $cms->DATA['LANG'] = $lang;
$cms->DATA['TINYMCE_LANG'] = $lang_short; $cms->DATA['TINYMCE_LANG'] = $lang_short;
// debug data, if DEBUG flag is on, this data is print out // 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_error_msg'] = $cms->running_time();
$cms->DEBUG_DATA['DEBUG'] = @$DEBUG_TMPL; $cms->DEBUG_DATA['DEBUG'] = @$DEBUG_TMPL;
// create main data array // create main data array
$cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA); $cms->CONTENT_DATA = array_merge($cms->HEADER, $cms->DATA, $cms->DEBUG_DATA);
// data is 1:1 mapping (all vars, values, etc) // data is 1:1 mapping (all vars, values, etc)
while (list($key, $value) = each($cms->CONTENT_DATA)) while (list($key, $value) = each($cms->CONTENT_DATA)) {
{
$smarty->assign($key, $value); $smarty->assign($key, $value);
} }
$smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang); $smarty->display($MASTER_TEMPLATE_NAME, $TEMPLATE.$lang, $TEMPLATE.$lang);
?>
+16 -17
View File
@@ -1,21 +1,20 @@
<? <?
$ENABLE_ERROR_HANDLING = 0; $ENABLE_ERROR_HANDLING = 0;
$DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations $DEBUG_ALL_OVERRIDE = 0; // set to 1 to debug on live/remote server locations
$DEBUG_ALL = 1; $DEBUG_ALL = 1;
$PRINT_ALL = 1; $PRINT_ALL = 1;
$DB_DEBUG = 1; $DB_DEBUG = 1;
$LOG_PER_RUN = 1; $LOG_PER_RUN = 1;
define('USE_DATABASE', true); define('USE_DATABASE', true);
require("header.inc"); require("header.inc");
$MASTER_TEMPLATE_NAME = 'main_body.tpl'; $MASTER_TEMPLATE_NAME = 'main_body.tpl';
$TEMPLATE_NAME = 'smarty_test.tpl'; $TEMPLATE_NAME = 'smarty_test.tpl';
$PAGE_WIDTH = 750; $PAGE_WIDTH = 750;
require("set_paths.inc"); require("set_paths.inc");
// smarty test // smarty test
$cms->DATA['SMARTY_TEST'] = 'Test Data'; $cms->DATA['SMARTY_TEST'] = 'Test Data';
require("smarty.inc"); require("smarty.inc");
require("footer.inc"); require("footer.inc");
?>
+2 -3
View File
@@ -1,5 +1,5 @@
<? <?
$edit_access = array ( $edit_access = array (
"table_array" => array ( "table_array" => array (
"edit_access_id" => array ( "edit_access_id" => array (
"value" => $GLOBALS["edit_access_id"], "value" => $GLOBALS["edit_access_id"],
@@ -73,5 +73,4 @@
) )
) )
) )
); );
?>
+2 -3
View File
@@ -1,5 +1,5 @@
<? <?
$edit_groups = array ( $edit_groups = array (
"table_array" => array ( "table_array" => array (
"edit_group_id" => array ( "edit_group_id" => array (
"value" => $GLOBALS["edit_group_id"], "value" => $GLOBALS["edit_group_id"],
@@ -96,5 +96,4 @@
) )
) // edit pages ggroup ) // edit pages ggroup
) )
); );
?>
@@ -1,5 +1,5 @@
<? <?
$edit_languages=array ( $edit_languages=array (
"table_array" => array ( "table_array" => array (
"edit_language_id" => array ( "edit_language_id" => array (
"value" => $GLOBALS["edit_language_id"], "value" => $GLOBALS["edit_language_id"],
@@ -69,5 +69,4 @@
) )
), ),
"table_name" => "edit_language" "table_name" => "edit_language"
); );
?>
@@ -1,5 +1,5 @@
<? <?
$edit_menu_group = array ( $edit_menu_group = array (
"table_array" => array ( "table_array" => array (
"edit_menu_group_id" => array ( "edit_menu_group_id" => array (
"value" => $GLOBALS["edit_menu_group_id"], "value" => $GLOBALS["edit_menu_group_id"],
@@ -34,5 +34,4 @@
"name" => "name" "name" => "name"
) )
) )
); );
?>
+10 -11
View File
@@ -1,5 +1,5 @@
<? <?
$edit_pages = array ( $edit_pages = array (
"table_array" => array ( "table_array" => array (
"edit_page_id" => array ( "edit_page_id" => array (
"value" => $GLOBALS["edit_page_id"], "value" => $GLOBALS["edit_page_id"],
@@ -102,19 +102,19 @@
"name" => "filename", "name" => "filename",
"before_value" => "Filename: " "before_value" => "Filename: "
), ),
array( array (
"name" => "online", "name" => "online",
"binary" => array("Yes","No"), "binary" => array ("Yes","No"),
"before_value" => "Online: " "before_value" => "Online: "
), ),
array( array (
"name" => "menu", "name" => "menu",
"binary" => array("Yes","No"), "binary" => array ("Yes","No"),
"before_value" => "Menu: " "before_value" => "Menu: "
), ),
array( array (
"name" => "popup", "name" => "popup",
"binary" => array("Yes","No"), "binary" => array ("Yes","No"),
"before_value" => "Popup: " "before_value" => "Popup: "
) )
), ),
@@ -159,13 +159,13 @@
"output_name" => "Enabled", "output_name" => "Enabled",
"int" => 1, "int" => 1,
"type" => "checkbox", "type" => "checkbox",
"element_list" => array(1) "element_list" => array (1)
), ),
"dynamic" => array ( "dynamic" => array (
"output_name" => "Dynamic", "output_name" => "Dynamic",
"int" => 1, "int" => 1,
"type" => "checkbox", "type" => "checkbox",
"element_list" => array(1) "element_list" => array (1)
), ),
"edit_query_string_id" => array ( "edit_query_string_id" => array (
"type" => "hidden", "type" => "hidden",
@@ -174,5 +174,4 @@
) // elements ) // elements
) // query_string element list ) // query_string element list
) // element list ) // element list
); );
?>
@@ -1,5 +1,5 @@
<? <?
$edit_schemes = array ( $edit_schemes = array (
"table_array" => array ( "table_array" => array (
"edit_scheme_id" => array ( "edit_scheme_id" => array (
"value" => $GLOBALS["edit_scheme_id"], "value" => $GLOBALS["edit_scheme_id"],
@@ -51,5 +51,5 @@
"before_value" => "Enabled: " "before_value" => "Enabled: "
) )
) )
); // main array ); // main array
?>
+8 -9
View File
@@ -1,5 +1,5 @@
<? <?
$edit_users = array ( $edit_users = array (
"table_array" => array ( "table_array" => array (
"edit_user_id" => array ( "edit_user_id" => array (
"value" => $GLOBALS["edit_user_id"], "value" => $GLOBALS["edit_user_id"],
@@ -177,27 +177,27 @@
), ),
array ( array (
"name" => "enabled", "name" => "enabled",
"binary" => array("Yes", "No"), "binary" => array ("Yes", "No"),
"before_value" => "Enabled: " "before_value" => "Enabled: "
), ),
array ( array (
"name" => "debug", "name" => "debug",
"binary" => array("Yes", "No"), "binary" => array ("Yes", "No"),
"before_value" => "Debug: " "before_value" => "Debug: "
), ),
array ( array (
"name" => "db_debug", "name" => "db_debug",
"binary" => array("Yes", "No"), "binary" => array ("Yes", "No"),
"before_value" => "DB Debug: " "before_value" => "DB Debug: "
), ),
array ( array (
"name" => "strict", "name" => "strict",
"binary" => array("Yes", "No"), "binary" => array ("Yes", "No"),
"before_value" => "Strict: " "before_value" => "Strict: "
), ),
array ( array (
"name" => "locked", "name" => "locked",
"binary" => array("Yes", "No"), "binary" => array ("Yes", "No"),
"before_value" => "Locked: " "before_value" => "Locked: "
), ),
array ( array (
@@ -228,7 +228,7 @@
"type" => "checkbox", "type" => "checkbox",
"output_name" => "Activate", "output_name" => "Activate",
"int" => 1, "int" => 1,
"element_list" => array(1) "element_list" => array (1)
), ),
"edit_access_right_id" => array ( "edit_access_right_id" => array (
"type" => "drop_down_db", "type" => "drop_down_db",
@@ -250,5 +250,4 @@
) )
) // edit pages ggroup ) // edit pages ggroup
) )
); );
?>
@@ -28,4 +28,3 @@
) )
) )
); );
?>
+189 -194
View File
@@ -1,150 +1,152 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/06/10 * CREATED: 2003/06/10
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* configuration file * configuration file
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
/************* SESSION NAMES *************/ /************* SESSION NAMES *************/
// backend // backend
DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>"); DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>");
// frontend // frontend
DEFINE('SESSION_NAME', "<SESSION NAME>"); DEFINE('SESSION_NAME', "<SESSION NAME>");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
/************* LANGUAGE / ENCODING *******/ /************* LANGUAGE / ENCODING *******/
DEFINE('DEFAULT_LANG', "en_utf8"); DEFINE('DEFAULT_LANG', "en_utf8");
// default web page encoding setting // default web page encoding setting
DEFINE('DEFAULT_ENCODING', "UTF-8"); DEFINE('DEFAULT_ENCODING', "UTF-8");
/************* PATHS *********************/ /************* PATHS *********************/
// ** NEW/BETTER DIR DECLARATIONS ** // ** NEW/BETTER DIR DECLARATIONS **
// path to original file (if symlink) // path to original file (if symlink)
DEFINE('DIR', __DIR__."/"); DEFINE('DIR', __DIR__."/");
// libs base path based on DIR // libs base path based on DIR
DEFINE('LIBDIR', DIR.'libs/'); DEFINE('LIBDIR', DIR.'libs/');
// SMARTY path based on DIR // SMARTY path based on DIR
DEFINE('SMARTYDIR', DIR.'Smarty/'); DEFINE('SMARTYDIR', DIR.'Smarty/');
// table arrays for Class Form // table arrays for Class Form
DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); DEFINE('TABLEARRAYDIR', DIR.'table_arrays/');
// ** OLD DIR DECLARATIONS ** // ** OLD DIR DECLARATIONS **
// path to document root of file called // path to document root of file called
DEFINE('ROOT', getcwd()."/"); DEFINE('ROOT', getcwd()."/");
// libs path // libs path
DEFINE('LIBS', "libs/"); DEFINE('LIBS', "libs/");
// includes (strings, arrays for static, etc) // includes (strings, arrays for static, etc)
DEFINE('INCLUDES', "includes/"); DEFINE('INCLUDES', "includes/");
// layout base path // layout base path
DEFINE('LAYOUT', 'layout/'); DEFINE('LAYOUT', 'layout/');
// pic-root (compatible to CMS) // pic-root (compatible to CMS)
DEFINE('PICTURES', "images/"); DEFINE('PICTURES', "images/");
// images // images
DEFINE('IMAGES', "images/"); DEFINE('IMAGES', "images/");
// icons (below the images/ folder) // icons (below the images/ folder)
DEFINE('ICONS', 'icons/'); DEFINE('ICONS', 'icons/');
// media // media
DEFINE('MEDIA', "media/"); DEFINE('MEDIA', "media/");
// flash-root (below media) // flash-root (below media)
DEFINE('FLASH', "flash/"); DEFINE('FLASH', "flash/");
// uploads (anything to keep) // uploads (anything to keep)
DEFINE('UPLOADS', "uploads/"); DEFINE('UPLOADS', "uploads/");
// files (binaries) (below media) // files (binaries) (below media)
DEFINE('BINARIES', "binaries/"); DEFINE('BINARIES', "binaries/");
// files (videos) (below media) // files (videos) (below media)
DEFINE('VIDEOS', "videos/"); DEFINE('VIDEOS', "videos/");
// files (documents) (below media) // files (documents) (below media)
DEFINE('DOCUMENTS', "documents/"); DEFINE('DOCUMENTS', "documents/");
// files (pdfs) (below media) // files (pdfs) (below media)
DEFINE('PDFS', "documents/"); DEFINE('PDFS', "documents/");
// css // css
DEFINE('CSS', "css/"); DEFINE('CSS', "css/");
// js // js
DEFINE('JS', "javascript/"); DEFINE('JS', "javascript/");
// table arrays // table arrays
DEFINE('TABLE_ARRAYS', "table_arrays/"); DEFINE('TABLE_ARRAYS', "table_arrays/");
// smarty libs path // smarty libs path
DEFINE('SMARTY', "Smarty/"); DEFINE('SMARTY', "Smarty/");
// po langs // po langs
DEFINE('LANG', "lang/"); DEFINE('LANG', "lang/");
// cache path // cache path
DEFINE('CACHE', "cache/"); DEFINE('CACHE', "cache/");
// temp path // temp path
DEFINE('TMP', "tmp/"); DEFINE('TMP', "tmp/");
// log files // log files
DEFINE('LOG', 'log/'); DEFINE('LOG', 'log/');
// template base // template base
DEFINE('TEMPLATES', "templates/"); DEFINE('TEMPLATES', "templates/");
// frontend template dir', only for admin // frontend template dir', only for admin
DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); DEFINE('TEMPLATES_FRONTEND', "templates_frontend/");
// default template // default template
DEFINE('DEFAULT_TEMPLATE', "default/"); DEFINE('DEFAULT_TEMPLATE', "default/");
// default template file // default template file
DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl');
/************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ /************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/
// default hash type // default hash type
DEFINE('DEFAULT_HASH', 'sha256'); DEFINE('DEFAULT_HASH', 'sha256');
// default acl level // default acl level
DEFINE('DEFAULT_ACL_LEVEL', 80); DEFINE('DEFAULT_ACL_LEVEL', 80);
// default levels for certain actions // default levels for certain actions
/* DEFINE('DEFAULT_ACL_READ', 20); /* DEFINE('DEFAULT_ACL_READ', 20);
DEFINE('DEFAULT_ACL_CONFIRM', 35); DEFINE('DEFAULT_ACL_CONFIRM', 35);
DEFINE('DEFAULT_ACL_MOD', 40); DEFINE('DEFAULT_ACL_MOD', 40);
DEFINE('DEFAULT_ACL_WRITE', 60); DEFINE('DEFAULT_ACL_WRITE', 60);
DEFINE('DEFAULT_ACL_SEND', 70); DEFINE('DEFAULT_ACL_SEND', 70);
DEFINE('DEFAULT_ACL_DEL', 80); DEFINE('DEFAULT_ACL_DEL', 80);
DEFINE('DEFAULT_ACL_ADMIN', 100); */ DEFINE('DEFAULT_ACL_ADMIN', 100); */
// SSL host name // SSL host name
// DEFINE('SSL_HOST', "ssl.host.name"); // DEFINE('SSL_HOST', "ssl.host.name");
// error page strictness, Default is 3 // 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 // 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 // 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 // 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 // 4: very strict, even on normal fixable errors through error
// DEFINE('ERROR_STRICT', 3); // 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); // DEFINE('ALLOW_SMARTY_CACHE', FALSE);
// cache life time, in seconds, default here is 2 days (172800s) // cache life time, in seconds, default here is 2 days (172800s)
// -1 is never expire cache // -1 is never expire cache
// DEFINE('SMARTY_CACHE_LIFETIME', -1); // DEFINE('SMARTY_CACHE_LIFETIME', -1);
/************* LOGOUT ********************/ /************* LOGOUT ********************/
// logout target // logout target
DEFINE('LOGOUT_TARGET', ''); DEFINE('LOGOUT_TARGET', '');
// password change allowed // password change allowed
DEFINE('PASSWORD_CHANGE', false); DEFINE('PASSWORD_CHANGE', false);
/************* AJAX / ACCESS *************/ /************* AJAX / ACCESS *************/
// ajax request type // ajax request type
DEFINE('AJAX_REQUEST_TYPE', 'POST'); DEFINE('AJAX_REQUEST_TYPE', 'POST');
// what AJAX type to use // what AJAX type to use
DEFINE('USE_PROTOTYPE', true); DEFINE('USE_PROTOTYPE', true);
DEFINE('USE_SCRIPTACULOUS', false); DEFINE('USE_SCRIPTACULOUS', false);
DEFINE('USE_JQUERY', false); DEFINE('USE_JQUERY', false);
/************* LAYOUT WIDTHS *************/ /************* LAYOUT WIDTHS *************/
DEFINE('PAGE_WIDTH', 800); DEFINE('PAGE_WIDTH', 800);
// the default template name // the default template name
DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl');
/************* QUEUE TABLE *************/ /************* QUEUE TABLE *************/
// if we have a dev/live system // if we have a dev/live system
// set_live is a per page/per item // set_live is a per page/per item
// live_queue is a global queue system // live_queue is a global queue system
// DEFINE('QUEUE', 'live_queue'); // DEFINE('QUEUE', 'live_queue');
/************* DB PATHS (PostgreSQL) *****************/ /************* DB PATHS (PostgreSQL) *****************/
// schema names, can also be defined per <DB INFO> // schema names, can also be defined per <DB INFO>
DEFINE('PUBLIC_SCHEMA', 'public'); DEFINE('PUBLIC_SCHEMA', 'public');
DEFINE('DEV_SCHEMA', 'public'); DEFINE('DEV_SCHEMA', 'public');
DEFINE('TEST_SCHEMA', 'public'); DEFINE('TEST_SCHEMA', 'public');
// non constant part // non constant part
/************* DB ACCESS *****************/ /************* DB ACCESS *****************/
// please be VERY carefull only to change the right side // please be VERY carefull only to change the right side
$DB_CONFIG = array( $DB_CONFIG = array (
"<db id>" => array ( "<db id>" => array (
"db_name" => "<database>", "db_name" => "<database>",
"db_user" => "<user>", "db_user" => "<user>",
@@ -156,104 +158,100 @@
"db_encoding" => '', "db_encoding" => '',
"db_ssl" => 'disable' // allow, disable, require, prefer "db_ssl" => 'disable' // allow, disable, require, prefer
) )
); );
// File and Folder paths // File and Folder paths
// ID is TARGET (first array element) // ID is TARGET (first array element)
// $PATHS["test"]["csv_path"] = ""; // $PATHS["test"]["csv_path"] = "";
// $PATHS["test"]["perl_bin"] = ""; // $PATHS["test"]["perl_bin"] = "";
// $PATHS["test"]["redirect_url"] = ""; // $PATHS["test"]["redirect_url"] = "";
// each host has a different db_host // each host has a different db_host
// development host // development host
$DB_HOST['<host>'] = "<db id>"; $DB_HOST['<host>'] = "<db id>";
// target host (live) // target host (live)
// $DB_TARGET_HOST['<host>'] = "<DB ID>"; // $DB_TARGET_HOST['<host>'] = "<DB ID>";
// url redirect database // url redirect database
// $DB_URL_REDIRECT_HOST['<host>'] = "<DB ID>"; // $DB_URL_REDIRECT_HOST['<host>'] = "<DB ID>";
// location flagging // location flagging
// test/dev/live // test/dev/live
$LOCATION['<host>'] = '<test|live|remote|etc>'; $LOCATION['<host>'] = '<test|live|remote|etc>';
// show DEBUG override // show DEBUG override
// true/false // true/false
$DEBUG_FLAG['<host>'] = true; $DEBUG_FLAG['<host>'] = true;
// set postgresql paths (schemas) // set postgresql paths (schemas)
$DB_PATH['<host>'] = PUBLIC_SCHEMA; $DB_PATH['<host>'] = PUBLIC_SCHEMA;
// set the USE_DATABASE var, if there is nothing set, we assume TRUE // set the USE_DATABASE var, if there is nothing set, we assume TRUE
$USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; $USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true;
// live frontend pages // live frontend pages
// ** missing live domains ** // ** missing live domains **
// get the name without the port // get the name without the port
list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null);
if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) {
{
echo "No matching DB config found. Contact Admin<br>"; echo "No matching DB config found. Contact Admin<br>";
exit -1; exit -1;
} }
// define the static names // define the static names
DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]);
DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]);
DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]);
// DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]); // DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]);
// DEFINE('URL_REDIRECT_DB', $DB_URL_REDIRECT_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('DEV_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']);
// DEFINE('TEST_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('PUBLIC_SCHEMA', $DB_CONFIG[TARGET_DB]['db_schema']);
DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are 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('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('TARGET', $LOCATION[$HOST_NAME]);
// DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']); // DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']);
// DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']); // DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']);
// DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']); // DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']);
DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]);
DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled
/************* GENERAL PAGE TITLE ********/ /************* GENERAL PAGE TITLE ********/
$G_TITLE = '<OVERALL PAGE TITLE>'; $G_TITLE = '<OVERALL PAGE TITLE>';
/************ STYLE SHEETS / JS **********/ /************ STYLE SHEETS / JS **********/
$EDIT_STYLESHEET = "edit.css"; $EDIT_STYLESHEET = "edit.css";
$EDIT_JAVASCRIPT = "edit.js"; $EDIT_JAVASCRIPT = "edit.js";
$STYLESHEET = "frontend.css"; $STYLESHEET = "frontend.css";
$JAVASCRIPT = "frontend.js"; $JAVASCRIPT = "frontend.js";
/************* CONVERT *******************/ /************* CONVERT *******************/
$paths = array ( $paths = array (
'/bin', '/bin',
'/usr/bin', '/usr/bin',
'/usr/local/bin' '/usr/local/bin'
); );
// find convert // find convert
foreach ($paths as $path) foreach ($paths as $path) {
{ if (file_exists($path."/convert") && is_file($path."/convert")) {
if (file_exists($path."/convert") && is_file($path."/convert"))
{
// image magick convert location // image magick convert location
DEFINE('CONVERT', $path."/convert"); DEFINE('CONVERT', $path."/convert");
} }
} }
// turn off debug if debug flag is OFF // turn off debug if debug flag is OFF
if (DEBUG == false) if (DEBUG == false) {
{
$ECHO_ALL = 0; $ECHO_ALL = 0;
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
$DB_DEBUG = 0; $DB_DEBUG = 0;
$ENABLE_ERROR_HANDLING = 0; $ENABLE_ERROR_HANDLING = 0;
} }
// any other global definitons here // any other global definitons here
// DEFINE('SOME_ID', <SOME VALUE>); // DEFINE('SOME_ID', <SOME VALUE>);
// function that will be called on top of each class include to load the class // function that will be called on top of each class include to load the class
function _spl_autoload($include_file) function _spl_autoload($include_file)
{ {
// where to search for the files to include // where to search for the files to include
$dirs = array ( $dirs = array (
LIBDIR, LIBDIR,
@@ -267,14 +265,11 @@
__DIR__.'/'.SMARTY __DIR__.'/'.SMARTY
); );
// try to find and load the class ifle // try to find and load the class ifle
foreach ($dirs as $folder) foreach ($dirs as $folder) {
{ if (file_exists($folder.$include_file)) {
if (file_exists($folder.$include_file))
{
require_once($folder.$include_file); require_once($folder.$include_file);
return true; return true;
} }
} }
return false; return false;
} }
?>
+189 -194
View File
@@ -1,150 +1,152 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/06/10 * CREATED: 2003/06/10
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* configuration file * configuration file
* HISTORY: * HISTORY:
*********************************************************************/ *********************************************************************/
/************* SESSION NAMES *************/ /************* SESSION NAMES *************/
// backend // backend
DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>"); DEFINE('EDIT_SESSION_NAME', "<ADMIN SESSION NAME>");
// frontend // frontend
DEFINE('SESSION_NAME', "<SESSION NAME>"); DEFINE('SESSION_NAME', "<SESSION NAME>");
// set the session name
define('SET_SESSION_NAME', EDIT_SESSION_NAME);
/************* LANGUAGE / ENCODING *******/ /************* LANGUAGE / ENCODING *******/
DEFINE('DEFAULT_LANG', "en_utf8"); DEFINE('DEFAULT_LANG', "en_utf8");
// default web page encoding setting // default web page encoding setting
DEFINE('DEFAULT_ENCODING', "UTF-8"); DEFINE('DEFAULT_ENCODING', "UTF-8");
/************* PATHS *********************/ /************* PATHS *********************/
// ** NEW/BETTER DIR DECLARATIONS ** // ** NEW/BETTER DIR DECLARATIONS **
// path to original file (if symlink) // path to original file (if symlink)
DEFINE('DIR', __DIR__."/"); DEFINE('DIR', __DIR__."/");
// libs base path based on DIR // libs base path based on DIR
DEFINE('LIBDIR', DIR.'libs/'); DEFINE('LIBDIR', DIR.'libs/');
// SMARTY path based on DIR // SMARTY path based on DIR
DEFINE('SMARTYDIR', DIR.'Smarty/'); DEFINE('SMARTYDIR', DIR.'Smarty/');
// table arrays for Class Form // table arrays for Class Form
DEFINE('TABLEARRAYDIR', DIR.'table_arrays/'); DEFINE('TABLEARRAYDIR', DIR.'table_arrays/');
// ** OLD DIR DECLARATIONS ** // ** OLD DIR DECLARATIONS **
// path to document root of file called // path to document root of file called
DEFINE('ROOT', getcwd()."/"); DEFINE('ROOT', getcwd()."/");
// libs path // libs path
DEFINE('LIBS', "libs/"); DEFINE('LIBS', "libs/");
// includes (strings, arrays for static, etc) // includes (strings, arrays for static, etc)
DEFINE('INCLUDES', "includes/"); DEFINE('INCLUDES', "includes/");
// layout base path // layout base path
DEFINE('LAYOUT', 'layout/'); DEFINE('LAYOUT', 'layout/');
// pic-root (compatible to CMS) // pic-root (compatible to CMS)
DEFINE('PICTURES', "images/"); DEFINE('PICTURES', "images/");
// images // images
DEFINE('IMAGES', "images/"); DEFINE('IMAGES', "images/");
// icons (below the images/ folder) // icons (below the images/ folder)
DEFINE('ICONS', 'icons/'); DEFINE('ICONS', 'icons/');
// media // media
DEFINE('MEDIA', "media/"); DEFINE('MEDIA', "media/");
// flash-root (below media) // flash-root (below media)
DEFINE('FLASH', "flash/"); DEFINE('FLASH', "flash/");
// uploads (anything to keep) // uploads (anything to keep)
DEFINE('UPLOADS', "uploads/"); DEFINE('UPLOADS', "uploads/");
// files (binaries) (below media) // files (binaries) (below media)
DEFINE('BINARIES', "binaries/"); DEFINE('BINARIES', "binaries/");
// files (videos) (below media) // files (videos) (below media)
DEFINE('VIDEOS', "videos/"); DEFINE('VIDEOS', "videos/");
// files (documents) (below media) // files (documents) (below media)
DEFINE('DOCUMENTS', "documents/"); DEFINE('DOCUMENTS', "documents/");
// files (pdfs) (below media) // files (pdfs) (below media)
DEFINE('PDFS', "documents/"); DEFINE('PDFS', "documents/");
// css // css
DEFINE('CSS', "css/"); DEFINE('CSS', "css/");
// js // js
DEFINE('JS', "javascript/"); DEFINE('JS', "javascript/");
// table arrays // table arrays
DEFINE('TABLE_ARRAYS', "table_arrays/"); DEFINE('TABLE_ARRAYS', "table_arrays/");
// smarty libs path // smarty libs path
DEFINE('SMARTY', "Smarty/"); DEFINE('SMARTY', "Smarty/");
// po langs // po langs
DEFINE('LANG', "lang/"); DEFINE('LANG', "lang/");
// cache path // cache path
DEFINE('CACHE', "cache/"); DEFINE('CACHE', "cache/");
// temp path // temp path
DEFINE('TMP', "tmp/"); DEFINE('TMP', "tmp/");
// log files // log files
DEFINE('LOG', 'log/'); DEFINE('LOG', 'log/');
// template base // template base
DEFINE('TEMPLATES', "templates/"); DEFINE('TEMPLATES', "templates/");
// frontend template dir', only for admin // frontend template dir', only for admin
DEFINE('TEMPLATES_FRONTEND', "templates_frontend/"); DEFINE('TEMPLATES_FRONTEND', "templates_frontend/");
// default template // default template
DEFINE('DEFAULT_TEMPLATE', "default/"); DEFINE('DEFAULT_TEMPLATE', "default/");
// default template file // default template file
DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl'); DEFINE('DEFAULT_TEMPLATE_FILE', 'default.tpl');
/************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/ /************* HASH / ACL DEFAULT / ERROR SETTINGS / SMARTY *************/
// default hash type // default hash type
DEFINE('DEFAULT_HASH', 'sha256'); DEFINE('DEFAULT_HASH', 'sha256');
// default acl level // default acl level
DEFINE('DEFAULT_ACL_LEVEL', 80); DEFINE('DEFAULT_ACL_LEVEL', 80);
// default levels for certain actions // default levels for certain actions
/* DEFINE('DEFAULT_ACL_READ', 20); /* DEFINE('DEFAULT_ACL_READ', 20);
DEFINE('DEFAULT_ACL_CONFIRM', 35); DEFINE('DEFAULT_ACL_CONFIRM', 35);
DEFINE('DEFAULT_ACL_MOD', 40); DEFINE('DEFAULT_ACL_MOD', 40);
DEFINE('DEFAULT_ACL_WRITE', 60); DEFINE('DEFAULT_ACL_WRITE', 60);
DEFINE('DEFAULT_ACL_SEND', 70); DEFINE('DEFAULT_ACL_SEND', 70);
DEFINE('DEFAULT_ACL_DEL', 80); DEFINE('DEFAULT_ACL_DEL', 80);
DEFINE('DEFAULT_ACL_ADMIN', 100); */ DEFINE('DEFAULT_ACL_ADMIN', 100); */
// SSL host name // SSL host name
// DEFINE('SSL_HOST', "ssl.host.name"); // DEFINE('SSL_HOST', "ssl.host.name");
// error page strictness, Default is 3 // 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 // 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 // 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 // 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 // 4: very strict, even on normal fixable errors through error
// DEFINE('ERROR_STRICT', 3); // 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); // DEFINE('ALLOW_SMARTY_CACHE', FALSE);
// cache life time, in seconds, default here is 2 days (172800s) // cache life time, in seconds, default here is 2 days (172800s)
// -1 is never expire cache // -1 is never expire cache
// DEFINE('SMARTY_CACHE_LIFETIME', -1); // DEFINE('SMARTY_CACHE_LIFETIME', -1);
/************* LOGOUT ********************/ /************* LOGOUT ********************/
// logout target // logout target
DEFINE('LOGOUT_TARGET', ''); DEFINE('LOGOUT_TARGET', '');
// password change allowed // password change allowed
DEFINE('PASSWORD_CHANGE', false); DEFINE('PASSWORD_CHANGE', false);
/************* AJAX / ACCESS *************/ /************* AJAX / ACCESS *************/
// ajax request type // ajax request type
DEFINE('AJAX_REQUEST_TYPE', 'POST'); DEFINE('AJAX_REQUEST_TYPE', 'POST');
// what AJAX type to use // what AJAX type to use
DEFINE('USE_PROTOTYPE', true); DEFINE('USE_PROTOTYPE', true);
DEFINE('USE_SCRIPTACULOUS', false); DEFINE('USE_SCRIPTACULOUS', false);
DEFINE('USE_JQUERY', false); DEFINE('USE_JQUERY', false);
/************* LAYOUT WIDTHS *************/ /************* LAYOUT WIDTHS *************/
DEFINE('PAGE_WIDTH', 800); DEFINE('PAGE_WIDTH', 800);
// the default template name // the default template name
DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl'); DEFINE('MASTER_TEMPLATE_NAME', 'main_body.tpl');
/************* QUEUE TABLE *************/ /************* QUEUE TABLE *************/
// if we have a dev/live system // if we have a dev/live system
// set_live is a per page/per item // set_live is a per page/per item
// live_queue is a global queue system // live_queue is a global queue system
// DEFINE('QUEUE', 'live_queue'); // DEFINE('QUEUE', 'live_queue');
/************* DB PATHS (PostgreSQL) *****************/ /************* DB PATHS (PostgreSQL) *****************/
// schema names, can also be defined per <DB INFO> // schema names, can also be defined per <DB INFO>
DEFINE('PUBLIC_SCHEMA', 'public'); DEFINE('PUBLIC_SCHEMA', 'public');
DEFINE('DEV_SCHEMA', 'public'); DEFINE('DEV_SCHEMA', 'public');
DEFINE('TEST_SCHEMA', 'public'); DEFINE('TEST_SCHEMA', 'public');
// non constant part // non constant part
/************* DB ACCESS *****************/ /************* DB ACCESS *****************/
// please be VERY carefull only to change the right side // please be VERY carefull only to change the right side
$DB_CONFIG = array( $DB_CONFIG = array (
"<DB ID>" => array ( "<DB ID>" => array (
"db_name" => "<DB NAME>", "db_name" => "<DB NAME>",
"db_user" => "<DB USER>", "db_user" => "<DB USER>",
@@ -156,104 +158,100 @@
"db_encoding" => '', "db_encoding" => '',
"db_ssl" => 'disable' // allow, disable, require, prefer "db_ssl" => 'disable' // allow, disable, require, prefer
) )
); );
// File and Folder paths // File and Folder paths
// ID is TARGET (first array element) // ID is TARGET (first array element)
// $PATHS["test"]["csv_path"] = ""; // $PATHS["test"]["csv_path"] = "";
// $PATHS["test"]["perl_bin"] = ""; // $PATHS["test"]["perl_bin"] = "";
// $PATHS["test"]["redirect_url"] = ""; // $PATHS["test"]["redirect_url"] = "";
// each host has a different db_host // each host has a different db_host
// development host // development host
$DB_HOST['<HOST NAME>'] = "<DB ID>"; $DB_HOST['<HOST NAME>'] = "<DB ID>";
// target host (live) // target host (live)
// $DB_TARGET_HOST['<HOST NAME>'] = "<DB ID>"; // $DB_TARGET_HOST['<HOST NAME>'] = "<DB ID>";
// url redirect database // url redirect database
// $DB_URL_REDIRECT_HOST['<HOST NAME>'] = "<DB ID>"; // $DB_URL_REDIRECT_HOST['<HOST NAME>'] = "<DB ID>";
// location flagging // location flagging
// test/dev/live // test/dev/live
$LOCATION['<HOST NAME>'] = '<test|live|remote|etc>'; $LOCATION['<HOST NAME>'] = '<test|live|remote|etc>';
// show DEBUG override // show DEBUG override
// true/false // true/false
$DEBUG_FLAG['<HOST NAME>'] = true; $DEBUG_FLAG['<HOST NAME>'] = true;
// set postgresql paths (schemas) // set postgresql paths (schemas)
$DB_PATH['<HOST NAME>'] = PUBLIC_SCHEMA; $DB_PATH['<HOST NAME>'] = PUBLIC_SCHEMA;
// set the USE_DATABASE var, if there is nothing set, we assume TRUE // set the USE_DATABASE var, if there is nothing set, we assume TRUE
$USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true; $USE_DATABASE = defined('USE_DATABASE') ? USE_DATABASE : true;
// live frontend pages // live frontend pages
// ** missing live domains ** // ** missing live domains **
// get the name without the port // get the name without the port
list($HOST_NAME) = explode(":", $_SERVER['HTTP_HOST']); list($HOST_NAME, $PORT) = array_pad(explode(":", $_SERVER['HTTP_HOST'], 2), 2, null);
if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) if (!$DB_HOST[$HOST_NAME] && $USE_DATABASE) {
{
echo "No matching DB config found. Contact Admin<br>"; echo "No matching DB config found. Contact Admin<br>";
exit -1; exit -1;
} }
// define the static names // define the static names
DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]); DEFINE('LOGIN_DB', $DB_HOST[$HOST_NAME]);
DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]); DEFINE('MAIN_DB', $DB_HOST[$HOST_NAME]);
DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]); DEFINE('DB_SCHEMA', $DB_PATH[$HOST_NAME]);
// DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]); // DEFINE('TARGET_DB', $DB_TARGET_HOST[$HOST_NAME]);
// DEFINE('URL_REDIRECT_DB', $DB_URL_REDIRECT_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('DEV_SCHEMA', $DB_CONFIG[MAIN_DB]['db_schema']);
// DEFINE('TEST_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('PUBLIC_SCHEMA', $DB_CONFIG[TARGET_DB]['db_schema']);
DEFINE('LOGIN_DB_SCHEMA', 'public'); // where the edit* tables are 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('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('TARGET', $LOCATION[$HOST_NAME]);
// DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']); // DEFINE('CSV_PATH', $PATHS[TARGET]['csv_path']);
// DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']); // DEFINE('EXPORT_SCRIPT', $PATHS[TARGET]['perl_bin']);
// DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']); // DEFINE('REDIRECT_URL', $PATHS[TARGET]['redirect_url']);
DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]); DEFINE('DEBUG', $DEBUG_FLAG[$HOST_NAME]);
DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled DEFINE('SHOW_ALL_ERRORS', false); // show all errors if debug_all & show_error_handling are enabled
/************* GENERAL PAGE TITLE ********/ /************* GENERAL PAGE TITLE ********/
$G_TITLE = '<OVERALL PAGE TITLE>'; $G_TITLE = '<OVERALL PAGE TITLE>';
/************ STYLE SHEETS / JS **********/ /************ STYLE SHEETS / JS **********/
$EDIT_STYLESHEET = "edit.css"; $EDIT_STYLESHEET = "edit.css";
$EDIT_JAVASCRIPT = "edit.js"; $EDIT_JAVASCRIPT = "edit.js";
$STYLESHEET = "frontend.css"; $STYLESHEET = "frontend.css";
$JAVASCRIPT = "frontend.js"; $JAVASCRIPT = "frontend.js";
/************* CONVERT *******************/ /************* CONVERT *******************/
$paths = array ( $paths = array (
'/bin', '/bin',
'/usr/bin', '/usr/bin',
'/usr/local/bin' '/usr/local/bin'
); );
// find convert // find convert
foreach ($paths as $path) foreach ($paths as $path) {
{ if (file_exists($path."/convert") && is_file($path."/convert")) {
if (file_exists($path."/convert") && is_file($path."/convert"))
{
// image magick convert location // image magick convert location
DEFINE('CONVERT', $path."/convert"); DEFINE('CONVERT', $path."/convert");
} }
} }
// turn off debug if debug flag is OFF // turn off debug if debug flag is OFF
if (DEBUG == false) if (DEBUG == false) {
{
$ECHO_ALL = 0; $ECHO_ALL = 0;
$DEBUG_ALL = 0; $DEBUG_ALL = 0;
$PRINT_ALL = 0; $PRINT_ALL = 0;
$DB_DEBUG = 0; $DB_DEBUG = 0;
$ENABLE_ERROR_HANDLING = 0; $ENABLE_ERROR_HANDLING = 0;
} }
// any other global definitons here // any other global definitons here
// DEFINE('SOME_ID', <SOME VALUE>); // DEFINE('SOME_ID', <SOME VALUE>);
// function that will be called on top of each class include to load the class // function that will be called on top of each class include to load the class
function _spl_autoload($include_file) function _spl_autoload($include_file)
{ {
// where to search for the files to include // where to search for the files to include
$dirs = array ( $dirs = array (
LIBDIR, LIBDIR,
@@ -267,14 +265,11 @@
__DIR__.'/'.SMARTY __DIR__.'/'.SMARTY
); );
// try to find and load the class ifle // try to find and load the class ifle
foreach ($dirs as $folder) foreach ($dirs as $folder) {
{ if (file_exists($folder.$include_file)) {
if (file_exists($folder.$include_file))
{
require_once($folder.$include_file); require_once($folder.$include_file);
return true; return true;
} }
} }
return false; return false;
} }
?>
+133 -211
View File
@@ -15,416 +15,353 @@
padding: 0; padding: 0;
} */ } */
body body {
{
background-color: white; background-color: white;
color: black; color: black;
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
} }
.large .large {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 16pt; font-size : 16pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.big .big {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 12pt; font-size : 12pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.normal .normal {
{ font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 9pt; font-size : 9pt;
font-family: Verdana,Arial,Helvetica,sans-serif;
} }
.small .small {
{
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
} }
.smallbold .smallbold {
{
font-size : 8pt;
font-family: Verdana,Arial,Helvetica,sans-serif; font-family: Verdana,Arial,Helvetica,sans-serif;
font-size : 8pt;
font-weight: bold; font-weight: bold;
} }
a:link a:link {
{
color: #FF0000; color: #FF0000;
text-decoration: none; text-decoration: none;
} }
a:active a:active {
{
color: #FFFF00; color: #FFFF00;
text-decoration: none; text-decoration: none;
} }
a:visited a:visited {
{
color: #550000; color: #550000;
text-decoration: none; text-decoration: none;
} }
a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover a:hover, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover {
{
color: #FF0000;
background-color: #e5e5e5; background-color: #e5e5e5;
border-bottom: 1px dotted red; border-bottom: 1px dotted red;
color: #FF0000;
} }
a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover a:focus, a.item_loaded:hover, a.item_deleted:hover, a.item_loaded_deleted:hover {
{
color: #ff0000;
background-color: #b3b3b3; background-color: #b3b3b3;
border-top: 1px dotted red;
border-bottom: 1px dotted red; border-bottom: 1px dotted red;
border-top: 1px dotted red;
color: #ff0000;
} }
/* link highlight */ /* link highlight */
a.item_loaded a.item_loaded {
{
font-weight: bold;
color: #451010;
background-color: #d5d6d6; background-color: #d5d6d6;
color: #451010;
font-weight: bold;
} }
a.item_deleted a.item_deleted {
{
text-decoration: line-through; text-decoration: line-through;
} }
a.item_loaded_deleted a.item_loaded_deleted {
{
text-decoration: line-through;
font-weight: bold;
color: #451010;
background-color: #d5d6d6; background-color: #d5d6d6;
color: #451010;
font-weight: bold;
text-decoration: line-through;
} }
/* experimental */ /* experimental */
input[type="text"] input[type="text"] {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
}
input[type="password"]
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="submit"] input[type="password"] {
{ border: 1px solid #999999;
}
input[type="submit"] {
border: 1px solid #666666; border: 1px solid #666666;
} }
input[type="checkbox"] input[type="checkbox"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="radio"] input[type="radio"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="file"] input[type="file"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
input[type="button"] input[type="button"] {
{
border: 1px solid #999999; border: 1px solid #999999;
} }
textarea textarea {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
border: 1px solid #999999;
} }
select select {
{
border: 1px solid #999999;
background-color: #efefef; background-color: #efefef;
border: 1px solid #999999;
} }
/* mouse over */ /* 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; border: 1px dashed red;
} }
/* selected */ /* 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 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;
background-color: #ffffff; background-color: #ffffff;
border: 1px solid red;
} }
input[type="text"]:focus, textarea:focus, select:focus input[type="text"]:focus, textarea:focus, select:focus {
{
border: 1px solid red;
background-color: #ffffff; background-color: #ffffff;
border: 1px solid red;
} }
/* error & status layouts for messges */ /* error & status layouts for messges */
.error .error {
{
border: 1px solid red; border: 1px solid red;
margin: 5px;
padding: 2px;
color: red; color: red;
margin: 5px;
padding: 2px;
text-align: center; text-align: center;
} }
.warning .warning {
{
border: 1px solid #df7700; border: 1px solid #df7700;
margin: 5px;
padding: 2px;
color: #d57200; color: #d57200;
text-align: center;
}
.info
{
border: 1px solid #72C47E;
margin: 5px; margin: 5px;
padding: 2px; padding: 2px;
color: #1D731A;
text-align: center; text-align: center;
} }
.div_error .info {
{ border: 1px solid #72C47E;
border: 1px solid red; color: #1D731A;
margin-top: 1px; margin: 5px;
margin-bottom: 1px; 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; border: 1px solid #df7700;
} }
/* borders */ /* borders */
.border_all .border_all {
{
border: 1px solid black; border: 1px solid black;
} }
.border_bottom_title .border_bottom_title {
{
font-weight: bold;
border-bottom: 1px solid black; border-bottom: 1px solid black;
font-weight: bold;
} }
.border_top .border_top {
{
border-top: 1px solid #DCDCCC; border-top: 1px solid #DCDCCC;
} }
.border_all_error .border_all_error {
{
border: 1px solid red; border: 1px solid red;
} }
.border_group .border_group {
{
border: 1px solid #a89c5a; border: 1px solid #a89c5a;
} }
.border_master .border_master {
{
border: 1px solid white; border: 1px solid white;
} }
.border_sub .border_sub {
{
border: 1px solid gray; border: 1px solid gray;
} }
.border_sub_sub .border_sub_sub {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* employee hardware/software borders */ /* employee hardware/software borders */
.border_hardware .border_hardware {
{ background-color: #e9e9e9;
border: 2px solid black; border: 2px solid black;
background-color: #e9e9e9;
} }
.border_hardware_usage_end .border_hardware_usage_end {
{ background-color: #e9e9e9;
border: 2px solid red; border: 2px solid red;
background-color: #e9e9e9;
} }
.border_hardware_line .border_hardware_line {
{
border-left: 2px solid black;
border-bottom: 2px solid black; border-bottom: 2px solid black;
border-left: 2px solid black;
} }
.border_software .border_software {
{
border: 2px solid #a89c5a;
background-color: #d5d4c8; background-color: #d5d4c8;
border: 2px solid #a89c5a;
} }
.border_software_line .border_software_line {
{
border-left: 2px solid #a89c5a;
border-bottom: 2px solid #a89c5a; border-bottom: 2px solid #a89c5a;
border-left: 2px solid #a89c5a;
} }
.border_software_line_left .border_software_line_left {
{
border-left: 2px solid #a89c5a; border-left: 2px solid #a89c5a;
padding-bottom: 10px; padding-bottom: 10px;
} }
.border_software_line_bottom .border_software_line_bottom {
{
border-bottom: 2px solid #a89c5a; border-bottom: 2px solid #a89c5a;
padding-left: 2px; padding-left: 2px;
} }
/* highlight */ /* highlight */
.highlight .highlight {
{
background-color: #e7e7e7; background-color: #e7e7e7;
font-weight: bold; font-weight: bold;
} }
/* hide & show */ /* hide & show */
.visible .visible {
{
visibility: visible; visibility: visible;
} }
.hidden .hidden {
{
visibility: hidden;
display: none; display: none;
visibility: hidden;
} }
/* spacer for line break in float elements */ /* spacer for line break in float elements */
div.spacer .spacer {
{
clear: both; clear: both;
} }
/* unique definitions */ /* unique definitions */
/* main body */ /* main body */
/* menu on top */ /* menu on top */
.menu .menu {
{
border-bottom: 1px solid #a4a4a4; border-bottom: 1px solid #a4a4a4;
font-size: 10px; font-size: 10px;
} }
.pagename .pagename {
{
text-align: center; font-size: 15px;
background-color: #e7e7e7; background-color: #e7e7e7;
font-size: 15px;
font-weight: bold; font-weight: bold;
padding: 5px; padding: 5px;
text-align: center;
} }
/* overlay side menu */ /* overlay side menu */
.sidemenu .sidemenu {
{
border: 1px solid black;
background-color: white; background-color: white;
border: 1px solid black;
} }
.buttongroup .buttongroup {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* input group field */ /* input group field */
/* normal */ /* normal */
.input_group .input_group {
{
border: 1px solid #e5ddba; border: 1px solid #e5ddba;
} }
/* loaded with id */ /* loaded with id */
.input_group_id .input_group_id {
{
border: 1px solid #8a7d3a; border: 1px solid #8a7d3a;
} }
/* deleted */ /* deleted */
.input_group_deleted .input_group_deleted {
{
border: 1px solid #8a7d3a;
background-color: #d5d4c8; background-color: #d5d4c8;
border: 1px solid #8a7d3a;
} }
/* header part */ /* header part */
/* normal */ /* normal */
.input_group_header .input_group_header {
{
background-color: #e9e9e9; background-color: #e9e9e9;
} }
/* loaded with id */ /* loaded with id */
.input_group_header_id .input_group_header_id {
{
background-color: #d5d5d5; background-color: #d5d5d5;
} }
/* deleted */ /* deleted */
.input_group_header_deleted .input_group_header_deleted {
{
background-color: #bfb59d; background-color: #bfb59d;
} }
/* error & warning messages */ /* error & warning messages */
.top_error_message .top_error_message {
{ border: 2px solid red;
color: red;
font-size: 18px;
margin: 5px; margin: 5px;
padding: 10px; padding: 10px;
border: 2px solid red;
font-size: 18px;
text-align: center; text-align: center;
color: red;
} }
.top_inventory_number .top_inventory_number {
{
margin: 5px;
padding: 10px;
border: 2px solid orange; border: 2px solid orange;
font-size: 18px; font-size: 18px;
text-align: center;
}
.top_info_message
{
border: 2px solid green;
margin: 5px; margin: 5px;
padding: 10px; padding: 10px;
text-align: center; 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; border-top: 1px solid #a4a4a4;
color: #a4a4a4; color: #a4a4a4;
font-size: 8px; font-size: 8px;
@@ -434,78 +371,63 @@ div.spacer
/* set all colors here and not in the config file */ /* set all colors here and not in the config file */
/* for edit interface */ /* for edit interface */
.menu_bgcolor .menu_bgcolor {
{
background-color: #666666; background-color: #666666;
} }
.menu_fgcolor .menu_fgcolor {
{
background-color: #DDDDDD; background-color: #DDDDDD;
} }
.menu_fgcolor_na .menu_fgcolor_na {
{
background-color: #CCCCCC; background-color: #CCCCCC;
} }
.menu_fgcolor_a .menu_fgcolor_a {
{
background-color: #EEEEEE; background-color: #EEEEEE;
} }
.edit_bgcolor .edit_bgcolor {
{
background-color: #666666; background-color: #666666;
} }
.edit_fgcolor .edit_fgcolor {
{
background-color: #FFFFDF; background-color: #FFFFDF;
} }
.edit_fgcolor_mod_a .edit_fgcolor_mod_a {
{
background-color: #CECEB5; background-color: #CECEB5;
} }
.edit_fgcolor_mod_b .edit_fgcolor_mod_b {
{
background-color: #DEDEC3; background-color: #DEDEC3;
} }
.edit_fgcolor_2 .edit_fgcolor_2 {
{
background-color: #AADAA2; background-color: #AADAA2;
} }
.edit_fgcolor_no .edit_fgcolor_no {
{
background-color: #CECEB5; background-color: #CECEB5;
} }
.edit_fgcolor_alt .edit_fgcolor_alt {
{
background-color: #CCCCCC; background-color: #CCCCCC;
} }
.edit_fgcolor_delete .edit_fgcolor_delete {
{
background-color: red; background-color: red;
} }
.font_error .font_error {
{
color: red; color: red;
} }
.edit_fgcolor_special .edit_fgcolor_special {
{
background-color: #EEEEEE; background-color: #EEEEEE;
} }
.edit_temp .edit_temp {
{
background-color: #FFDF6F; background-color: #FFDF6F;
} }
+2 -3
View File
@@ -9,9 +9,8 @@
*/ */
// if debug is set to true, console log messages are printed // if debug is set to true, console log messages are printed
if (!DEBUG) if (!DEBUG) {
{
$($H(window.console)).each(function(w) { $($H(window.console)).each(function(w) {
window.console[w.key] = function() {} window.console[w.key] = function() {};
}); });
} }
+45 -46
View File
@@ -6,50 +6,43 @@
* Some browser detection * Some browser detection
*/ */
var clientPC = navigator.userAgent.toLowerCase(); // Get client info var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) var is_gecko = ((clientPC.indexOf('gecko') != -1) && (clientPC.indexOf('spoofer') == -1) &&
&& (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1)); (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0') == -1));
var is_safari = ((clientPC.indexOf('AppleWebKit') != -1) && (clientPC.indexOf('spoofer') == -1)); var is_safari = ((clientPC.indexOf('AppleWebKit') != -1) && (clientPC.indexOf('spoofer') == -1));
var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled )); 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 = true;
var is_opera_preseven = (window.opera && !document.childNodes); var is_opera_preseven = (window.opera && !document.childNodes);
var is_opera_seven = (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 = window.open(theURL, winName, features);
winName.focus(); winName.focus();
} }
function emd_check_checkbox() function emd_check_checkbox() {
{ for (i = 0; i < document.manage_emails.length; i ++) {
for (i = 0; i < document.manage_emails.length; i ++) if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox') {
{
if (document.manage_emails.elements[i].checked == false && document.manage_emails.elements[i].type == 'checkbox')
{
document.manage_emails.elements[i].checked = true; document.manage_emails.elements[i].checked = true;
} }
} }
} }
function expandTA(ta_id) function expandTA(ta_id) {
{
var ta; var ta;
// if a string comes, its a get by id, else use it as an element pass on // 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; ta = ta_id;
else } else {
ta = document.getElementById(ta_id); ta = document.getElementById(ta_id);
}
var maxChars = ta.cols; var maxChars = ta.cols;
var theRows = ta.value.split("\n"); var theRows = ta.value.split("\n");
var numNewRows = 0; var numNewRows = 0;
for ( var i = 0; i < theRows.length; i++ ) for ( var i = 0; i < theRows.length; i++ ) {
{ if ((theRows[i].length+2) > maxChars) {
if ((theRows[i].length+2) > maxChars)
{
numNewRows += Math.ceil( (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 // DESC: shows or hides the menu
function ShowHideMenu(status, id) function ShowHideMenu(status, id)
{ {
if (status == 'show') if (status == 'show') {
{
document.getElementById(id).style.visibility = 'visible'; 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'; document.getElementById('search_results').style.visibility = 'visible';
} }
else if (status == 'hide') } else if (status == 'hide') {
{
document.getElementById(id).style.visibility = 'hidden'; 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'; document.getElementById('search_results').style.visibility = 'hidden';
} }
}
} }
function ShowHideDiv(id) function ShowHideDiv(id)
{ {
element = document.getElementById(id); element = document.getElementById(id);
if (element.className == 'visible' || !element.className) if (element.className == 'visible' || !element.className) {
element.className = 'hidden'; element.className = 'hidden';
else } else {
element.className = 'visible'; element.className = 'visible';
}
// alert('E: ' + element.className + ' -- ' + element.style.visibility); // alert('E: ' + element.className + ' -- ' + element.style.visibility);
} }
@@ -100,14 +93,16 @@ function mv(id, direction)
function le(id) function le(id)
{ {
document.forms[form_name].action.value = 'load'; 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?'); 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_yes.value = 'true';
}
document.forms[form_name].action_id.value = id; document.forms[form_name].action_id.value = id;
document.forms[form_name].action_menu.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(); document.forms[form_name].submit();
}
} }
// METHOD: getWindowSize // METHOD: getWindowSize
@@ -119,7 +114,10 @@ function getWindowSize()
var width, height; var width, height;
width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth); width = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight); height = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
return {width: width, height: height}; return {
width: width,
height: height
};
} }
// METHOD: getScrollOffset // METHOD: getScrollOffset
@@ -131,7 +129,10 @@ function getScrollOffset()
var left, top; var left, top;
left = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft); left = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
top = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop); top = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
return {left: left, top: top}; return {
left: left,
top: top
};
} }
// METHOD: setCenter // METHOD: setCenter
@@ -142,22 +143,23 @@ function setCenter(id, left, top)
{ {
// get size of id // get size of id
var dimensions = $(id).getDimensions(); var dimensions = $(id).getDimensions();
var type = $(id).getStyle('position');
var viewport = getWindowSize(); var viewport = getWindowSize();
var offset = getScrollOffset(); var offset = getScrollOffset();
console.log('Id %s, dimensions %s x %s, viewport %s x %s', id, dimensions.width, dimensions.height, viewport.width, viewport.height); // 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('Scrolloffset left: %s, top: %s', offset.left, offset.top);
console.log('Left: %s, Top: %s', parseInt((viewport.width / 2) - (dimensions.width / 2)), parseInt((viewport.height / 2) - (dimensions.height / 2))); // 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 ({ $(id).setStyle ({
left: parseInt((viewport.width / 2) - (dimensions.width / 2) + offset.left) + 'px' 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 ({ $(id).setStyle ({
top: parseInt((viewport.height / 2) - (dimensions.height / 2) + offset.top) + 'px' top: top_pos + 'px'
}); });
} }
} }
@@ -175,15 +177,12 @@ function sh(id, showText, hideText)
// get status from element (hidden or visible) // get status from element (hidden or visible)
divStatus = $(id).visible(); divStatus = $(id).visible();
//console.log('Set flag %s for element %s', divStatus, id); //console.log('Set flag %s for element %s', divStatus, id);
if (divStatus) if (divStatus) {
{
// hide the element // hide the element
Effect.BlindUp(id, {duration:0.3}); Effect.BlindUp(id, {duration:0.3});
$(flag).value = 0; $(flag).value = 0;
$(btn).innerHTML = showText; $(btn).innerHTML = showText;
} } else if (!divStatus) {
else if (!divStatus)
{
// show the element // show the element
Effect.BlindDown(id, {duration:0.3}); Effect.BlindDown(id, {duration:0.3});
$(flag).value = 1; $(flag).value = 1;
@@ -10,7 +10,7 @@ var ConsoleSetup = function() {
for (var i = 0; i < names.length; ++i) { for (var i = 0; i < names.length; ++i) {
if (!window.console[names[i]]) { if (!window.console[names[i]]) {
window.console[names[i]] = function() {} window.console[names[i]] = function() {};
} }
} }
}(); }();
+1 -2
View File
@@ -1,5 +1,4 @@
.debug_message .debug_message {
{
border-top: 1px solid #a4a4a4; border-top: 1px solid #a4a4a4;
color: #a4a4a4; color: #a4a4a4;
font-size: 8px; font-size: 8px;
@@ -8,10 +8,10 @@
// PARAMS: front/back -> what image to show // PARAMS: front/back -> what image to show
// RETURN: none // RETURN: none
// DESC: ajax call to switch the main image in the detail view // DESC: ajax call to switch the main image in the detail view
function SwitchImage(image) function SwitchImage(image) {
{ if (image != 'front' || image != 'back') {
if (image != 'front' || image != 'back')
image = 'front'; image = 'front';
}
// disable / enable the href for the other side // disable / enable the href for the other side
x_ajax_afSwitchImage(image, OutputSwitchImage); x_ajax_afSwitchImage(image, OutputSwitchImage);
} }
@@ -20,7 +20,6 @@ function SwitchImage(image)
// PARAMS: data -> the image full path for the new image // PARAMS: data -> the image full path for the new image
// RETURN: none // RETURN: none
// DESC: replace the image in the product detail with the back image // DESC: replace the image in the product detail with the back image
function OutputSwitchImage(data) function OutputSwitchImage(data) {
{
} }
+104 -94
View File
@@ -1,32 +1,32 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2006/08/15 * CREATED: 2006/08/15
* VERSION: 0.1.0 * VERSION: 0.1.0
* RELEASED LICENSE: GNU GPL 3 * RELEASED LICENSE: GNU GPL 3
* DESCRIPTION * DESCRIPTION
* Basic Admin interface backend * Basic Admin interface backend
* - sets action flags * - sets action flags
* - menu creation * - menu creation
* - array vars for smarty * - array vars for smarty
* *
* PUBLIC VARIABLES * PUBLIC VARIABLES
* *
* PRIVATE VARIABLES * PRIVATE VARIABLES
* *
* PUBLIC METHODS * PUBLIC METHODS
* *
* PRIVATE METHODS * PRIVATE METHODS
* *
* HISTORY: * HISTORY:
* *
*********************************************************************/ *********************************************************************/
// try to include file from LIBS path, or from normal path // try to include file from LIBS path, or from normal path
_spl_autoload('Class.DB.IO.inc'); _spl_autoload('Class.DB.IO.inc');
class AdminBackend extends db_io class AdminBackend extends db_io
{ {
// page name // page name
public $page_name; // the name of the current page public $page_name; // the name of the current page
public $menu = array(); public $menu = array();
@@ -81,8 +81,7 @@
$this->page_name = $this->get_page_name(); $this->page_name = $this->get_page_name();
// set the action ids // set the action ids
foreach ($this->action_list as $_action) foreach ($this->action_list as $_action) {
{
$this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : ''; $this->$_action = (isset($_POST[$_action])) ? $_POST[$_action] : '';
} }
@@ -95,9 +94,17 @@
$this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62) $this->key_length = 4; // pow($this->one_key_length, 4); // hardcoded, should be more than enought (62*62*62*62)
// queue key // queue key
if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) if (preg_match("/^(add|save|delete|remove|move|up|down|push_live)$/", $this->action)) {
{ $this->queue_key = join(
$this->queue_key = join('', array_map(function () { $range = $GLOBALS['_KEY_RANGE']; return $range[rand(0, (count($range) - 1))]; }, range(1, 3))); '',
array_map(
function () {
$range = $GLOBALS['_KEY_RANGE'];
return $range[rand(0, (count($range) - 1))];
},
range(1, 3)
)
);
} }
} }
@@ -118,13 +125,11 @@
// DESC: writes all action vars plus other info into edit_log table // DESC: writes all action vars plus other info into edit_log table
public function adbEditLog($event = '', $data = '', $write_type = 'STRING') public function adbEditLog($event = '', $data = '', $write_type = 'STRING')
{ {
if ($write_type == 'BINARY') if ($write_type == 'BINARY') {
{
$data_binary = $this->db_escape_bytea(bzcompress(serialize($data))); $data_binary = $this->db_escape_bytea(bzcompress(serialize($data)));
$data = 'see bzip compressed data_binary field'; $data = 'see bzip compressed data_binary field';
} }
if ($write_type == 'STRING') if ($write_type == 'STRING') {
{
$data = $this->db_escape_string(serialize($data)); $data = $this->db_escape_string(serialize($data));
} }
@@ -134,8 +139,16 @@
$q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) "; $q .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES "; $q .= "VALUES ";
$q .= "(".@$_SESSION['EUID'].", NOW(), '".$this->db_escape_string($event)."', '".$data."', '".$data_binary."', '".$this->page_name."', "; $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 .= "'".@$_SERVER["REMOTE_ADDR"]."', '".$this->db_escape_string(@$_SERVER['HTTP_USER_AGENT'])."', ";
$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)."')"; $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'); $this->db_exec($q, 'NULL');
} }
@@ -152,80 +165,72 @@
// DESC: menu creater // DESC: menu creater
public function adbTopMenu($flag = 0) public function adbTopMenu($flag = 0)
{ {
if ($this->menu_show_flag) if ($this->menu_show_flag) {
$flag = $this->menu_show_flag; $flag = $this->menu_show_flag;
}
// get the session pages array // get the session pages array
$pages = $_SESSION["PAGES"]; $pages = $_SESSION["PAGES"];
if (!is_array($pages)) if (!is_array($pages)) {
$pages = array (); $pages = array ();
}
//$this->debug('pages', $this->print_ar($pages)); //$this->debug('pages', $this->print_ar($pages));
// if flag is 0, then we show all, else, we show only the matching flagges array points // if flag is 0, then we show all, else, we show only the matching flagges array points
// array is already sorted after correct order // array is already sorted after correct order
reset($pages); reset($pages);
for ($i = 0; $i < count($pages); $i ++) for ($i = 0; $i < count($pages); $i ++) {
{
$show = 0; $show = 0;
// is it visible in the menu & is it online // is it visible in the menu & is it online
if ($pages[$i]["menu"] && $pages[$i]["online"]) if ($pages[$i]["menu"] && $pages[$i]["online"]) {
{
// check if it falls into our flag if we have a flag // check if it falls into our flag if we have a flag
if ($flag) if ($flag) {
{ foreach ($pages[$i]["visible"] as $name => $key) {
foreach ($pages[$i]["visible"] AS $name => $key) if ($key == $flag) {
{
if ($key == $flag)
$show = 1; $show = 1;
} }
} }
else } else {
{
// if no flag given, show all menu points // if no flag given, show all menu points
$show = 1; $show = 1;
} }
if ($show) if ($show) {
{
// if it is popup, write popup arrayound // if it is popup, write popup arrayound
if ($pages[$i]["popup"]) if ($pages[$i]["popup"]) {
{
$type = "popup"; $type = "popup";
} } else {
else
{
$type = "normal"; $type = "normal";
} }
$query_string = ''; $query_string = '';
if (count($pages[$i]["query"])) if (count($pages[$i]["query"])) {
{ for ($j = 0; $j < count($pages[$i]["query"]); $j ++) {
for ($j = 0; $j < count($pages[$i]["query"]); $j ++) if (strlen($query_string)) {
{
if (strlen($query_string))
$query_string .= "&"; $query_string .= "&";
}
$query_string .= $pages[$i]["query"][$j]["name"]."="; $query_string .= $pages[$i]["query"][$j]["name"]."=";
if (!$pages[$i]["query"][$j]["dynamic"]) if (!$pages[$i]["query"][$j]["dynamic"]) {
$query_string .= urlencode($pages[$i]["query"][$j]["value"]); $query_string .= urlencode($pages[$i]["query"][$j]["value"]);
else } else {
$query_string .= (($_GET[$pages[$i]["query"][$j]["value"]]) ? urlencode($_GET[$pages[$i]["query"][$j]["value"]]) : urlencode($_POST[$pages[$i]["query"][$j]["value"]])); $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"]; $url = $pages[$i]["filename"];
if (strlen($query_string)) if (strlen($query_string)) {
$url .= "?".$query_string; $url .= "?".$query_string;
}
$name = $pages[$i]["page_name"]; $name = $pages[$i]["page_name"];
// if page name matchs -> set selected flag // if page name matchs -> set selected flag
$selected = 0; $selected = 0;
if ($this->get_page_name() == $pages[$i]["filename"]) if ($this->get_page_name() == $pages[$i]["filename"]) {
{
$selected = 1; $selected = 1;
$this->page_name = $name; $this->page_name = $name;
} }
// last check, is this menu point okay to show // last check, is this menu point okay to show
$enabled = 0; $enabled = 0;
if ($this->adbShowMenuPoint($pages[$i]["filename"])) if ($this->adbShowMenuPoint($pages[$i]["filename"])) {
{
$enabled = 1; $enabled = 1;
} }
// write in to view menu array // write in to view menu array
@@ -243,8 +248,7 @@
public function adbShowMenuPoint($filename) public function adbShowMenuPoint($filename)
{ {
$enabled = 0; $enabled = 0;
switch ($filename) switch ($filename) {
{
default: default:
$enabled = 1; $enabled = 1;
break; break;
@@ -295,17 +299,23 @@
// DESC: wrapper function to fill up the mssages array // DESC: wrapper function to fill up the mssages array
public function adbMsg($level, $msg, $vars = array ()) public function adbMsg($level, $msg, $vars = array ())
{ {
if (!preg_match("/^info|warning|error$/", $level)) if (!preg_match("/^info|warning|error$/", $level)) {
$level = "info"; $level = "info";
}
$this->messages[] = array ( $this->messages[] = array (
'msg' => sprintf($this->l->__($msg), $vars), 'msg' => sprintf($this->l->__($msg), $vars),
'class' => $level 'class' => $level
); );
switch ($level) switch ($level) {
{ case 'info':
case 'info': $this->info = 1; break; $this->info = 1;
case 'warning': $this->warning = 1; break; break;
case 'error': $this->error = 1; break; case 'warning':
$this->warning = 1;
break;
case 'error':
$this->error = 1;
break;
} }
} }
@@ -320,12 +330,16 @@
// file -> string for special file copy actions; mostyle "test#live;..." // file -> string for special file copy actions; mostyle "test#live;..."
// RETURN: none // RETURN: none
// DESC: writes live queue // DESC: writes live queue
public function adbLiveQueue($queue_key, $type, $target, $data, $key_name, $key_value, $associate = NULL, $file = NULL) 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 = "INSERT INTO ".GLOBAL_DB_SCHEMA.".live_queue (";
$q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file"; $q .= "queue_key, key_value, key_name, type, target, data, group_key, action, associate, file";
$q .= ") VALUES ("; $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)."')"; $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); $this->db_exec($q);
} }
@@ -338,10 +352,12 @@
public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1) public function adbPrintDateTime($year, $month, $day, $hour, $min, $suffix = '', $min_steps = 1)
{ {
// if suffix given, add _ before // if suffix given, add _ before
if ($suffix) if ($suffix) {
$suffix = '_'.$suffix; $suffix = '_'.$suffix;
if ($min_steps < 1 || $min_steps > 59) }
if ($min_steps < 1 || $min_steps > 59) {
$min_steps = 1; $min_steps = 1;
}
$on_change_call = 'dt_list(\''.$suffix.'\');'; $on_change_call = 'dt_list(\''.$suffix.'\');';
@@ -363,38 +379,32 @@
// from now to ? // from now to ?
$string = $this->l->__('Year').' '; $string = $this->l->__('Year').' ';
$string .= '<select id="year'.$suffix.'" name="year'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="year'.$suffix.'" name="year'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = date("Y"); $i <= $max_year; $i ++) for ($i = date("Y"); $i <= $max_year; $i ++) {
{
$string .= '<option value="'.$i.'" '.(($year == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.$i.'" '.(($year == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Month').' '; $string .= '</select> '.$this->l->__('Month').' ';
$string .= '<select id="month'.$suffix.'" name="month'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="month'.$suffix.'" name="month'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 1; $i <= 12; $i ++) for ($i = 1; $i <= 12; $i ++) {
{
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($month == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($month == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Day').' '; $string .= '</select> '.$this->l->__('Day').' ';
$string .= '<select id="day'.$suffix.'" name="day'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="day'.$suffix.'" name="day'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 1; $i <= $days_in_month; $i ++) for ($i = 1; $i <= $days_in_month; $i ++) {
{
// set weekday text based on current month ($month) and year ($year) // set weekday text based on current month ($month) and year ($year)
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($day == $i) ? 'selected' : '').'>'.$i.' ('.$this->l->__(date('D', mktime(0, 0, 0, $month, $i, $year))).')</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($day == $i) ? 'selected' : '').'>'.$i.' ('.$this->l->__(date('D', mktime(0, 0, 0, $month, $i, $year))).')</option>';
} }
$string .= '</select> '.$this->l->__('Hour').' '; $string .= '</select> '.$this->l->__('Hour').' ';
$string .= '<select id="hour'.$suffix.'" name="hour'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="hour'.$suffix.'" name="hour'.$suffix.'" onChange="'.$on_change_call.'">';
for ($i = 0; $i <= 23; $i ++) for ($i = 0; $i <= 23; $i ++) {
{
$string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($hour == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(($i < 10) ? '0'.$i : $i).'" '.(($hour == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select> '.$this->l->__('Minute').' '; $string .= '</select> '.$this->l->__('Minute').' ';
$string .= '<select id="min'.$suffix.'" name="min'.$suffix.'" onChange="'.$on_change_call.'">'; $string .= '<select id="min'.$suffix.'" name="min'.$suffix.'" onChange="'.$on_change_call.'">';
for ( $i = 0; $i <= 59; $i += $min_steps) for ($i = 0; $i <= 59; $i += $min_steps) {
{
$string .= '<option value="'.(( $i < 10) ? '0'.$i : $i).'" '.(($min == $i) ? 'selected' : '').'>'.$i.'</option>'; $string .= '<option value="'.(( $i < 10) ? '0'.$i : $i).'" '.(($min == $i) ? 'selected' : '').'>'.$i.'</option>';
} }
$string .= '</select>'; $string .= '</select>';
// return the datetime select string // return the datetime select string
return $string; return $string;
} }
} }
?>
+518 -517
View File
File diff suppressed because it is too large Load Diff
+169 -188
View File
@@ -1,47 +1,47 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2002/12/17 * CREATED: 2002/12/17
* VERSION: 0.4.0 * VERSION: 0.4.0
* RELEASED LICENSE: GNU GPL 3 * RELEASED LICENSE: GNU GPL 3
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* DB Array IO Class: * DB Array IO Class:
* writes, reads or deletes a complete array (one data set) in/out a * writes, reads or deletes a complete array (one data set) in/out a
* table from the connected DB. * table from the connected DB.
* you don't have to write any SQL queries, worry over update/insert * you don't have to write any SQL queries, worry over update/insert
* *
* PUBLIC VARIABLES * PUBLIC VARIABLES
* *
* PRIVATE VARIABLES * PRIVATE VARIABLES
* *
* PUBLIC METHODS * PUBLIC METHODS
* *
* PRIVATE METHODS * PRIVATE METHODS
* *
* HISTORY: * HISTORY:
* 2005/07/07 (cs) updated array class for postgres: set 0 & NULL if int field given, insert uses () values () syntax * 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 * 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-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, * 2003-02-26: db_array_io is no longer single class but extens db_io,
* as it needs it anyway * as it needs it anyway
* moved the class info vars into class_info array into * moved the class info vars into class_info array into
* the constructor, removed info function * the constructor, removed info function
* 2003-02-24: in db_delete moved query build to top, or pk_name/value * 2003-02-24: in db_delete moved query build to top, or pk_name/value
* will be reset before delete is done * will be reset before delete is done
* 2002-12-20: just added info() method * 2002-12-20: just added info() method
* 2002-12-17: splitted the class from other file (with main db wrapper) * 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 // 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 // as it actually has nothing to do with this one here ? (or at least
// put into separete function in this class) // put into separete function in this class)
// try to include file from LIBS path, or from normal path // try to include file from LIBS path, or from normal path
_spl_autoload('Class.DB.IO.inc'); _spl_autoload('Class.DB.IO.inc');
// subclass for one array handling // subclass for one array handling
class db_array_io extends db_io class db_array_io extends db_io
{ {
// main calss variables // main calss variables
public $table_array; // the array from the table to work on public $table_array; // the array from the table to work on
public $table_name; // the table_name public $table_name; // the table_name
@@ -68,13 +68,12 @@
$this->table_name = $table_name; $this->table_name = $table_name;
// set primary key for given table_array // set primary key for given table_array
if ($this->table_array) if ($this->table_array) {
{ while (list($key, $value) = each($table_array)) {
while (list($key, $value) = each($table_array)) if ($value["pk"]) {
{
if ($value["pk"])
$this->pk_name = $key; $this->pk_name = $key;
} }
}
} // set pk_name IF table_array was given } // set pk_name IF table_array was given
// internal // internal
$this->class_info["db_array_io"] = array( $this->class_info["db_array_io"] = array(
@@ -100,14 +99,14 @@
// used with the read function // used with the read function
public function convert_data($text) public function convert_data($text)
{ {
$text = eregi_replace ('&lt;b&gt;', '<B>', $text); $text = str_replace('&lt;b&gt;', '<b>', $text);
$text = eregi_replace ('&lt;/b&gt;', '</B>', $text); $text = str_replace('&lt;/b&gt;', '</b>', $text);
$text = eregi_replace ('&lt;i&gt;', '<I>', $text); $text = str_replace('&lt;i&gt;', '<i>', $text);
$text = eregi_replace ('&lt;/i&gt;', '</I>', $text); $text = str_replace('&lt;/i&gt;', '</i>', $text);
// my need a change // my need a change
$text = eregi_replace ('&lt;a href=&quot;', '<A TARGET="_blank" HREF="', $text); $text = str_replace('&lt;a href=&quot;', '<a target="_blank" href="', $text);
$text = eregi_replace ('&quot;&gt;', '">', $text); $text = str_replace('&quot;&gt;', '">', $text);
$text = eregi_replace ('&lt;/a&gt;', '</A>', $text); $text = str_replace('&lt;/a&gt;', '</a>', $text);
return $text; return $text;
} }
@@ -132,13 +131,13 @@
public function db_dump_array($write = 0) public function db_dump_array($write = 0)
{ {
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
$string .= "<b>".$column."</b> -> ".$data_array["value"]."<br>"; $string .= "<b>".$column."</b> -> ".$data_array["value"]."<br>";
} }
// add output to internal error_msg // add output to internal error_msg
if ($write) if ($write) {
$this->error_msg['db'] .= $string; $this->error_msg['db'] .= $string;
}
return $string; return $string;
} }
@@ -162,19 +161,19 @@
public function db_check_pk_set() public function db_check_pk_set()
{ {
// if pk_id is set, overrule ... // if pk_id is set, overrule ...
if ($this->pk_id) if ($this->pk_id) {
$this->table_array[$this->pk_name]["value"] = $this->pk_id; $this->table_array[$this->pk_name]["value"] = $this->pk_id;
}
// if not set ... produce error // if not set ... produce error
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
{
// if no PK found, error ... // if no PK found, error ...
$this->error_id = 21; $this->error_id = 21;
$this->_db_error(); $this->_db_error();
return 0; return 0;
} } else {
else
return 1; return 1;
} }
}
// METHOD db_reset_array // METHOD db_reset_array
// PARAMS reset_pk -> if set reset the pk too // PARAMS reset_pk -> if set reset the pk too
@@ -183,14 +182,14 @@
public function db_reset_array($reset_pk = 0) public function db_reset_array($reset_pk = 0)
{ {
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{ if (!$this->table_array[$column]["pk"]) {
if (!$this->table_array[$column]["pk"])
unset($this->table_array[$column]["value"]); unset($this->table_array[$column]["value"]);
else if ($reset_pk) } elseif ($reset_pk) {
unset($this->table_array[$column]["value"]); unset($this->table_array[$column]["value"]);
} }
} }
}
// METHOD db_delete // METHOD db_delete
// PARAMS optional the table_array, if not given uses class var // PARAMS optional the table_array, if not given uses class var
@@ -198,32 +197,34 @@
// DESC deletes one dataset // DESC deletes one dataset
public function db_delete($table_array = 0) public function db_delete($table_array = 0)
{ {
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
if (!$this->db_check_pk_set()) }
if (!$this->db_check_pk_set()) {
return $this->table_array; return $this->table_array;
}
// delete query // delete query
$q = "DELETE FROM ".$this->table_name." WHERE "; $q = "DELETE FROM ".$this->table_name." WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
// delete files and build FK query // delete files and build FK query
reset($this->table_array); reset($this->table_array);
while(list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
// suchen nach bildern und löschen ... // 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 ($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"])) {
if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"]))
unlink($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"]); $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]);
if (file_exists($this->table_array[$column]["path"].$dateiname)) if (file_exists($this->table_array[$column]["path"].$dateiname)) {
unlink($this->table_array[$column]["path"].$dateiname); unlink($this->table_array[$column]["path"].$dateiname);
} }
}
if ($this->table_array[$column]["fk"]) if ($this->table_array[$column]["fk"]) {
{
// zusammenstellen der FKs // zusammenstellen der FKs
if ($q_where) if ($q_where) {
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column." = ".$this->table_array[$column]["value"]; $q_where .= $column." = ".$this->table_array[$column]["value"];
} }
// allgemeines zurücksetzen des arrays // allgemeines zurücksetzen des arrays
@@ -231,12 +232,12 @@
} }
// attach fk row if there ... // attach fk row if there ...
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// if 0, error // if 0, error
unset ($this->pk_id); unset($this->pk_id);
if (!$this->db_exec($q)) if (!$this->db_exec($q)) {
{
$this->error_id=22; $this->error_id=22;
$this->_db_error(); $this->_db_error();
} }
@@ -250,23 +251,25 @@
public function db_read($edit = 0, $table_array = 0) public function db_read($edit = 0, $table_array = 0)
{ {
// if array give, overrules internal array // if array give, overrules internal array
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
if (!$this->db_check_pk_set()) }
if (!$this->db_check_pk_set()) {
return $this->table_array; return $this->table_array;
}
reset($this->table_array); reset($this->table_array);
// create select part & addition FK part // create select part & addition FK part
while (list($column, $data_array)=each($this->table_array)) while (list($column, $data_array)=each($this->table_array)) {
{ if ($q_select) {
if ($q_select)
$q_select .= ", "; $q_select .= ", ";
}
$q_select .= $column; $q_select .= $column;
// check FK ... // check FK ...
if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) {
{ if ($q_where) {
if ($q_where)
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column .= " = ".$this->table_array[$column]["value"]; $q_where .= $column .= " = ".$this->table_array[$column]["value"];
} }
} }
@@ -275,31 +278,25 @@
$q .= $q_select; $q .= $q_select;
$q .= " FROM ".$this->table_name." WHERE "; $q .= " FROM ".$this->table_name." WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// if query was executed okay, else set error // if query was executed okay, else set error
if ($this->db_exec($q)) if ($this->db_exec($q)) {
{ if ($res = $this->db_fetch_array()) {
if ($res = $this->db_fetch_array())
{
reset($this->table_array); reset($this->table_array);
while (list($column, $data_array) = each($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 // 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 // ?? 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]."<br>"; // echo "EDIT: $edit | Spalte: $column | type: ".$this->table_array[$column]["type"]." | Res: ".$res[$column]."<br>";
if ($edit) if ($edit) {
{
$this->table_array[$column]["value"] = $res[$column]; $this->table_array[$column]["value"] = $res[$column];
// if password, also write to hidden // if password, also write to hidden
if ($this->table_array[$column]["type"] == "password") if ($this->table_array[$column]["type"] == "password") {
{
$this->table_array[$column]["HIDDEN_value"] = $res[$column]; $this->table_array[$column]["HIDDEN_value"] = $res[$column];
} }
} } else {
else
{
$this->table_array[$column]["value"] = $this->convert_data(nl2br($res[$column])); $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 // had to put out the htmlentities from the line above as it breaks japanese characters
} }
@@ -307,9 +304,7 @@
} }
// possible db_fetch_array errors ... // possible db_fetch_array errors ...
$this->pk_id = $this->table_array[$this->pk_name]["value"]; $this->pk_id = $this->table_array[$this->pk_name]["value"];
} } else {
else
{
$this->error_id = 22; $this->error_id = 22;
$this->_db_error(); $this->_db_error();
} }
@@ -322,44 +317,43 @@
// DESC writes on set into DB or updates one set (if PK exists) // DESC writes on set into DB or updates one set (if PK exists)
public function db_write($addslashes = 0, $table_array = 0) public function db_write($addslashes = 0, $table_array = 0)
{ {
if (is_array($table_array)) if (is_array($table_array)) {
$this->table_array = $table_array; $this->table_array = $table_array;
}
// PK ID check // PK ID check
// if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) // if ($this->pk_id && !$this->table_array[$this->pk_name]["value"]) {
// $this->table_array[$this->pk_name]["value"]=$this->pk_id; // $this->table_array[$this->pk_name]["value"]=$this->pk_id;
// }
// checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR! // checken ob PKs gesetzt, wenn alle -> update, wenn keiner -> insert, wenn ein paar -> ERROR!
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
$insert = 1; $insert = 1;
else } else {
$insert = 0; $insert = 0;
}
reset ($this->table_array); reset($this->table_array);
while (list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
/********************************* START FILE *************************************/ /********************************* START FILE *************************************/
// file upload // file upload
if ($this->table_array[$column]["file"]) if ($this->table_array[$column]["file"]) {
{
// falls was im tmp drinnen, sprich ein upload, datei kopieren, Dateinamen in db schreiben // 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 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) // falls in "delete" "ja" dann loeschen (und gibts eh nur beim update)
if ($this->table_array[$column]["delete"]) if ($this->table_array[$column]["delete"]) {
{
unset($this->table_array[$column]["delete"]); unset($this->table_array[$column]["delete"]);
if (file_exists($this->table_array[$column]["path"].$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"]); 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"] = "";
} }
else $dateiname = str_replace("_tn", "", $this->table_array[$column]["value"]);
{ if (file_exists($this->table_array[$column]["path"].$dateiname)) {
if ($this->table_array[$column]["tmp"] != "none" && $this->table_array[$column]["tmp"]) 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 // Dateiname zusammenbasteln: org-name + _pkid liste + .ext
list($name, $ext) = explode(".",$this->table_array[$column]["dn"]); list($name, $ext) = explode(".", $this->table_array[$column]["dn"]);
// mozilla, patch // mozilla, patch
$fn_name = explode("/", $this->table_array[$column]["dn"]); $fn_name = explode("/", $this->table_array[$column]["dn"]);
@@ -373,20 +367,17 @@
//echo "Dn: $dateiname"; //echo "Dn: $dateiname";
copy($this->table_array[$column]["tmp"], $this->table_array[$column]["path"].$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 .. // 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") if (strtolower($ext) == "jpeg" || strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png") {
{
$dateiname_tn = $name.$pk_ids_file."_tn.".$ext; $dateiname_tn = $name.$pk_ids_file."_tn.".$ext;
$eingang = $this->table_array[$column]["path"].$dateiname; $eingang = $this->table_array[$column]["path"].$dateiname;
$ausgang = $this->table_array[$column]["path"].$dateiname_tn; $ausgang = $this->table_array[$column]["path"].$dateiname_tn;
$com = "convert -geometry 115 $eingang $ausgang"; $com = "convert -geometry 115 $eingang $ausgang";
exec($com); exec($com);
$this->table_array[$column]["value"] = $dateiname_tn; $this->table_array[$column]["value"] = $dateiname_tn;
} } else {
else
$this->table_array[$column]["value"] = $dateiname; $this->table_array[$column]["value"] = $dateiname;
} }
else if (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) } elseif (file_exists($this->table_array[$column]["path"].$this->table_array[$column]["value"])) {
{
// mach gar nix, wenn bild schon da ??? // mach gar nix, wenn bild schon da ???
} }
} // delete or upload } // delete or upload
@@ -394,55 +385,52 @@
/********************************* END FILE **************************************/ /********************************* END FILE **************************************/
// do not write 'pk' (primary key) or 'view' values // do not write 'pk' (primary key) or 'view' values
if (!$this->table_array[$column]["pk"] && $this->table_array[$column]['type'] != 'view' && strlen($column) > 0 ) 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 // for password use hidden value if main is not set
if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) if ($this->table_array[$column]["type"] == "password" && !$this->table_array[$column]["value"]) {
$this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"]; $this->table_array[$column]["value"] = $this->table_array[$column]["HIDDEN_value"];
if (!$insert)
{
if (strlen($q_data))
$q_data .= ", ";
$q_data .= $column." = ";
} }
else if (!$insert) {
// this is insert if (strlen($q_data)) {
{
if (strlen($q_data))
$q_data .= ", "; $q_data .= ", ";
if ($q_vars) }
$q_data .= $column." = ";
} else {
// this is insert
if (strlen($q_data)) {
$q_data .= ", ";
}
if ($q_vars) {
$q_vars .= ", "; $q_vars .= ", ";
}
$q_vars .= $column; $q_vars .= $column;
} }
// integer is different // integer is different
if ($this->table_array[$column]["int"] || $this->table_array[$column]["int_null"]) 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"]);
$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"]) {
if (!$this->table_array[$column]["value"] && $this->table_array[$column]["int_null"])
$_value = 'NULL'; $_value = 'NULL';
elseif (!isset($this->table_array[$column]["value"])) } elseif (!isset($this->table_array[$column]["value"])) {
$_value = 0; $_value = 0;
else } else {
$_value = $this->table_array[$column]["value"]; $_value = $this->table_array[$column]["value"];
$q_data .= $_value;
} }
elseif ($this->table_array[$column]["interval"]) $q_data .= $_value;
{ } elseif ($this->table_array[$column]["interval"]) {
// for interval we check if no value, then we set null // for interval we check if no value, then we set null
if (!$this->table_array[$column]["value"]) if (!$this->table_array[$column]["value"]) {
$_value = 'NULL'; $_value = 'NULL';
$q_data .= $_value;
} }
else $q_data .= $_value;
} else {
// normal string // normal string
{
$q_data .= "'"; $q_data .= "'";
// if add slashes do convert & add slashes else write AS is // if add slashes do convert & add slashes else write AS is
if ($addslashes) if ($addslashes) {
$q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"])); $q_data .= $this->db_escape_string($this->convert_entities($this->table_array[$column]["value"]));
else } else {
$q_data .= $this->db_escape_string($this->table_array[$column]["value"]); $q_data .= $this->db_escape_string($this->table_array[$column]["value"]);
}
$q_data .= "'"; $q_data .= "'";
} }
} }
@@ -452,65 +440,58 @@ $this->debug('write_check', "[$column][".$this->table_array[$column]["value"]."]
// get it at the end, cause now we can be more sure of no double IDs, etc // get it at the end, cause now we can be more sure of no double IDs, etc
reset($this->table_array); reset($this->table_array);
// create select part & addition FK part // create select part & addition FK part
while (list($column, $data_array) = each($this->table_array)) while (list($column, $data_array) = each($this->table_array)) {
{
// check FK ... // check FK ...
if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) if ($this->table_array[$column]["fk"] && $this->table_array[$column]["value"]) {
{ if ($q_where) {
if ($q_where)
$q_where .= " AND "; $q_where .= " AND ";
}
$q_where .= $column .= " = ".$this->table_array[$column]["value"]; $q_where .= $column .= " = ".$this->table_array[$column]["value"];
} }
} }
// if no PK set, then get max ID from DB // if no PK set, then get max ID from DB
if (!$this->table_array[$this->pk_name]["value"]) if (!$this->table_array[$this->pk_name]["value"]) {
{ // max id, falls INSERT
// max id, falls INSERT
$q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name; $q = "SELECT MAX(".$this->pk_name.") + 1 AS pk_id FROM ".$this->table_name;
$res = $this->db_return_row($q); $res = $this->db_return_row($q);
if (!$res["pk_id"]) if (!$res["pk_id"]) {
$res["pk_id"] = 1; $res["pk_id"] = 1;
}
$this->table_array[$this->pk_name]["value"] = $res["pk_id"]; $this->table_array[$this->pk_name]["value"] = $res["pk_id"];
} }
if (!$insert) if (!$insert) {
{
$q = "UPDATE ".$this->table_name." SET "; $q = "UPDATE ".$this->table_name." SET ";
$q .= $q_data; $q .= $q_data;
$q .= " WHERE "; $q .= " WHERE ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
if ($q_where) if ($q_where) {
$q .= " AND ".$q_where; $q .= " AND ".$q_where;
}
// set pk_id ... if it has changed or so // set pk_id ... if it has changed or so
$this->pk_id = $this->table_array[$this->pk_name]["value"]; $this->pk_id = $this->table_array[$this->pk_name]["value"];
} } else {
else
{
$q = "INSERT INTO ".$this->table_name." "; $q = "INSERT INTO ".$this->table_name." ";
$q .= "(".$q_vars.") "; $q .= "(".$q_vars.") ";
$q .= "VALUES (".$q_data.")"; $q .= "VALUES (".$q_data.")";
// write primary key too // write primary key too
/* if ($q_data) // if ($q_data)
$q .= ", "; // $q .= ", ";
$q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." "; // $q .= $this->pk_name." = ".$this->table_array[$this->pk_name]["value"]." ";
$this->pk_id = $this->table_array[$this->pk_name]["value"]; // $this->pk_id = $this->table_array[$this->pk_name]["value"];
*/
} }
// return success or not // return success or not
if (!$this->db_exec($q)) if (!$this->db_exec($q)) {
{
$this->error_id = 22; $this->error_id = 22;
$this->_db_error(); $this->_db_error();
} }
// set primary key // set primary key
if ($insert) if ($insert) {
{
$this->table_array[$this->pk_name]["value"] = $this->insert_id; $this->table_array[$this->pk_name]["value"] = $this->insert_id;
$this->ok = $this->insert_id; $this->ok = $this->insert_id;
} }
// return the table if needed // return the table if needed
return $this->table_array; return $this->table_array;
} }
} // end of class } // end of class
?>
+516 -605
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+219 -284
View File
@@ -1,67 +1,67 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2000/06/01 * CREATED: 2000/06/01
* VERSION: 4.0.0 * VERSION: 4.0.0
* RELEASED LICENSE: GNU GPL 3 * RELEASED LICENSE: GNU GPL 3
* SHORT DESCRIPTON: * SHORT DESCRIPTON:
* ~ 2003/03/03: change the whole include file into one class * ~ 2003/03/03: change the whole include file into one class
* advantages are a) can include before actuall call, can control it * advantages are a) can include before actuall call, can control it
* easer (login db, etc), etc etc etc * easer (login db, etc), etc etc etc
* *
* a login lib that should stand out of all others * a login lib that should stand out of all others
* will be a class one day * will be a class one day
* *
* descrption of session_vars * descrption of session_vars
* DEBUG_ALL - set to one, prints out error_msg var at end of php execution * DEBUG_ALL - set to one, prints out error_msg var at end of php execution
* DB_DEBUG - prints out database debugs (query, etc) * DB_DEBUG - prints out database debugs (query, etc)
* GROUP_LEVEL - the level he can access (numeric) * GROUP_LEVEL - the level he can access (numeric)
* USER_NAME - login name from user * USER_NAME - login name from user
* LANG - lang to show edit interface (not yet used) * LANG - lang to show edit interface (not yet used)
* DEFAULT_CHARSET - in connection with LANG (not yet used) * DEFAULT_CHARSET - in connection with LANG (not yet used)
* PAGES - array of hashes * PAGES - array of hashes
* edit_page_id - ID from the edit_pages table * edit_page_id - ID from the edit_pages table
* filename - name of the file * filename - name of the file
* page_name - name in menu * page_name - name in menu
* menu - appears in menu * menu - appears in menu
* popup - is a popup * popup - is a popup
* popup_x - if popup -> width * popup_x - if popup -> width
* popup_y - if popup -> height * popup_y - if popup -> height
* online - page is online (user can access) * online - page is online (user can access)
* query_string - string to paste for popup (will change) * query_string - string to paste for popup (will change)
* *
* HISTORY: * HISTORY:
* 2010/12/21 (cs) merge back password change interface * 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 * 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 * 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/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/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/07/01 (cs) start adepting login class to new edit interface layout
* 2005/03/31 (cs) fixed the class call with all debug vars * 2005/03/31 (cs) fixed the class call with all debug vars
* 2004/11/17 (cs) unused var cleanup * 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) 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 * 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-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 * 2003-06-12: added flag to PAGES array
* changed the get vars from GLOBALS to _POST * changed the get vars from GLOBALS to _POST
* changed the session registration. no more GLOBAL vars are registered * changed the session registration. no more GLOBAL vars are registered
* only _SESSION["..."] * only _SESSION["..."]
* 2003-06-09: added mobile phone login possibility * 2003-06-09: added mobile phone login possibility
* 2003-03-04: droped ADMIN and added GROUP_LEVEL * 2003-03-04: droped ADMIN and added GROUP_LEVEL
* 2003-03-03: started to change the include file function collection * 2003-03-03: started to change the include file function collection
* to become a class * to become a class
* 2003-02-28: various advances and changes, but far from perfect * 2003-02-28: various advances and changes, but far from perfect
* decided to change it into a class for easier handling * decided to change it into a class for easier handling
* add also possibility to change what will stored in the * add also possibility to change what will stored in the
* login session ? * login session ?
* 2000-06-01: created basic idea and functions * 2000-06-01: created basic idea and functions
*********************************************************************/ *********************************************************************/
// try to include file from LIBS path, or from normal path // try to include file from LIBS path, or from normal path
_spl_autoload('Class.DB.IO.inc'); _spl_autoload('Class.DB.IO.inc');
class login extends db_io class login extends db_io
{ {
private $euid; // the user id var 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 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 public $login; // pressed login
@@ -95,8 +95,7 @@
parent::__construct($db_config, $debug, $db_debug, $echo, $print); parent::__construct($db_config, $debug, $db_debug, $echo, $print);
// no session could be found at all // no session could be found at all
if (!session_id()) if (!session_id()) {
{
echo "<b>Session not started!</b><br>Use 'session_start();'.<br>For less problems with other session, you can set a session name with 'session_name(\"name\");'.<br>"; echo "<b>Session not started!</b><br>Use 'session_start();'.<br>For less problems with other session, you can set a session name with 'session_name(\"name\");'.<br>";
exit; exit;
} }
@@ -112,24 +111,33 @@
$this->euid = array_key_exists('EUID', $_SESSION) ? $_SESSION['EUID'] : 0; // if there is none, there is none, saves me POST/GET check $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 // get login vars, are so, can't be changed
// prepare // prepare
if (!isset($_POST['login_login'])) if (!isset($_POST['login_login'])) {
$_POST['login_login'] = ''; $_POST['login_login'] = '';
if (!isset($_POST['login_username'])) }
if (!isset($_POST['login_username'])) {
$_POST['login_username'] = ''; $_POST['login_username'] = '';
if (!isset($_POST['login_password'])) }
if (!isset($_POST['login_password'])) {
$_POST['login_password'] = ''; $_POST['login_password'] = '';
if (!isset($_POST['login_logout'])) }
if (!isset($_POST['login_logout'])) {
$_POST['login_logout'] = ''; $_POST['login_logout'] = '';
if (!isset($_POST['change_password'])) }
if (!isset($_POST['change_password'])) {
$_POST['change_password'] = ''; $_POST['change_password'] = '';
if (!isset($_POST['pw_username'])) }
if (!isset($_POST['pw_username'])) {
$_POST['pw_username'] = ''; $_POST['pw_username'] = '';
if (!isset($_POST['pw_old_password'])) }
if (!isset($_POST['pw_old_password'])) {
$_POST['pw_old_password'] = ''; $_POST['pw_old_password'] = '';
if (!isset($_POST['pw_new_password'])) }
if (!isset($_POST['pw_new_password'])) {
$_POST['pw_new_password'] = ''; $_POST['pw_new_password'] = '';
if (!isset($_POST['pw_new_password_confirm'])) }
if (!isset($_POST['pw_new_password_confirm'])) {
$_POST['pw_new_password_confirm'] = ''; $_POST['pw_new_password_confirm'] = '';
}
// pass on vars to Object vars // pass on vars to Object vars
$this->login = $_POST["login_login"]; $this->login = $_POST["login_login"];
$this->username = $_POST["login_username"]; $this->username = $_POST["login_username"];
@@ -146,8 +154,9 @@
// disallow user list for password change // disallow user list for password change
$this->pw_change_deny_users = array ('admin'); $this->pw_change_deny_users = array ('admin');
// set flag if password change is okay // set flag if password change is okay
if (defined('PASSWORD_CHANGE')) if (defined('PASSWORD_CHANGE')) {
$this->password_change = PASSWORD_CHANGE; $this->password_change = PASSWORD_CHANGE;
}
// max login counts before error reporting // max login counts before error reporting
$this->max_login_error_count = 10; $this->max_login_error_count = 10;
// users that never get locked, even if they are set strict // users that never get locked, even if they are set strict
@@ -165,8 +174,7 @@
$_SESSION['DEFAULT_ACL_LIST'] = array (); $_SESSION['DEFAULT_ACL_LIST'] = array ();
// read the current edit_access_right list into an 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"; $q = "SELECT level, type, name FROM edit_access_right WHERE level >= 0 ORDER BY level";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// level to description format (numeric) // level to description format (numeric)
$this->default_acl_list[$res['level']] = array ( $this->default_acl_list[$res['level']] = array (
'type' => $res['type'], 'type' => $res['type'],
@@ -183,25 +191,25 @@
// logsout user // logsout user
$this->login_logout_user(); $this->login_logout_user();
// if the password change flag is okay, run the password change method // if the password change flag is okay, run the password change method
if ($this->password_change) if ($this->password_change) {
$this->login_password_change(); $this->login_password_change();
}
// if !$euid || permission not okay, print login screan // if !$euid || permission not okay, print login screan
echo $this->login_print_login(); echo $this->login_print_login();
// closing all connections, depending on error status, exit // closing all connections, depending on error status, exit
if (!$this->login_close_class()) if (!$this->login_close_class()) {
{
// do not go anywhere, quit processing here // do not go anywhere, quit processing here
// do something with possible debug data? // do something with possible debug data?
if (TARGET == 'live' || TARGET == 'remote') if (TARGET == 'live' || TARGET == 'remote') {
{
// login // login
$this->debug_output_all = DEBUG ? 1 : 0; $this->debug_output_all = DEBUG ? 1 : 0;
$this->echo_output_all = 0; $this->echo_output_all = 0;
$this->print_output_all = DEBUG ? 1 : 0; $this->print_output_all = DEBUG ? 1 : 0;
} }
$status_msg = $this->print_error_msg(); $status_msg = $this->print_error_msg();
if ($this->echo_output_all) if ($this->echo_output_all) {
echo $status_msg; echo $status_msg;
}
exit; exit;
} }
// set acls for this user/group and this page // set acls for this user/group and this page
@@ -224,14 +232,10 @@
private function login_login_user() private function login_login_user()
{ {
// have to get the global stuff here for setting it later // have to get the global stuff here for setting it later
if (!$this->euid && $this->login) if (!$this->euid && $this->login) {
{ if (!($this->password && $this->username)) {
if (!($this->password && $this->username))
{
$this->login_error = 102; $this->login_error = 102;
} } else {
else
{
// we have to get the themes in here too // 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 = "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 .= "debug, db_debug, ";
@@ -251,12 +255,9 @@
$q .= "(LOWER(username) = '".strtolower($this->username)."') "; $q .= "(LOWER(username) = '".strtolower($this->username)."') ";
$res = $this->db_return($q); $res = $this->db_return($q);
// username is wrong, but we throw for wrong username and wrong password the same error // username is wrong, but we throw for wrong username and wrong password the same error
if (!$this->cursor_ext[md5($q)]["num_rows"]) if (!$this->cursor_ext[md5($q)]["num_rows"]) {
{
$this->login_error = 1010; $this->login_error = 1010;
} } else {
else
{
// if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try // if login errors is half of max errors and the last login error was less than 10s ago, forbid any new login try
// check with what kind of prefix the password begins: // check with what kind of prefix the password begins:
@@ -273,39 +274,28 @@
// - encrypted password matches // - encrypted password matches
// - plain password matches // - plain password matches
if (!$res["enabled"]) {
// user is 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 // user is locked, either set or auto set
elseif ($res['locked'])
{
$this->login_error = 105; $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)) {
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;
$this->login_error = 9999; // this means password cannot be decrypted because of missing crypt methods } 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 // 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 // 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 {
// nromal user processing // normal user processing
else
{
// set class var and session var // set class var and session var
$_SESSION["EUID"] = $this->euid = $res["edit_user_id"]; $_SESSION["EUID"] = $this->euid = $res["edit_user_id"];
// check if user is okay // check if user is okay
$this->login_check_permissions(); $this->login_check_permissions();
if (!$this->login_error) if (!$this->login_error) {
{
// now set all session vars and read page permissions // now set all session vars and read page permissions
$GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"]; $GLOBALS["DEBUG_ALL"] = $_SESSION["DEBUG_ALL"] = $res["debug"];
$GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"]; $GLOBALS["DB_DEBUG"] = $_SESSION["DB_DEBUG"] = $res["db_debug"];
@@ -322,8 +312,7 @@
$_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"]; $_SESSION["DEFAULT_CHARSET"] = $res["lang_iso"];
$_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"])); $_SESSION["DEFAULT_LANG"] = $res["lang_short"].'_'.strtolower(str_replace('-', '', $res["lang_iso"]));
// reset any login error count for this user // reset any login error count for this user
if ($res['login_error_count'] > 0) 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']; $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); $this->db_exec($q);
} }
@@ -335,8 +324,7 @@
$q .= "WHERE ep.edit_page_id = epa.edit_page_id AND ear.edit_access_right_id = epa.edit_access_right_id "; $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 .= "AND epa.enabled = 1 AND epa.edit_group_id = ".$res["edit_group_id"]." ";
$q .= "ORDER BY ep.order_number"; $q .= "ORDER BY ep.order_number";
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// page id array for sub data readout // page id array for sub data readout
$edit_page_ids[] = $res['edit_page_id']; $edit_page_ids[] = $res['edit_page_id'];
// create the array for pages // create the array for pages
@@ -357,15 +345,12 @@
)); ));
// make reference filename -> level // make reference filename -> level
$pages_acl[$res["filename"]] = $res["level"]; $pages_acl[$res["filename"]] = $res["level"];
} // for each page } // for each page
// get the visible groups for all pages and write them to the pages // get the visible groups for all pages and write them to the pages
$_edit_page_id = 0; $_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"; $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)) while ($res = $this->db_return($q)) {
{ if ($res['edit_page_id'] != $_edit_page_id) {
if ($res['edit_page_id'] != $_edit_page_id)
{
// search the pos in the array push // search the pos in the array push
$pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id');
$_edit_page_id = $res['edit_page_id']; $_edit_page_id = $res['edit_page_id'];
@@ -375,10 +360,8 @@
// get the same for the query strings // get the same for the query strings
$_edit_page_id = 0; $_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"; $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)) while ($res = $this->db_return($q)) {
{ if ($res['edit_page_id'] != $_edit_page_id) {
if ($res['edit_page_id'] != $_edit_page_id)
{
// search the pos in the array push // search the pos in the array push
$pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id'); $pos = $this->array_search_recursive($res['edit_page_id'], $pages, 'edit_page_id');
$_edit_page_id = $res['edit_page_id']; $_edit_page_id = $res['edit_page_id'];
@@ -400,13 +383,11 @@
$unit_access = array(); $unit_access = array();
$eauid = array(); $eauid = array();
$unit_acl = array(); $unit_acl = array();
while ($res = $this->db_return($q)) while ($res = $this->db_return($q)) {
{
// read edit access data fields and drop them into the unit access array // 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']; $q_sub ="SELECT name, value FROM edit_access_data WHERE enabled = 1 AND edit_access_id = ".$res['edit_access_id'];
$ea_data = array (); $ea_data = array ();
while ($res_sub = $this->db_return($q_sub)) while ($res_sub = $this->db_return($q_sub)) {
{
$ea_data[$res_sub['name']] = $res_sub['value']; $ea_data[$res_sub['name']] = $res_sub['value'];
} }
// build master unit array // build master unit array
@@ -421,8 +402,9 @@
'data' => $ea_data 'data' => $ea_data
); );
// set the default unit // set the default unit
if ($res['edit_default']) if ($res['edit_default']) {
$_SESSION["UNIT_DEFAULT"] = $res['edit_access_id']; $_SESSION["UNIT_DEFAULT"] = $res['edit_access_id'];
}
// sub arrays for simple access // sub arrays for simple access
array_push($eauid, $res['edit_access_id']); array_push($eauid, $res['edit_access_id']);
$unit_acl[$res['edit_access_id']] = $res['level']; $unit_acl[$res['edit_access_id']] = $res['level'];
@@ -432,21 +414,19 @@
$_SESSION['EAID'] = $eauid; $_SESSION['EAID'] = $eauid;
} // user has permission to THIS page } // user has permission to THIS page
} // user was not enabled or other login error } // user was not enabled or other login error
if ($this->login_error) if ($this->login_error) {
{ if ($res['login_error_count'] == 0) {
if ($res['login_error_count'] == 0)
$login_error_date_first = ', login_error_date_first = NOW()'; $login_error_date_first = ', login_error_date_first = NOW()';
}
// update login error count for this user // 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']; $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); $this->db_exec($q);
// totally lock the user if error max is reached // totally lock the user if error max is reached
if ($res['login_error_count'] + 1 > $this->max_login_error_count) if ($res['login_error_count'] + 1 > $this->max_login_error_count) {
{
// do some alert reporting in case this error is too big // do some alert reporting in case this error is too big
// if strict is set, lock this user // if strict is set, lock this user
// this needs manual unlocking by an admin user // this needs manual unlocking by an admin user
if ($res['strict'] && !in_array($this->username, $this->lock_deny_users)) 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']; $q = "UPDATE edit_user SET locked = 1 WHERE edit_user_id = ".$res['edit_user_id'];
} }
} }
@@ -454,8 +434,7 @@
} // user was not found } // user was not found
} // if not username AND password where given } // if not username AND password where given
// if there was an login error, show login screen // if there was an login error, show login screen
if ($this->login_error) if ($this->login_error) {
{
// reset the perm var, to confirm logout // reset the perm var, to confirm logout
$this->permission_okay = 0; $this->permission_okay = 0;
} }
@@ -468,8 +447,7 @@
// DESC : for every page the user access this script checks if he is allowed to do so // DESC : for every page the user access this script checks if he is allowed to do so
public function login_check_permissions() public function login_check_permissions()
{ {
if ($this->euid && $this->login_error != 103) if ($this->euid && $this->login_error != 103) {
{
$q = "SELECT filename "; $q = "SELECT filename ";
$q .= "FROM edit_page ep, edit_page_access epa, edit_group eg, edit_user eu "; $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 .= "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 ";
@@ -478,12 +456,9 @@
// unset mem limit if debug is set to 1 // 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) // if (($GLOBALS["DEBUG_ALL"] || $GLOBALS["DB_DEBUG"] || $_SESSION["DEBUG_ALL"] || $_SESSION["DB_DEBUG"]) && ini_get('memory_limit') != -1)
// ini_set('memory_limit', -1); // ini_set('memory_limit', -1);
if ($res["filename"] == $this->page_name) if ($res["filename"] == $this->page_name) {
{
$this->permission_okay = 1; $this->permission_okay = 1;
} } else {
else
{
$this->login_error = 103; $this->login_error = 103;
$this->permission_okay = 0; $this->permission_okay = 0;
} }
@@ -498,8 +473,7 @@
// DESC : if a user pressed on logout, destroyes session and unsets all global vars // DESC : if a user pressed on logout, destroyes session and unsets all global vars
public function login_logout_user() public function login_logout_user()
{ {
if ($this->logout || $this->login_error) if ($this->logout || $this->login_error) {
{
// unregister and destroy session vars // unregister and destroy session vars
unset($_SESSION["EUID"]); unset($_SESSION["EUID"]);
unset($_SESSION["GROUP_LEVEL"]); unset($_SESSION["GROUP_LEVEL"]);
@@ -544,28 +518,22 @@
$this->acl['base'] = DEFAULT_ACL_LEVEL; $this->acl['base'] = DEFAULT_ACL_LEVEL;
// set admin flag and base to 100 // set admin flag and base to 100
if ($_SESSION['ADMIN']) if ($_SESSION['ADMIN']) {
{
$this->acl['admin'] = 1; $this->acl['admin'] = 1;
$this->acl['base'] = 100; $this->acl['base'] = 100;
} } else {
else
{
// now go throw the flow and set the correct ACL // now go throw the flow and set the correct ACL
// user > page > group // user > page > group
// group ACL 0 // group ACL 0
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
{
$this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL']; $this->acl['base'] = $_SESSION['GROUP_ACL_LEVEL'];
} }
// page ACL 1 // page ACL 1
if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) if ($_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) {
{
$this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name]; $this->acl['base'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
} }
// user ACL 2 // user ACL 2
if ($_SESSION['USER_ACL_LEVEL'] != -1) if ($_SESSION['USER_ACL_LEVEL'] != -1) {
{
$this->acl['base'] = $_SESSION['USER_ACL_LEVEL']; $this->acl['base'] = $_SESSION['USER_ACL_LEVEL'];
} }
} }
@@ -575,29 +543,24 @@
// set group if not -1, overrides default // set group if not -1, overrides default
// set page if not -1, overrides group set // set page if not -1, overrides group set
$this->acl['page'] = DEFAULT_ACL_LEVEL; $this->acl['page'] = DEFAULT_ACL_LEVEL;
if ($_SESSION['GROUP_ACL_LEVEL'] != -1) if ($_SESSION['GROUP_ACL_LEVEL'] != -1) {
{
$this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL']; $this->acl['page'] = $_SESSION['GROUP_ACL_LEVEL'];
} }
if (isset($_SESSION['PAGES_ACL_LEVEL'][$this->page_name]) && $_SESSION['PAGES_ACL_LEVEL'][$this->page_name] != -1) 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]; $this->acl['page'] = $_SESSION['PAGES_ACL_LEVEL'][$this->page_name];
} }
// PER ACCOUNT (UNIT/edit access)-> // PER ACCOUNT (UNIT/edit access)->
foreach ($_SESSION['UNIT'] as $ea_id => $unit) foreach ($_SESSION['UNIT'] as $ea_id => $unit) {
{
// if admin flag is set, all units are set to 100 // if admin flag is set, all units are set to 100
if ($this->acl['admin']) 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']; $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 // detail name/level set
$this->acl['unit_detail'][$ea_id] = array ( $this->acl['unit_detail'][$ea_id] = array (
@@ -608,23 +571,22 @@
'data' => $unit['data'] 'data' => $unit['data']
); );
// set default // set default
if ($unit['default']) if ($unit['default']) {
{
$this->acl['unit_id'] = $unit['id']; $this->acl['unit_id'] = $unit['id'];
$this->acl['unit_name'] = $unit['name']; $this->acl['unit_name'] = $unit['name'];
$this->acl['unit_uid'] = $unit['uid']; $this->acl['unit_uid'] = $unit['uid'];
} }
} }
// flag if to show extra edit access drop downs (because user has multiple groups assigned) // flag if to show extra edit access drop downs (because user has multiple groups assigned)
if (count($_SESSION['UNIT']) > 1) if (count($_SESSION['UNIT']) > 1) {
$this->acl['show_ea_extra'] = 1; $this->acl['show_ea_extra'] = 1;
else } else {
$this->acl['show_ea_extra'] = 0; $this->acl['show_ea_extra'] = 0;
}
// set the default edit access // set the default edit access
$this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT']; $this->acl['default_edit_access'] = $_SESSION['UNIT_DEFAULT'];
// integrate the type acl list, but only for the keyword -> level // integrate the type acl list, but only for the keyword -> level
foreach ($this->default_acl_list as $level => $data) foreach ($this->default_acl_list as $level => $data) {
{
$this->acl['min'][$data['type']] = $level; $this->acl['min'][$data['type']] = $level;
} }
// set the full acl list too // set the full acl list too
@@ -639,11 +601,12 @@
// DESC : checks if this edit access id is valid // DESC : checks if this edit access id is valid
public function login_check_edit_access($edit_access_id) public function login_check_edit_access($edit_access_id)
{ {
if (array_key_exists($edit_access_id, $this->acl['unit'])) if (array_key_exists($edit_access_id, $this->acl['unit'])) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: login_password_change // METHOD: login_password_change
// PARAMS: none // PARAMS: none
@@ -651,70 +614,56 @@
// DESC : changes a user password // DESC : changes a user password
private function login_password_change() private function login_password_change()
{ {
if ($this->change_password) if ($this->change_password) {
{
$event = 'Password Change'; $event = 'Password Change';
// check that given username is NOT in the deny list, else silent skip (with error log) // 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 (!in_array($this->pw_username, $this->pw_change_deny_users)) {
{ if (!$this->pw_username || !$this->pw_password) {
if (!$this->pw_username || !$this->pw_password)
{
$this->login_error = 200; $this->login_error = 200;
$data = 'Missing username or old password.'; $data = 'Missing username or old password.';
} }
// check user exist, if not -> error // check user exist, if not -> error
if (!$this->login_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)."'"; $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); list ($edit_user_id) = $this->db_return_row($q);
if (!$edit_user_id) if (!$edit_user_id) {
{
// username wrong // username wrong
$this->login_error = 201; $this->login_error = 201;
$data = 'User could not be found'; $data = 'User could not be found';
} }
} }
// check old passwords match -> error // check old passwords match -> error
if (!$this->login_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)."'"; $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); list ($edit_user_id) = $this->db_return_row($q);
if (!$edit_user_id) if (!$edit_user_id) {
{
// old password wrong // old password wrong
$this->login_error = 202; $this->login_error = 202;
$data = 'The old password does not match'; $data = 'The old password does not match';
} }
} }
// check if new passwords were filled out -> error // check if new passwords were filled out -> error
if (!$this->login_error) if (!$this->login_error) {
{ if (!$this->pw_new_password || !$this->pw_new_password_confirm) {
if (!$this->pw_new_password || !$this->pw_new_password_confirm)
{
$this->login_error = 203; $this->login_error = 203;
$data = 'Missing new password or new password confirm.'; $data = 'Missing new password or new password confirm.';
} }
} }
// check new passwords both match -> error // check new passwords both match -> error
if (!$this->login_error) if (!$this->login_error) {
{ if ($this->pw_new_password != $this->pw_new_password_confirm) {
if ($this->pw_new_password != $this->pw_new_password_confirm)
{
$this->login_error = 204; $this->login_error = 204;
$data = 'The new passwords do not match: '.$this->pw_new_password.' == '.$this->pw_new_password_confirm; $data = 'The new passwords do not match: '.$this->pw_new_password.' == '.$this->pw_new_password_confirm;
} }
} }
// no error change this users password // no error change this users password
if (!$this->login_error) if (!$this->login_error) {
{
// update the user (edit_user_id) with the new password // 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; $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); $this->db_exec($q);
$data = 'Password change for user "'.$this->pw_username.'" from "'.$this->pw_old_password.'" to "'.$this->pw_new_password.'"'; $data = 'Password change for user "'.$this->pw_username.'" from "'.$this->pw_old_password.'" to "'.$this->pw_new_password.'"';
} }
} } else {
else
{
// illegal user error // illegal user error
$this->login_error = '220'; $this->login_error = '220';
$data = 'Illegal user for password change: '.$this->pw_username; $data = 'Illegal user for password change: '.$this->pw_username;
@@ -730,50 +679,47 @@
// DESC : prints out login html part if no permission (error) is set // DESC : prints out login html part if no permission (error) is set
private function login_print_login() private function login_print_login()
{ {
if (!$this->permission_okay) if (!$this->permission_okay) {
{
// set the templates now // set the templates now
$this->login_set_templates(); $this->login_set_templates();
// if there is a global logout target ... // if there is a global logout target ...
if (file_exists($this->logout_target) && $this->logout_target) if (file_exists($this->logout_target) && $this->logout_target) {
{
$LOGOUT_TARGET = $this->logout_target; $LOGOUT_TARGET = $this->logout_target;
} else } else {
{
$LOGOUT_TARGET = ""; $LOGOUT_TARGET = "";
} }
$html_string = $this->login_template['template']; $html_string = $this->login_template['template'];
// if password change is okay // if password change is okay
if ($this->password_change) if ($this->password_change) {
{
$html_string_password_change = $this->login_template['password_change']; $html_string_password_change = $this->login_template['password_change'];
// pre change the data in the PASSWORD_CHANGE_DIV first // pre change the data in the PASSWORD_CHANGE_DIV first
foreach ($this->login_template['strings'] as $string => $data) foreach ($this->login_template['strings'] as $string => $data) {
{ if ($data) {
if ($data)
$html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change); $html_string_password_change = str_replace("{".$string."}", $data, $html_string_password_change);
} }
}
$this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change; $this->login_template['strings']['PASSWORD_CHANGE_DIV'] = $html_string_password_change;
} }
// put in the logout redirect string // put in the logout redirect string
if ($this->logout && $LOGOUT_TARGET) if ($this->logout && $LOGOUT_TARGET) {
$html_string = str_replace("{LOGOUT_TARGET}", '<meta http-equiv="refresh" content="0; URL='.$LOGOUT_TARGET.'">', $html_string); $html_string = str_replace("{LOGOUT_TARGET}", '<meta http-equiv="refresh" content="0; URL='.$LOGOUT_TARGET.'">', $html_string);
else } else {
$html_string = str_replace("{LOGOUT_TARGET}", '', $html_string); $html_string = str_replace("{LOGOUT_TARGET}", '', $html_string);
}
// print error messagae // print error messagae
if ($this->login_error) if ($this->login_error) {
$html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."<br>", $html_string); $html_string = str_replace("{ERROR_MSG}", $this->login_error_msg[$this->login_error]."<br>", $html_string);
else } else {
$html_string = str_replace("{ERROR_MSG}", "<br>", $html_string); $html_string = str_replace("{ERROR_MSG}", "<br>", $html_string);
}
// create the replace array context // create the replace array context
foreach ($this->login_template['strings'] as $string => $data) foreach ($this->login_template['strings'] as $string => $data) {
{
$html_string = str_replace("{".$string."}", $data, $html_string); $html_string = str_replace("{".$string."}", $data, $html_string);
} }
@@ -789,20 +735,19 @@
private function login_close_class() private function login_close_class()
{ {
// write to LOG table ... // write to LOG table ...
if ($this->login_error || $this->login || $this->logout) if ($this->login_error || $this->login || $this->logout) {
{
$username = ''; $username = '';
$password = ''; $password = '';
// set event // set event
if ($this->login) if ($this->login) {
$event = "Login"; $event = "Login";
else if ($this->logout) } elseif ($this->logout) {
$event = "Logout"; $event = "Logout";
else } else {
$event = "No Permission"; $event = "No Permission";
}
// prepare for log // prepare for log
if ($this->euid) if ($this->euid) {
{
// get user from user table // get user from user table
$q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid; $q = "SELECT username, password FROM edit_user WHERE edit_user_id = ".$this->euid;
list($username, $password) = $this->db_return_row($q); list($username, $password) = $this->db_return_row($q);
@@ -811,12 +756,9 @@
} // write log under certain settings } // write log under certain settings
// now close DB connection // now close DB connection
// $this->error_msg = $this->_login(); // $this->error_msg = $this->_login();
if (!$this->permission_okay) if (!$this->permission_okay) {
{
return false; return false;
} } else {
else
{
return true; return true;
} }
} }
@@ -857,8 +799,7 @@
); );
// if password change is okay // if password change is okay
if ($this->password_change) if ($this->password_change) {
{
$strings = array_merge($strings, array ( $strings = array_merge($strings, array (
'TITLE_PASSWORD_CHANGE' => 'Change Password for User', 'TITLE_PASSWORD_CHANGE' => 'Change Password for User',
'OLD_PASSWORD' => $this->l->__("Old Password"), 'OLD_PASSWORD' => $this->l->__("Old Password"),
@@ -881,9 +822,7 @@
</table> </table>
</div> </div>
EOM; EOM;
} } else {
else
{
$strings = array_merge($strings, array ( $strings = array_merge($strings, array (
'JS_SHOW_HIDE' => '', 'JS_SHOW_HIDE' => '',
'PASSWORD_CHANGE_BUTTON' => '', 'PASSWORD_CHANGE_BUTTON' => '',
@@ -892,26 +831,21 @@ EOM;
} }
// first check if all strings are set from outside, if not, set with default ones // first check if all strings are set from outside, if not, set with default ones
while (list($string, $data) = each($strings)) while (list($string, $data) = each($strings)) {
{ if (!array_key_exists($string, $this->login_template['strings'])) {
if (!array_key_exists($string, $this->login_template['strings']))
{
$this->login_template['strings'][$string] = $data; $this->login_template['strings'][$string] = $data;
} }
} }
// error msgs the same // error msgs the same
while (list($code, $data) = each($error_msgs)) while (list($code, $data) = each($error_msgs)) {
{ if (!array_key_exists($code, $this->login_error_msg)) {
if (!array_key_exists($code, $this->login_error_msg))
{
$this->login_error_msg[$code] = $data; $this->login_error_msg[$code] = $data;
} }
} }
// now check templates // now check templates
if (!$this->login_template['template']) if (!$this->login_template['template']) {
{
$this->login_template['template'] = <<<EOM $this->login_template['template'] = <<<EOM
<html> <html>
<head> <head>
@@ -937,37 +871,36 @@ h3 { font-size: 18px; }
<form method="post"> <form method="post">
<table width="500" border="0" cellpadding="2" cellspacing="1"> <table width="500" border="0" cellpadding="2" cellspacing="1">
<tr> <tr>
<td class="norm" align="right"> <td class="norm" align="right">
<h3>{TITLE}</h3> <h3>{TITLE}</h3>
</td> </td>
<td>&nbsp;</td> <td>&nbsp;</td>
</tr> </tr>
<tr> <tr>
<td class="norm" colspan="2" align="center"> <td class="norm" colspan="2" align="center">
{ERROR_MSG} {ERROR_MSG}
</td> </td>
</tr> </tr>
<tr> <tr>
<td align="right" class="norm">{USERNAME}</td> <td align="right" class="norm">{USERNAME}</td>
<td><input type="text" name="login_username"></td> <td><input type="text" name="login_username"></td>
</tr> </tr>
<tr> <tr>
<td align="right" class="norm">{PASSWORD}</td> <td align="right" class="norm">{PASSWORD}</td>
<td><input type="password" name="login_password"></td> <td><input type="password" name="login_password"></td>
</tr> </tr>
<tr> <tr>
<td align="right"> <td align="right"></td>
</td> <td>
<td>
<input type="submit" name="login_login" value="{LOGIN}"> <input type="submit" name="login_login" value="{LOGIN}">
{PASSWORD_CHANGE_BUTTON} {PASSWORD_CHANGE_BUTTON}
</td> </td>
</tr> </tr>
<tr> <tr>
<td align="right"> <td align="right">
<br><br> <br><br>
</td> </td>
<td>&nbsp;</td> <td>&nbsp;</td>
</tr> </tr>
</table> </table>
{PASSWORD_CHANGE_DIV} {PASSWORD_CHANGE_DIV}
@@ -986,10 +919,11 @@ EOM;
// DESC : writes detailed data into the edit user log table (keep log what user does) // DESC : writes detailed data into the edit user log table (keep log what user does)
private function write_log($event, $data, $error = "", $username = "", $password = "") private function write_log($event, $data, $error = "", $username = "", $password = "")
{ {
if ($this->login) if ($this->login) {
$this->action = 'Login'; $this->action = 'Login';
elseif ($this->logout) } elseif ($this->logout) {
$this->action = 'Logout'; $this->action = 'Logout';
}
$_data_binary = array ( $_data_binary = array (
'_SESSION' => $_SESSION, '_SESSION' => $_SESSION,
'_GET' => $_GET, '_GET' => $_GET,
@@ -1003,14 +937,15 @@ EOM;
$q .= "(username, password, euid, event_date, event, error, data, data_binary, page, "; $q .= "(username, password, euid, event_date, event, error, 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 .= "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 .= "action, action_id, action_yes, action_flag, action_menu, action_loaded, action_value, action_error) ";
$q .= "VALUES ('".$this->db_escape_string($username)."', '".$this->db_escape_string($password)."', ".(($this->euid) ? $this->euid : 'NULL').", NOW(), '".$this->db_escape_string($event)."', '".$this->db_escape_string($error)."', '".$this->db_escape_string($data)."', '".$data_binary."', '".$this->page_name."', "; $q .= "VALUES ('".$this->db_escape_string($username)."', '".$this->db_escape_string($password)."', ".(($this->euid) ? $this->euid : 'NULL').", ";
foreach (array('REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING') as $server_code) $q .= "NOW(), '".$this->db_escape_string($event)."', '".$this->db_escape_string($error)."', '".$this->db_escape_string($data)."', '".$data_binary."', '".$this->page_name."', ";
{ foreach (array('REMOTE_ADDR', 'HTTP_USER_AGENT', 'HTTP_REFERER', 'SCRIPT_FILENAME', 'QUERY_STRING', 'SERVER_NAME', 'HTTP_HOST', 'HTTP_ACCEPT', 'HTTP_ACCEPT_CHARSET', 'HTTP_ACCEPT_ENCODING') as $server_code) {
if (array_key_exists($server_code, $_SERVER)) if (array_key_exists($server_code, $_SERVER)) {
$q .= "'".$this->db_escape_string($_SERVER[$server_code])."', "; $q .= "'".$this->db_escape_string($_SERVER[$server_code])."', ";
else } else {
$q .= "NULL, "; $q .= "NULL, ";
} }
}
$q .= "'".session_id()."', "; $q .= "'".session_id()."', ";
$q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->username)."', NULL, '".$this->db_escape_string($this->login_error)."', NULL, NULL, '".$this->db_escape_string($this->permission_okay)."', NULL)"; $q .= "'".$this->db_escape_string($this->action)."', '".$this->db_escape_string($this->username)."', NULL, '".$this->db_escape_string($this->login_error)."', NULL, NULL, '".$this->db_escape_string($this->permission_okay)."', NULL)";
$this->db_exec($q, 'NULL'); $this->db_exec($q, 'NULL');
@@ -1022,11 +957,12 @@ EOM;
// DESC : checks that the given edit access id is valid for this user // DESC : checks that the given edit access id is valid for this user
public function login_check_edit_access_id($edit_access_id) public function login_check_edit_access_id($edit_access_id)
{ {
if (!array_key_exists($edit_access_id, $_SESSION["UNIT"])) if (!array_key_exists($edit_access_id, $_SESSION["UNIT"])) {
return $_SESSION["UNIT_DEFAULT"]; return $_SESSION["UNIT_DEFAULT"];
else } else {
return $edit_access_id; return $edit_access_id;
} }
}
// METHOD: login_set_edit_access_data // METHOD: login_set_edit_access_data
// PARAMS: edit access id, key value to search for // PARAMS: edit access id, key value to search for
@@ -1034,11 +970,10 @@ EOM;
// DESC : searchs in the data set for the unit for the data key and returns the value asociated with it // DESC : searchs in the data set for the unit for the data key and returns the value asociated with it
public function login_set_edit_access_data($edit_access_id, $data_key) public function login_set_edit_access_data($edit_access_id, $data_key)
{ {
if (!$_SESSION['UNIT'][$edit_access_id]['data'][$data_key]) if (!$_SESSION['UNIT'][$edit_access_id]['data'][$data_key]) {
return false; return false;
else } else {
return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key]; return $_SESSION['UNIT'][$edit_access_id]['data'][$data_key];
} }
}
} // close class } // close class
?>
+104 -102
View File
@@ -73,10 +73,12 @@ class ProgressBar
public function __construct($width = 0, $height = 0) public function __construct($width = 0, $height = 0)
{ {
$this->code = substr(md5(microtime()), 0, 6); $this->code = substr(md5(microtime()), 0, 6);
if ($width > 0) if ($width > 0) {
$this->width = $width; $this->width = $width;
if ($height > 0) }
if ($height > 0) {
$this->height = $height; $this->height = $height;
}
// needs to be called twice or I do not get any output // needs to be called twice or I do not get any output
$this->_flushCache($this->clear_buffer_size_init); $this->_flushCache($this->clear_buffer_size_init);
$this->_flushCache($this->clear_buffer_size_init); $this->_flushCache($this->clear_buffer_size_init);
@@ -86,8 +88,9 @@ class ProgressBar
private function _flushCache($clear_buffer_size = 0) private function _flushCache($clear_buffer_size = 0)
{ {
if (!$clear_buffer_size) if (!$clear_buffer_size) {
$clear_buffer_size = $this->clear_buffer_size; $clear_buffer_size = $this->clear_buffer_size;
}
echo str_repeat(' ', $clear_buffer_size); echo str_repeat(' ', $clear_buffer_size);
ob_flush(); ob_flush();
flush(); flush();
@@ -96,18 +99,19 @@ class ProgressBar
private function _calculatePercent($step) private function _calculatePercent($step)
{ {
// avoid divison through 0 // avoid divison through 0
if ($this->max - $this->min == 0) if ($this->max - $this->min == 0) {
$this->max ++; $this->max ++;
}
$percent = round(($step - $this->min) / ($this->max - $this->min) * 100); $percent = round(($step - $this->min) / ($this->max - $this->min) * 100);
if ($percent > 100) if ($percent > 100) {
$percent = 100; $percent = 100;
}
return $percent; return $percent;
} }
private function _calculatePosition($step) private function _calculatePosition($step)
{ {
switch ($this->direction) switch ($this->direction) {
{
case 'right': case 'right':
case 'left': case 'left':
$bar = $this->width; $bar = $this->width;
@@ -118,16 +122,18 @@ class ProgressBar
break; break;
} }
// avoid divison through 0 // avoid divison through 0
if ($this->max - $this->min == 0) if ($this->max - $this->min == 0) {
$this->max ++; $this->max ++;
}
$pixel = round(($step - $this->min) * ($bar - ($this->pedding * 2)) / ($this->max - $this->min)); $pixel = round(($step - $this->min) * ($bar - ($this->pedding * 2)) / ($this->max - $this->min));
if ($step <= $this->min) if ($step <= $this->min) {
$pixel = 0; $pixel = 0;
if ($step >= $this->max) }
if ($step >= $this->max) {
$pixel = $bar - ($this->pedding * 2); $pixel = $bar - ($this->pedding * 2);
}
switch ($this->direction) switch ($this->direction) {
{
case 'right': case 'right':
$position['left'] = $this->pedding; $position['left'] = $this->pedding;
$position['top'] = $this->pedding; $position['top'] = $this->pedding;
@@ -158,10 +164,12 @@ class ProgressBar
private function _setStep($step) private function _setStep($step)
{ {
if ($step > $this->max) if ($step > $this->max) {
$step = $this->max; $step = $this->max;
if ($step < $this->min) }
if ($step < $this->min) {
$step = $this->min; $step = $this->min;
}
$this->step = $step; $this->step = $step;
} }
@@ -179,16 +187,17 @@ class ProgressBar
'brd_color' => '#dfdfdf #404040 #404040 #dfdfdf' 'brd_color' => '#dfdfdf #404040 #404040 #dfdfdf'
); );
if ($width > 0) if ($width > 0) {
$this->frame['width'] = $width; $this->frame['width'] = $width;
if ($height > 0) }
if ($height > 0) {
$this->frame['height'] = $height; $this->frame['height'] = $height;
} }
}
public function addLabel($type, $name, $value = '&nbsp;') public function addLabel($type, $name, $value = '&nbsp;')
{ {
switch($type) switch ($type) {
{
case 'text': case 'text':
$this->label[$name] = array( $this->label[$name] = array(
'type' => 'text', 'type' => 'text',
@@ -242,10 +251,11 @@ class ProgressBar
case 'percentlbl': case 'percentlbl':
case 'percent': case 'percent':
// check font size // check font size
if ($this->height <= 11) if ($this->height <= 11) {
$font_size = $this->height - 1; $font_size = $this->height - 1;
else } else {
$font_size = 11; $font_size = 11;
}
$this->label[$name] = array( $this->label[$name] = array(
'type' => $type, // either percent or percentlbl 'type' => $type, // either percent or percentlbl
'value' => $value, 'value' => $value,
@@ -288,23 +298,23 @@ class ProgressBar
$this->label[$name]['target'] = $target; $this->label[$name]['target'] = $target;
} }
public function setLabelPosition($name, $left, $top, $width, $height, $align='') public function setLabelPosition($name, $left, $top, $width, $height, $align = '')
{ {
// print "SET POSITION[$name]: $left<br>"; // print "SET POSITION[$name]: $left<br>";
// if this is percent, we ignore anything, it is auto positioned // if this is percent, we ignore anything, it is auto positioned
if ($this->label[$name]['type'] != 'percent') if ($this->label[$name]['type'] != 'percent') {
{ foreach (array('top', 'left', 'width', 'height') as $pos_name) {
if ($$pos_name !== false) {
foreach (array('top', 'left', 'width', 'height') as $pos_name)
if ($$pos_name !== false)
$this->label[$name][$pos_name] = intval($$pos_name); $this->label[$name][$pos_name] = intval($$pos_name);
}
}
if ($align != '') if ($align != '') {
$this->label[$name]['align'] = $align; $this->label[$name]['align'] = $align;
} }
}
// init // init
if ($this->status != 'new') if ($this->status != 'new') {
{
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.top="'.$this->label[$name]['top'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.top="'.$this->label[$name]['top'].'px";';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.left="'.$this->label[$name]['left'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.left="'.$this->label[$name]['left'].'px";';
@@ -320,8 +330,7 @@ class ProgressBar
public function setLabelColor($name, $color) public function setLabelColor($name, $color)
{ {
$this->label[$name]['color'] = $color; $this->label[$name]['color'] = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.color="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.color="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -330,8 +339,7 @@ class ProgressBar
public function setLabelBackground($name, $color) public function setLabelBackground($name, $color)
{ {
$this->label[$name]['bgr_color'] = $color; $this->label[$name]['bgr_color'] = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("plbl'.$name.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -340,24 +348,28 @@ class ProgressBar
public function setLabelFont($name, $size, $family = '', $weight = '') public function setLabelFont($name, $size, $family = '', $weight = '')
{ {
// just in case if it is too small // just in case if it is too small
if (intval($size) < 0) if (intval($size) < 0) {
$size = 11; $size = 11;
}
// if this is percent, the size is not allowed to be bigger than the bar size - 5px // if this is percent, the size is not allowed to be bigger than the bar size - 5px
if ($this->label[$name]['type'] == 'percent' && intval($size) >= $this->height) if ($this->label[$name]['type'] == 'percent' && intval($size) >= $this->height) {
$size = $this->height - 1; $size = $this->height - 1;
}
// position the label new if this is percent // position the label new if this is percent
if ($this->label[$name]['type'] == 'percent') if ($this->label[$name]['type'] == 'percent') {
$this->label[$name]['top'] = round(($this->height - intval($size)) / log($this->height - intval($size), 7), 0) - $this->pedding; $this->label[$name]['top'] = round(($this->height - intval($size)) / log($this->height - intval($size), 7), 0) - $this->pedding;
}
// print "HEIGHT: ".$this->height.", Size: ".intval($size).", Pedding: ".$this->pedding.", Calc: ".round($this->height - intval($size)).", Log: ".log($this->height - intval($size), 7)."<br>"; // print "HEIGHT: ".$this->height.", Size: ".intval($size).", Pedding: ".$this->pedding.", Calc: ".round($this->height - intval($size)).", Log: ".log($this->height - intval($size), 7)."<br>";
// then set like usual // then set like usual
$this->label[$name]['font-size'] = intval($size); $this->label[$name]['font-size'] = intval($size);
if ($family != '') if ($family != '') {
$this->label[$name]['font-family'] = $family; $this->label[$name]['font-family'] = $family;
if ($weight != '') }
if ($weight != '') {
$this->label[$name]['font-weight'] = $weight; $this->label[$name]['font-weight'] = $weight;
}
if ($this->status != 'new') if ($this->status != 'new') {
{
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-size="'.$this->label[$name]['font-size'].'px";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-size="'.$this->label[$name]['font-size'].'px";';
$output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-family="'.$this->label[$name]['font-family'].'";'; $output .= 'document.getElementById("plbl'.$name.$this->code.'").style.font-family="'.$this->label[$name]['font-family'].'";';
@@ -372,8 +384,7 @@ class ProgressBar
{ {
$this->label[$name]['value'] = $value; $this->label[$name]['value'] = $value;
// print "NAME[$name], Status: ".$this->status.": ".$value."<Br>"; // print "NAME[$name], Status: ".$this->status.": ".$value."<Br>";
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">PBlabelText'.$this->code.'("'.$name.'","'.$this->label[$name]['value'].'");</script>'."\n"; echo '<script type="text/JavaScript">PBlabelText'.$this->code.'("'.$name.'","'.$this->label[$name]['value'].'");</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -382,8 +393,7 @@ class ProgressBar
public function setBarColor($color) public function setBarColor($color)
{ {
$this->color = $color; $this->color = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("pbar'.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("pbar'.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -392,8 +402,7 @@ class ProgressBar
public function setBarBackground($color) public function setBarBackground($color)
{ {
$this->bgr_color = $color; $this->bgr_color = $color;
if ($this->status != 'new') if ($this->status != 'new') {
{
echo '<script type="text/JavaScript">document.getElementById("pbrd'.$this->code.'").style.background="'.$color.'";</script>'."\n"; echo '<script type="text/JavaScript">document.getElementById("pbrd'.$this->code.'").style.background="'.$color.'";</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -403,8 +412,7 @@ class ProgressBar
{ {
$this->direction = $direction; $this->direction = $direction;
if ($this->status != 'new') if ($this->status != 'new') {
{
$this->position = $this->_calculatePosition($this->step); $this->position = $this->_calculatePosition($this->step);
echo '<script type="text/JavaScript">'; echo '<script type="text/JavaScript">';
@@ -426,25 +434,30 @@ class ProgressBar
$this->_setStep($this->step); $this->_setStep($this->step);
$this->position = $this->_calculatePosition($this->step); $this->position = $this->_calculatePosition($this->step);
if ($this->top || $this->left) if ($this->top || $this->left) {
$style_master = 'position:relative;top:'.$this->top.'px;left:'.$this->left.'px;width:'.($this->width + 10).'px;'; $style_master = 'position:relative;top:'.$this->top.'px;left:'.$this->left.'px;width:'.($this->width + 10).'px;';
}
$html = '<div id="pbm'.$this->code.'" style="'.$style_master.'background:'.$this->bgr_color_master.';">'; $html = '<div id="pbm'.$this->code.'" style="'.$style_master.'background:'.$this->bgr_color_master.';">';
$style_brd = 'width:'.$this->width.'px;height:'.$this->height.'px;background:'.$this->bgr_color.';'; $style_brd = 'width:'.$this->width.'px;height:'.$this->height.'px;background:'.$this->bgr_color.';';
if ($this->border > 0) if ($this->border > 0) {
$style_brd .= 'border:'.$this->border.'px solid; border-color:'.$this->brd_color.'; -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;'; $style_brd .= 'border:'.$this->border.'px solid; border-color:'.$this->brd_color.'; -webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;';
}
$style_bar = 'position:relative;width:'.$this->position['width'].'px;height:'.$this->position['height'].'px;background:'.$this->color.';'; $style_bar = 'position:relative;width:'.$this->position['width'].'px;height:'.$this->position['height'].'px;background:'.$this->color.';';
if ($this->position['top'] !== false) if ($this->position['top'] !== false) {
$style_bar .= 'top:'.$this->position['top'].'px;'; $style_bar .= 'top:'.$this->position['top'].'px;';
if ($this->position['left'] !== false) }
if ($this->position['left'] !== false) {
$style_bar .= 'left:'.$this->position['left'].'px;'; $style_bar .= 'left:'.$this->position['left'].'px;';
if ($this->border > 0) }
if ($this->border > 0) {
$style_bar .= '-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;'; $style_bar .= '-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px; -webkit-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.25) inset;';
}
if ($this->frame['show'] == true) if ($this->frame['show'] == true) {
{ if ($this->frame['border'] > 0) {
if ($this->frame['border'] > 0)
$border = 'border:'.$this->frame['border'].'px solid;border-color:'.$this->frame['brd_color'].';margin-top:2px;-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px;'; $border = 'border:'.$this->frame['border'].'px solid;border-color:'.$this->frame['brd_color'].';margin-top:2px;-webkit-border-radius: 5px 5px 5px 5px; border-radius: 5px 5px 5px 5px;';
}
$html .= '<div id="pfrm'.$this->code.'" style="width:'.$this->frame['width'].'px;height:'.$this->frame['height'].'px;'.$border.'background:'.$this->frame['color'].';">'."\n"; $html .= '<div id="pfrm'.$this->code.'" style="width:'.$this->frame['width'].'px;height:'.$this->frame['height'].'px;'.$border.'background:'.$this->frame['color'].';">'."\n";
} }
@@ -465,34 +478,39 @@ class ProgressBar
$js .= '}'."\n"; $js .= '}'."\n";
//print "DUMP LABEL: <br><pre>".print_r($this->label, 1)."</pre><br>"; //print "DUMP LABEL: <br><pre>".print_r($this->label, 1)."</pre><br>";
foreach ($this->label as $name => $data) foreach ($this->label as $name => $data) {
{
// set what type of move we do // set what type of move we do
$move_prefix = $data['type'] == 'button' ? 'margin' : 'padding'; $move_prefix = $data['type'] == 'button' ? 'margin' : 'padding';
$style_lbl = 'position:relative;'; $style_lbl = 'position:relative;';
if ($data['top'] !== false) if ($data['top'] !== false) {
$style_lbl .= $move_prefix.'-top:'.$data['top'].'px;'; $style_lbl .= $move_prefix.'-top:'.$data['top'].'px;';
if ($data['left'] !== false) }
if ($data['left'] !== false) {
$style_lbl .= $move_prefix.'-left:'.$data['left'].'px;'; $style_lbl .= $move_prefix.'-left:'.$data['left'].'px;';
}
$style_lbl .= 'text-align:'.$data['align'].';'; $style_lbl .= 'text-align:'.$data['align'].';';
if ($data['width'] > 0) if ($data['width'] > 0) {
$style_lbl .= 'width:'.$data['width'].'px;'; $style_lbl .= 'width:'.$data['width'].'px;';
if ($data['height'] > 0) }
if ($data['height'] > 0) {
$style_lbl .= 'height:'.$data['height'].'px;'; $style_lbl .= 'height:'.$data['height'].'px;';
}
if (array_key_exists('font-size', $data)) if (array_key_exists('font-size', $data)) {
$style_lbl .= 'font-size:'.$data['font-size'].'px;'; $style_lbl .= 'font-size:'.$data['font-size'].'px;';
if (array_key_exists('font-family', $data)) }
if (array_key_exists('font-family', $data)) {
$style_lbl .= 'font-family:'.$data['font-family'].';'; $style_lbl .= 'font-family:'.$data['font-family'].';';
if (array_key_exists('font-weight', $data)) }
if (array_key_exists('font-weight', $data)) {
$style_lbl .= 'font-weight:'.$data['font-weight'].';'; $style_lbl .= 'font-weight:'.$data['font-weight'].';';
if (array_key_exists('bgr_color', $data) && ($data['bgr_color'] != '')) }
if (array_key_exists('bgr_color', $data) && ($data['bgr_color'] != '')) {
$style_lbl .= 'background:'.$data['bgr_color'].';'; $style_lbl .= 'background:'.$data['bgr_color'].';';
}
if (array_key_exists('type', $data)) if (array_key_exists('type', $data)) {
{ switch ($data['type']) {
switch ($data['type'])
{
case 'text': case 'text':
$html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'margin-bottom:2px;">'.$data['value'].'</div>'."\n"; $html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'margin-bottom:2px;">'.$data['value'].'</div>'."\n";
break; break;
@@ -505,8 +523,9 @@ class ProgressBar
case 'percent': case 'percent':
// only one inner percent // only one inner percent
// print "STYLE[$name]: ".$style_lbl."<br>"; // print "STYLE[$name]: ".$style_lbl."<br>";
if (!$html_percent) if (!$html_percent) {
$html_percent = '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;line-height:1;text-shadow: 0 0 .2em white, 0 0 .5em white;">'.$this->_calculatePercent($this->step).'%</div>'."\n"; $html_percent = '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;line-height:1;text-shadow: 0 0 .2em white, 0 0 .5em white;">'.$this->_calculatePercent($this->step).'%</div>'."\n";
}
break; break;
case 'percentlbl': case 'percentlbl':
$html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;">'.$this->_calculatePercent($this->step).'%</div>'."\n"; $html .= '<div id="plbl'.$name.$this->code.'" style="'.$style_lbl.'width:'.$data['width'].'px;">'.$this->_calculatePercent($this->step).'%</div>'."\n";
@@ -535,17 +554,14 @@ class ProgressBar
$html .= $html_bar_bottom; $html .= $html_bar_bottom;
$html .= $html_button; // any buttons on bottom $html .= $html_button; // any buttons on bottom
if (count($this->label) > 0) if (count($this->label) > 0) {
{
$js .= 'function PBlabelText'.$this->code.'(name,text) {'."\n"; $js .= 'function PBlabelText'.$this->code.'(name,text) {'."\n";
$js .= ' name = "plbl" + name + "'.$this->code.'";'."\n"; $js .= ' name = "plbl" + name + "'.$this->code.'";'."\n";
$js .= ' document.getElementById(name).innerHTML=text;'."\n"; $js .= ' document.getElementById(name).innerHTML=text;'."\n";
$js .= '}'."\n"; $js .= '}'."\n";
} }
if ($this->frame['show'] == true) if ($this->frame['show'] == true) {
{
$html .= '</div>'."\n"; $html .= '</div>'."\n";
} }
@@ -572,40 +588,31 @@ class ProgressBar
$js = ''; $js = '';
$new_position = $this->_calculatePosition($this->step); $new_position = $this->_calculatePosition($this->step);
if ($new_position['width'] != $this->position['width'] && ($this->direction == 'right' || $this->direction == 'left')) if ($new_position['width'] != $this->position['width'] && ($this->direction == 'right' || $this->direction == 'left')) {
{ if ($this->direction=='left') {
if ($this->direction=='left')
{
$js .= 'PBposition'.$this->code.'("left",'.$new_position['left'].');'; $js .= 'PBposition'.$this->code.'("left",'.$new_position['left'].');';
} }
$js .= 'PBposition'.$this->code.'("width",'.$new_position['width'].');'; $js .= 'PBposition'.$this->code.'("width",'.$new_position['width'].');';
} }
if ($new_position['height'] != $this->position['height'] && ($this->direction == 'up' || $this->direction == 'down')) if ($new_position['height'] != $this->position['height'] && ($this->direction == 'up' || $this->direction == 'down')) {
{ if ($this->direction=='up') {
if ($this->direction=='up')
{
$js .= 'PBposition'.$this->code.'("top",'.$new_position['top'].');'; $js .= 'PBposition'.$this->code.'("top",'.$new_position['top'].');';
} }
$js .= 'PBposition'.$this->code.'("height",'.$new_position['height'].');'; $js .= 'PBposition'.$this->code.'("height",'.$new_position['height'].');';
} }
$this->position = $new_position; $this->position = $new_position;
foreach($this->label as $name => $data) foreach ($this->label as $name => $data) {
{ if (array_key_exists('type', $data)) {
if (array_key_exists('type', $data)) switch($data['type']) {
{
switch($data['type'])
{
case 'step': case 'step':
if ($this->step != $last_step) if ($this->step != $last_step) {
{
$js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$this->step.'/'.$this->max.'");'; $js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$this->step.'/'.$this->max.'");';
} }
break; break;
case 'percentlbl': case 'percentlbl':
case 'percent': case 'percent':
$percent = $this->_calculatePercent($this->step); $percent = $this->_calculatePercent($this->step);
if ($percent != $this->_calculatePercent($last_step)) if ($percent != $this->_calculatePercent($last_step)) {
{
$js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$percent.'%");'; $js .= 'PBlabelText'.$this->code.'("'.$name.'","'.$percent.'%");';
} }
break; break;
@@ -615,8 +622,7 @@ class ProgressBar
} }
} }
} }
if ($js != '') if ($js != '') {
{
echo '<script type="text/JavaScript">'.$js.'</script>'."\n"; echo '<script type="text/JavaScript">'.$js.'</script>'."\n";
$this->_flushCache(); $this->_flushCache();
} }
@@ -634,8 +640,7 @@ class ProgressBar
public function hide() public function hide()
{ {
if ($this->status == 'show') if ($this->status == 'show') {
{
$this->status = 'hide'; $this->status = 'hide';
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
@@ -648,8 +653,7 @@ class ProgressBar
public function unhide() public function unhide()
{ {
if ($this->status == 'hide') if ($this->status == 'hide') {
{
$this->status = 'show'; $this->status = 'show';
$output = '<script type="text/JavaScript">'; $output = '<script type="text/JavaScript">';
@@ -659,6 +663,4 @@ class ProgressBar
$this->_flushCache(); $this->_flushCache();
} }
} }
} }
?>
+15 -17
View File
@@ -1,20 +1,20 @@
<? <?
/******************************************************************** /********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2004/12/21 * CREATED: 2004/12/21
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* extends smarty with the l10n class so I can use __(, etc calls * extends smarty with the l10n class so I can use __(, etc calls
* HISTORY: * HISTORY:
* 2005/06/22 (cs) include smarty class here, so there is no need to include it in the main file * 2005/06/22 (cs) include smarty class here, so there is no need to include it in the main file
*********************************************************************/ *********************************************************************/
// read in the Smarty class for definition // read in the Smarty class for definition
// use smarty BC for backwards compability // use smarty BC for backwards compability
// try to include file from LIBS path, or from normal path // try to include file from LIBS path, or from normal path
_spl_autoload('SmartyBC.class.php'); _spl_autoload('SmartyBC.class.php');
class SmartyML extends SmartyBC class SmartyML extends SmartyBC
{ {
public $l10n; public $l10n;
// constructor class, just sets the language stuff // constructor class, just sets the language stuff
@@ -26,6 +26,4 @@
// variable variable register // variable variable register
$this->register_modifier('getvar', array(&$this, 'get_template_vars')); $this->register_modifier('getvar', array(&$this, 'get_template_vars'));
} }
}
}
?>
+44 -43
View File
@@ -1,33 +1,33 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2004/11/18 * CREATED: 2004/11/18
* VERSION: 0.1.1 * VERSION: 0.1.1
* RELEASED LICENSE: GNU GPL 3 * RELEASED LICENSE: GNU GPL 3
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* init class for gettext. Original was just a function & var setting include for wordpress. * init class for gettext. Original was just a function & var setting include for wordpress.
* I changed that to a class to be more portable with my style of coding * I changed that to a class to be more portable with my style of coding
* *
* PUBLIC VARIABLES * PUBLIC VARIABLES
* *
* PRIVATE VARIABLES * PRIVATE VARIABLES
* *
* PUBLIC METHODS * PUBLIC METHODS
* __: returns string (translated or original if not found) * __: returns string (translated or original if not found)
* _e: echos out string (translated or original if not found) * _e: echos out string (translated or original if not found)
* __ngettext: should return plural. never tested this. * __ngettext: should return plural. never tested this.
* *
* PRIVATE METHODS * PRIVATE METHODS
* *
* HISTORY: * HISTORY:
* 2005/10/17 (cs) made an on the fly switch method (reload of lang) * 2005/10/17 (cs) made an on the fly switch method (reload of lang)
*********************************************************************/ *********************************************************************/
// try to include file from LIBS path, or from normal path // try to include file from LIBS path, or from normal path
_spl_autoload('Class.Basic.inc'); _spl_autoload('Class.Basic.inc');
class l10n extends basic class l10n extends basic
{ {
private $lang = ''; private $lang = '';
private $mofile = ''; private $mofile = '';
private $input; private $input;
@@ -35,26 +35,30 @@
public function __construct($lang = '', $path = DEFAULT_TEMPLATE) public function __construct($lang = '', $path = DEFAULT_TEMPLATE)
{ {
foreach (array('streams.php', 'gettext.php') as $include_file) foreach (array('streams.php', 'gettext.php') as $include_file) {
_spl_autoload($include_file); _spl_autoload($include_file);
}
if (!$lang) if (!$lang) {
$this->lang = 'en'; $this->lang = 'en';
else } else {
$this->lang = $lang; $this->lang = $lang;
}
if (is_dir(LAYOUT.$path.LANG)) if (is_dir(LAYOUT.$path.LANG)) {
$path = LAYOUT.$path.LANG; $path = LAYOUT.$path.LANG;
elseif (!is_dir($path)) } elseif (!is_dir($path)) {
$path = ''; $path = '';
}
$this->mofile = $path.$this->lang.".mo"; $this->mofile = $path.$this->lang.".mo";
// check if get a readable mofile // check if get a readable mofile
if (is_readable($this->mofile)) if (is_readable($this->mofile)) {
$this->input = new FileReader($this->mofile); $this->input = new FileReader($this->mofile);
else } else {
$this->input = false; $this->input = false;
}
$this->l10n = new gettext_reader($this->input); $this->l10n = new gettext_reader($this->input);
} }
@@ -67,21 +71,19 @@
$this->lang = $lang; $this->lang = $lang;
if (is_dir(LAYOUT.$path.LANG)) if (is_dir(LAYOUT.$path.LANG)) {
$path = LAYOUT.$path.LANG; $path = LAYOUT.$path.LANG;
elseif (!is_dir($path)) } elseif (!is_dir($path)) {
$path = ''; $path = '';
}
$this->mofile = $path.$this->lang.".mo"; $this->mofile = $path.$this->lang.".mo";
// check if get a readable mofile // check if get a readable mofile
if (is_readable($this->mofile)) if (is_readable($this->mofile)) {
{
$this->input = new FileReader($this->mofile); $this->input = new FileReader($this->mofile);
$this->l10n = new gettext_reader($this->input); $this->l10n = new gettext_reader($this->input);
} } else {
else
{
// else fall back to the old ones // else fall back to the old ones
$this->mofile = $old_mofile; $this->mofile = $old_mofile;
$this->lang = $old_lang; $this->lang = $old_lang;
@@ -113,5 +115,4 @@
{ {
return $this->mofile; return $this->mofile;
} }
} }
?>
+34 -37
View File
@@ -1,26 +1,26 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens Schwaighofer * AUTHOR: Clemens Schwaighofer
* CREATED: 2011/2/8 * CREATED: 2011/2/8
* DESCRIPTION: pre function to collect all non critical errors into a log file if possible * DESCRIPTION: pre function to collect all non critical errors into a log file if possible
* include this file at the very beginning of the script to get the notices, strict, etc messages. * include this file at the very beginning of the script to get the notices, strict, etc messages.
* error etc will still be written to the log/display * error etc will still be written to the log/display
*********************************************************************/ *********************************************************************/
// define the base working directory outside because in the function it might return undefined // define the base working directory outside because in the function it might return undefined
DEFINE('CURRENT_WORKING_DIR', getcwd().'/'); DEFINE('CURRENT_WORKING_DIR', getcwd().'/');
// METHOD: MyErrorHandler // METHOD: MyErrorHandler
// PARAMS: $type: the error code from PHP // PARAMS: $type: the error code from PHP
// $message: the error message from php // $message: the error message from php
// $file: in which file the error happend. this is the source file (eg include) // $file: in which file the error happend. this is the source file (eg include)
// $line: in which line the error happened // $line: in which line the error happened
// $context: array with all the variable // $context: array with all the variable
// RETURN: true, so cought errors do not get processed by the PHP error engine // RETURN: true, so cought errors do not get processed by the PHP error engine
// DESC: will catch any error except E_ERROR and try to write them to the log file in log/php_error-<DAY>.llog // DESC: will catch any error except E_ERROR and try to write them to the log file in log/php_error-<DAY>.llog
// if this fails, it will print the data to the window via echo // if this fails, it will print the data to the window via echo
function MyErrorHandler ($type, $message, $file, $line, $context) function MyErrorHandler($type, $message, $file, $line, $context)
{ {
if (!(error_reporting() & $type) && !SHOW_ALL_ERRORS) { if (!(error_reporting() & $type) && !SHOW_ALL_ERRORS) {
// This error code is not included in error_reporting // This error code is not included in error_reporting
return; return;
@@ -59,34 +59,31 @@
$ROOT = CURRENT_WORKING_DIR; $ROOT = CURRENT_WORKING_DIR;
$LOG = 'log/'; $LOG = 'log/';
// if the log folder is not found, try to create it // if the log folder is not found, try to create it
if (!is_dir($ROOT.$LOG) && !is_file($ROOT.LOG)) if (!is_dir($ROOT.$LOG) && !is_file($ROOT.LOG)) {
$ok = mkdir($ROOT.$LOG); $ok = mkdir($ROOT.$LOG);
}
$error = 0; $error = 0;
// again, if the folder now exists, else set error flag // again, if the folder now exists, else set error flag
if (is_dir($ROOT.$LOG)) if (is_dir($ROOT.$LOG)) {
{
$fn = $ROOT.$LOG.'php_errors-'.date('Y-m-d').'.log'; $fn = $ROOT.$LOG.'php_errors-'.date('Y-m-d').'.log';
// when opening, surpress the warning so we can catch the no file pointer below without throwing a warning for this // when opening, surpress the warning so we can catch the no file pointer below without throwing a warning for this
$fp = @fopen($fn, 'a'); $fp = @fopen($fn, 'a');
// write if we have a file pointer, else set error flag // write if we have a file pointer, else set error flag
if ($fp) if ($fp) {
{
fwrite($fp, $output."\n"); fwrite($fp, $output."\n");
fclose($fp); fclose($fp);
} } else {
else
$error = 1; $error = 1;
} }
else } else {
$error = 1; $error = 1;
}
// if the above writing failed // if the above writing failed
if ($error) if ($error) {
{
// if the display errors is on // if the display errors is on
// pretty print output for HTML // pretty print output for HTML
if (ini_get("display_errors")) if (ini_get("display_errors")) {
{
echo "<div style='border: 1px dotted red; background-color: #ffffe5; color: #000000; padding: 5px; margin-bottom: 2px;'>"; echo "<div style='border: 1px dotted red; background-color: #ffffe5; color: #000000; padding: 5px; margin-bottom: 2px;'>";
echo "<div style='color: orange; font-weight: bold;'>".$error_level[$type].":</div>"; echo "<div style='color: orange; font-weight: bold;'>".$error_level[$type].":</div>";
echo "<b>$message</b> on line <b>$line</b> in <b>$file</b>"; echo "<b>$message</b> on line <b>$line</b> in <b>$file</b>";
@@ -94,14 +91,14 @@
} }
// if write to log is on // if write to log is on
// simplified, remove datetime for log file // simplified, remove datetime for log file
if (ini_get('log_errors')) if (ini_get('log_errors')) {
error_log('{'.$page_temp.'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message); error_log('{'.$page_temp.'} ['.$file.'] <'.$line.'> ['.$error_level[$type].'|'.$type.']: '.$message);
} }
}
// return true, to avoid that php calls its own error stuff // return true, to avoid that php calls its own error stuff
// if E_ERROR, the php one gets called anyway // if E_ERROR, the php one gets called anyway
return true; return true;
} }
// init the error handler // init the error handler
set_error_handler("MyErrorHandler"); set_error_handler("MyErrorHandler");
?>
+44 -29
View File
@@ -3,18 +3,20 @@
/** /**
* Handle file uploads via XMLHttpRequest * Handle file uploads via XMLHttpRequest
*/ */
class qqUploadedFileXhr { class qqUploadedFileXhr
{
/** /**
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save($path)
{
$input = fopen("php://input", "r"); $input = fopen("php://input", "r");
$temp = tmpfile(); $temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp); $realSize = stream_copy_to_stream($input, $temp);
fclose($input); fclose($input);
if ($realSize != $this->getSize()){ if ($realSize != $this->getSize()) {
return false; return false;
} }
@@ -25,11 +27,13 @@ class qqUploadedFileXhr {
return true; return true;
} }
function getName() { public function getName()
{
return $_GET['qqfile']; return $_GET['qqfile'];
} }
function getSize() { public function getSize()
if (isset($_SERVER["CONTENT_LENGTH"])){ {
if (isset($_SERVER["CONTENT_LENGTH"])) {
return (int)$_SERVER["CONTENT_LENGTH"]; return (int)$_SERVER["CONTENT_LENGTH"];
} else { } else {
throw new Exception('Getting content length is not supported.'); throw new Exception('Getting content length is not supported.');
@@ -40,31 +44,37 @@ class qqUploadedFileXhr {
/** /**
* Handle file uploads via regular form post (uses the $_FILES array) * Handle file uploads via regular form post (uses the $_FILES array)
*/ */
class qqUploadedFileForm { class qqUploadedFileForm
{
/** /**
* Save the file to the specified path * Save the file to the specified path
* @return boolean TRUE on success * @return boolean TRUE on success
*/ */
function save($path) { public function save($path)
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){ {
if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
return false; return false;
} }
return true; return true;
} }
function getName() { public function getName()
{
return $_FILES['qqfile']['name']; return $_FILES['qqfile']['name'];
} }
function getSize() { public function getSize()
{
return $_FILES['qqfile']['size']; return $_FILES['qqfile']['size'];
} }
} }
class qqFileUploader { class qqFileUploader
{
private $allowedExtensions = array(); private $allowedExtensions = array();
private $sizeLimit = 10485760; private $sizeLimit = 10485760;
private $file; private $file;
function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){ public function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760)
{
$allowedExtensions = array_map("strtolower", $allowedExtensions); $allowedExtensions = array_map("strtolower", $allowedExtensions);
$this->allowedExtensions = $allowedExtensions; $this->allowedExtensions = $allowedExtensions;
@@ -81,23 +91,30 @@ class qqFileUploader {
} }
} }
private function checkServerSettings(){ private function checkServerSettings()
{
$postSize = $this->toBytes(ini_get('post_max_size')); $postSize = $this->toBytes(ini_get('post_max_size'));
$uploadSize = $this->toBytes(ini_get('upload_max_filesize')); $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){ if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit) {
$size = max(1, $this->sizeLimit / 1024 / 1024) . 'M'; $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
die("{'error':'increase post_max_size and upload_max_filesize to $size'}"); die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
} }
} }
private function toBytes($str){ private function toBytes($str)
{
$val = trim($str); $val = trim($str);
$last = strtolower($str[strlen($str)-1]); $last = strtolower($str[strlen($str)-1]);
switch($last) { switch ($last) {
case 'g': $val *= 1024; case 'g':
case 'm': $val *= 1024; $val *= 1024;
case 'k': $val *= 1024; // no break
case 'm':
$val *= 1024;
// no break
case 'k':
$val *= 1024;
} }
return $val; return $val;
} }
@@ -105,12 +122,13 @@ class qqFileUploader {
/** /**
* Returns array('success'=>true) or array('error'=>'error message') * Returns array('success'=>true) or array('error'=>'error message')
*/ */
function handleUpload($uploadDirectory, $replaceOldFile = FALSE){ public function handleUpload($uploadDirectory, $replaceOldFile = false)
if (!is_writable($uploadDirectory)){ {
if (!is_writable($uploadDirectory)) {
return array('error' => "Server error. Upload directory isn't writable."); return array('error' => "Server error. Upload directory isn't writable.");
} }
if (!$this->file){ if (!$this->file) {
return array('error' => 'No files were uploaded.'); return array('error' => 'No files were uploaded.');
} }
@@ -129,12 +147,12 @@ class qqFileUploader {
//$filename = md5(uniqid()); //$filename = md5(uniqid());
$ext = $pathinfo['extension']; $ext = $pathinfo['extension'];
if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){ if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)) {
$these = implode(', ', $this->allowedExtensions); $these = implode(', ', $this->allowedExtensions);
return array('error' => 'File has an invalid extension, it should be one of '. $these . '.'); return array('error' => 'File has an invalid extension, it should be one of '. $these . '.');
} }
if(!$replaceOldFile){ if (!$replaceOldFile) {
/// don't overwrite previous files that were uploaded /// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) { while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99); $filename .= rand(10, 99);
@@ -144,14 +162,11 @@ class qqFileUploader {
$this->uploadFileName = $uploadDirectory . $filename . '.' . $ext; $this->uploadFileName = $uploadDirectory . $filename . '.' . $ext;
$this->uploadFileExt = $ext; $this->uploadFileExt = $ext;
if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){ if ($this->file->save($uploadDirectory . $filename . '.' . $ext)) {
return array('success'=>true); return array('success'=>true);
} else { } else {
return array('error'=> 'Could not save uploaded file.' . return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered'); 'The upload was cancelled, or server error encountered');
} }
} }
} }
?>
+60 -70
View File
@@ -1,41 +1,41 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/04/09 * CREATED: 2003/04/09
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* pgsq; wrapper calls * pgsq; wrapper calls
* HISTORY: * HISTORY:
* 2008/04/16 (cs) wrapper for pg escape string * 2008/04/16 (cs) wrapper for pg escape string
* 2007/01/11 (cs) add prepare/execute for postgres * 2007/01/11 (cs) add prepare/execute for postgres
* 2006/09/12 (cs) in case db_query retuns false, save the query and run the query through the send/get procedure to get correct error data from the db * 2006/09/12 (cs) in case db_query retuns false, save the query and run the query through the send/get procedure to get correct error data from the db
* 2006/06/26 (cs) added port for db connection * 2006/06/26 (cs) added port for db connection
* 2006/04/03 (cs) added meta data for table * 2006/04/03 (cs) added meta data for table
* 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working * 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working
* 2005/07/07 (cs) the default it is table_name _ id * 2005/07/07 (cs) the default it is table_name _ id
* 2005/01/19 (cs) changed the pgsql connect, so it dies if it can't connect to the DB * 2005/01/19 (cs) changed the pgsql connect, so it dies if it can't connect to the DB
* 2004/09/30 (cs) layout cleanup * 2004/09/30 (cs) layout cleanup
* / * /
/* collection of PostgreSQL wrappers /* collection of PostgreSQL wrappers
* REQUIRES 5.4 PHP!!! (should do check for this) * REQUIRES 5.4 PHP!!! (should do check for this)
* *
* pg_prepare * pg_prepare
* pg_execute * pg_execute
* pg_num_rows * pg_num_rows
* pg_num_fields * pg_num_fields
* pg_field_name * pg_field_name
* pg_affected_rows (*) * pg_affected_rows (*)
* pg_fetch_array * pg_fetch_array
* pg_query * pg_query
* pg_close * pg_close
* pg_connect (*) * pg_connect (*)
* pg_meta_data * pg_meta_data
* pg_escape_string * pg_escape_string
* *
*/ */
trait db_pgsql trait db_pgsql
{ {
private $last_error_query; private $last_error_query;
private $currval_query; private $currval_query;
@@ -47,8 +47,7 @@
{ {
// read out the query status and save the query if needed // read out the query status and save the query if needed
$result = @pg_query($dbh, $query); $result = @pg_query($dbh, $query);
if (!$result) if (!$result) {
{
$this->last_error_query = $query; $this->last_error_query = $query;
} }
return $result; return $result;
@@ -136,22 +135,21 @@
private function _db_insert_id($dbh, $query, $pk_name) private function _db_insert_id($dbh, $query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list($schema, $table) = explode('.', $_table); list ($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plurar, make it singular // if name is plurar, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
// set pk_name to "id" // set pk_name to "id"
$pk_name = $table."_id"; $pk_name = $table."_id";
} }
@@ -160,12 +158,9 @@
$this->currval_query = $q; $this->currval_query = $q;
//echo "Q: $q<Br>"; //echo "Q: $q<Br>";
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
if ($q = @pg_query($dbh, $q)) if ($q = @pg_query($dbh, $q)) {
{
list($id) = pg_fetch_array($q); list($id) = pg_fetch_array($q);
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -179,13 +174,11 @@
private function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') private function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
$this->dbh = @pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl); $this->dbh = @pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl);
if (!$this->dbh) if (!$this->dbh) {
{
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->");
} }
return $this->dbh; return $this->dbh;
@@ -198,15 +191,15 @@
private function _db_print_error($dbh, $cursor = '') private function _db_print_error($dbh, $cursor = '')
{ {
// run the query again for the error result here // run the query again for the error result here
if (!$cursor && $this->last_error_query) if (!$cursor && $this->last_error_query) {
{
pg_send_query($dbh, $this->last_error_query); pg_send_query($dbh, $this->last_error_query);
$this->last_error_query = ""; $this->last_error_query = "";
$cursor = pg_get_result($dbh); $cursor = pg_get_result($dbh);
} }
if (pg_result_error($cursor)) if (pg_result_error($cursor)) {
return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>"; return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>";
} }
}
// METHOD: _db_meta_data // METHOD: _db_meta_data
// PARAMS: database handler, table name // PARAMS: database handler, table name
@@ -243,27 +236,24 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
private function _db_array_parse($text, &$output, $limit = false, $offset = 1) private function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>
+89 -96
View File
@@ -1,47 +1,46 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2003/04/09 * CREATED: 2003/04/09
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* pgsql wrapper calls * pgsql wrapper calls
* HISTORY: * HISTORY:
* 2008/04/16 (cs) wrapper for pg escape string * 2008/04/16 (cs) wrapper for pg escape string
* 2007/01/11 (cs) add prepare/execute for postgres * 2007/01/11 (cs) add prepare/execute for postgres
* 2006/09/12 (cs) in case db_query retuns false, save the query and run the query through the send/get procedure to get correct error data from the db * 2006/09/12 (cs) in case db_query retuns false, save the query and run the query through the send/get procedure to get correct error data from the db
* 2006/06/26 (cs) added port for db connection * 2006/06/26 (cs) added port for db connection
* 2006/04/03 (cs) added meta data for table * 2006/04/03 (cs) added meta data for table
* 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working * 2005/07/25 (cs) removed the plural s remove, not needed and not 100% working
* 2005/07/07 (cs) the default it is table_name _ id * 2005/07/07 (cs) the default it is table_name _ id
* 2005/01/19 (cs) changed the pgsql connect, so it dies if it can't connect to the DB * 2005/01/19 (cs) changed the pgsql connect, so it dies if it can't connect to the DB
* 2004/09/30 (cs) layout cleanup * 2004/09/30 (cs) layout cleanup
* / * /
* collection of PostgreSQL wrappers * collection of PostgreSQL wrappers
* REQUIRES 5.x PHP!!! * REQUIRES 5.x PHP!!!
* *
* pg_prepare * pg_prepare
* pg_execute * pg_execute
* pg_num_rows * pg_num_rows
* pg_num_fields * pg_num_fields
* pg_field_name * pg_field_name
* pg_affected_rows (*) * pg_affected_rows (*)
* pg_fetch_array * pg_fetch_array
* pg_query * pg_query
* pg_send_query * pg_send_query
* pg_get_result * pg_get_result
* pg_connection_busy * pg_connection_busy
* pg_close * pg_close
* pg_connect (*) * pg_connect (*)
* pg_meta_data * pg_meta_data
* pg_escape_string * pg_escape_string
* *
*/ */
class db_pgsql class db_pgsql
{ {
private $last_error_query; private $last_error_query;
private $dbh; private $dbh;
// public $currval_query;
// METHOD: __construct // METHOD: __construct
// PARAMS: none // PARAMS: none
@@ -53,11 +52,12 @@
public function _db_last_error_query() public function _db_last_error_query()
{ {
if ($this->last_error_query) if ($this->last_error_query) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: _db_query // METHOD: _db_query
// PARAMS: query // PARAMS: query
@@ -68,8 +68,9 @@
$this->last_error_query = ''; $this->last_error_query = '';
// read out the query status and save the query if needed // read out the query status and save the query if needed
$result = pg_query($this->dbh, $query); $result = pg_query($this->dbh, $query);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -90,8 +91,9 @@
{ {
$this->last_error_query = ''; $this->last_error_query = '';
$result = pg_get_result($this->dbh); $result = pg_get_result($this->dbh);
if ($error = pg_result_error($result)) if ($error = pg_result_error($result)) {
$this->last_error_query = $error; $this->last_error_query = $error;
}
return $result; return $result;
} }
@@ -101,10 +103,12 @@
// DESC : wrapper for pg_close // DESC : wrapper for pg_close
public function _db_close() public function _db_close()
{ {
if (is_resource($this->dbh)) if (is_resource($this->dbh)) {
if (pg_connection_status($this->dbh) === PGSQL_CONNECTION_OK) if (pg_connection_status($this->dbh) === PGSQL_CONNECTION_OK) {
pg_close($this->dbh); pg_close($this->dbh);
} }
}
}
// METHOD: _db_prepare // METHOD: _db_prepare
// PARAMS: prepare name, query // PARAMS: prepare name, query
@@ -113,8 +117,9 @@
public function _db_prepare($name, $query) public function _db_prepare($name, $query)
{ {
$result = pg_prepare($this->dbh, $name, $query); $result = pg_prepare($this->dbh, $name, $query);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -125,8 +130,9 @@
public function _db_execute($name, $data) public function _db_execute($name, $data)
{ {
$result = pg_execute($this->dbh, $name, $data); $result = pg_execute($this->dbh, $name, $data);
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $result; return $result;
} }
@@ -164,11 +170,12 @@
public function _db_fetch_array($cursor, $result_type = '') public function _db_fetch_array($cursor, $result_type = '')
{ {
// result type is passed on as is [should be checked] // result type is passed on as is [should be checked]
if ($result_type) if ($result_type) {
return pg_fetch_array($cursor, NULL, $result_type); return pg_fetch_array($cursor, null, $result_type);
else } else {
return pg_fetch_array($cursor); return pg_fetch_array($cursor);
} }
}
// METHOD: _db_fetch_all // METHOD: _db_fetch_all
// PARAMS: cursor // PARAMS: cursor
@@ -198,36 +205,31 @@
public function _db_insert_id($query, $pk_name) public function _db_insert_id($query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
$schema = ''; $schema = '';
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list($schema, $table) = explode('.', $_table); list($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plurar, make it singular // if name is plurar, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
// set pk_name to "id" // set pk_name to "id"
$pk_name = $table."_id"; $pk_name = $table."_id";
} }
$seq = (($schema) ? $schema.'.' : '').$table."_".$pk_name."_seq"; $seq = (($schema) ? $schema.'.' : '').$table."_".$pk_name."_seq";
$q = "SELECT CURRVAL('$seq') AS insert_id"; $q = "SELECT CURRVAL('$seq') AS insert_id";
// $this->currval_query = $q;
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
if ($q = $this->_db_query($q)) if ($q = $this->_db_query($q)) {
{
list($id) = $this->_db_fetch_array($q); list($id) = $this->_db_fetch_array($q);
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -240,17 +242,14 @@
// DESC : queries database for the primary key name to this table in the selected schema // DESC : queries database for the primary key name to this table in the selected schema
public function _db_primary_key($table, $schema = '') public function _db_primary_key($table, $schema = '')
{ {
if ($table) if ($table) {
{
// check if schema set is different from schema given, only needed if schema is not empty // check if schema set is different from schema given, only needed if schema is not empty
$table_prefix = ''; $table_prefix = '';
if ($schema) if ($schema) {
{
$q = "SHOW search_path"; $q = "SHOW search_path";
$cursor = $this->_db_query($q); $cursor = $this->_db_query($q);
$search_path = $this->_db_fetch_array($cursor)['search_path']; $search_path = $this->_db_fetch_array($cursor)['search_path'];
if ($search_path != $schema) if ($search_path != $schema) {
{
$table_prefix = $schema.'.'; $table_prefix = $schema.'.';
} }
} }
@@ -258,14 +257,14 @@
// faster primary key get // faster primary key get
$q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "; $q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type ";
$q .= "FROM pg_index, pg_class, pg_attribute "; $q .= "FROM pg_index, pg_class, pg_attribute ";
if ($schema) if ($schema) {
$q .= ", pg_namespace "; $q .= ", pg_namespace ";
}
$q .= "WHERE "; $q .= "WHERE ";
// regclass translates the OID to the name // regclass translates the OID to the name
$q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND "; $q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND ";
$q .= "indrelid = pg_class.oid AND "; $q .= "indrelid = pg_class.oid AND ";
if ($schema) if ($schema) {
{
$q .= "nspname = '".$schema."' AND "; $q .= "nspname = '".$schema."' AND ";
$q .= "pg_class.relnamespace = pg_namespace.oid AND "; $q .= "pg_class.relnamespace = pg_namespace.oid AND ";
} }
@@ -273,13 +272,12 @@
$q .= "pg_attribute.attnum = any(pg_index.indkey) "; $q .= "pg_attribute.attnum = any(pg_index.indkey) ";
$q .= "AND indisprimary"; $q .= "AND indisprimary";
$cursor = $this->_db_query($q); $cursor = $this->_db_query($q);
if ($cursor) if ($cursor) {
return $this->_db_fetch_array($cursor)['column_name']; return $this->_db_fetch_array($cursor)['column_name'];
else } else {
return false; return false;
} }
else } else {
{
return false; return false;
} }
} }
@@ -291,13 +289,11 @@
public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
$this->dbh = pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl); $this->dbh = pg_connect("host=".$db_host." port=".$db_port." user=".$db_user." password=".$db_pass." dbname=".$db_name." sslmode=".$db_ssl);
if (!$this->dbh) if (!$this->dbh) {
{
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."] //-->");
} }
return $this->dbh; return $this->dbh;
@@ -310,15 +306,15 @@
public function _db_print_error($cursor = '') public function _db_print_error($cursor = '')
{ {
// run the query again for the error result here // run the query again for the error result here
if (!$cursor && $this->last_error_query) if (!$cursor && $this->last_error_query) {
{
pg_send_query($this->dbh, $this->last_error_query); pg_send_query($this->dbh, $this->last_error_query);
$this->last_error_query = ''; $this->last_error_query = '';
$cursor = pg_get_result($this->dbh); $cursor = pg_get_result($this->dbh);
} }
if (pg_result_error($cursor)) if (pg_result_error($cursor)) {
return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>"; return "<span style=\"color: red;\"><b>-PostgreSQL-Error-></b> ".pg_result_error($cursor)."</span><br>";
} }
}
// METHOD: _db_meta_data // METHOD: _db_meta_data
// PARAMS: table name // PARAMS: table name
@@ -376,27 +372,24 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
public function _db_array_parse($text, &$output, $limit = false, $offset = 1) public function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>
+67 -81
View File
@@ -1,19 +1,19 @@
<? <?
/********************************************************************* /*********************************************************************
* AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org) * AUTHOR: Clemens "Gullevek" Schwaighofer (www.gullevek.org)
* CREATED: 2014/12/3 * CREATED: 2014/12/3
* SHORT DESCRIPTION: * SHORT DESCRIPTION:
* pgsql pdo wrapper calls * pgsql pdo wrapper calls
* HISTORY: * HISTORY:
* / * /
/* collection of PostgreSQL wrappers /* collection of PostgreSQL wrappers
* REQUIRES 5.x PHP with compiled pdo pgsql (--with-pdo-pgsql) * REQUIRES 5.x PHP with compiled pdo pgsql (--with-pdo-pgsql)
* *
*/ */
class db_pgsql class db_pgsql
{ {
private $last_error_query; private $last_error_query;
private $dbh; private $dbh;
private $cursor = array(); private $cursor = array();
@@ -28,11 +28,12 @@
public function _db_last_error_query() public function _db_last_error_query()
{ {
if ($this->last_error_query) if ($this->last_error_query) {
return true; return true;
else } else {
return false; return false;
} }
}
// METHOD: _db_query // METHOD: _db_query
// PARAMS: query // PARAMS: query
@@ -47,8 +48,9 @@
$this->last_error_query = $query; */ $this->last_error_query = $query; */
$cursor = $this->_db_prepare(md5($query), $query); $cursor = $this->_db_prepare(md5($query), $query);
$result = $this->_db_execute(md5($query), array ()); $result = $this->_db_execute(md5($query), array ());
if (!$result) if (!$result) {
$this->last_error_query = $query; $this->last_error_query = $query;
}
return $cursor; return $cursor;
} }
@@ -67,7 +69,7 @@
// DESC : sends an async query to the server // DESC : sends an async query to the server
public function _db_send_query($query) public function _db_send_query($query)
{ {
// return @pg_send_query($this->dbh, $query); // return @pg_send_query($this->dbh, $query);
} }
// METHOD: _db_get_result // METHOD: _db_get_result
@@ -78,8 +80,9 @@
{ {
$this->last_error_query = ''; $this->last_error_query = '';
/* $result = pg_get_result($this->dbh); /* $result = pg_get_result($this->dbh);
if ($error = pg_result_error($result)) if ($error = pg_result_error($result)) {
$this->last_error_query = $error; */ $this->last_error_query = $error;
}*/
return $result; return $result;
} }
@@ -89,10 +92,8 @@
// DESC : wrapper for pg_close // DESC : wrapper for pg_close
public function _db_close() public function _db_close()
{ {
if (is_array($this->cursor)) if (is_array($this->cursor)) {
{ foreach ($this->cursor as $key => $data) {
foreach ($this->cursor as $key => $data)
{
$this->cursor[$key]->closeCursor; $this->cursor[$key]->closeCursor;
$this->cursor[$key] = null; $this->cursor[$key] = null;
} }
@@ -106,7 +107,7 @@
// DESC : wrapper for pg_prepare // DESC : wrapper for pg_prepare
public function _db_prepare($name, $query) public function _db_prepare($name, $query)
{ {
// return @pg_prepare($this->dbh, $name, $query); // return @pg_prepare($this->dbh, $name, $query);
$this->cursor[$name] = $this->dbh->prepare($query); $this->cursor[$name] = $this->dbh->prepare($query);
return $this->cursor[$name]; return $this->cursor[$name];
} }
@@ -117,7 +118,7 @@
// DESC : wrapper for pg_execute for running a prepared statement // DESC : wrapper for pg_execute for running a prepared statement
public function _db_execute($name, $data) public function _db_execute($name, $data)
{ {
// return @pg_execute($this->dbh, $name, $data); // return @pg_execute($this->dbh, $name, $data);
return $this->cursor[$name]->execute($data); return $this->cursor[$name]->execute($data);
} }
@@ -127,7 +128,7 @@
// DESC : wrapper for pg_num_rows // DESC : wrapper for pg_num_rows
public function _db_num_rows($cursor) public function _db_num_rows($cursor)
{ {
// return pg_num_rows($cursor); // return pg_num_rows($cursor);
return $cusor->rowCount(); return $cusor->rowCount();
} }
@@ -137,7 +138,7 @@
// DESC : wrapper for pg_num_fields // DESC : wrapper for pg_num_fields
public function _db_num_fields($cursor) public function _db_num_fields($cursor)
{ {
// return pg_num_fields($cursor); // return pg_num_fields($cursor);
return $cursor->columnCount(); return $cursor->columnCount();
} }
@@ -147,7 +148,7 @@
// DESC : wrapper for pg_field_name // DESC : wrapper for pg_field_name
public function _db_field_name($cursor, $i) public function _db_field_name($cursor, $i)
{ {
// return pg_field_name($cursor, $i); // return pg_field_name($cursor, $i);
} }
// METHOD: _db_fetch_array // METHOD: _db_fetch_array
@@ -156,7 +157,7 @@
// DESC : wrapper for pg_fetch_array // DESC : wrapper for pg_fetch_array
public function _db_fetch_array($cursor) public function _db_fetch_array($cursor)
{ {
// return pg_fetch_array($cursor); // return pg_fetch_array($cursor);
return $cursor->fetch(); return $cursor->fetch();
} }
@@ -166,7 +167,7 @@
// DESC : wrapper for pg_affected_rows // DESC : wrapper for pg_affected_rows
public function _db_affected_rows($cursor) public function _db_affected_rows($cursor)
{ {
// return pg_affected_rows($cursor); // return pg_affected_rows($cursor);
return $cusor->rowCount(); return $cusor->rowCount();
} }
@@ -180,23 +181,22 @@
public function _db_insert_id($query, $pk_name) public function _db_insert_id($query, $pk_name)
{ {
// only if an insert has been done // only if an insert has been done
if (preg_match("/^insert /i", $query)) if (preg_match("/^insert /i", $query)) {
{
$schema = ''; $schema = '';
// get table name from insert // get table name from insert
$array = explode(' ', $query); $array = explode(' ', $query);
$_table = $array[2]; $_table = $array[2];
// if there is a dot inside, we need to split // if there is a dot inside, we need to split
if (strstr($_table, '.')) if (strstr($_table, '.')) {
list($schema, $table) = explode('.', $_table); list($schema, $table) = explode('.', $_table);
else } else {
$table = $_table; $table = $_table;
}
// no PK name given at all // no PK name given at all
if (!$pk_name) if (!$pk_name) {
{
// if name is plural, make it singular // if name is plural, make it singular
// if (preg_match("/.*s$/i", $table)) // if (preg_match("/.*s$/i", $table))
// $table = substr($table, 0, -1); // $table = substr($table, 0, -1);
// set pk_name to "id" // set pk_name to "id"
$pk_name = $table."_id"; $pk_name = $table."_id";
} }
@@ -204,12 +204,9 @@
$q = "SELECT CURRVAL('$seq') AS insert_id"; $q = "SELECT CURRVAL('$seq') AS insert_id";
// I have to do manually or I overwrite the original insert internal vars ... // I have to do manually or I overwrite the original insert internal vars ...
$row = $this->_db_query_result($q); $row = $this->_db_query_result($q);
if ($row['insert_id']) if ($row['insert_id']) {
{
$id = $row['insert_id']; $id = $row['insert_id'];
} } else {
else
{
$id = array(-1, $q); $id = array(-1, $q);
} }
return $id; return $id;
@@ -222,18 +219,15 @@
// DESC : queries database for the primary key name to this table in the selected schema // DESC : queries database for the primary key name to this table in the selected schema
public function _db_primary_key($table, $schema = '') public function _db_primary_key($table, $schema = '')
{ {
if ($table) if ($table) {
{
// check if schema set is different from schema given, only needed if schema is not empty // check if schema set is different from schema given, only needed if schema is not empty
$table_prefix = ''; $table_prefix = '';
if ($schema) if ($schema) {
{
$q = "SHOW search_path"; $q = "SHOW search_path";
// $cursor = $this->_db_query($q); // $cursor = $this->_db_query($q);
// $search_path = $this->_db_fetch_array($cursor)['search_path']; // $search_path = $this->_db_fetch_array($cursor)['search_path'];
$search_path = $this->_db_query_result($q)['search_path']; $search_path = $this->_db_query_result($q)['search_path'];
if ($search_path != $schema) if ($search_path != $schema) {
{
$table_prefix = $schema.'.'; $table_prefix = $schema.'.';
} }
} }
@@ -241,14 +235,14 @@
// faster primary key get // faster primary key get
$q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type "; $q = "SELECT pg_attribute.attname AS column_name, format_type(pg_attribute.atttypid, pg_attribute.atttypmod) AS type ";
$q .= "FROM pg_index, pg_class, pg_attribute "; $q .= "FROM pg_index, pg_class, pg_attribute ";
if ($schema) if ($schema) {
$q .= ", pg_namespace "; $q .= ", pg_namespace ";
}
$q .= "WHERE "; $q .= "WHERE ";
// regclass translates the OID to the name // regclass translates the OID to the name
$q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND "; $q .= "pg_class.oid = '".$table_prefix.$table."'::regclass AND ";
$q .= "indrelid = pg_class.oid AND "; $q .= "indrelid = pg_class.oid AND ";
if ($schema) if ($schema) {
{
$q .= "nspname = '".$schema."' AND "; $q .= "nspname = '".$schema."' AND ";
$q .= "pg_class.relnamespace = pg_namespace.oid AND "; $q .= "pg_class.relnamespace = pg_namespace.oid AND ";
} }
@@ -256,13 +250,12 @@
$q .= "pg_attribute.attnum = any(pg_index.indkey) "; $q .= "pg_attribute.attnum = any(pg_index.indkey) ";
$q .= "AND indisprimary"; $q .= "AND indisprimary";
$row = $this->_db_query_result($q); $row = $this->_db_query_result($q);
if ($row === FALSE) if ($row === false) {
return false; return false;
else } else {
return $row['column_name']; return $row['column_name'];
} }
else } else {
{
return false; return false;
} }
} }
@@ -274,16 +267,12 @@
public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow') public function _db_connect($db_host, $db_user, $db_pass, $db_name, $db_port = 5432, $db_ssl = 'allow')
{ {
// to avoid empty db_port // to avoid empty db_port
if (!$db_port) if (!$db_port) {
{
$db_port = 5432; $db_port = 5432;
} }
try try {
{
$this->dbh = new PDO('pgsql:host='.$db_host.';dbname='.$db_name.';port='.$db_port.';sslmode='.$db_ssl, $db_user, $db_pass); $this->dbh = new PDO('pgsql:host='.$db_host.';dbname='.$db_name.';port='.$db_port.';sslmode='.$db_ssl, $db_user, $db_pass);
} } catch (PDOException $e) {
catch (PDOException $e)
{
print "Error!: ".$e->getMessage()."\n"; print "Error!: ".$e->getMessage()."\n";
die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."]: ".$e->getMEssage()."//-->"); die("<!-- Can't connect [host=".$db_host." port=".$db_port." user=".$db_user." password=XXXX dbname=".$db_name." sslmode=".$db_ssl."]: ".$e->getMEssage()."//-->");
} }
@@ -313,7 +302,7 @@
// DESC : wrapper for pg_emta_data // DESC : wrapper for pg_emta_data
public function _db_meta_data($table) public function _db_meta_data($table)
{ {
// return @pg_meta_data($this->dbh, $table); // return @pg_meta_data($this->dbh, $table);
} }
// METHOD: _db_escape_string // METHOD: _db_escape_string
@@ -322,7 +311,7 @@
// DESC : wrapper for pg_escape_string // DESC : wrapper for pg_escape_string
public function _db_escape_string($string) public function _db_escape_string($string)
{ {
// return pg_escape_string($this->dbh, $string); // return pg_escape_string($this->dbh, $string);
} }
// METHOD: _db_escape_bytea // METHOD: _db_escape_bytea
@@ -331,7 +320,7 @@
// DESC : wrapper for pg_escape_bytea // DESC : wrapper for pg_escape_bytea
public function _db_escape_bytea($bytea) public function _db_escape_bytea($bytea)
{ {
// return pg_escape_bytea($this->dbh, $bytea); // return pg_escape_bytea($this->dbh, $bytea);
} }
// METHOD: _db_connection_busy // METHOD: _db_connection_busy
@@ -340,7 +329,7 @@
// DESC : wrapper for pg_connection_busy // DESC : wrapper for pg_connection_busy
public function _db_connection_busy() public function _db_connection_busy()
{ {
// return pg_connection_busy($this->dbh); // return pg_connection_busy($this->dbh);
} }
// METHOD: _db_version // METHOD: _db_version
@@ -363,27 +352,24 @@
// DESC : postgresql array to php array // DESC : postgresql array to php array
public function _db_array_parse($text, &$output, $limit = false, $offset = 1) public function _db_array_parse($text, &$output, $limit = false, $offset = 1)
{ {
if (false === $limit) if (false === $limit) {
{
$limit = strlen($text) - 1; $limit = strlen($text) - 1;
$output = array(); $output = array();
} }
if ('{}' != $text) if ('{}' != $text) {
do do {
{ if ('{' != $text{$offset}) {
if ('{' != $text{$offset})
{
preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset); preg_match("/(\\{?\"([^\"\\\\]|\\\\.)*\"|[^,{}]+)+([,}]+)/", $text, $match, 0, $offset);
$offset += strlen($match[0]); $offset += strlen($match[0]);
$output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1))); $output[] = ('"' != $match[1]{0} ? $match[1] : stripcslashes(substr($match[1], 1, -1)));
if ('},' == $match[3]) if ('},' == $match[3]) {
return $offset; return $offset;
} }
else } else {
$offset = pg_array_parse($text, $output[], $limit, $offset + 1); $offset = pg_array_parse($text, $output[], $limit, $offset + 1);
} }
while ($limit > $offset); } while ($limit > $offset);
}
return $output; return $output;
} }
} }
?>
+101 -77
View File
@@ -18,37 +18,37 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with PHP-gettext; if not, write to the Free Software along with PHP-gettext; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
/** /**
* Provides a simple gettext replacement that works independently from * Provides a simple gettext replacement that works independently from
* the system's gettext abilities. * the system's gettext abilities.
* It can read MO files and use them for translating strings. * It can read MO files and use them for translating strings.
* The files are passed to gettext_reader as a Stream (see streams.php) * The files are passed to gettext_reader as a Stream (see streams.php)
* *
* This version has the ability to cache all strings and translations to * This version has the ability to cache all strings and translations to
* speed up the string lookup. * speed up the string lookup.
* While the cache is enabled by default, it can be switched off with the * While the cache is enabled by default, it can be switched off with the
* second parameter in the constructor (e.g. whenusing very large MO files * second parameter in the constructor (e.g. whenusing very large MO files
* that you don't want to keep in memory) * that you don't want to keep in memory)
*/ */
class gettext_reader { class gettext_reader
//public: {
var $error = 0; // public variable that holds error code (0 if no error) // public:
public $error = 0; // public variable that holds error code (0 if no error)
//private: //private:
var $BYTEORDER = 0; // 0: low endian, 1: big endian private $BYTEORDER = 0; // 0: low endian, 1: big endian
var $STREAM = NULL; private $STREAM = null;
var $short_circuit = false; private $short_circuit = false;
var $enable_cache = false; private $enable_cache = false;
var $originals = NULL; // offset of original table private $originals = null; // offset of original table
var $translations = NULL; // offset of translation table private $translations = null; // offset of translation table
var $pluralheader = NULL; // cache header field for plural forms private $pluralheader = null; // cache header field for plural forms
var $total = 0; // total string count private $total = 0; // total string count
var $table_originals = NULL; // table for original strings (offsets) private $table_originals = null; // table for original strings (offsets)
var $table_translations = NULL; // table for translated strings (offsets) private $table_translations = null; // table for translated strings (offsets)
var $cache_translations = NULL; // original -> translation mapping private $cache_translations = null; // original -> translation mapping
/* Methods */ /* Methods */
@@ -60,19 +60,21 @@ class gettext_reader {
* @access private * @access private
* @return Integer from the Stream * @return Integer from the Stream
*/ */
function readint() { private function readint()
{
if ($this->BYTEORDER == 0) { if ($this->BYTEORDER == 0) {
// low endian // low endian
$input=unpack('V', $this->STREAM->read(4)); $input = unpack('V', $this->STREAM->read(4));
return array_shift($input); return array_shift($input);
} else { } else {
// big endian // big endian
$input=unpack('N', $this->STREAM->read(4)); $input = unpack('N', $this->STREAM->read(4));
return array_shift($input); return array_shift($input);
} }
} }
function read($bytes) { public function read($bytes)
{
return $this->STREAM->read($bytes); return $this->STREAM->read($bytes);
} }
@@ -82,7 +84,8 @@ class gettext_reader {
* @param int count How many elements should be read * @param int count How many elements should be read
* @return Array of Integers * @return Array of Integers
*/ */
function readintarray($count) { public function readintarray($count)
{
if ($this->BYTEORDER == 0) { if ($this->BYTEORDER == 0) {
// low endian // low endian
return unpack('V'.$count, $this->STREAM->read(4 * $count)); return unpack('V'.$count, $this->STREAM->read(4 * $count));
@@ -98,9 +101,10 @@ class gettext_reader {
* @param object Reader the StreamReader object * @param object Reader the StreamReader object
* @param boolean enable_cache Enable or disable caching of strings (default on) * @param boolean enable_cache Enable or disable caching of strings (default on)
*/ */
function __construct($Reader, $enable_cache = true) { public function __construct($Reader, $enable_cache = true)
{
// If there isn't a StreamReader, turn on short circuit mode. // If there isn't a StreamReader, turn on short circuit mode.
if (! $Reader || isset($Reader->error) ) { if (!$Reader || isset($Reader->error)) {
$this->short_circuit = true; $this->short_circuit = true;
return; return;
} }
@@ -137,11 +141,13 @@ class gettext_reader {
* *
* @access private * @access private
*/ */
function load_tables() { private function load_tables()
{
if (is_array($this->cache_translations) && if (is_array($this->cache_translations) &&
is_array($this->table_originals) && is_array($this->table_originals) &&
is_array($this->table_translations)) is_array($this->table_translations)) {
return; return;
}
/* get original and translations tables */ /* get original and translations tables */
if (!is_array($this->table_originals)) { if (!is_array($this->table_originals)) {
@@ -173,11 +179,13 @@ class gettext_reader {
* @param int num Offset number of original string * @param int num Offset number of original string
* @return string Requested string if found, otherwise '' * @return string Requested string if found, otherwise ''
*/ */
function get_original_string($num) { private function get_original_string($num)
{
$length = $this->table_originals[$num * 2 + 1]; $length = $this->table_originals[$num * 2 + 1];
$offset = $this->table_originals[$num * 2 + 2]; $offset = $this->table_originals[$num * 2 + 2];
if (! $length) if (!$length) {
return ''; return '';
}
$this->STREAM->seekto($offset); $this->STREAM->seekto($offset);
$data = $this->STREAM->read($length); $data = $this->STREAM->read($length);
return (string)$data; return (string)$data;
@@ -190,11 +198,13 @@ class gettext_reader {
* @param int num Offset number of original string * @param int num Offset number of original string
* @return string Requested string if found, otherwise '' * @return string Requested string if found, otherwise ''
*/ */
function get_translation_string($num) { private function get_translation_string($num)
{
$length = $this->table_translations[$num * 2 + 1]; $length = $this->table_translations[$num * 2 + 1];
$offset = $this->table_translations[$num * 2 + 2]; $offset = $this->table_translations[$num * 2 + 2];
if (! $length) if (!$length) {
return ''; return '';
}
$this->STREAM->seekto($offset); $this->STREAM->seekto($offset);
$data = $this->STREAM->read($length); $data = $this->STREAM->read($length);
return (string)$data; return (string)$data;
@@ -209,7 +219,8 @@ class gettext_reader {
* @param int end (internally used in recursive function) * @param int end (internally used in recursive function)
* @return int string number (offset in originals table) * @return int string number (offset in originals table)
*/ */
function find_string($string, $start = -1, $end = -1) { private function find_string($string, $start = -1, $end = -1)
{
if (($start == -1) or ($end == -1)) { if (($start == -1) or ($end == -1)) {
// find_string is called with only one parameter, set start end end // find_string is called with only one parameter, set start end end
$start = 0; $start = 0;
@@ -218,28 +229,30 @@ class gettext_reader {
if (abs($start - $end) <= 1) { if (abs($start - $end) <= 1) {
// We're done, now we either found the string, or it doesn't exist // We're done, now we either found the string, or it doesn't exist
$txt = $this->get_original_string($start); $txt = $this->get_original_string($start);
if ($string == $txt) if ($string == $txt) {
return $start; return $start;
else } else {
return -1; return -1;
} else if ($start > $end) { }
} elseif ($start > $end) {
// start > end -> turn around and start over // start > end -> turn around and start over
return $this->find_string($string, $end, $start); return $this->find_string($string, $end, $start);
} else { } else {
// Divide table in two parts // Divide table in two parts
$half = (int)(($start + $end) / 2); $half = (int)(($start + $end) / 2);
$cmp = strcmp($string, $this->get_original_string($half)); $cmp = strcmp($string, $this->get_original_string($half));
if ($cmp == 0) if ($cmp == 0) {
// string is exactly in the middle => return it // string is exactly in the middle => return it
return $half; return $half;
else if ($cmp < 0) } elseif ($cmp < 0) {
// The string is in the upper half // The string is in the upper half
return $this->find_string($string, $start, $half); return $this->find_string($string, $start, $half);
else } else {
// The string is in the lower half // Translateshe string is in the lower half
return $this->find_string($string, $half, $end); return $this->find_string($string, $half, $end);
} }
} }
}
/** /**
* Translates a string * Translates a string
@@ -248,26 +261,30 @@ class gettext_reader {
* @param string string to be translated * @param string string to be translated
* @return string translated string (or original, if not found) * @return string translated string (or original, if not found)
*/ */
function translate($string) { public function translate($string)
if ($this->short_circuit) {
if ($this->short_circuit) {
return $string; return $string;
}
$this->load_tables(); $this->load_tables();
if ($this->enable_cache) { if ($this->enable_cache) {
// Caching enabled, get translated string from cache // Caching enabled, get translated string from cache
if (array_key_exists($string, $this->cache_translations)) if (array_key_exists($string, $this->cache_translations)) {
return $this->cache_translations[$string]; return $this->cache_translations[$string];
else } else {
return $string; return $string;
}
} else { } else {
// Caching not enabled, try to find string // Caching not enabled, try to find string
$num = $this->find_string($string); $num = $this->find_string($string);
if ($num == -1) if ($num == -1) {
return $string; return $string;
else } else {
return $this->get_translation_string($num); return $this->get_translation_string($num);
} }
} }
}
/** /**
* Sanitize plural form expression for use in PHP eval call. * Sanitize plural form expression for use in PHP eval call.
@@ -275,7 +292,8 @@ class gettext_reader {
* @access private * @access private
* @return string sanitized plural form expression * @return string sanitized plural form expression
*/ */
function sanitize_plural_expression($expr) { private function sanitize_plural_expression($expr)
{
// Get rid of disallowed characters. // Get rid of disallowed characters.
$expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr); $expr = preg_replace('@[^a-zA-Z0-9_:;\(\)\?\|\&=!<>+*/\%-]@', '', $expr);
@@ -294,7 +312,7 @@ class gettext_reader {
$res .= ') : ('; $res .= ') : (';
break; break;
case ';': case ';':
$res .= str_repeat( ')', $p) . ';'; $res .= str_repeat(')', $p).';';
$p = 0; $p = 0;
break; break;
default: default:
@@ -310,11 +328,13 @@ class gettext_reader {
* @access private * @access private
* @return string verbatim plural form header field * @return string verbatim plural form header field
*/ */
function extract_plural_forms_header_from_po_header($header) { private function extract_plural_forms_header_from_po_header($header)
if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs)) {
if (preg_match("/(^|\n)plural-forms: ([^\n]*)\n/i", $header, $regs)) {
$expr = $regs[2]; $expr = $regs[2];
else } else {
$expr = "nplurals=2; plural=n == 1 ? 0 : 1;"; $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
}
return $expr; return $expr;
} }
@@ -324,7 +344,8 @@ class gettext_reader {
* @access private * @access private
* @return string plural form header * @return string plural form header
*/ */
function get_plural_forms() { private function get_plural_forms()
{
// lets assume message number 0 is header // lets assume message number 0 is header
// this is true, right? // this is true, right?
$this->load_tables(); $this->load_tables();
@@ -349,17 +370,20 @@ class gettext_reader {
* @param n count * @param n count
* @return int array index of the right plural form * @return int array index of the right plural form
*/ */
function select_string($n) { private function select_string($n)
{
$string = $this->get_plural_forms(); $string = $this->get_plural_forms();
$string = str_replace('nplurals',"\$total",$string); $string = str_replace('nplurals', "\$total", $string);
$string = str_replace("n",$n,$string); $string = str_replace("n", $n, $string);
$string = str_replace('plural',"\$plural",$string); $string = str_replace('plural', "\$plural", $string);
$total = 0; $total = 0;
$plural = 0; $plural = 0;
eval("$string"); eval("$string");
if ($plural >= $total) $plural = $total - 1; if ($plural >= $total) {
$plural = $total - 1;
}
return $plural; return $plural;
} }
@@ -372,13 +396,15 @@ class gettext_reader {
* @param string number * @param string number
* @return translated plural form * @return translated plural form
*/ */
function ngettext($single, $plural, $number) { public function ngettext($single, $plural, $number)
{
if ($this->short_circuit) { if ($this->short_circuit) {
if ($number != 1) if ($number != 1) {
return $plural; return $plural;
else } else {
return $single; return $single;
} }
}
// find out the appropriate form // find out the appropriate form
$select = $this->select_string($number); $select = $this->select_string($number);
@@ -386,7 +412,6 @@ class gettext_reader {
// this should contains all strings separated by NULLs // this should contains all strings separated by NULLs
$key = $single . chr(0) . $plural; $key = $single . chr(0) . $plural;
if ($this->enable_cache) { if ($this->enable_cache) {
if (! array_key_exists($key, $this->cache_translations)) { if (! array_key_exists($key, $this->cache_translations)) {
return ($number != 1) ? $plural : $single; return ($number != 1) ? $plural : $single;
@@ -407,26 +432,25 @@ class gettext_reader {
} }
} }
function pgettext($context, $msgid) { public function pgettext($context, $msgid)
$key = $context . chr(4) . $msgid; {
$key = $context.chr(4).$msgid;
$ret = $this->translate($key); $ret = $this->translate($key);
if (strpos($ret, "\004") !== FALSE) { if (strpos($ret, "\004") !== false) {
return $msgid; return $msgid;
} else { } else {
return $ret; return $ret;
} }
} }
function npgettext($context, $singular, $plural, $number) { public function npgettext($context, $singular, $plural, $number)
$key = $context . chr(4) . $singular; {
$key = $context.chr(4).$singular;
$ret = $this->ngettext($key, $plural, $number); $ret = $this->ngettext($key, $plural, $number);
if (strpos($ret, "\004") !== FALSE) { if (strpos($ret, "\004") !== false) {
return $singular; return $singular;
} else { } else {
return $ret; return $ret;
} }
} }
} }
?>
+60 -45
View File
@@ -17,81 +17,93 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with PHP-gettext; if not, write to the Free Software along with PHP-gettext; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
// Simple class to wrap file streams, string streams, etc. // Simple class to wrap file streams, string streams, etc.
// seek is essential, and it should be byte stream // seek is essential, and it should be byte stream
class StreamReader { class StreamReader
{
// should return a string [FIXME: perhaps return array of bytes?] // should return a string [FIXME: perhaps return array of bytes?]
function read($bytes) { public function read($bytes)
{
return false; return false;
} }
// should return new position // should return new position
function seekto($position) { public function seekto($position)
{
return false; return false;
} }
// returns current position // returns current position
function currentpos() { public function currentpos()
{
return false; return false;
} }
// returns length of entire stream (limit for seekto()s) // returns length of entire stream (limit for seekto()s)
function length() { public function length()
{
return false; return false;
} }
}; }
class StringReader { class StringReader
var $_pos; {
var $_str; public $_pos;
public $_str;
function __construct($str='') { public function __construct($str = '')
{
$this->_str = $str; $this->_str = $str;
$this->_pos = 0; $this->_pos = 0;
} }
function read($bytes) { public function read($bytes)
{
$data = substr($this->_str, $this->_pos, $bytes); $data = substr($this->_str, $this->_pos, $bytes);
$this->_pos += $bytes; $this->_pos += $bytes;
if (strlen($this->_str)<$this->_pos) if (strlen($this->_str) < $this->_pos) {
$this->_pos = strlen($this->_str); $this->_pos = strlen($this->_str);
}
return $data; return $data;
} }
function seekto($pos) { public function seekto($pos)
{
$this->_pos = $pos; $this->_pos = $pos;
if (strlen($this->_str)<$this->_pos) if (strlen($this->_str) < $this->_pos) {
$this->_pos = strlen($this->_str); $this->_pos = strlen($this->_str);
}
return $this->_pos; return $this->_pos;
} }
function currentpos() { public function currentpos()
{
return $this->_pos; return $this->_pos;
} }
function length() { public function length()
{
return strlen($this->_str); return strlen($this->_str);
} }
}
};
class FileReader { class FileReader
var $_pos; {
var $_fd; public $_pos;
var $_length; public $_fd;
public $_length;
function __construct($filename) { public function __construct($filename)
{
if (file_exists($filename)) { if (file_exists($filename)) {
$this->_length = filesize($filename);
$this->_length=filesize($filename);
$this->_pos = 0; $this->_pos = 0;
$this->_fd = fopen($filename,'rb'); $this->_fd = fopen($filename, 'rb');
if (!$this->_fd) { if (!$this->_fd) {
$this->error = 3; // Cannot read file, probably permissions $this->error = 3; // Cannot read file, probably permissions
return false; return false;
@@ -102,7 +114,8 @@ class FileReader {
} }
} }
function read($bytes) { public function read($bytes)
{
if ($bytes) { if ($bytes) {
fseek($this->_fd, $this->_pos); fseek($this->_fd, $this->_pos);
@@ -117,37 +130,43 @@ class FileReader {
$this->_pos = ftell($this->_fd); $this->_pos = ftell($this->_fd);
return $data; return $data;
} else return ''; } else {
return '';
}
} }
function seekto($pos) { public function seekto($pos)
{
fseek($this->_fd, $pos); fseek($this->_fd, $pos);
$this->_pos = ftell($this->_fd); $this->_pos = ftell($this->_fd);
return $this->_pos; return $this->_pos;
} }
function currentpos() { public function currentpos()
{
return $this->_pos; return $this->_pos;
} }
function length() { public function length()
{
return $this->_length; return $this->_length;
} }
function close() { public function close()
{
fclose($this->_fd); fclose($this->_fd);
} }
}
};
// Preloads entire file in memory first, then creates a StringReader // Preloads entire file in memory first, then creates a StringReader
// over it (it assumes knowledge of StringReader internals) // over it (it assumes knowledge of StringReader internals)
class CachedFileReader extends StringReader { class CachedFileReader extends StringReader
function __construct($filename) { {
public function __construct($filename)
{
if (file_exists($filename)) { if (file_exists($filename)) {
$length = filesize($filename);
$length=filesize($filename); $fd = fopen($filename, 'rb');
$fd = fopen($filename,'rb');
if (!$fd) { if (!$fd) {
$this->error = 3; // Cannot read file, probably permissions $this->error = 3; // Cannot read file, probably permissions
@@ -155,13 +174,9 @@ class CachedFileReader extends StringReader {
} }
$this->_str = fread($fd, $length); $this->_str = fread($fd, $length);
fclose($fd); fclose($fd);
} else { } else {
$this->error = 2; // File doesn't exist $this->error = 2; // File doesn't exist
return false; return false;
} }
} }
}; }
?>
@@ -91,19 +91,21 @@ function smarty_function_html_checkboxes($params, $template)
if (method_exists($_sel, "__toString")) { if (method_exists($_sel, "__toString")) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); $_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else { } else {
trigger_error("html_checkboxes: selected attribute contains an object of class '" . get_class($_sel) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_checkboxes: selected attribute contains an object of class '" .
get_class($_sel) . "' without __toString() method", E_USER_NOTICE);
continue; continue;
} }
} else { } else {
$_sel = smarty_function_escape_special_chars((string) $_sel); $_sel = smarty_function_escape_special_chars((string) $_sel);
} }
$selected[$_sel] = true; $selected[ $_sel ] = true;
} }
} elseif (is_object($_val)) { } elseif (is_object($_val)) {
if (method_exists($_val, "__toString")) { if (method_exists($_val, "__toString")) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString()); $selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else { } else {
trigger_error("html_checkboxes: selected attribute is an object of class '" . get_class($_val) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_checkboxes: selected attribute is an object of class '" . get_class($_val) .
"' without __toString() method", E_USER_NOTICE);
} }
} else { } else {
$selected = smarty_function_escape_special_chars((string) $_val); $selected = smarty_function_escape_special_chars((string) $_val);
@@ -111,7 +113,8 @@ function smarty_function_html_checkboxes($params, $template)
break; break;
case 'checkboxes': case 'checkboxes':
trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING); trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead',
E_USER_WARNING);
$options = (array) $_val; $options = (array) $_val;
break; break;
@@ -127,9 +130,10 @@ function smarty_function_html_checkboxes($params, $template)
case 'disabled': case 'disabled':
case 'readonly': case 'readonly':
if (!empty($params['strict'])) { if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) { if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE); trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
} }
if ($_val === true || $_val === $_key) { if ($_val === true || $_val === $_key) {
@@ -158,25 +162,30 @@ function smarty_function_html_checkboxes($params, $template)
if (isset($options)) { if (isset($options)) {
foreach ($options as $_key => $_val) { foreach ($options as $_key => $_val) {
$_pos = isset($pos[$_key]) ? $pos[$_key] : ''; $_pos = isset($pos[ $_key ]) ? $pos[ $_key ] : '';
$_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $_pos, $escape); $_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $_pos, $escape);
} }
} else { } else {
foreach ($values as $_i => $_key) { foreach ($values as $_i => $_key) {
$_val = isset($output[$_i]) ? $output[$_i] : ''; $_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_pos = isset($pos[$_i]) ? $pos[$_i] : ''; $_pos = isset($pos[ $_i ]) ? $pos[ $_i ] : '';
$_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $_pos, $escape); $_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $_pos, $escape);
} }
} }
if (!empty($params['assign'])) { if (!empty($params[ 'assign' ])) {
$template->assign($params['assign'], $_html_result); $template->assign($params[ 'assign' ], $_html_result);
} else { } else {
return implode("\n", $_html_result); return implode("\n", $_html_result);
} }
} }
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $pos, $escape = true) function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels,
$label_ids, $pos, $escape = true)
{ {
$_output = ''; $_output = '';
@@ -184,7 +193,8 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
if (method_exists($value, "__toString")) { if (method_exists($value, "__toString")) {
$value = (string) $value->__toString(); $value = (string) $value->__toString();
} else { } else {
trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_options: value is an object of class '" . get_class($value) .
"' without __toString() method", E_USER_NOTICE);
return ''; return '';
} }
@@ -196,7 +206,8 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
if (method_exists($output, "__toString")) { if (method_exists($output, "__toString")) {
$output = (string) $output->__toString(); $output = (string) $output->__toString();
} else { } else {
trigger_error("html_options: output is an object of class '" . get_class($output) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_options: output is an object of class '" . get_class($output) .
"' without __toString() method", E_USER_NOTICE);
return ''; return '';
} }
@@ -206,7 +217,8 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
if ($labels) { if ($labels) {
if ($label_ids) { if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_',
$name . '_' . $value));
$_output .= '<label for="' . $_id . '">'; $_output .= '<label for="' . $_id . '">';
} else { } else {
$_output .= '<label>'; $_output .= '<label>';
@@ -226,7 +238,7 @@ function smarty_function_html_checkboxes_output($name, $value, $output, $selecte
} }
if (is_array($selected)) { if (is_array($selected)) {
if (isset($selected[$value])) { if (isset($selected[ $value ])) {
$_output .= ' checked="checked"'; $_output .= ' checked="checked"';
} }
} elseif ($value === $selected) { } elseif ($value === $selected) {
@@ -73,19 +73,21 @@ function smarty_function_html_options($params)
if (method_exists($_sel, "__toString")) { if (method_exists($_sel, "__toString")) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); $_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else { } else {
trigger_error("html_options: selected attribute contains an object of class '" . get_class($_sel) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_options: selected attribute contains an object of class '" .
get_class($_sel) . "' without __toString() method", E_USER_NOTICE);
continue; continue;
} }
} else { } else {
$_sel = smarty_function_escape_special_chars((string) $_sel); $_sel = smarty_function_escape_special_chars((string) $_sel);
} }
$selected[$_sel] = true; $selected[ $_sel ] = true;
} }
} elseif (is_object($_val)) { } elseif (is_object($_val)) {
if (method_exists($_val, "__toString")) { if (method_exists($_val, "__toString")) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString()); $selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else { } else {
trigger_error("html_options: selected attribute is an object of class '" . get_class($_val) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_options: selected attribute is an object of class '" . get_class($_val) .
"' without __toString() method", E_USER_NOTICE);
} }
} else { } else {
$selected = smarty_function_escape_special_chars((string) $_val); $selected = smarty_function_escape_special_chars((string) $_val);
@@ -102,9 +104,10 @@ function smarty_function_html_options($params)
case 'disabled': case 'disabled':
case 'readonly': case 'readonly':
if (!empty($params['strict'])) { if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) { if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute", E_USER_NOTICE); trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
} }
if ($_val === true || $_val === $_key) { if ($_val === true || $_val === $_key) {
@@ -140,7 +143,7 @@ function smarty_function_html_options($params)
} }
} else { } else {
foreach ($values as $_i => $_key) { foreach ($values as $_i => $_key) {
$_val = isset($output[$_i]) ? $output[$_i] : ''; $_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $label, $_idx); $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $label, $_idx);
} }
} }
@@ -148,7 +151,9 @@ function smarty_function_html_options($params)
if (!empty($name)) { if (!empty($name)) {
$_html_class = !empty($class) ? ' class="' . $class . '"' : ''; $_html_class = !empty($class) ? ' class="' . $class . '"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '"' : ''; $_html_id = !empty($id) ? ' id="' . $id . '"' : '';
$_html_result = '<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result . '</select>' . "\n"; $_html_result =
'<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result .
'</select>' . "\n";
} }
return $_html_result; return $_html_result;
@@ -160,7 +165,7 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
$_key = smarty_function_escape_special_chars($key); $_key = smarty_function_escape_special_chars($key);
$_html_result = '<option' . (($label == 'true') ? ' label="' . smarty_function_escape_special_chars($value) . '"' : '') . ' value="' . $_key . '"'; $_html_result = '<option' . (($label == 'true') ? ' label="' . smarty_function_escape_special_chars($value) . '"' : '') . ' value="' . $_key . '"';
if (is_array($selected)) { if (is_array($selected)) {
if (isset($selected[$_key])) { if (isset($selected[ $_key ])) {
$_html_result .= ' selected="selected"'; $_html_result .= ' selected="selected"';
} }
} elseif ($_key === $selected) { } elseif ($_key === $selected) {
@@ -172,7 +177,8 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
if (method_exists($value, "__toString")) { if (method_exists($value, "__toString")) {
$value = smarty_function_escape_special_chars((string) $value->__toString()); $value = smarty_function_escape_special_chars((string) $value->__toString());
} else { } else {
trigger_error("html_options: value is an object of class '" . get_class($value) . "' without __toString() method", E_USER_NOTICE); trigger_error("html_options: value is an object of class '" . get_class($value) .
"' without __toString() method", E_USER_NOTICE);
return ''; return '';
} }
@@ -183,7 +189,9 @@ function smarty_function_html_options_optoutput($key, $value, $selected, $id, $c
$idx ++; $idx ++;
} else { } else {
$_idx = 0; $_idx = 0;
$_html_result = smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null, $class, $label, $_idx); $_html_result =
smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null,
$class, $label, $_idx);
$idx ++; $idx ++;
} }
+22
View File
@@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
+222
View File
@@ -0,0 +1,222 @@
#################
## Eclipse
#################
*.pydevproject
.project
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
#################
## Visual Studio
#################
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
build/
[Bb]in/
[Oo]bj/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#############
## Windows detritus
#############
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store
#############
## Python
#############
*.py[co]
# Packages
*.egg
*.egg-info
dist/
build/
eggs/
parts/
var/
sdist/
develop-eggs/
.installed.cfg
# Installer logs
pip-log.txt
# Unit test / coverage reports
.coverage
.tox
#Translations
*.mo
#Mr Developer
.mr.developer.cfg
.idea/
.idea\
# Smarty
lexer/*.php
lexer/*.out
+18
View File
@@ -0,0 +1,18 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
allow_failures:
- php: hhvm
install:
- git clone --depth=50 --branch=master git://github.com/smarty-php/smarty-phpunit.git
script:
- cd smarty-phpunit
- phpunit ./
+107
View File
@@ -0,0 +1,107 @@
<?php
/**
* Smarty Autoloader
*
* @package Smarty
*/
/**
* Smarty Autoloader
*
* @package Smarty
* @author Uwe Tews
* Usage:
* require_once '...path/Autoloader.php';
* Smarty_Autoloader::register();
* $smarty = new Smarty();
* Note: This autoloader is not needed if you use Composer.
* Composer will automatically add the classes of the Smarty package to it common autoloader.
*/
class Smarty_Autoloader
{
/**
* Filepath to Smarty root
*
* @var string
*/
public static $SMARTY_DIR = '';
/**
* Filepath to Smarty internal plugins
*
* @var string
*/
public static $SMARTY_SYSPLUGINS_DIR = '';
/**
* Array with Smarty core classes and their filename
*
* @var array
*/
public static $rootClasses = array('smarty' => 'Smarty.class.php', 'smartybc' => 'SmartyBC.class.php',);
/**
* Registers Smarty_Autoloader backward compatible to older installations.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function registerBC($prepend = false)
{
/**
* register the class autoloader
*/
if (!defined('SMARTY_SPL_AUTOLOAD')) {
define('SMARTY_SPL_AUTOLOAD', 0);
}
if (SMARTY_SPL_AUTOLOAD &&
set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false
) {
$registeredAutoLoadFunctions = spl_autoload_functions();
if (!isset($registeredAutoLoadFunctions[ 'spl_autoload' ])) {
spl_autoload_register();
}
} else {
self::register($prepend);
}
}
/**
* Registers Smarty_Autoloader as an SPL autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function register($prepend = false)
{
self::$SMARTY_DIR = defined('SMARTY_DIR') ? SMARTY_DIR : dirname(__FILE__) . DIRECTORY_SEPARATOR;
self::$SMARTY_SYSPLUGINS_DIR = defined('SMARTY_SYSPLUGINS_DIR') ? SMARTY_SYSPLUGINS_DIR :
self::$SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR;
if (version_compare(phpversion(), '5.3.0', '>=')) {
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
} else {
spl_autoload_register(array(__CLASS__, 'autoload'));
}
}
/**
* Handles auto loading of classes.
*
* @param string $class A class name.
*/
public static function autoload($class)
{
$_class = strtolower($class);
if (strpos($_class, 'smarty') !== 0) {
return;
}
$file = self::$SMARTY_SYSPLUGINS_DIR . $_class . '.php';
if (is_file($file)) {
include $file;
} else if (isset(self::$rootClasses[ $_class ])) {
$file = self::$SMARTY_DIR . self::$rootClasses[ $_class ];
if (is_file($file)) {
include $file;
}
}
return;
}
}
File diff suppressed because it is too large Load Diff
+455
View File
@@ -0,0 +1,455 @@
<?php
/**
* Project: Smarty: the PHP compiling template engine
* File: SmartyBC.class.php
* SVN: $Id: $
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @author Rodney Rehm
* @package Smarty
*/
/**
* @ignore
*/
require_once(dirname(__FILE__) . '/Smarty.class.php');
/**
* Smarty Backward Compatibility Wrapper Class
*
* @package Smarty
*/
class SmartyBC extends Smarty
{
/**
* Smarty 2 BC
*
* @var string
*/
public $_version = self::SMARTY_VERSION;
/**
* This is an array of directories where trusted php scripts reside.
*
* @var array
*/
public $trusted_dir = array();
/**
* Initialize new SmartyBC object
*
*/
public function __construct()
{
parent::__construct();
}
/**
* wrapper for assign_by_ref
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to assign
*/
public function assign_by_ref($tpl_var, &$value)
{
$this->assignByRef($tpl_var, $value);
}
/**
* wrapper for append_by_ref
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to append
* @param boolean $merge flag if array elements shall be merged
*/
public function append_by_ref($tpl_var, &$value, $merge = false)
{
$this->appendByRef($tpl_var, $value, $merge);
}
/**
* clear the given assigned template variable.
*
* @param string $tpl_var the template variable to clear
*/
public function clear_assign($tpl_var)
{
$this->clearAssign($tpl_var);
}
/**
* Registers custom function to be used in templates
*
* @param string $function the name of the template function
* @param string $function_impl the name of the PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*/
public function register_function($function, $function_impl, $cacheable = true, $cache_attrs = null)
{
$this->registerPlugin('function', $function, $function_impl, $cacheable, $cache_attrs);
}
/**
* Unregister custom function
*
* @param string $function name of template function
*/
public function unregister_function($function)
{
$this->unregisterPlugin('function', $function);
}
/**
* Registers object to be used in templates
*
* @param string $object name of template object
* @param object $object_impl the referenced PHP object to register
* @param array $allowed list of allowed methods (empty = all)
* @param boolean $smarty_args smarty argument format, else traditional
* @param array $block_methods list of methods that are block format
*
* @throws SmartyException
* @internal param array $block_functs list of methods that are block format
*/
public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true,
$block_methods = array())
{
settype($allowed, 'array');
settype($smarty_args, 'boolean');
$this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods);
}
/**
* Unregister object
*
* @param string $object name of template object
*/
public function unregister_object($object)
{
$this->unregisterObject($object);
}
/**
* Registers block function to be used in templates
*
* @param string $block name of template block
* @param string $block_impl PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*/
public function register_block($block, $block_impl, $cacheable = true, $cache_attrs = null)
{
$this->registerPlugin('block', $block, $block_impl, $cacheable, $cache_attrs);
}
/**
* Unregister block function
*
* @param string $block name of template function
*/
public function unregister_block($block)
{
$this->unregisterPlugin('block', $block);
}
/**
* Registers compiler function
*
* @param string $function name of template function
* @param string $function_impl name of PHP function to register
* @param bool $cacheable
*/
public function register_compiler_function($function, $function_impl, $cacheable = true)
{
$this->registerPlugin('compiler', $function, $function_impl, $cacheable);
}
/**
* Unregister compiler function
*
* @param string $function name of template function
*/
public function unregister_compiler_function($function)
{
$this->unregisterPlugin('compiler', $function);
}
/**
* Registers modifier to be used in templates
*
* @param string $modifier name of template modifier
* @param string $modifier_impl name of PHP function to register
*/
public function register_modifier($modifier, $modifier_impl)
{
$this->registerPlugin('modifier', $modifier, $modifier_impl);
}
/**
* Unregister modifier
*
* @param string $modifier name of template modifier
*/
public function unregister_modifier($modifier)
{
$this->unregisterPlugin('modifier', $modifier);
}
/**
* Registers a resource to fetch a template
*
* @param string $type name of resource
* @param array $functions array of functions to handle resource
*/
public function register_resource($type, $functions)
{
$this->registerResource($type, $functions);
}
/**
* Unregister a resource
*
* @param string $type name of resource
*/
public function unregister_resource($type)
{
$this->unregisterResource($type);
}
/**
* Registers a prefilter function to apply
* to a template before compiling
*
* @param callable $function
*/
public function register_prefilter($function)
{
$this->registerFilter('pre', $function);
}
/**
* Unregister a prefilter function
*
* @param callable $function
*/
public function unregister_prefilter($function)
{
$this->unregisterFilter('pre', $function);
}
/**
* Registers a postfilter function to apply
* to a compiled template after compilation
*
* @param callable $function
*/
public function register_postfilter($function)
{
$this->registerFilter('post', $function);
}
/**
* Unregister a postfilter function
*
* @param callable $function
*/
public function unregister_postfilter($function)
{
$this->unregisterFilter('post', $function);
}
/**
* Registers an output filter function to apply
* to a template output
*
* @param callable $function
*/
public function register_outputfilter($function)
{
$this->registerFilter('output', $function);
}
/**
* Unregister an outputfilter function
*
* @param callable $function
*/
public function unregister_outputfilter($function)
{
$this->unregisterFilter('output', $function);
}
/**
* load a filter of specified type and name
*
* @param string $type filter type
* @param string $name filter name
*/
public function load_filter($type, $name)
{
$this->loadFilter($type, $name);
}
/**
* clear cached content for the given template and cache id
*
* @param string $tpl_file name of template file
* @param string $cache_id name of cache_id
* @param string $compile_id name of compile_id
* @param string $exp_time expiration time
*
* @return boolean
*/
public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null)
{
return $this->clearCache($tpl_file, $cache_id, $compile_id, $exp_time);
}
/**
* clear the entire contents of cache (all templates)
*
* @param string $exp_time expire time
*
* @return boolean
*/
public function clear_all_cache($exp_time = null)
{
return $this->clearCache(null, null, null, $exp_time);
}
/**
* test to see if valid cache exists for this template
*
* @param string $tpl_file name of template file
* @param string $cache_id
* @param string $compile_id
*
* @return boolean
*/
public function is_cached($tpl_file, $cache_id = null, $compile_id = null)
{
return $this->isCached($tpl_file, $cache_id, $compile_id);
}
/**
* clear all the assigned template variables.
*/
public function clear_all_assign()
{
$this->clearAllAssign();
}
/**
* clears compiled version of specified template resource,
* or all compiled template files if one is not specified.
* This function is for advanced use only, not normally needed.
*
* @param string $tpl_file
* @param string $compile_id
* @param string $exp_time
*
* @return boolean results of {@link smarty_core_rm_auto()}
*/
public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null)
{
return $this->clearCompiledTemplate($tpl_file, $compile_id, $exp_time);
}
/**
* Checks whether requested template exists.
*
* @param string $tpl_file
*
* @return boolean
*/
public function template_exists($tpl_file)
{
return $this->templateExists($tpl_file);
}
/**
* Returns an array containing template variables
*
* @param string $name
*
* @return array
*/
public function get_template_vars($name = null)
{
return $this->getTemplateVars($name);
}
/**
* Returns an array containing config variables
*
* @param string $name
*
* @return array
*/
public function get_config_vars($name = null)
{
return $this->getConfigVars($name);
}
/**
* load configuration values
*
* @param string $file
* @param string $section
* @param string $scope
*/
public function config_load($file, $section = null, $scope = 'global')
{
$this->ConfigLoad($file, $section, $scope);
}
/**
* return a reference to a registered object
*
* @param string $name
*
* @return object
*/
public function get_registered_object($name)
{
return $this->getRegisteredObject($name);
}
/**
* clear configuration values
*
* @param string $var
*/
public function clear_config($var = null)
{
$this->clearConfig($var);
}
/**
* trigger Smarty error
*
* @param string $error_msg
* @param integer $error_type
*/
public function trigger_error($error_msg, $error_type = E_USER_WARNING)
{
trigger_error("Smarty error: $error_msg", $error_type);
}
}
+160
View File
@@ -0,0 +1,160 @@
{capture name='_smarty_debug' assign=debug_output}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Smarty Debug Console</title>
<style type="text/css">
{literal}
body, h1, h2, h3, td, th, p {
font-family: sans-serif;
font-weight: normal;
font-size: 0.9em;
margin: 1px;
padding: 0;
}
h1 {
margin: 0;
text-align: left;
padding: 2px;
background-color: #f0c040;
color: black;
font-weight: bold;
font-size: 1.2em;
}
h2 {
background-color: #9B410E;
color: white;
text-align: left;
font-weight: bold;
padding: 2px;
border-top: 1px solid black;
}
h3 {
text-align: left;
font-weight: bold;
color: black;
font-size: 0.7em;
padding: 2px;
}
body {
background: black;
}
p, table, div {
background: #f0ead8;
}
p {
margin: 0;
font-style: italic;
text-align: center;
}
table {
width: 100%;
}
th, td {
font-family: monospace;
vertical-align: top;
text-align: left;
}
td {
color: green;
}
.odd {
background-color: #eeeeee;
}
.even {
background-color: #fafafa;
}
.exectime {
font-size: 0.8em;
font-style: italic;
}
#bold div {
color: black;
font-weight: bold;
}
#blue h3 {
color: blue;
}
#normal div {
color: black;
font-weight: normal;
}
#table_assigned_vars th {
color: blue;
font-weight: bold;
}
#table_config_vars th {
color: maroon;
}
{/literal}
</style>
</head>
<body>
<h1>Smarty {Smarty::SMARTY_VERSION} Debug Console
- {if isset($template_name)}{$template_name|debug_print_var nofilter} {/if}{if !empty($template_data)}Total Time {$execution_time|string_format:"%.5f"}{/if}</h1>
{if !empty($template_data)}
<h2>included templates &amp; config files (load time in seconds)</h2>
<div>
{foreach $template_data as $template}
<font color=brown>{$template.name}</font>
<br>&nbsp;&nbsp;<span class="exectime">
(compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"})
</span>
<br>
{/foreach}
</div>
{/if}
<h2>assigned template variables</h2>
<table id="table_assigned_vars">
{foreach $assigned_vars as $vars}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<td><h3><font color=blue>${$vars@key}</font></h3>
{if isset($vars['nocache'])}<b>Nocache</b></br>{/if}
{if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td><h3>Value</h3>{$vars['value']|debug_print_var:10:80 nofilter}</td>
<td>{if isset($vars['attributes'])}<h3>Attributes</h3>{$vars['attributes']|debug_print_var nofilter} {/if}</td>
{/foreach}
</table>
<h2>assigned config file variables</h2>
<table id="table_config_vars">
{foreach $config_vars as $vars}
<tr class="{if $vars@iteration % 2 eq 0}odd{else}even{/if}">
<td><h3><font color=blue>#{$vars@key}#</font></h3>
{if isset($vars['scope'])}<b>Origin:</b> {$vars['scope']|debug_print_var nofilter}{/if}
</td>
<td>{$vars['value']|debug_print_var:10:80 nofilter}</td>
</tr>
{/foreach}
</table>
</body>
</html>
{/capture}
<script type="text/javascript">
{$id = '__Smarty__'}
{if $display_mode}{$id = "$offset$template_name"|md5}{/if}
_smarty_console = window.open("", "console{$id}", "width=1024,height=600,left={$offset},top={$offset},resizable,scrollbars=yes");
_smarty_console.document.write("{$debug_output|escape:'javascript' nofilter}");
_smarty_console.document.close();
</script>
+120
View File
@@ -0,0 +1,120 @@
<?php
/**
* smarty-gettext.php - Gettext support for smarty
*
* ------------------------------------------------------------------------- *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
* ------------------------------------------------------------------------- *
*
* To register as a smarty block function named 't', use:
* $smarty->register_block('t', 'smarty_translate');
*
* @package smarty-gettext
* @version $Id: block.t.php 4737 2013-12-11 06:29:51Z gullevek $
* @link http://smarty-gettext.sf.net/
* @author Sagi Bashari <sagi@boom.org.il>
* @copyright 2004 Sagi Bashari
*/
/**
* Replace arguments in a string with their values. Arguments are represented by % followed by their number.
*
* @param string Source string
* @param mixed Arguments, can be passed in an array or through single variables.
* @returns string Modified string
*/
function strarg($str)
{
$tr = array();
$p = 0;
for ($i=1; $i < func_num_args(); $i++) {
$arg = func_get_arg($i);
if (is_array($arg)) {
foreach ($arg as $aarg) {
$tr['%'.++$p] = $aarg;
}
} else {
$tr['%'.++$p] = $arg;
}
}
return strtr($str, $tr);
}
/**
* Smarty block function, provides gettext support for smarty.
*
* The block content is the text that should be translated.
*
* Any parameter that is sent to the function will be represented as %n in the translation text,
* where n is 1 for the first parameter. The following parameters are reserved:
* - escape - sets escape mode:
* - 'html' for HTML escaping, this is the default.
* - 'js' for javascript escaping.
* - 'no'/'off'/0 - turns off escaping
* - plural - The plural version of the text (2nd parameter of ngettext())
* - count - The item count for plural mode (3rd parameter of ngettext())
*/
// cs modified: __ calls instead of direct gettext calls
function smarty_block_t($params, $text, $template, &$repeat)
{
if ($text) {
$text = stripslashes($text);
// set escape mode
if (isset($params['escape'])) {
$escape = $params['escape'];
unset($params['escape']);
}
// set plural version
if (isset($params['plural'])) {
$plural = $params['plural'];
unset($params['plural']);
// set count
if (isset($params['count'])) {
$count = $params['count'];
unset($params['count']);
}
}
// use plural if required parameters are set
if (isset($count) && isset($plural)) {
$text = $template->l10n->__ngettext($text, $plural, $count);
} else { // use normal
$text = $template->l10n->__($text);
}
// run strarg if there are parameters
if (count($params)) {
$text = strarg($text, $params);
}
if (!isset($escape) || $escape == 'html') { // html escape, default
$text = nl2br(htmlspecialchars($text));
} elseif (isset($escape) && ($escape == 'javascript' || $escape == 'js')) { // javascript escape
$text = str_replace('\'','\\\'',stripslashes($text));
}
return $text;
}
}
?>
@@ -0,0 +1,112 @@
<?php
/**
* Smarty plugin to format text blocks
*
* @package Smarty
* @subpackage PluginsBlock
*/
/**
* Smarty {textformat}{/textformat} block plugin
* Type: block function<br>
* Name: textformat<br>
* Purpose: format text a certain way with preset styles
* or custom wrap/indent settings<br>
* Params:
* <pre>
* - style - string (email)
* - indent - integer (0)
* - wrap - integer (80)
* - wrap_char - string ("\n")
* - indent_char - string (" ")
* - wrap_boundary - boolean (true)
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat}
* (Smarty online manual)
*
* @param array $params parameters
* @param string $content contents of the block
* @param Smarty_Internal_Template $template template object
* @param boolean &$repeat repeat flag
*
* @return string content re-formatted
* @author Monte Ohrt <monte at ohrt dot com>
*/
function smarty_block_textformat($params, $content, $template, &$repeat)
{
if (is_null($content)) {
return;
}
$style = null;
$indent = 0;
$indent_first = 0;
$indent_char = ' ';
$wrap = 80;
$wrap_char = "\n";
$wrap_cut = false;
$assign = null;
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'style':
case 'indent_char':
case 'wrap_char':
case 'assign':
$$_key = (string) $_val;
break;
case 'indent':
case 'indent_first':
case 'wrap':
$$_key = (int) $_val;
break;
case 'wrap_cut':
$$_key = (bool) $_val;
break;
default:
trigger_error("textformat: unknown attribute '$_key'");
}
}
if ($style == 'email') {
$wrap = 72;
}
// split into paragraphs
$_paragraphs = preg_split('![\r\n]{2}!', $content);
foreach ($_paragraphs as &$_paragraph) {
if (!$_paragraph) {
continue;
}
// convert mult. spaces & special chars to single space
$_paragraph =
preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER),
array(' ', ''), $_paragraph);
// indent first line
if ($indent_first > 0) {
$_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph;
}
// wordwrap sentences
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php');
$_paragraph = smarty_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut);
} else {
$_paragraph = wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut);
}
// indent lines
if ($indent > 0) {
$_paragraph = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraph);
}
}
$_output = implode($wrap_char . $wrap_char, $_paragraphs);
if ($assign) {
$template->assign($assign, $_output);
} else {
return $_output;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {counter} function plugin
* Type: function<br>
* Name: counter<br>
* Purpose: print out a counter value
*
* @author Monte Ohrt <monte at ohrt dot com>
* @link http://www.smarty.net/manual/en/language.function.counter.php {counter}
* (Smarty online manual)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_counter($params, $template)
{
static $counters = array();
$name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default';
if (!isset($counters[ $name ])) {
$counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1);
}
$counter =& $counters[ $name ];
if (isset($params[ 'start' ])) {
$counter[ 'start' ] = $counter[ 'count' ] = (int) $params[ 'start' ];
}
if (!empty($params[ 'assign' ])) {
$counter[ 'assign' ] = $params[ 'assign' ];
}
if (isset($counter[ 'assign' ])) {
$template->assign($counter[ 'assign' ], $counter[ 'count' ]);
}
if (isset($params[ 'print' ])) {
$print = (bool) $params[ 'print' ];
} else {
$print = empty($counter[ 'assign' ]);
}
if ($print) {
$retval = $counter[ 'count' ];
} else {
$retval = null;
}
if (isset($params[ 'skip' ])) {
$counter[ 'skip' ] = $params[ 'skip' ];
}
if (isset($params[ 'direction' ])) {
$counter[ 'direction' ] = $params[ 'direction' ];
}
if ($counter[ 'direction' ] == "down") {
$counter[ 'count' ] -= $counter[ 'skip' ];
} else {
$counter[ 'count' ] += $counter[ 'skip' ];
}
return $retval;
}
@@ -0,0 +1,105 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {cycle} function plugin
* Type: function<br>
* Name: cycle<br>
* Date: May 3, 2002<br>
* Purpose: cycle through given values<br>
* Params:
* <pre>
* - name - name of cycle (optional)
* - values - comma separated list of values to cycle, or an array of values to cycle
* (this can be left out for subsequent calls)
* - reset - boolean - resets given var to true
* - print - boolean - print var or not. default is true
* - advance - boolean - whether or not to advance the cycle
* - delimiter - the value delimiter, default is ","
* - assign - boolean, assigns to template var instead of printed.
* </pre>
* Examples:<br>
* <pre>
* {cycle values="#eeeeee,#d0d0d0d"}
* {cycle name=row values="one,two,three" reset=true}
* {cycle name=row}
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Mark Priatel <mpriatel@rogers.com>
* @author credit to Gerard <gerard@interfold.com>
* @author credit to Jason Sweat <jsweat_php@yahoo.com>
* @version 1.3
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_cycle($params, $template)
{
static $cycle_vars;
$name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ];
$print = (isset($params[ 'print' ])) ? (bool) $params[ 'print' ] : true;
$advance = (isset($params[ 'advance' ])) ? (bool) $params[ 'advance' ] : true;
$reset = (isset($params[ 'reset' ])) ? (bool) $params[ 'reset' ] : false;
if (!isset($params[ 'values' ])) {
if (!isset($cycle_vars[ $name ][ 'values' ])) {
trigger_error("cycle: missing 'values' parameter");
return;
}
} else {
if (isset($cycle_vars[ $name ][ 'values' ]) && $cycle_vars[ $name ][ 'values' ] != $params[ 'values' ]) {
$cycle_vars[ $name ][ 'index' ] = 0;
}
$cycle_vars[ $name ][ 'values' ] = $params[ 'values' ];
}
if (isset($params[ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ];
} elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = ',';
}
if (is_array($cycle_vars[ $name ][ 'values' ])) {
$cycle_array = $cycle_vars[ $name ][ 'values' ];
} else {
$cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]);
}
if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) {
$cycle_vars[ $name ][ 'index' ] = 0;
}
if (isset($params[ 'assign' ])) {
$print = false;
$template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]);
}
if ($print) {
$retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ];
} else {
$retval = null;
}
if ($advance) {
if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) {
$cycle_vars[ $name ][ 'index' ] = 0;
} else {
$cycle_vars[ $name ][ 'index' ] ++;
}
}
return $retval;
}
@@ -0,0 +1,221 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {fetch} plugin
* Type: function<br>
* Name: fetch<br>
* Purpose: fetch file, web or ftp data and display results
*
* @link http://www.smarty.net/manual/en/language.function.fetch.php {fetch}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable
*/
function smarty_function_fetch($params, $template)
{
if (empty($params[ 'file' ])) {
trigger_error("[plugin] fetch parameter 'file' cannot be empty", E_USER_NOTICE);
return;
}
// strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7);
}
$protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
}
if (isset($template->smarty->security_policy)) {
if ($protocol) {
// remote resource (or php stream, …)
if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) {
return;
}
} else {
// local file
if (!$template->smarty->security_policy->isTrustedResourceDir($params[ 'file' ])) {
return;
}
}
}
$content = '';
if ($protocol == 'http') {
// http fetch
if ($uri_parts = parse_url($params[ 'file' ])) {
// set defaults
$host = $server_name = $uri_parts[ 'host' ];
$timeout = 30;
$accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*";
$agent = "Smarty Template Engine " . Smarty::SMARTY_VERSION;
$referer = "";
$uri = !empty($uri_parts[ 'path' ]) ? $uri_parts[ 'path' ] : '/';
$uri .= !empty($uri_parts[ 'query' ]) ? '?' . $uri_parts[ 'query' ] : '';
$_is_proxy = false;
if (empty($uri_parts[ 'port' ])) {
$port = 80;
} else {
$port = $uri_parts[ 'port' ];
}
if (!empty($uri_parts[ 'user' ])) {
$user = $uri_parts[ 'user' ];
}
if (!empty($uri_parts[ 'pass' ])) {
$pass = $uri_parts[ 'pass' ];
}
// loop through parameters, setup headers
foreach ($params as $param_key => $param_value) {
switch ($param_key) {
case "file":
case "assign":
case "assign_headers":
break;
case "user":
if (!empty($param_value)) {
$user = $param_value;
}
break;
case "pass":
if (!empty($param_value)) {
$pass = $param_value;
}
break;
case "accept":
if (!empty($param_value)) {
$accept = $param_value;
}
break;
case "header":
if (!empty($param_value)) {
if (!preg_match('![\w\d-]+: .+!', $param_value)) {
trigger_error("[plugin] invalid header format '" . $param_value . "'", E_USER_NOTICE);
return;
} else {
$extra_headers[] = $param_value;
}
}
break;
case "proxy_host":
if (!empty($param_value)) {
$proxy_host = $param_value;
}
break;
case "proxy_port":
if (!preg_match('!\D!', $param_value)) {
$proxy_port = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
break;
case "agent":
if (!empty($param_value)) {
$agent = $param_value;
}
break;
case "referer":
if (!empty($param_value)) {
$referer = $param_value;
}
break;
case "timeout":
if (!preg_match('!\D!', $param_value)) {
$timeout = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
break;
default:
trigger_error("[plugin] unrecognized attribute '" . $param_key . "'", E_USER_NOTICE);
return;
}
}
if (!empty($proxy_host) && !empty($proxy_port)) {
$_is_proxy = true;
$fp = fsockopen($proxy_host, $proxy_port, $errno, $errstr, $timeout);
} else {
$fp = fsockopen($server_name, $port, $errno, $errstr, $timeout);
}
if (!$fp) {
trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE);
return;
} else {
if ($_is_proxy) {
fputs($fp, 'GET ' . $params[ 'file' ] . " HTTP/1.0\r\n");
} else {
fputs($fp, "GET $uri HTTP/1.0\r\n");
}
if (!empty($host)) {
fputs($fp, "Host: $host\r\n");
}
if (!empty($accept)) {
fputs($fp, "Accept: $accept\r\n");
}
if (!empty($agent)) {
fputs($fp, "User-Agent: $agent\r\n");
}
if (!empty($referer)) {
fputs($fp, "Referer: $referer\r\n");
}
if (isset($extra_headers) && is_array($extra_headers)) {
foreach ($extra_headers as $curr_header) {
fputs($fp, $curr_header . "\r\n");
}
}
if (!empty($user) && !empty($pass)) {
fputs($fp, "Authorization: BASIC " . base64_encode("$user:$pass") . "\r\n");
}
fputs($fp, "\r\n");
while (!feof($fp)) {
$content .= fgets($fp, 4096);
}
fclose($fp);
$csplit = preg_split("!\r\n\r\n!", $content, 2);
$content = $csplit[ 1 ];
if (!empty($params[ 'assign_headers' ])) {
$template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ]));
}
}
} else {
trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE);
return;
}
} else {
$content = @file_get_contents($params[ 'file' ]);
if ($content === false) {
throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'");
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $content);
} else {
return $content;
}
}
@@ -0,0 +1,256 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_checkboxes} function plugin
* File: function.html_checkboxes.php<br>
* Type: function<br>
* Name: html_checkboxes<br>
* Date: 24.Feb.2003<br>
* Purpose: Prints out a list of checkbox input types<br>
* Examples:
* <pre>
* {html_checkboxes values=$ids output=$names}
* {html_checkboxes values=$ids name='box' separator='<br>' output=$names}
* {html_checkboxes values=$ids checked=$checked separator='<br>' output=$names}
* </pre>
* Params:
* <pre>
* - name (optional) - string default "checkbox"
* - values (required) - array
* - options (optional) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or &nbsp;
* - output (optional) - the output next to each checkbox
* - assign (optional) - assign the output as an array to this variable
* - escape (optional) - escape the content (not value), defaults to true
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param object $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_checkboxes($params, $template)
{
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$name = 'checkbox';
$values = null;
$options = null;
$selected = array();
$separator = '';
$escape = true;
$labels = true;
$label_ids = false;
$output = null;
$pos = null;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'separator':
$$_key = (string) $_val;
break;
case 'escape':
case 'labels':
case 'label_ids':
$$_key = (bool) $_val;
break;
case 'options':
$$_key = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'checked':
case 'selected':
if (is_array($_val)) {
$selected = array();
foreach ($_val as $_sel) {
if (is_object($_sel)) {
if (method_exists($_sel, "__toString")) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else {
trigger_error("html_checkboxes: selected attribute contains an object of class '" .
get_class($_sel) . "' without __toString() method", E_USER_NOTICE);
continue;
}
} else {
$_sel = smarty_function_escape_special_chars((string) $_sel);
}
$selected[ $_sel ] = true;
}
} elseif (is_object($_val)) {
if (method_exists($_val, "__toString")) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error("html_checkboxes: selected attribute is an object of class '" . get_class($_val) .
"' without __toString() method", E_USER_NOTICE);
}
} else {
$selected = smarty_function_escape_special_chars((string) $_val);
}
break;
case 'checkboxes':
trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead',
E_USER_WARNING);
$options = (array) $_val;
break;
case 'assign':
break;
case 'pos':
$$_key = array_values((array)$_val);
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_checkboxes: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
return '';
} /* raise error here? */
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_pos = isset($pos[ $_key ]) ? $pos[ $_key ] : '';
$_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $_pos, $escape);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_pos = isset($pos[ $_i ]) ? $pos[ $_i ] : '';
$_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $_pos, $escape);
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result);
} else {
return implode("\n", $_html_result);
}
}
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels,
$label_ids, $pos, $escape = true)
{
$_output = '';
if (is_object($value)) {
if (method_exists($value, "__toString")) {
$value = (string) $value->__toString();
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) .
"' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
$value = (string) $value;
}
if (is_object($output)) {
if (method_exists($output, "__toString")) {
$output = (string) $output->__toString();
} else {
trigger_error("html_options: output is an object of class '" . get_class($output) .
"' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
$output = (string) $output;
}
if ($labels) {
if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_',
$name . '_' . $value));
$_output .= '<label for="' . $_id . '">';
} else {
$_output .= '<label>';
}
}
$name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value);
if ($escape) {
$output = smarty_function_escape_special_chars($output);
}
$_output .= '<input type="checkbox" name="' . $name . '[' . $pos . ']" value="' . $value . '"';
if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"';
}
if (is_array($selected)) {
if (isset($selected[ $value ])) {
$_output .= ' checked="checked"';
}
} elseif ($value === $selected) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) {
$_output .= '</label>';
}
$_output .= $separator;
return $_output;
}
@@ -0,0 +1,164 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_image} function plugin
* Type: function<br>
* Name: html_image<br>
* Date: Feb 24, 2003<br>
* Purpose: format HTML tags for the image<br>
* Examples: {html_image file="/images/masthead.gif"}<br>
* Output: <img src="/images/masthead.gif" width=400 height=23><br>
* Params:
* <pre>
* - file - (required) - file (and path) of image
* - height - (optional) - image height (default actual height)
* - width - (optional) - image width (default actual width)
* - basedir - (optional) - base directory for absolute paths, default is environment variable DOCUMENT_ROOT
* - path_prefix - prefix for path output (optional, default empty)
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.html.image.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Duda <duda@big.hu>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_image($params, $template)
{
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$alt = '';
$file = '';
$height = '';
$width = '';
$extra = '';
$prefix = '';
$suffix = '';
$path_prefix = '';
$basedir = isset($_SERVER[ 'DOCUMENT_ROOT' ]) ? $_SERVER[ 'DOCUMENT_ROOT' ] : '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'file':
case 'height':
case 'width':
case 'dpi':
case 'path_prefix':
case 'basedir':
$$_key = $_val;
break;
case 'alt':
if (!is_array($_val)) {
$$_key = smarty_function_escape_special_chars($_val);
} else {
throw new SmartyException ("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
case 'link':
case 'href':
$prefix = '<a href="' . $_val . '">';
$suffix = '</a>';
break;
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
throw new SmartyException ("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (empty($file)) {
trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE);
return;
}
if ($file[ 0 ] == '/') {
$_image_path = $basedir . $file;
} else {
$_image_path = $file;
}
// strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7);
}
$protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
}
if (isset($template->smarty->security_policy)) {
if ($protocol) {
// remote resource (or php stream, …)
if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) {
return;
}
} else {
// local file
if (!$template->smarty->security_policy->isTrustedResourceDir($_image_path)) {
return;
}
}
}
if (!isset($params[ 'width' ]) || !isset($params[ 'height' ])) {
// FIXME: (rodneyrehm) getimagesize() loads the complete file off a remote resource, use custom [jpg,png,gif]header reader!
if (!$_image_data = @getimagesize($_image_path)) {
if (!file_exists($_image_path)) {
trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE);
return;
} elseif (!is_readable($_image_path)) {
trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE);
return;
} else {
trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE);
return;
}
}
if (!isset($params[ 'width' ])) {
$width = $_image_data[ 0 ];
}
if (!isset($params[ 'height' ])) {
$height = $_image_data[ 1 ];
}
}
if (isset($params[ 'dpi' ])) {
if (strstr($_SERVER[ 'HTTP_USER_AGENT' ], 'Mac')) {
// FIXME: (rodneyrehm) wrong dpi assumption
// don't know who thought this up… even if it was true in 1998, it's definitely wrong in 2011.
$dpi_default = 72;
} else {
$dpi_default = 96;
}
$_resize = $dpi_default / $params[ 'dpi' ];
$width = round($width * $_resize);
$height = round($height * $_resize);
}
return $prefix . '<img src="' . $path_prefix . $file . '" alt="' . $alt . '" width="' . $width . '" height="' .
$height . '"' . $extra . ' />' . $suffix;
}
@@ -0,0 +1,210 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_options} function plugin
* Type: function<br>
* Name: html_options<br>
* Purpose: Prints the list of <option> tags generated from
* the passed parameters<br>
* Params:
* <pre>
* - name (optional) - string default "select"
* - values (required) - if no options supplied) - array
* - options (required) - if no values supplied) - associative array
* - selected (optional) - string default not set
* - output (required) - if not options supplied) - array
* - id (optional) - string default not set
* - class (optional) - string default not set
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.html.options.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Ralf Strehle (minor optimization) <ralf dot strehle at yahoo dot de>
*
* @param array $params parameters
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_options($params)
{
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$name = null;
$values = null;
$options = null;
$selected = null;
$output = null;
$id = null;
$class = null;
$label = true;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'class':
case 'id':
$$_key = (string) $_val;
break;
case 'options':
$options = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'selected':
if (is_array($_val)) {
$selected = array();
foreach ($_val as $_sel) {
if (is_object($_sel)) {
if (method_exists($_sel, "__toString")) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else {
trigger_error("html_options: selected attribute contains an object of class '" .
get_class($_sel) . "' without __toString() method", E_USER_NOTICE);
continue;
}
} else {
$_sel = smarty_function_escape_special_chars((string) $_sel);
}
$selected[ $_sel ] = true;
}
} elseif (is_object($_val)) {
if (method_exists($_val, "__toString")) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error("html_options: selected attribute is an object of class '" . get_class($_val) .
"' without __toString() method", E_USER_NOTICE);
}
} else {
$selected = smarty_function_escape_special_chars((string) $_val);
}
break;
case 'label':
if ($_val == 'true' || $_val == 'false')
$$_key = (string)$_val;
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
$_html_result = '';
$_idx = 0;
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $label, $_idx);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $label, $_idx);
}
}
if (!empty($name)) {
$_html_class = !empty($class) ? ' class="' . $class . '"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '"' : '';
$_html_result =
'<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result .
'</select>' . "\n";
}
return $_html_result;
}
function smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $label, &$idx)
{
if (!is_array($value)) {
$_key = smarty_function_escape_special_chars($key);
$_html_result = '<option' . (($label == 'true') ? ' label="' . smarty_function_escape_special_chars($value) . '"' : '') . ' value="' . $_key . '"';
if (is_array($selected)) {
if (isset($selected[ $_key ])) {
$_html_result .= ' selected="selected"';
}
} elseif ($_key === $selected) {
$_html_result .= ' selected="selected"';
}
$_html_class = !empty($class) ? ' class="' . $class . ' option"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '-' . $idx . '"' : '';
if (is_object($value)) {
if (method_exists($value, "__toString")) {
$value = smarty_function_escape_special_chars((string) $value->__toString());
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) .
"' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
$value = smarty_function_escape_special_chars((string) $value);
}
$_html_result .= $_html_class . $_html_id . '>' . $value . '</option>' . "\n";
$idx ++;
} else {
$_idx = 0;
$_html_result =
smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null,
$class, $label, $_idx);
$idx ++;
}
return $_html_result;
}
function smarty_function_html_options_optgroup($key, $values, $selected, $id, $class, $label, &$idx)
{
$optgroup_html = '<optgroup label="' . smarty_function_escape_special_chars($key) . '">' . "\n";
foreach ($values as $key => $value) {
$optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $label, $idx);
}
$optgroup_html .= "</optgroup>\n";
return $optgroup_html;
}
@@ -0,0 +1,232 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_radios} function plugin
* File: function.html_radios.php<br>
* Type: function<br>
* Name: html_radios<br>
* Date: 24.Feb.2003<br>
* Purpose: Prints out a list of radio input types<br>
* Params:
* <pre>
* - name (optional) - string default "radio"
* - values (required) - array
* - options (required) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or &nbsp;
* - output (optional) - the output next to each radio button
* - assign (optional) - assign the output as an array to this variable
* - escape (optional) - escape the content (not value), defaults to true
* </pre>
* Examples:
* <pre>
* {html_radios values=$ids output=$names}
* {html_radios values=$ids name='box' separator='<br>' output=$names}
* {html_radios values=$ids checked=$checked separator='<br>' output=$names}
* </pre>
*
* @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_radios($params, $template)
{
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$name = 'radio';
$values = null;
$options = null;
$selected = null;
$separator = '';
$escape = true;
$labels = true;
$label_ids = false;
$output = null;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'separator':
$$_key = (string) $_val;
break;
case 'checked':
case 'selected':
if (is_array($_val)) {
trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING);
} elseif (is_object($_val)) {
if (method_exists($_val, "__toString")) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error("html_radios: selected attribute is an object of class '" . get_class($_val) .
"' without __toString() method", E_USER_NOTICE);
}
} else {
$selected = (string) $_val;
}
break;
case 'escape':
case 'labels':
case 'label_ids':
$$_key = (bool) $_val;
break;
case 'options':
$$_key = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'radios':
trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead',
E_USER_WARNING);
$options = (array) $_val;
break;
case 'assign':
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: $_key attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_radios: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result);
} else {
return implode("\n", $_html_result);
}
}
function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids,
$escape)
{
$_output = '';
if (is_object($value)) {
if (method_exists($value, "__toString")) {
$value = (string) $value->__toString();
} else {
trigger_error("html_options: value is an object of class '" . get_class($value) .
"' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
$value = (string) $value;
}
if (is_object($output)) {
if (method_exists($output, "__toString")) {
$output = (string) $output->__toString();
} else {
trigger_error("html_options: output is an object of class '" . get_class($output) .
"' without __toString() method", E_USER_NOTICE);
return '';
}
} else {
$output = (string) $output;
}
if ($labels) {
if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_',
$name . '_' . $value));
$_output .= '<label for="' . $_id . '">';
} else {
$_output .= '<label>';
}
}
$name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value);
if ($escape) {
$output = smarty_function_escape_special_chars($output);
}
$_output .= '<input type="radio" name="' . $name . '" value="' . $value . '"';
if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"';
}
if ($value === $selected) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) {
$_output .= '</label>';
}
$_output .= $separator;
return $_output;
}
@@ -0,0 +1,391 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* @ignore
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
/**
* @ignore
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
/**
* Smarty {html_select_date} plugin
* Type: function<br>
* Name: html_select_date<br>
* Purpose: Prints the dropdowns for date selection.
* ChangeLog:
* <pre>
* - 1.0 initial release
* - 1.1 added support for +/- N syntax for begin
* and end year values. (Monte)
* - 1.2 added support for yyyy-mm-dd syntax for
* time value. (Jan Rosier)
* - 1.3 added support for choosing format for
* month values (Gary Loescher)
* - 1.3.1 added support for choosing format for
* day values (Marcus Bointon)
* - 1.3.2 support negative timestamps, force year
* dropdown to include given date unless explicitly set (Monte)
* - 1.3.4 fix behaviour of 0000-00-00 00:00:00 dates to match that
* of 0000-00-00 dates (cybot, boots)
* - 2.0 complete rewrite for performance,
* added attributes month_names, *_id
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.html.select.date.php {html_select_date}
* (Smarty online manual)
* @version 2.0
* @author Andrei Zmievski
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string
*/
function smarty_function_html_select_date($params)
{
// generate timestamps used for month names only
static $_month_timestamps = null;
static $_current_year = null;
if ($_month_timestamps === null) {
$_current_year = date('Y');
$_month_timestamps = array();
for ($i = 1; $i <= 12; $i ++) {
$_month_timestamps[ $i ] = mktime(0, 0, 0, $i, 1, 2000);
}
}
/* Default values. */
$prefix = "Date_";
$start_year = null;
$end_year = null;
$display_days = true;
$display_months = true;
$display_years = true;
$month_format = "%B";
/* Write months as numbers by default GL */
$month_value_format = "%m";
$day_format = "%02d";
/* Write day values using this format MB */
$day_value_format = "%d";
$year_as_text = false;
/* Display years in reverse order? Ie. 2000,1999,.... */
$reverse_years = false;
/* Should the select boxes be part of an array when returned from PHP?
e.g. setting it to "birthday", would create "birthday[Day]",
"birthday[Month]" & "birthday[Year]". Can be combined with prefix */
$field_array = null;
/* <select size>'s of the different <select> tags.
If not set, uses default dropdown. */
$day_size = null;
$month_size = null;
$year_size = null;
/* Unparsed attributes common to *ALL* the <select>/<input> tags.
An example might be in the template: all_extra ='class ="foo"'. */
$all_extra = null;
/* Separate attributes for the tags. */
$day_extra = null;
$month_extra = null;
$year_extra = null;
/* Order in which to display the fields.
"D" -> day, "M" -> month, "Y" -> year. */
$field_order = 'MDY';
/* String printed between the different fields. */
$field_separator = "\n";
$option_separator = "\n";
$time = null;
// $all_empty = null;
// $day_empty = null;
// $month_empty = null;
// $year_empty = null;
$extra_attrs = '';
$all_id = null;
$day_id = null;
$month_id = null;
$year_id = null;
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'time':
if (!is_array($_value) && $_value !== null) {
$time = smarty_make_timestamp($_value);
}
break;
case 'month_names':
if (is_array($_value) && count($_value) == 12) {
$$_key = $_value;
} else {
trigger_error("html_select_date: month_names must be an array of 12 strings", E_USER_NOTICE);
}
break;
case 'prefix':
case 'field_array':
case 'start_year':
case 'end_year':
case 'day_format':
case 'day_value_format':
case 'month_format':
case 'month_value_format':
case 'day_size':
case 'month_size':
case 'year_size':
case 'all_extra':
case 'day_extra':
case 'month_extra':
case 'year_extra':
case 'field_order':
case 'field_separator':
case 'option_separator':
case 'all_empty':
case 'month_empty':
case 'day_empty':
case 'year_empty':
case 'all_id':
case 'month_id':
case 'day_id':
case 'year_id':
$$_key = (string) $_value;
break;
case 'display_days':
case 'display_months':
case 'display_years':
case 'year_as_text':
case 'reverse_years':
$$_key = (bool) $_value;
break;
default:
if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
} else {
trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
// Note: date() is faster than strftime()
// Note: explode(date()) is faster than date() date() date()
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Year' ])) {
// $_REQUEST[$field_array] given
foreach (array('Y' => 'Year', 'm' => 'Month', 'd' => 'Day') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
date($_elementKey);
}
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Year' ])) {
// $_REQUEST given
foreach (array('Y' => 'Year', 'm' => 'Month', 'd' => 'Day') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
}
} else {
// no date found, use NOW
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} elseif ($time === null) {
if (array_key_exists('time', $params)) {
$_year = $_month = $_day = $time = null;
} else {
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} else {
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time));
}
// make syntax "+N" or "-N" work with $start_year and $end_year
// Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr
foreach (array('start', 'end') as $key) {
$key .= '_year';
$t = $$key;
if ($t === null) {
$$key = (int) $_current_year;
} elseif ($t[ 0 ] == '+') {
$$key = (int) ($_current_year + (int) trim(substr($t, 1)));
} elseif ($t[ 0 ] == '-') {
$$key = (int) ($_current_year - (int) trim(substr($t, 1)));
} else {
$$key = (int) $$key;
}
}
// flip for ascending or descending
if (($start_year > $end_year && !$reverse_years) || ($start_year < $end_year && $reverse_years)) {
$t = $end_year;
$end_year = $start_year;
$start_year = $t;
}
// generate year <select> or <input>
if ($display_years) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Year]') : ($prefix . 'Year');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($year_extra) {
$_extra .= ' ' . $year_extra;
}
if ($year_as_text) {
$_html_years =
'<input type="text" name="' . $_name . '" value="' . $_year . '" size="4" maxlength="4"' . $_extra .
$extra_attrs . ' />';
} else {
$_html_years = '<select name="' . $_name . '"';
if ($year_id !== null || $all_id !== null) {
$_html_years .= ' id="' . smarty_function_escape_special_chars($year_id !== null ?
($year_id ? $year_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($year_size) {
$_html_years .= ' size="' . $year_size . '"';
}
$_html_years .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($year_empty) || isset($all_empty)) {
$_html_years .= '<option value="">' . (isset($year_empty) ? $year_empty : $all_empty) . '</option>' .
$option_separator;
}
$op = $start_year > $end_year ? - 1 : 1;
for ($i = $start_year; $op > 0 ? $i <= $end_year : $i >= $end_year; $i += $op) {
$_html_years .= '<option value="' . $i . '"' . ($_year == $i ? ' selected="selected"' : '') . '>' . $i .
'</option>' . $option_separator;
}
$_html_years .= '</select>';
}
}
// generate month <select> or <input>
if ($display_months) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Month]') : ($prefix . 'Month');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($month_extra) {
$_extra .= ' ' . $month_extra;
}
$_html_months = '<select name="' . $_name . '"';
if ($month_id !== null || $all_id !== null) {
$_html_months .= ' id="' . smarty_function_escape_special_chars($month_id !== null ?
($month_id ? $month_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($month_size) {
$_html_months .= ' size="' . $month_size . '"';
}
$_html_months .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($month_empty) || isset($all_empty)) {
$_html_months .= '<option value="">' . (isset($month_empty) ? $month_empty : $all_empty) . '</option>' .
$option_separator;
}
for ($i = 1; $i <= 12; $i ++) {
$_val = sprintf('%02d', $i);
$_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[ $i ]) :
($month_format == "%m" ? $_val : strftime($month_format, $_month_timestamps[ $i ]));
$_value = $month_value_format == "%m" ? $_val : strftime($month_value_format, $_month_timestamps[ $i ]);
$_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_months .= '</select>';
}
// generate day <select> or <input>
if ($display_days) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Day]') : ($prefix . 'Day');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($day_extra) {
$_extra .= ' ' . $day_extra;
}
$_html_days = '<select name="' . $_name . '"';
if ($day_id !== null || $all_id !== null) {
$_html_days .= ' id="' .
smarty_function_escape_special_chars($day_id !== null ? ($day_id ? $day_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)) . '"';
}
if ($day_size) {
$_html_days .= ' size="' . $day_size . '"';
}
$_html_days .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($day_empty) || isset($all_empty)) {
$_html_days .= '<option value="">' . (isset($day_empty) ? $day_empty : $all_empty) . '</option>' .
$option_separator;
}
for ($i = 1; $i <= 31; $i ++) {
$_val = sprintf('%02d', $i);
$_text = $day_format == '%02d' ? $_val : sprintf($day_format, $i);
$_value = $day_value_format == '%02d' ? $_val : sprintf($day_value_format, $i);
$_html_days .= '<option value="' . $_value . '"' . ($_val == $_day ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator;
}
$_html_days .= '</select>';
}
// order the fields for output
$_html = '';
for ($i = 0; $i <= 2; $i ++) {
switch ($field_order[ $i ]) {
case 'Y':
case 'y':
if (isset($_html_years)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_years;
}
break;
case 'm':
case 'M':
if (isset($_html_months)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_months;
}
break;
case 'd':
case 'D':
if (isset($_html_days)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_days;
}
break;
}
}
return $_html;
}
@@ -0,0 +1,366 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* @ignore
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
/**
* @ignore
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
/**
* Smarty {html_select_time} function plugin
* Type: function<br>
* Name: html_select_time<br>
* Purpose: Prints the dropdowns for time selection
*
* @link http://www.smarty.net/manual/en/language.function.html.select.time.php {html_select_time}
* (Smarty online manual)
* @author Roberto Berto <roberto@berto.net>
* @author Monte Ohrt <monte AT ohrt DOT com>
*
* @param array $params parameters
*
* @return string
* @uses smarty_make_timestamp()
*/
function smarty_function_html_select_time($params)
{
$prefix = "Time_";
$field_array = null;
$field_separator = "\n";
$option_separator = "\n";
$time = null;
$display_hours = true;
$display_minutes = true;
$display_seconds = true;
$display_meridian = true;
$hour_format = '%02d';
$hour_value_format = '%02d';
$minute_format = '%02d';
$minute_value_format = '%02d';
$second_format = '%02d';
$second_value_format = '%02d';
$hour_size = null;
$minute_size = null;
$second_size = null;
$meridian_size = null;
$all_empty = null;
$hour_empty = null;
$minute_empty = null;
$second_empty = null;
$meridian_empty = null;
$all_id = null;
$hour_id = null;
$minute_id = null;
$second_id = null;
$meridian_id = null;
$use_24_hours = true;
$minute_interval = 1;
$second_interval = 1;
$extra_attrs = '';
$all_extra = null;
$hour_extra = null;
$minute_extra = null;
$second_extra = null;
$meridian_extra = null;
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'time':
if (!is_array($_value) && $_value !== null) {
$time = smarty_make_timestamp($_value);
}
break;
case 'prefix':
case 'field_array':
case 'field_separator':
case 'option_separator':
case 'all_extra':
case 'hour_extra':
case 'minute_extra':
case 'second_extra':
case 'meridian_extra':
case 'all_empty':
case 'hour_empty':
case 'minute_empty':
case 'second_empty':
case 'meridian_empty':
case 'all_id':
case 'hour_id':
case 'minute_id':
case 'second_id':
case 'meridian_id':
case 'hour_format':
case 'hour_value_format':
case 'minute_format':
case 'minute_value_format':
case 'second_format':
case 'second_value_format':
$$_key = (string) $_value;
break;
case 'display_hours':
case 'display_minutes':
case 'display_seconds':
case 'display_meridian':
case 'use_24_hours':
$$_key = (bool) $_value;
break;
case 'minute_interval':
case 'second_interval':
case 'hour_size':
case 'minute_size':
case 'second_size':
case 'meridian_size':
$$_key = (int) $_value;
break;
default:
if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
} else {
trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Hour' ])) {
// $_REQUEST[$field_array] given
foreach (array('H' => 'Hour', 'i' => 'Minute', 's' => 'Second') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
date($_elementKey);
}
$_meridian =
isset($params[ 'time' ][ $prefix . 'Meridian' ]) ? (' ' . $params[ 'time' ][ $prefix . 'Meridian' ]) :
'';
$time = strtotime($_hour . ':' . $_minute . ':' . $_second . $_meridian);
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Hour' ])) {
// $_REQUEST given
foreach (array('H' => 'Hour', 'i' => 'Minute', 's' => 'Second') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
}
$_meridian = isset($params[ 'time' ][ $field_array ][ $prefix . 'Meridian' ]) ?
(' ' . $params[ 'time' ][ $field_array ][ $prefix . 'Meridian' ]) : '';
$time = strtotime($_hour . ':' . $_minute . ':' . $_second . $_meridian);
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} else {
// no date found, use NOW
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} elseif ($time === null) {
if (array_key_exists('time', $params)) {
$_hour = $_minute = $_second = $time = null;
} else {
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s'));
}
} else {
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
}
// generate hour <select>
if ($display_hours) {
$_html_hours = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Hour]') : ($prefix . 'Hour');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($hour_extra) {
$_extra .= ' ' . $hour_extra;
}
$_html_hours = '<select name="' . $_name . '"';
if ($hour_id !== null || $all_id !== null) {
$_html_hours .= ' id="' .
smarty_function_escape_special_chars($hour_id !== null ? ($hour_id ? $hour_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)) . '"';
}
if ($hour_size) {
$_html_hours .= ' size="' . $hour_size . '"';
}
$_html_hours .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($hour_empty) || isset($all_empty)) {
$_html_hours .= '<option value="">' . (isset($hour_empty) ? $hour_empty : $all_empty) . '</option>' .
$option_separator;
}
$start = $use_24_hours ? 0 : 1;
$end = $use_24_hours ? 23 : 12;
for ($i = $start; $i <= $end; $i ++) {
$_val = sprintf('%02d', $i);
$_text = $hour_format == '%02d' ? $_val : sprintf($hour_format, $i);
$_value = $hour_value_format == '%02d' ? $_val : sprintf($hour_value_format, $i);
if (!$use_24_hours) {
$_hour12 = $_hour == 0 ? 12 : ($_hour <= 12 ? $_hour : $_hour - 12);
}
$selected = $_hour !== null ? ($use_24_hours ? $_hour == $_val : $_hour12 == $_val) : null;
$_html_hours .= '<option value="' . $_value . '"' . ($selected ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator;
}
$_html_hours .= '</select>';
}
// generate minute <select>
if ($display_minutes) {
$_html_minutes = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Minute]') : ($prefix . 'Minute');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($minute_extra) {
$_extra .= ' ' . $minute_extra;
}
$_html_minutes = '<select name="' . $_name . '"';
if ($minute_id !== null || $all_id !== null) {
$_html_minutes .= ' id="' . smarty_function_escape_special_chars($minute_id !== null ?
($minute_id ? $minute_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($minute_size) {
$_html_minutes .= ' size="' . $minute_size . '"';
}
$_html_minutes .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($minute_empty) || isset($all_empty)) {
$_html_minutes .= '<option value="">' . (isset($minute_empty) ? $minute_empty : $all_empty) . '</option>' .
$option_separator;
}
$selected = $_minute !== null ? ($_minute - $_minute % $minute_interval) : null;
for ($i = 0; $i <= 59; $i += $minute_interval) {
$_val = sprintf('%02d', $i);
$_text = $minute_format == '%02d' ? $_val : sprintf($minute_format, $i);
$_value = $minute_value_format == '%02d' ? $_val : sprintf($minute_value_format, $i);
$_html_minutes .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_minutes .= '</select>';
}
// generate second <select>
if ($display_seconds) {
$_html_seconds = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Second]') : ($prefix . 'Second');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($second_extra) {
$_extra .= ' ' . $second_extra;
}
$_html_seconds = '<select name="' . $_name . '"';
if ($second_id !== null || $all_id !== null) {
$_html_seconds .= ' id="' . smarty_function_escape_special_chars($second_id !== null ?
($second_id ? $second_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($second_size) {
$_html_seconds .= ' size="' . $second_size . '"';
}
$_html_seconds .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($second_empty) || isset($all_empty)) {
$_html_seconds .= '<option value="">' . (isset($second_empty) ? $second_empty : $all_empty) . '</option>' .
$option_separator;
}
$selected = $_second !== null ? ($_second - $_second % $second_interval) : null;
for ($i = 0; $i <= 59; $i += $second_interval) {
$_val = sprintf('%02d', $i);
$_text = $second_format == '%02d' ? $_val : sprintf($second_format, $i);
$_value = $second_value_format == '%02d' ? $_val : sprintf($second_value_format, $i);
$_html_seconds .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_seconds .= '</select>';
}
// generate meridian <select>
if ($display_meridian && !$use_24_hours) {
$_html_meridian = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Meridian]') : ($prefix . 'Meridian');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($meridian_extra) {
$_extra .= ' ' . $meridian_extra;
}
$_html_meridian = '<select name="' . $_name . '"';
if ($meridian_id !== null || $all_id !== null) {
$_html_meridian .= ' id="' . smarty_function_escape_special_chars($meridian_id !== null ?
($meridian_id ? $meridian_id :
$_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($meridian_size) {
$_html_meridian .= ' size="' . $meridian_size . '"';
}
$_html_meridian .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($meridian_empty) || isset($all_empty)) {
$_html_meridian .= '<option value="">' . (isset($meridian_empty) ? $meridian_empty : $all_empty) .
'</option>' . $option_separator;
}
$_html_meridian .= '<option value="am"' . ($_hour > 0 && $_hour < 12 ? ' selected="selected"' : '') .
'>AM</option>' . $option_separator . '<option value="pm"' .
($_hour < 12 ? '' : ' selected="selected"') . '>PM</option>' . $option_separator .
'</select>';
}
$_html = '';
foreach (array('_html_hours', '_html_minutes', '_html_seconds', '_html_meridian') as $k) {
if (isset($$k)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $$k;
}
}
return $_html;
}
@@ -0,0 +1,176 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_table} function plugin
* Type: function<br>
* Name: html_table<br>
* Date: Feb 17, 2003<br>
* Purpose: make an html table from an array of data<br>
* Params:
* <pre>
* - loop - array to loop through
* - cols - number of columns, comma separated list of column names
* or array of column names
* - rows - number of rows
* - table_attr - table attributes
* - th_attr - table heading attributes (arrays are cycled)
* - tr_attr - table row attributes (arrays are cycled)
* - td_attr - table cell attributes (arrays are cycled)
* - trailpad - value to pad trailing cells with
* - caption - text for caption element
* - vdir - vertical direction (default: "down", means top-to-bottom)
* - hdir - horizontal direction (default: "right", means left-to-right)
* - inner - inner loop (default "cols": print $loop line by line,
* $loop will be printed column by column otherwise)
* </pre>
* Examples:
* <pre>
* {table loop=$data}
* {table loop=$data cols=4 tr_attr='"bgcolor=red"'}
* {table loop=$data cols="first,second,third" tr_attr=$colors}
* </pre>
*
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Messju Mohr <messju at lammfellpuschen dot de>
* @author credit to boots <boots dot smarty at yahoo dot com>
* @version 1.1
* @link http://www.smarty.net/manual/en/language.function.html.table.php {html_table}
* (Smarty online manual)
*
* @param array $params parameters
*
* @return string
*/
function smarty_function_html_table($params)
{
$table_attr = 'border="1"';
$tr_attr = '';
$th_attr = '';
$td_attr = '';
$cols = $cols_count = 3;
$rows = 3;
$trailpad = '&nbsp;';
$vdir = 'down';
$hdir = 'right';
$inner = 'cols';
$caption = '';
$loop = null;
if (!isset($params[ 'loop' ])) {
trigger_error("html_table: missing 'loop' parameter", E_USER_WARNING);
return;
}
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'loop':
$$_key = (array) $_value;
break;
case 'cols':
if (is_array($_value) && !empty($_value)) {
$cols = $_value;
$cols_count = count($_value);
} elseif (!is_numeric($_value) && is_string($_value) && !empty($_value)) {
$cols = explode(',', $_value);
$cols_count = count($cols);
} elseif (!empty($_value)) {
$cols_count = (int) $_value;
} else {
$cols_count = $cols;
}
break;
case 'rows':
$$_key = (int) $_value;
break;
case 'table_attr':
case 'trailpad':
case 'hdir':
case 'vdir':
case 'inner':
case 'caption':
$$_key = (string) $_value;
break;
case 'tr_attr':
case 'td_attr':
case 'th_attr':
$$_key = $_value;
break;
}
}
$loop_count = count($loop);
if (empty($params[ 'rows' ])) {
/* no rows specified */
$rows = ceil($loop_count / $cols_count);
} elseif (empty($params[ 'cols' ])) {
if (!empty($params[ 'rows' ])) {
/* no cols specified, but rows */
$cols_count = ceil($loop_count / $rows);
}
}
$output = "<table $table_attr>\n";
if (!empty($caption)) {
$output .= '<caption>' . $caption . "</caption>\n";
}
if (is_array($cols)) {
$cols = ($hdir == 'right') ? $cols : array_reverse($cols);
$output .= "<thead><tr>\n";
for ($r = 0; $r < $cols_count; $r ++) {
$output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>';
$output .= $cols[ $r ];
$output .= "</th>\n";
}
$output .= "</tr></thead>\n";
}
$output .= "<tbody>\n";
for ($r = 0; $r < $rows; $r ++) {
$output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n";
$rx = ($vdir == 'down') ? $r * $cols_count : ($rows - 1 - $r) * $cols_count;
for ($c = 0; $c < $cols_count; $c ++) {
$x = ($hdir == 'right') ? $rx + $c : $rx + $cols_count - 1 - $c;
if ($inner != 'cols') {
/* shuffle x to loop over rows*/
$x = floor($x / $cols_count) + ($x % $cols_count) * $rows;
}
if ($x < $loop_count) {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[ $x ] . "</td>\n";
} else {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">$trailpad</td>\n";
}
}
$output .= "</tr>\n";
}
$output .= "</tbody>\n";
$output .= "</table>\n";
return $output;
}
function smarty_function_html_table_cycle($name, $var, $no)
{
if (!is_array($var)) {
$ret = $var;
} else {
$ret = $var[ $no % count($var) ];
}
return ($ret) ? ' ' . $ret : '';
}
@@ -0,0 +1,153 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {mailto} function plugin
* Type: function<br>
* Name: mailto<br>
* Date: May 21, 2002
* Purpose: automate mailto address link creation, and optionally encode them.<br>
* Params:
* <pre>
* - address - (required) - e-mail address
* - text - (optional) - text to display, default is address
* - encode - (optional) - can be one of:
* * none : no encoding (default)
* * javascript : encode with javascript
* * javascript_charcode : encode with javascript charcode
* * hex : encode with hexidecimal (no javascript)
* - cc - (optional) - address(es) to carbon copy
* - bcc - (optional) - address(es) to blind carbon copy
* - subject - (optional) - e-mail subject
* - newsgroups - (optional) - newsgroup(s) to post to
* - followupto - (optional) - address(es) to follow up to
* - extra - (optional) - extra tags for the href link
* </pre>
* Examples:
* <pre>
* {mailto address="me@domain.com"}
* {mailto address="me@domain.com" encode="javascript"}
* {mailto address="me@domain.com" encode="hex"}
* {mailto address="me@domain.com" subject="Hello to you!"}
* {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"}
* {mailto address="me@domain.com" extra='class="mailto"'}
* </pre>
*
* @link http://www.smarty.net/manual/en/language.function.mailto.php {mailto}
* (Smarty online manual)
* @version 1.2
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Jason Sweat (added cc, bcc and subject functionality)
*
* @param array $params parameters
*
* @return string
*/
function smarty_function_mailto($params)
{
static $_allowed_encoding =
array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true);
$extra = '';
if (empty($params[ 'address' ])) {
trigger_error("mailto: missing 'address' parameter", E_USER_WARNING);
return;
} else {
$address = $params[ 'address' ];
}
$text = $address;
// netscape and mozilla do not decode %40 (@) in BCC field (bug?)
// so, don't encode it.
$search = array('%40', '%2C');
$replace = array('@', ',');
$mail_parms = array();
foreach ($params as $var => $value) {
switch ($var) {
case 'cc':
case 'bcc':
case 'followupto':
if (!empty($value)) {
$mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value));
}
break;
case 'subject':
case 'newsgroups':
$mail_parms[] = $var . '=' . rawurlencode($value);
break;
case 'extra':
case 'text':
$$var = $value;
default:
}
}
if ($mail_parms) {
$address .= '?' . join('&', $mail_parms);
}
$encode = (empty($params[ 'encode' ])) ? 'none' : $params[ 'encode' ];
if (!isset($_allowed_encoding[ $encode ])) {
trigger_error("mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex",
E_USER_WARNING);
return;
}
// FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed!
if ($encode == 'javascript') {
$string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');';
$js_encode = '';
for ($x = 0, $_length = strlen($string); $x < $_length; $x ++) {
$js_encode .= '%' . bin2hex($string[ $x ]);
}
return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>';
} elseif ($encode == 'javascript_charcode') {
$string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
for ($x = 0, $y = strlen($string); $x < $y; $x ++) {
$ord[] = ord($string[ $x ]);
}
$_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" .
implode(',', $ord) . "))" . "}\n" . "</script>\n";
return $_ret;
} elseif ($encode == 'hex') {
preg_match('!^(.*)(\?.*)$!', $address, $match);
if (!empty($match[ 2 ])) {
trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.", E_USER_WARNING);
return;
}
$address_encode = '';
for ($x = 0, $_length = strlen($address); $x < $_length; $x ++) {
if (preg_match('!\w!' . Smarty::$_UTF8_MODIFIER, $address[ $x ])) {
$address_encode .= '%' . bin2hex($address[ $x ]);
} else {
$address_encode .= $address[ $x ];
}
}
$text_encode = '';
for ($x = 0, $_length = strlen($text); $x < $_length; $x ++) {
$text_encode .= '&#x' . bin2hex($text[ $x ]) . ';';
}
$mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;";
return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>';
} else {
// no encoding
return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
/**
* Smarty plugin
* This plugin is only for Smarty2 BC
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {math} function plugin
* Type: function<br>
* Name: math<br>
* Purpose: handle math computations in template
*
* @link http://www.smarty.net/manual/en/language.function.math.php {math}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_math($params, $template)
{
static $_allowed_funcs =
array('int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true,
'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true, 'rand' => true,
'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true, 'tan' => true);
// be sure equation parameter is present
if (empty($params[ 'equation' ])) {
trigger_error("math: missing equation parameter", E_USER_WARNING);
return;
}
$equation = $params[ 'equation' ];
// make sure parenthesis are balanced
if (substr_count($equation, "(") != substr_count($equation, ")")) {
trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
return;
}
// disallow backticks
if (strpos($equation, '`') !== false) {
trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
return;
}
// also disallow dollar signs
if (strpos($equation, '$') !== false) {
trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
return;
}
// match all vars in equation, make sure all are passed
preg_match_all('!(?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)!', $equation, $match);
foreach ($match[ 1 ] as $curr_var) {
if ($curr_var && !isset($params[ $curr_var ]) && !isset($_allowed_funcs[ $curr_var ])) {
trigger_error("math: function call $curr_var not allowed", E_USER_WARNING);
return;
}
}
foreach ($params as $key => $val) {
if ($key != "equation" && $key != "format" && $key != "assign") {
// make sure value is not empty
if (strlen($val) == 0) {
trigger_error("math: parameter $key is empty", E_USER_WARNING);
return;
}
if (!is_numeric($val)) {
trigger_error("math: parameter $key: is not numeric", E_USER_WARNING);
return;
}
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
}
}
$smarty_math_result = null;
eval("\$smarty_math_result = " . $equation . ";");
if (empty($params[ 'format' ])) {
if (empty($params[ 'assign' ])) {
return $smarty_math_result;
} else {
$template->assign($params[ 'assign' ], $smarty_math_result);
}
} else {
if (empty($params[ 'assign' ])) {
printf($params[ 'format' ], $smarty_math_result);
} else {
$template->assign($params[ 'assign' ], sprintf($params[ 'format' ], $smarty_math_result));
}
}
}
@@ -0,0 +1,119 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {popup} function plugin
*
* Type: function<br>
* Name: popup<br>
* Purpose: make text pop up in windows via overlib
* @link http://smarty.php.net/manual/en/language.function.popup.php {popup}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_popup($params, &$smarty)
{
$append = '';
foreach ($params as $_key=>$_value) {
switch ($_key) {
case 'text':
case 'trigger':
case 'function':
case 'inarray':
$$_key = (string)$_value;
if ($_key == 'function' || $_key == 'inarray')
$append .= ',' . strtoupper($_key) . ",'$_value'";
break;
case 'caption':
case 'closetext':
case 'status':
$append .= ',' . strtoupper($_key) . ",'" . str_replace("'","\'",$_value) . "'";
break;
case 'fgcolor':
case 'bgcolor':
case 'textcolor':
case 'capcolor':
case 'closecolor':
case 'textfont':
case 'captionfont':
case 'closefont':
case 'fgbackground':
case 'bgbackground':
case 'caparray':
case 'capicon':
case 'background':
case 'frame':
$append .= ',' . strtoupper($_key) . ",'$_value'";
break;
case 'textsize':
case 'captionsize':
case 'closesize':
case 'width':
case 'height':
case 'border':
case 'offsetx':
case 'offsety':
case 'snapx':
case 'snapy':
case 'fixx':
case 'fixy':
case 'padx':
case 'pady':
case 'timeout':
case 'delay':
$append .= ',' . strtoupper($_key) . ",$_value";
break;
case 'sticky':
case 'left':
case 'right':
case 'center':
case 'above':
case 'below':
case 'noclose':
case 'autostatus':
case 'autostatuscap':
case 'fullhtml':
case 'hauto':
case 'vauto':
case 'mouseoff':
case 'followmouse':
case 'closeclick':
if ($_value) $append .= ',' . strtoupper($_key);
break;
default:
$smarty->trigger_error("[popup] unknown parameter $_key", E_USER_WARNING);
}
}
if (empty($text) && !isset($inarray) && empty($function)) {
$smarty->trigger_error("overlib: attribute 'text' or 'inarray' or 'function' required");
return false;
}
if (empty($trigger)) { $trigger = "onmouseover"; }
$retval = $trigger . '="return overlib(\''.preg_replace(array("!'!","![\r\n]!"),array("\'",'\r'),$text).'\'';
$retval .= $append . ');"';
if ($trigger == 'onmouseover')
$retval .= ' onmouseout="nd();"';
return $retval;
}
/* vim: set expandtab: */
?>
@@ -0,0 +1,40 @@
<?php
/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {popup_init} function plugin
*
* Type: function<br>
* Name: popup_init<br>
* Purpose: initialize overlib
* @link http://smarty.php.net/manual/en/language.function.popup.init.php {popup_init}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @param array
* @param Smarty
* @return string
*/
function smarty_function_popup_init($params, &$smarty)
{
$zindex = 1000;
if (!empty($params['zindex'])) {
$zindex = $params['zindex'];
}
if (!empty($params['src'])) {
return '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:'.$zindex.';"></div>' . "\n"
. '<script type="text/javascript" language="JavaScript" src="'.$params['src'].'"></script>' . "\n";
} else {
$smarty->trigger_error("popup_init: missing src parameter");
}
}
/* vim: set expandtab: */
?>
@@ -0,0 +1,101 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty capitalize modifier plugin
* Type: modifier<br>
* Name: capitalize<br>
* Purpose: capitalize words in the string
* {@internal {$string|capitalize:true:true} is the fastest option for MBString enabled systems }}
*
* @param string $string string to capitalize
* @param boolean $uc_digits also capitalize "x123" to "X123"
* @param boolean $lc_rest capitalize first letters, lowercase all following letters "aAa" to "Aaa"
*
* @return string capitalized string
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
*/
function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = false)
{
if (Smarty::$_MBSTRING) {
if ($lc_rest) {
// uppercase (including hyphenated words)
$upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET);
} else {
// uppercase word breaks
$upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_mbconvert_cb', $string);
}
// check uc_digits case
if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
PREG_OFFSET_CAPTURE)) {
foreach ($matches[ 1 ] as $match) {
$upper_string =
substr_replace($upper_string, mb_strtolower($match[ 0 ], Smarty::$_CHARSET), $match[ 1 ],
strlen($match[ 0 ]));
}
}
}
$upper_string =
preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert2_cb',
$upper_string);
return $upper_string;
}
// lowercase first
if ($lc_rest) {
$string = strtolower($string);
}
// uppercase (including hyphenated words)
$upper_string =
preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst_cb',
$string);
// check uc_digits case
if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
PREG_OFFSET_CAPTURE)) {
foreach ($matches[ 1 ] as $match) {
$upper_string =
substr_replace($upper_string, strtolower($match[ 0 ]), $match[ 1 ], strlen($match[ 0 ]));
}
}
}
$upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst2_cb',
$upper_string);
return $upper_string;
}
/*
*
* Bug: create_function() use exhausts memory when used in long loops
* Fix: use declared functions for callbacks instead of using create_function()
* Note: This can be fixed using anonymous functions instead, but that requires PHP >= 5.3
*
* @author Kyle Renfrow
*/
function smarty_mod_cap_mbconvert_cb($matches)
{
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 2 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
function smarty_mod_cap_mbconvert2_cb($matches)
{
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 3 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
function smarty_mod_cap_ucfirst_cb($matches)
{
return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 2 ]));
}
function smarty_mod_cap_ucfirst2_cb($matches)
{
return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 3 ]));
}
@@ -0,0 +1,65 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty date_format modifier plugin
* Type: modifier<br>
* Name: date_format<br>
* Purpose: format datestamps via strftime<br>
* Input:<br>
* - string: input date string
* - format: strftime format for output
* - default_date: default date if $string is empty
*
* @link http://www.smarty.net/manual/en/language.modifier.date.format.php date_format (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input date string
* @param string $format strftime format for output
* @param string $default_date default date if $string is empty
* @param string $formatter either 'strftime' or 'auto'
*
* @return string |void
* @uses smarty_make_timestamp()
*/
function smarty_modifier_date_format($string, $format = null, $default_date = '', $formatter = 'auto')
{
if ($format === null) {
$format = Smarty::$_DATE_FORMAT;
}
/**
* require_once the {@link shared.make_timestamp.php} plugin
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
if ($string != '' && $string != '0000-00-00' && $string != '0000-00-00 00:00:00') {
$timestamp = smarty_make_timestamp($string);
} elseif ($default_date != '') {
$timestamp = smarty_make_timestamp($default_date);
} else {
return;
}
if ($formatter == 'strftime' || ($formatter == 'auto' && strpos($format, '%') !== false)) {
if (DS == '\\') {
$_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
$_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
if (strpos($format, '%e') !== false) {
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $timestamp));
}
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $timestamp));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $timestamp);
} else {
return date($format, $timestamp);
}
}
@@ -0,0 +1,112 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage Debug
*/
/**
* Smarty debug_print_var modifier plugin
* Type: modifier<br>
* Name: debug_print_var<br>
* Purpose: formats variable contents for display in the console
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array|object $var variable to be formatted
* @param int $max maximum recursion depth if $var is an array or object
* @param int $length maximum string length if $var is a string
* @param int $depth actual recursion depth
* @param array $objects processed objects in actual depth to prevent recursive object processing
*
* @return string
*/
function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth = 0, $objects = array())
{
$_replace = array("\n" => '\n', "\r" => '\r', "\t" => '\t');
switch (gettype($var)) {
case 'array' :
$results = '<b>Array (' . count($var) . ')</b>';
if ($depth == $max) {
break;
}
foreach ($var as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b>' . strtr($curr_key, $_replace) .
'</b> =&gt; ' .
smarty_modifier_debug_print_var($curr_val, $max, $length, ++ $depth, $objects);
$depth --;
}
break;
case 'object' :
$object_vars = get_object_vars($var);
$results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>';
if (in_array($var, $objects)) {
$results .= ' called recursive';
break;
}
if ($depth == $max) {
break;
}
$objects[] = $var;
foreach ($object_vars as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b> -&gt;' . strtr($curr_key, $_replace) .
'</b> = ' . smarty_modifier_debug_print_var($curr_val, $max, $length, ++ $depth, $objects);
$depth --;
}
break;
case 'boolean' :
case 'NULL' :
case 'resource' :
if (true === $var) {
$results = 'true';
} elseif (false === $var) {
$results = 'false';
} elseif (null === $var) {
$results = 'null';
} else {
$results = htmlspecialchars((string) $var);
}
$results = '<i>' . $results . '</i>';
break;
case 'integer' :
case 'float' :
$results = htmlspecialchars((string) $var);
break;
case 'string' :
$results = strtr($var, $_replace);
if (Smarty::$_MBSTRING) {
if (mb_strlen($var, Smarty::$_CHARSET) > $length) {
$results = mb_substr($var, 0, $length - 3, Smarty::$_CHARSET) . '...';
}
} else {
if (isset($var[ $length ])) {
$results = substr($var, 0, $length - 3) . '...';
}
}
$results = htmlspecialchars('"' . $results . '"', ENT_QUOTES, Smarty::$_CHARSET);
break;
case 'unknown type' :
default :
$results = strtr((string) $var, $_replace);
if (Smarty::$_MBSTRING) {
if (mb_strlen($results, Smarty::$_CHARSET) > $length) {
$results = mb_substr($results, 0, $length - 3, Smarty::$_CHARSET) . '...';
}
} else {
if (strlen($results) > $length) {
$results = substr($results, 0, $length - 3) . '...';
}
}
$results = htmlspecialchars($results, ENT_QUOTES, Smarty::$_CHARSET);
}
return $results;
}
@@ -0,0 +1,200 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty escape modifier plugin
* Type: modifier<br>
* Name: escape<br>
* Purpose: escape string for output
*
* @link http://www.smarty.net/docs/en/language.modifier.escape
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $esc_type escape type
* @param string $char_set character set, used for htmlspecialchars() or htmlentities()
* @param boolean $double_encode encode already encoded entitites again, used for htmlspecialchars() or htmlentities()
*
* @return string escaped input string
*/
function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $double_encode = true)
{
static $_double_encode = null;
if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
}
if (!$char_set) {
$char_set = Smarty::$_CHARSET;
}
switch ($esc_type) {
case 'html':
if ($_double_encode) {
// php >=5.3.2 - go native
return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
return htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
case 'htmlall':
if (Smarty::$_MBSTRING) {
// mb_convert_encoding ignores htmlspecialchars()
if ($_double_encode) {
// php >=5.3.2 - go native
$string = htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string =
str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
// htmlentities() won't convert everything, so use mb_convert_encoding
return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set);
}
// no MBString fallback
if ($_double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set);
} else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlentities($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
return $string;
}
}
case 'url':
return rawurlencode($string);
case 'urlpathinfo':
return str_replace('%2F', '/', rawurlencode($string));
case 'quotes':
// escape unescaped single quotes
return preg_replace("%(?<!\\\\)'%", "\\'", $string);
case 'hex':
// escape every byte into hex
// Note that the UTF-8 encoded character ä will be represented as %c3%a4
$return = '';
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '%' . bin2hex($string[ $x ]);
}
return $return;
case 'hexentity':
$return = '';
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
$return = '';
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#x' . strtoupper(dechex($unicode)) . ';';
}
return $return;
}
// no MBString fallback
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#x' . bin2hex($string[ $x ]) . ';';
}
return $return;
case 'decentity':
$return = '';
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
$return = '';
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#' . $unicode . ';';
}
return $return;
}
// no MBString fallback
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#' . ord($string[ $x ]) . ';';
}
return $return;
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return strtr($string, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', "\r" => '\\r', "\n" => '\\n',
'</' => '<\/'));
case 'mail':
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
return smarty_mb_str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $string);
}
// no MBString fallback
return str_replace(array('@', '.'), array(' [AT] ', ' [DOT] '), $string);
case 'nonstd':
// escape non-standard chars, such as ms document quotes
$return = '';
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
if ($unicode >= 126) {
$return .= '&#' . $unicode . ';';
} else {
$return .= chr($unicode);
}
}
return $return;
}
$_length = strlen($string);
for ($_i = 0; $_i < $_length; $_i ++) {
$_ord = ord(substr($string, $_i, 1));
// non-standard char, escape it
if ($_ord >= 126) {
$return .= '&#' . $_ord . ';';
} else {
$return .= substr($string, $_i, 1);
}
}
return $return;
default:
return $string;
}
}
@@ -0,0 +1,58 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty regex_replace modifier plugin
* Type: modifier<br>
* Name: regex_replace<br>
* Purpose: regular expression search/replace
*
* @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php
* regex_replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string|array $search regular expression(s) to search for
* @param string|array $replace string(s) that should be replaced
* @param int $limit the maximum number of replacements
*
* @return string
*/
function smarty_modifier_regex_replace($string, $search, $replace, $limit = - 1)
{
if (is_array($search)) {
foreach ($search as $idx => $s) {
$search[ $idx ] = _smarty_regex_replace_check($s);
}
} else {
$search = _smarty_regex_replace_check($search);
}
return preg_replace($search, $replace, $string, $limit);
}
/**
* @param string $search string(s) that should be replaced
*
* @return string
* @ignore
*/
function _smarty_regex_replace_check($search)
{
// null-byte injection detection
// anything behind the first null-byte is ignored
if (($pos = strpos($search, "\0")) !== false) {
$search = substr($search, 0, $pos);
}
// remove eval-modifier from $search
if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[ 1 ], 'e') !== false)) {
$search = substr($search, 0, - strlen($match[ 1 ])) . preg_replace('![e\s]+!', '', $match[ 1 ]);
}
return $search;
}
@@ -0,0 +1,34 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty replace modifier plugin
* Type: modifier<br>
* Name: replace<br>
* Purpose: simple search/replace
*
* @link http://smarty.php.net/manual/en/language.modifier.replace.php replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param string $string input string
* @param string $search text to search for
* @param string $replace replacement text
*
* @return string
*/
function smarty_modifier_replace($string, $search, $replace)
{
if (Smarty::$_MBSTRING) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
return smarty_mb_str_replace($search, $replace, $string);
}
return str_replace($search, $replace, $string);
}
@@ -0,0 +1,27 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty spacify modifier plugin
* Type: modifier<br>
* Name: spacify<br>
* Purpose: add spaces between characters in a string
*
* @link http://smarty.php.net/manual/en/language.modifier.spacify.php spacify (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $spacify_char string to insert between characters.
*
* @return string
*/
function smarty_modifier_spacify($string, $spacify_char = ' ')
{
// well… what about charsets besides latin and UTF-8?
return implode($spacify_char, preg_split('//' . Smarty::$_UTF8_MODIFIER, $string, - 1, PREG_SPLIT_NO_EMPTY));
}
@@ -0,0 +1,66 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty truncate modifier plugin
* Type: modifier<br>
* Name: truncate<br>
* Purpose: Truncate a string to a certain length if necessary,
* optionally splitting in the middle of a word, and
* appending the $etc string or inserting $etc into the middle.
*
* @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param integer $length length of truncated text
* @param string $etc end string
* @param boolean $break_words truncate at word boundary
* @param boolean $middle truncate in the middle of text
*
* @return string truncated string
*/
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length == 0) {
return '';
}
if (Smarty::$_MBSTRING) {
if (mb_strlen($string, Smarty::$_CHARSET) > $length) {
$length -= min($length, mb_strlen($etc, Smarty::$_CHARSET));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/' . Smarty::$_UTF8_MODIFIER, '',
mb_substr($string, 0, $length + 1, Smarty::$_CHARSET));
}
if (!$middle) {
return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
}
return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc .
mb_substr($string, - $length / 2, $length, Smarty::$_CHARSET);
}
return $string;
}
// no MBString fallback
if (isset($string[ $length ])) {
$length -= min($length, strlen($etc));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
}
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
}
return $string;
}
@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty cat modifier plugin
* Type: modifier<br>
* Name: cat<br>
* Date: Feb 24, 2003<br>
* Purpose: catenate a value to a variable<br>
* Input: string to catenate<br>
* Example: {$var|cat:"foo"}
*
* @link http://smarty.php.net/manual/en/language.modifier.cat.php cat
* (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_cat($params)
{
return '(' . implode(').(', $params) . ')';
}
@@ -0,0 +1,32 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_characters modifier plugin
* Type: modifier<br>
* Name: count_characteres<br>
* Purpose: count the number of characters in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_characters($params)
{
if (!isset($params[ 1 ]) || $params[ 1 ] != 'true') {
return 'preg_match_all(\'/[^\s]/' . Smarty::$_UTF8_MODIFIER . '\',' . $params[ 0 ] . ', $tmp)';
}
if (Smarty::$_MBSTRING) {
return 'mb_strlen(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strlen(' . $params[ 0 ] . ')';
}
@@ -0,0 +1,27 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_paragraphs modifier plugin
* Type: modifier<br>
* Name: count_paragraphs<br>
* Purpose: count the number of paragraphs in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_paragraphs (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_paragraphs($params)
{
// count \r or \n characters
return '(preg_match_all(\'#[\r\n]+#\', ' . $params[ 0 ] . ', $tmp)+1)';
}
@@ -0,0 +1,27 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_sentences modifier plugin
* Type: modifier<br>
* Name: count_sentences
* Purpose: count the number of sentences in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_sentences (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_sentences($params)
{
// find periods, question marks, exclamation marks with a word before but not after.
return 'preg_match_all("#\w[\.\?\!](\W|$)#S' . Smarty::$_UTF8_MODIFIER . '", ' . $params[ 0 ] . ', $tmp)';
}
@@ -0,0 +1,32 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_words modifier plugin
* Type: modifier<br>
* Name: count_words<br>
* Purpose: count the number of words in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.words.php count_words (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_words($params)
{
if (Smarty::$_MBSTRING) {
// return 'preg_match_all(\'#[\w\pL]+#' . Smarty::$_UTF8_MODIFIER . '\', ' . $params[0] . ', $tmp)';
// expression taken from http://de.php.net/manual/en/function.str-word-count.php#85592
return 'preg_match_all(\'/\p{L}[\p{L}\p{Mn}\p{Pd}\\\'\x{2019}]*/' . Smarty::$_UTF8_MODIFIER . '\', ' .
$params[ 0 ] . ', $tmp)';
}
// no MBString fallback
return 'str_word_count(' . $params[ 0 ] . ')';
}
@@ -0,0 +1,35 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty default modifier plugin
* Type: modifier<br>
* Name: default<br>
* Purpose: designate default value for empty variables
*
* @link http://www.smarty.net/manual/en/language.modifier.default.php default (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_default($params)
{
$output = $params[ 0 ];
if (!isset($params[ 1 ])) {
$params[ 1 ] = "''";
}
array_shift($params);
foreach ($params as $param) {
$output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)';
}
return $output;
}
@@ -0,0 +1,117 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* @ignore
*/
require_once(SMARTY_PLUGINS_DIR . 'shared.literal_compiler_param.php');
/**
* Smarty escape modifier plugin
* Type: modifier<br>
* Name: escape<br>
* Purpose: escape string for output
*
* @link http://www.smarty.net/docsv2/en/language.modifier.escape count_characters (Smarty online manual)
* @author Rodney Rehm
*
* @param array $params parameters
* @param $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_escape($params, $compiler)
{
static $_double_encode = null;
if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
}
try {
$esc_type = smarty_literal_compiler_param($params, 1, 'html');
$char_set = smarty_literal_compiler_param($params, 2, Smarty::$_CHARSET);
$double_encode = smarty_literal_compiler_param($params, 3, true);
if (!$char_set) {
$char_set = Smarty::$_CHARSET;
}
switch ($esc_type) {
case 'html':
if ($_double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
case 'htmlall':
if (Smarty::$_MBSTRING) {
if ($_double_encode) {
// php >=5.2.3 - go native
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . ', ' . var_export($double_encode, true) .
'), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . '), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
}
// no MBString fallback
if ($_double_encode) {
// php >=5.2.3 - go native
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
case 'url':
return 'rawurlencode(' . $params[ 0 ] . ')';
case 'urlpathinfo':
return 'str_replace("%2F", "/", rawurlencode(' . $params[ 0 ] . '))';
case 'quotes':
// escape unescaped single quotes
return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[ 0 ] . ')';
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return 'strtr(' . $params[ 0 ] .
', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))';
}
}
catch (SmartyException $e) {
// pass through to regular plugin fallback
}
// could not optimize |escape call, so fallback to regular plugin
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->parent_compiler->template->compiled->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->parent_compiler->template->compiled->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'function' ] =
'smarty_modifier_escape';
} else {
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'function' ] =
'smarty_modifier_escape';
}
return 'smarty_modifier_escape(' . join(', ', $params) . ')';
}
@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty from_charset modifier plugin
* Type: modifier<br>
* Name: from_charset<br>
* Purpose: convert character encoding from $charset to internal encoding
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_from_charset($params)
{
if (!Smarty::$_MBSTRING) {
// FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ];
}
if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"';
}
return 'mb_convert_encoding(' . $params[ 0 ] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[ 1 ] . ')';
}
@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty indent modifier plugin
* Type: modifier<br>
* Name: indent<br>
* Purpose: indent lines of text
*
* @link http://www.smarty.net/manual/en/language.modifier.indent.php indent (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_indent($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 4;
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = "' '";
}
return 'preg_replace(\'!^!m\',str_repeat(' . $params[ 2 ] . ',' . $params[ 1 ] . '),' . $params[ 0 ] . ')';
}
@@ -0,0 +1,31 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty lower modifier plugin
* Type: modifier<br>
* Name: lower<br>
* Purpose: convert string to lowercase
*
* @link http://www.smarty.net/manual/en/language.modifier.lower.php lower (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_lower($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtolower(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strtolower(' . $params[ 0 ] . ')';
}
@@ -0,0 +1,21 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty noprint modifier plugin
* Type: modifier<br>
* Name: noprint<br>
* Purpose: return an empty string
*
* @author Uwe Tews
* @return string with compiled code
*/
function smarty_modifiercompiler_noprint()
{
return "''";
}
@@ -0,0 +1,25 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty string_format modifier plugin
* Type: modifier<br>
* Name: string_format<br>
* Purpose: format strings via sprintf
*
* @link http://www.smarty.net/manual/en/language.modifier.string.format.php string_format (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_string_format($params)
{
return 'sprintf(' . $params[ 1 ] . ',' . $params[ 0 ] . ')';
}
@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty strip modifier plugin
* Type: modifier<br>
* Name: strip<br>
* Purpose: Replace all repeated spaces, newlines, tabs
* with a single space or supplied replacement string.<br>
* Example: {$var|strip} {$var|strip:"&nbsp;"}<br>
* Date: September 25th, 2002
*
* @link http://www.smarty.net/manual/en/language.modifier.strip.php strip (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_strip($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = "' '";
}
return "preg_replace('!\s+!" . Smarty::$_UTF8_MODIFIER . "', {$params[1]},{$params[0]})";
}
@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty strip_tags modifier plugin
* Type: modifier<br>
* Name: strip_tags<br>
* Purpose: strip html tags from text
*
* @link http://www.smarty.net/docs/en/language.modifier.strip.tags.tpl strip_tags (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_strip_tags($params)
{
if (!isset($params[ 1 ]) || $params[ 1 ] === true || trim($params[ 1 ], '"') == 'true') {
return "preg_replace('!<[^>]*?>!', ' ', {$params[0]})";
} else {
return 'strip_tags(' . $params[ 0 ] . ')';
}
}
@@ -0,0 +1,33 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty to_charset modifier plugin
* Type: modifier<br>
* Name: to_charset<br>
* Purpose: convert character encoding from internal encoding to $charset
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_to_charset($params)
{
if (!Smarty::$_MBSTRING) {
// FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ];
}
if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"';
}
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 1 ] . ', "' . addslashes(Smarty::$_CHARSET) . '")';
}
@@ -0,0 +1,50 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty unescape modifier plugin
* Type: modifier<br>
* Name: unescape<br>
* Purpose: unescape html entities
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_unescape($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 'html';
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = '\'' . addslashes(Smarty::$_CHARSET) . '\'';
} else {
$params[ 2 ] = "'" . $params[ 2 ] . "'";
}
switch (trim($params[ 1 ], '"\'')) {
case 'entity':
case 'htmlall':
if (Smarty::$_MBSTRING) {
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'HTML-ENTITIES\')';
}
return 'html_entity_decode(' . $params[ 0 ] . ', ENT_NOQUOTES, ' . $params[ 2 ] . ')';
case 'html':
return 'htmlspecialchars_decode(' . $params[ 0 ] . ', ENT_QUOTES)';
case 'url':
return 'rawurldecode(' . $params[ 0 ] . ')';
default:
return $params[ 0 ];
}
}
@@ -0,0 +1,29 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty upper modifier plugin
* Type: modifier<br>
* Name: lower<br>
* Purpose: convert string to uppercase
*
* @link http://smarty.php.net/manual/en/language.modifier.upper.php lower (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_upper($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtoupper(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strtoupper(' . $params[ 0 ] . ')';
}
@@ -0,0 +1,51 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty wordwrap modifier plugin
* Type: modifier<br>
* Name: wordwrap<br>
* Purpose: wrap a string of text at a given length
*
* @link http://smarty.php.net/manual/en/language.modifier.wordwrap.php wordwrap (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
* @param $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_wordwrap($params, $compiler)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 80;
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = '"\n"';
}
if (!isset($params[ 3 ])) {
$params[ 3 ] = 'false';
}
$function = 'wordwrap';
if (Smarty::$_MBSTRING) {
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->parent_compiler->template->compiled->required_plugins[ 'nocache' ][ 'wordwrap' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php';
$compiler->template->required_plugins[ 'nocache' ][ 'wordwrap' ][ 'modifier' ][ 'function' ] =
'smarty_mb_wordwrap';
} else {
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'wordwrap' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'shared.mb_wordwrap.php';
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'wordwrap' ][ 'modifier' ][ 'function' ] =
'smarty_mb_wordwrap';
}
$function = 'smarty_mb_wordwrap';
}
return $function . '(' . $params[ 0 ] . ',' . $params[ 1 ] . ',' . $params[ 2 ] . ',' . $params[ 3 ] . ')';
}
@@ -0,0 +1,89 @@
<?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFilter
*/
/**
* Smarty trimwhitespace outputfilter plugin
* Trim unnecessary whitespace from HTML markup.
*
* @author Rodney Rehm
*
* @param string $source input string
*
* @return string filtered output
* @todo substr_replace() is not overloaded by mbstring.func_overload - so this function might fail!
*/
function smarty_outputfilter_trimwhitespace($source)
{
$store = array();
$_store = 0;
$_offset = 0;
// Unify Line-Breaks to \n
$source = preg_replace("/\015\012|\015|\012/", "\n", $source);
// capture Internet Explorer and KnockoutJS Conditional Comments
if (preg_match_all('#<!--((\[[^\]]+\]>.*?<!\[[^\]]+\])|(\s*/?ko\s+.+))-->#is', $source, $matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
// Strip all HTML-Comments
// yes, even the ones in <script> - see http://stackoverflow.com/a/808850/515124
$source = preg_replace('#<!--.*?-->#ms', '', $source);
// capture html elements not to be messed with
$_offset = 0;
if (preg_match_all('#(<script[^>]*>.*?</script[^>]*>)|(<textarea[^>]*>.*?</textarea[^>]*>)|(<pre[^>]*>.*?</pre[^>]*>)#is',
$source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
$expressions = array(// replace multiple spaces between tags by a single space
// can't remove them entirely, becaue that might break poorly implemented CSS display:inline-block elements
'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2',
// remove spaces between attributes (but not in attribute values!)
'#(([a-z0-9]\s*=\s*("[^"]*?")|(\'[^\']*?\'))|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \5',
// note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering?
'#^\s+<#Ss' => '<', '#>\s+$#Ss' => '>',);
$source = preg_replace(array_keys($expressions), array_values($expressions), $source);
// note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering?
// $source = trim( $source );
$_offset = 0;
if (preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$_length = strlen($match[ 0 ][ 0 ]);
$replace = $store[ $match[ 1 ][ 0 ] ];
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] + $_offset, $_length);
$_offset += strlen($replace) - $_length;
$_store ++;
}
}
return $source;
}
@@ -0,0 +1,34 @@
<?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
/**
* escape_special_chars common function
* Function: smarty_function_escape_special_chars<br>
* Purpose: used by other smarty functions to escape
* special chars except for already escaped ones
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string text that should by escaped
*
* @return string
*/
function smarty_function_escape_special_chars($string)
{
if (!is_array($string)) {
if (version_compare(PHP_VERSION, '5.2.3', '>=')) {
$string = htmlspecialchars($string, ENT_COMPAT, Smarty::$_CHARSET, false);
} else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
}
}
return $string;
}

Some files were not shown because too many files have changed in this diff Show More