Thread: [Cs-content-commits] SF.net SVN: cs-content:[410] trunk/1.0 (Page 2)
PHP Templating & Includes System
Brought to you by:
crazedsanity
From: <cra...@us...> - 2009-07-21 03:21:22
|
Revision: 410 http://cs-content.svn.sourceforge.net/cs-content/?rev=410&view=rev Author: crazedsanity Date: 2009-07-21 03:21:21 +0000 (Tue, 21 Jul 2009) Log Message: ----------- Fix sql quoting, insert style to allows non-quoted NULLs, update gives error. /cs_globalFunctions.class.php: * switch_force_sql_quotes(): -- if there's no new setting but an old value exists, use that instead of throwing an exception. * string_from_array(): -- (style=insert): change the two "if" statements to if/elseif, where the "NULL" value doesn't have single quotes around it. /cs_phpDB.class.php: * run_update(): -- capture error if one exists -- throw a different exception on error. Modified Paths: -------------- trunk/1.0/cs_globalFunctions.class.php trunk/1.0/cs_phpDB.class.php Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2009-07-20 21:57:33 UTC (rev 409) +++ trunk/1.0/cs_globalFunctions.class.php 2009-07-21 03:21:21 UTC (rev 410) @@ -54,6 +54,9 @@ $newSetting = 0; } } + elseif(!is_bool($newSetting) && is_bool($this->oldForceSqlQuotes)) { + $newSetting = $this->oldForceSqlQuotes; + } else { throw new exception(__METHOD__ .": invalid new setting (". $newSetting .")"); } @@ -191,14 +194,14 @@ foreach($array as $key=>$value) { @$tmp[0] = $this->create_list($tmp[0], $key); //clean the string, if required. - if($cleanString) { + if(is_null($value)) { + $value = "NULL"; + } + elseif($cleanString) { //make sure it's not full of poo... $value = $this->cleanString($value, "sql"); #$value = "'". $value ."'"; } - if((is_null($value)) OR ($value == "")) { - $value = "NULL"; - } @$tmp[1] = $this->create_list($tmp[1], $value, ",", 1); } Modified: trunk/1.0/cs_phpDB.class.php =================================================================== --- trunk/1.0/cs_phpDB.class.php 2009-07-20 21:57:33 UTC (rev 409) +++ trunk/1.0/cs_phpDB.class.php 2009-07-21 03:21:21 UTC (rev 410) @@ -165,9 +165,13 @@ public function run_update($sql, $zeroIsOk=false) { $this->exec($sql); + $dberror = $this->errorMsg(); $numAffected = $this->numAffected(); - if($numAffected==0 && $zeroIsOk == false) { + if(strlen($dberror)) { + throw new exception(__METHOD__ .": error while running update::: ". $dberror ." -- SQL::: ". $sql); + } + elseif($numAffected==0 && $zeroIsOk == false) { throw new exception(__METHOD__ .": no rows updated (". $numAffected ."), SQL::: ". $sql); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-03 17:41:27
|
Revision: 413 http://cs-content.svn.sourceforge.net/cs-content/?rev=413&view=rev Author: crazedsanity Date: 2009-08-03 17:41:13 +0000 (Mon, 03 Aug 2009) Log Message: ----------- Tests strictly for cs_globalFunctions. /cs_globalFunctions.class.php: * string_from_array(): -- removed unused $typesArr -- [update]: + clean only if it does not both start AND end in single quotes + if the entire value is one single quote, delimit it and wrap in single quotes. + empty values get an empty string value ('') -- [select]: + pass forceSqlQuotes to cleanString() + wrap in quotes if there's a separator, regardless of whether or not the value is numeric (the DB should be able to convert a text number into an actual number). * interpret_bool(): -- when a decimal number is passed, drop the decimal so it is handled as a whole number; otherwise, 0.1 is treated as though it were 0 (due to the settype() as integer call). /tests/testOfCSContent.php: * Dropped methods (moved to testOfCSGlobalFunctions.php): -- test_cleanString() -- test_string_from_array() -- test_interpret_bool() /tests/testOfCSGlobalFunctions.php [NEW]: * copied from testOfCSContent.php, with expanded tests. Modified Paths: -------------- trunk/1.0/cs_globalFunctions.class.php trunk/1.0/tests/testOfCSContent.php Added Paths: ----------- trunk/1.0/tests/testOfCSGlobalFunctions.php Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2009-07-29 19:03:37 UTC (rev 412) +++ trunk/1.0/cs_globalFunctions.class.php 2009-08-03 17:41:13 UTC (rev 413) @@ -162,7 +162,6 @@ } //make sure $style is valid. - $typesArr = array("insert", "update"); $style = strtolower($style); if(is_array($array)) { @@ -222,10 +221,17 @@ if(($value === "NULL" || $value === NULL) && !$this->forceSqlQuotes) { $sqlQuotes = 0; } - if($cleanString && !preg_match('/^\'/',$value)) { + if($cleanString && !(preg_match('/^\'/',$value) && preg_match('/\'$/', $value))) { //make sure it doesn't have crap in it... $value = $this->cleanString($value, "sql",$sqlQuotes); } + if($value == "'") { + //Fix possible SQL-injection. + $value = "'\''"; + } + elseif(!strlen($value)) { + $value = "''"; + } $retval = $this->create_list($retval, $field . $separator . $value); } break; @@ -277,9 +283,9 @@ } if($cleanString) { //make sure it doesn't have crap in it... - $value = $this->cleanString($value, "sql"); + $value = $this->cleanString($value, "sql", $this->forceSqlQuotes); } - if(!is_numeric($value) && isset($separator)) { + if(isset($separator)) { $value = "'". $value ."'"; } $retval = $this->create_list($retval, $field . $separator . $value, " $delimiter "); @@ -804,8 +810,12 @@ //now figure out the value to return. if(is_numeric($interpretThis)) { + if(preg_match('/\.[0-9]{1,}/', $interpretThis)) { + //if it is a decimal number, remove the dot (i.e. "0.000001" -> "0000001" -> 1) + $interpretThis = str_replace('.', '', $interpretThis); + } settype($interpretThis, 'integer'); - if($interpretThis == '0') { + if($interpretThis == 0) { $index=0; } else { Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-07-29 19:03:37 UTC (rev 412) +++ trunk/1.0/tests/testOfCSContent.php 2009-08-03 17:41:13 UTC (rev 413) @@ -33,154 +33,6 @@ //------------------------------------------------------------------------- - public function test_cleanString() { - - $gf = new cs_globalFunctions(); - - $cleanThis = '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS'; - $testSQL = array( - 'none' => $cleanThis, - 'query' => '@_=;34:/JuST THIS', - 'theDefault' => '34JuSTTHIS', - 'alphanumeric' => '34JuSTTHIS', - 'sql' => '~`!@#$^&*()_+-=[]{}|;34:\\\'<>?,.//\".JuST THIS', - 'sql_insert' => '~`!@#$^&*()_+-=[]{}|;34:\\\\\'<>?,.//".JuST THIS', - 'sql92_insert' => '~`!@#$^&*()_+-=[]{}|;34:\'\'<>?,.//".JuST THIS', - 'double_quote' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\.JuST THIS', - 'htmlspecial' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', - 'htmlspecial_q' => '~`!@#$^&*()_+-=[]\{}|;34:\\'\<>?,.//\".JuST THIS', - 'htmlspecial_nq' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', - 'htmlentity' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', - 'htmlentity_plus_brackets' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', - 'double_entity' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\.JuST THIS', - 'meta' => '~`!@#\$\^&\*\(\)_\+-=\[\]\\\\{}|;34:\\\\\'\\\<>\?,\.//\\\\"\.JuST THIS', - 'email' => '@_-34..JuSTTHIS', - 'email_plus_spaces' => '@_-34..JuST THIS', - 'phone_fax' => '()+-34 ', - 'integer' => '34', - 'numeric' => '34', - 'decimal' => '34..', - 'float' => '34..', - 'name' => '\'JuSTTHIS', - 'names' => '\'JuSTTHIS', - 'alpha' => 'JuSTTHIS', - 'bool' => 't', - 'varchar' => '\'@_=;34:/JuST THIS\'', - 'date' => '-34', - 'datetime' => '-34:\'.//.JuST THIS', - 'all' => '34JuSTTHIS' - ); - - foreach($testSQL as $name=>$expected) { - $cleanedData = $gf->cleanString($cleanThis, $name); - - //NOTE::: passing "%" in the message data causes an exception with the simpletest framework. - $this->assertEqual($expected, $cleanedData); - } - - - //test quoting (with a few exceptions). - $testQuotes = $testSQL; - unset($testQuotes['none'], $testQuotes['sql92_insert']); - foreach($testQuotes as $name=>$expected) { - $gf->switch_force_sql_quotes(1); - $cleanedDataPlusQuotes = $gf->cleanString($cleanThis, $name, 1); - $this->assertEqual("'". $expected ."'", $cleanedDataPlusQuotes, "Failed quoting with style=(". $name .")"); - - $gf->switch_force_sql_quotes(0); - $this->assertEqual("'". $expected ."'", $cleanedDataPlusQuotes, "Failed quoting with style=(". $name .")"); - } - - - //TEST NULLS - { - - $this->assertEqual($gf->cleanString("", "numeric",0), ""); - $this->assertEqual($gf->cleanString("", "numeric",1), "''"); - $this->assertEqual($gf->cleanString("", "integer",0), ""); - $this->assertEqual($gf->cleanString("", "integer",1), "''"); - $this->assertEqual($gf->cleanString(null, "numeric",0), "NULL"); - $this->assertEqual($gf->cleanString(null, "numeric",1), "NULL"); - $this->assertEqual($gf->cleanString(null, "integer",0), "NULL"); - $this->assertEqual($gf->cleanString(null, "integer",1), "NULL"); - - $this->assertEqual($gf->cleanString(null, "varchar",0), "NULL"); - $this->assertEqual($gf->cleanString(null, "varchar",1), "'NULL'"); - $this->assertEqual($gf->cleanString("", "varchar",0), "NULL"); - $this->assertEqual($gf->cleanString("", "varchar",1), "'NULL'"); - } - - }//end test_cleanString() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - function test_string_from_array() { - $gf = new cs_globalFunctions; - $gf->switch_force_sql_quotes(0); - - //Test some SQL-Specific stuff. - $testSQL = array( - 'column1' => "'my value ' OR 'x'='x'", - 'column two' => "Stuff" - ); - - //Test INSERT style. - { - $expected = "(column1, column two) VALUES ('my value ' OR 'x'='x','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert'), $expected); - - $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql'), $expected); - - $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql_insert'), $expected); - - $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql92_insert'), $expected); - - //now let's see what happens if we pass an array signifying how it should be cleaned. - $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql', 'column two'=>'sql')), $expected); - $expected = "(column1, column two) VALUES ('\\\\\'my value \\\\\' OR \\\\\'x\\\\\'=\\\\\'x\\\\\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql_insert', 'column two'=>'sql_insert')), $expected); - $expected = "(column1, column two) VALUES ('\'\'my value \'\' OR \'\'x\'\'=\'\'x\'\'','Stuff')"; - $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql92_insert', 'column two'=>'sql92_insert')), $expected); - - } - - }//end test_string_from_array() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - function test_interpret_bool() { - $gf=new cs_globalFunctions; - - $this->assertEqual($gf->interpret_bool('true'), true); - $this->assertEqual($gf->interpret_bool('false'), false); - $this->assertEqual($gf->interpret_bool('0'), false); - $this->assertEqual($gf->interpret_bool('1'), true); - $this->assertEqual($gf->interpret_bool(0), false); - $this->assertEqual($gf->interpret_bool(1), true); - $this->assertEqual($gf->interpret_bool('f'), false); - $this->assertEqual($gf->interpret_bool('t'), true); - $this->assertEqual($gf->interpret_bool("1stuff"), true); - $this->assertEqual($gf->interpret_bool(""), false); - $this->assertEqual($gf->interpret_bool(" true "), true); - $this->assertEqual($gf->interpret_bool(" false "), false); - - //now go through the same thing, but this time tell it to give back a specific value for true and false. - $this->assertEqual($gf->interpret_bool(false, array(0=>'FaLSe',1=>"crap")), 'FaLSe'); - $this->assertEqual($gf->interpret_bool(false, array(0=>"crap",1=>'FaLSe')), 'crap'); - }//end test_interpret_bool() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- public function test_siteConfig() { $configFile = constant('TEST_FILESDIR') .'/sampleConfig.xml'; $varPrefix = preg_replace("/:/", "_", __METHOD__ ."-"); Copied: trunk/1.0/tests/testOfCSGlobalFunctions.php (from rev 412, trunk/1.0/tests/testOfCSContent.php) =================================================================== --- trunk/1.0/tests/testOfCSGlobalFunctions.php (rev 0) +++ trunk/1.0/tests/testOfCSGlobalFunctions.php 2009-08-03 17:41:13 UTC (rev 413) @@ -0,0 +1,249 @@ +<?php +/* + * Created on Jan 13, 2009 + * + * + * FILE INFORMATION: + * + * $HeadURL$ + * $Id$ + * $LastChangedDate$ + * $LastChangedBy$ + * $LastChangedRevision$ + */ + + + +//============================================================================= +class TestOfCSGlobalFunctions extends UnitTestCase { + + //------------------------------------------------------------------------- + function __construct() { + require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); + require_once(dirname(__FILE__) .'/../cs_siteConfig.class.php'); + + $this->gfObj = new cs_globalFunctions; + $this->gfObj->debugPrintOpt=1; + + $filesDir = dirname(__FILE__) ."/files"; + define('TEST_FILESDIR', $filesDir); + }//end __construct() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + public function test_cleanString() { + + $gf = new cs_globalFunctions(); + + $cleanThis = '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS'; + $testSQL = array( + 'none' => $cleanThis, + 'query' => '@_=;34:/JuST THIS', + 'theDefault' => '34JuSTTHIS', + 'alphanumeric' => '34JuSTTHIS', + 'sql' => '~`!@#$^&*()_+-=[]{}|;34:\\\'<>?,.//\".JuST THIS', + 'sql_insert' => '~`!@#$^&*()_+-=[]{}|;34:\\\\\'<>?,.//".JuST THIS', + 'sql92_insert' => '~`!@#$^&*()_+-=[]{}|;34:\'\'<>?,.//".JuST THIS', + 'double_quote' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\.JuST THIS', + 'htmlspecial' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', + 'htmlspecial_q' => '~`!@#$^&*()_+-=[]\{}|;34:\\'\<>?,.//\".JuST THIS', + 'htmlspecial_nq' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', + 'htmlentity' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', + 'htmlentity_plus_brackets' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\".JuST THIS', + 'double_entity' => '~`!@#$^&*()_+-=[]\{}|;34:\\\'\<>?,.//\.JuST THIS', + 'meta' => '~`!@#\$\^&\*\(\)_\+-=\[\]\\\\{}|;34:\\\\\'\\\<>\?,\.//\\\\"\.JuST THIS', + 'email' => '@_-34..JuSTTHIS', + 'email_plus_spaces' => '@_-34..JuST THIS', + 'phone_fax' => '()+-34 ', + 'integer' => '34', + 'numeric' => '34', + 'decimal' => '34..', + 'float' => '34..', + 'name' => '\'JuSTTHIS', + 'names' => '\'JuSTTHIS', + 'alpha' => 'JuSTTHIS', + 'bool' => 't', + 'varchar' => '\'@_=;34:/JuST THIS\'', + 'date' => '-34', + 'datetime' => '-34:\'.//.JuST THIS', + 'all' => '34JuSTTHIS' + ); + + foreach($testSQL as $name=>$expected) { + $cleanedData = $gf->cleanString($cleanThis, $name); + + //NOTE::: passing "%" in the message data causes an exception with the simpletest framework. + $this->assertEqual($expected, $cleanedData); + } + + + //test quoting (with a few exceptions). + $testQuotes = $testSQL; + unset($testQuotes['none'], $testQuotes['sql92_insert']); + foreach($testQuotes as $name=>$expected) { + $gf->switch_force_sql_quotes(1); + $cleanedDataPlusQuotes = $gf->cleanString($cleanThis, $name, 1); + $this->assertEqual("'". $expected ."'", $cleanedDataPlusQuotes, "Failed quoting with style=(". $name .")"); + + $gf->switch_force_sql_quotes(0); + $this->assertEqual("'". $expected ."'", $cleanedDataPlusQuotes, "Failed quoting with style=(". $name .")"); + } + + + //TEST NULLS + { + + $this->assertEqual($gf->cleanString("", "numeric",0), ""); + $this->assertEqual($gf->cleanString("", "numeric",1), "''"); + $this->assertEqual($gf->cleanString("", "integer",0), ""); + $this->assertEqual($gf->cleanString("", "integer",1), "''"); + $this->assertEqual($gf->cleanString(null, "numeric",0), "NULL"); + $this->assertEqual($gf->cleanString(null, "numeric",1), "NULL"); + $this->assertEqual($gf->cleanString(null, "integer",0), "NULL"); + $this->assertEqual($gf->cleanString(null, "integer",1), "NULL"); + + $this->assertEqual($gf->cleanString(null, "varchar",0), "NULL"); + $this->assertEqual($gf->cleanString(null, "varchar",1), "'NULL'"); + $this->assertEqual($gf->cleanString("", "varchar",0), "NULL"); + $this->assertEqual($gf->cleanString("", "varchar",1), "'NULL'"); + } + + }//end test_cleanString() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + function test_string_from_array() { + $gf = new cs_globalFunctions; + $gf->switch_force_sql_quotes(0); + + //Test some SQL-Specific stuff. + $testSQL = array( + 'column1' => "'my value ' OR 'x'='x'", + 'column two' => "Stuff" + ); + + //Test INSERT style. + { + $expected = "(column1, column two) VALUES ('my value ' OR 'x'='x','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert'), $expected); + + $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql'), $expected); + + $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql_insert'), $expected); + + $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, 'sql92_insert'), $expected); + + //now let's see what happens if we pass an array signifying how it should be cleaned. + $expected = "(column1, column two) VALUES ('\'my value \' OR \'x\'=\'x\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql', 'column two'=>'sql')), $expected); + $expected = "(column1, column two) VALUES ('\\\\\'my value \\\\\' OR \\\\\'x\\\\\'=\\\\\'x\\\\\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql_insert', 'column two'=>'sql_insert')), $expected); + $expected = "(column1, column two) VALUES ('\'\'my value \'\' OR \'\'x\'\'=\'\'x\'\'','Stuff')"; + $this->assertEqual($gf->string_from_array($testSQL, 'insert', null, array('column1'=>'sql92_insert', 'column two'=>'sql92_insert')), $expected); + + } + + //make sure forceSqlQuotes is OFF. + $gf->switch_force_sql_quotes(0); + + //Test the SELECT style. + { + //a basic set of criteria... + $expected = "w='' AND x='y' AND y='0' AND z=''"; + $actual = $gf->string_from_array(array('w'=>'', 'x'=>"y", 'y'=>0,'z'=>NULL), 'select'); + $this->assertEqual($expected, $actual); + + //make sure it distinguishes between text "NULL" and literal NULL. + $expected = "w='' AND x='y' AND y='0' AND z='NULL'"; + $actual = $gf->string_from_array(array('w'=>'', 'x'=>"y", 'y'=>0,'z'=>"NULL"), 'select'); + $this->assertEqual($expected, $actual); + + //make sure it distinguishes between text "NULL" and literal NULL. + $expected = "w='' AND x='y' AND y='0' AND z='NULL'"; + $actual = $gf->string_from_array(array('w'=>'', 'x'=>"y", 'y'=>0,'z'=>"NULL"), 'select', null, 'sql'); + $this->assertEqual($expected, $actual); + + //check with specific cleaning styles. + $expected = "w='' AND x='y' AND y='0' AND z='NULL'"; + $cleanString = array('w'=>"nonexistent", 'x'=>"alpha", 'y'=>"numeric", 'z'=>"sql"); + $actual = $gf->string_from_array(array('w'=>'', 'x'=>"y", 'y'=>0,'z'=>"NULL"), 'select', null, $cleanString); + $this->assertEqual($expected, $actual); + } + + + //Test the UPDATE style. + { + //basic update. + $expected = "w='', x='y', y='0', z=''"; + $actual = $gf->string_from_array(array('w'=>"", 'x'=>"y", 'y'=>0, 'z'=>NULL), 'update', null, 'sql'); + $this->assertEqual($expected, $actual); + + + //basic update, but force SQL quotes... + $gf->switch_force_sql_quotes(1); + $expected = "w='', x='y', y='0', z=''"; + $actual = $gf->string_from_array(array('w'=>"", 'x'=>"y", 'y'=>0, 'z'=>NULL), 'update', null, 'sql'); + $this->assertEqual($expected, $actual); + $gf->switch_force_sql_quotes(0); + + //update with invalid quotes (attempts at SQL injection) + $expected = "w='\' ', x='\'', y='0', z=''"; + $actual = $gf->string_from_array(array('w'=>"' ", 'x'=>"'", 'y'=>0, 'z'=>NULL), 'update', null, 'sql'); + $this->assertEqual($expected, $actual); + } + + + }//end test_string_from_array() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + function test_interpret_bool() { + $gf=new cs_globalFunctions; + + $this->assertEqual($gf->interpret_bool('true'), true); + $this->assertEqual($gf->interpret_bool(true), true); + $this->assertEqual($gf->interpret_bool('false'), false); + $this->assertEqual($gf->interpret_bool(false), false); + $this->assertEqual($gf->interpret_bool('0'), false); + $this->assertEqual($gf->interpret_bool('1'), true); + $this->assertEqual($gf->interpret_bool(0), false); + $this->assertEqual($gf->interpret_bool(000000), false); + $this->assertEqual($gf->interpret_bool(1), true); + $this->assertEqual($gf->interpret_bool(0.1), true); + $this->assertEqual($gf->interpret_bool(0.01), true); + $this->assertEqual($gf->interpret_bool(0.001), true); + $this->assertEqual($gf->interpret_bool('f'), false); + $this->assertEqual($gf->interpret_bool('fa'), true); + $this->assertEqual($gf->interpret_bool('fal'), true); + $this->assertEqual($gf->interpret_bool('fals'), true); + $this->assertEqual($gf->interpret_bool('t'), true); + $this->assertEqual($gf->interpret_bool('tr'), true); + $this->assertEqual($gf->interpret_bool('tru'), true); + $this->assertEqual($gf->interpret_bool("1stuff"), true); + $this->assertEqual($gf->interpret_bool(""), false); + $this->assertEqual($gf->interpret_bool(" true "), true); + $this->assertEqual($gf->interpret_bool(" false "), false); + $this->assertEqual($gf->interpret_bool('false-showastrue'), true); + $this->assertEqual($gf->interpret_bool('true-showastrue'), true); + + + //now go through the same thing, but this time tell it to give back a specific value for true and false. + $this->assertEqual($gf->interpret_bool(false, array(0=>'FaLSe',1=>"crap")), 'FaLSe'); + $this->assertEqual($gf->interpret_bool(false, array(0=>"crap",1=>'FaLSe')), 'crap'); + }//end test_interpret_bool() + //------------------------------------------------------------------------- + + + +}//end TestOfCSContent +//============================================================================= +?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-05 20:29:07
|
Revision: 417 http://cs-content.svn.sourceforge.net/cs-content/?rev=417&view=rev Author: crazedsanity Date: 2009-08-05 20:28:56 +0000 (Wed, 05 Aug 2009) Log Message: ----------- Facilitating the database session storage. NOTE::: it sort of works, but currently it continuously creates new records with different session ID's... probably something very small that I'm missing. Modified Paths: -------------- trunk/1.0/cs_session.class.php Added Paths: ----------- trunk/1.0/cs_sessionDB.class.php Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2009-08-05 16:39:27 UTC (rev 416) +++ trunk/1.0/cs_session.class.php 2009-08-05 20:28:56 UTC (rev 417) @@ -13,10 +13,9 @@ class cs_session extends cs_contentAbstract { - protected $db; - public $uid; - public $sid; - public $sid_check = 1; + protected $uid; + protected $sid; + protected $sid_check = 1; //------------------------------------------------------------------------- /** @@ -27,7 +26,7 @@ * used as the session name. */ function __construct($createSession=1) { - parent::__construct(false); + parent::__construct(true); if($createSession) { if(!is_null($createSession) && strlen($createSession) && !is_numeric($createSession)) { session_name($createSession); @@ -139,6 +138,19 @@ return($retval); }//end drop_cookie() //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * PHP5 magic method for retrieving the value of internal vars; this allows + * code to find the value of these variables, but not modify them (modifying + * requires the "__set($var,$val)" method). + */ + public function __get($var) { + return($this->$var); + }//end __get() + //------------------------------------------------------------------------- }//end cs_session{} Copied: trunk/1.0/cs_sessionDB.class.php (from rev 416, trunk/1.0/cs_session.class.php) =================================================================== --- trunk/1.0/cs_sessionDB.class.php (rev 0) +++ trunk/1.0/cs_sessionDB.class.php 2009-08-05 20:28:56 UTC (rev 417) @@ -0,0 +1,329 @@ +<?php +/* + * FILE INFORMATION: + * $HeadURL$ + * $Id$ + * $LastChangedDate$ + * $LastChangedBy$ + * $LastChangedRevision$ + */ + +require_once(dirname(__FILE__) .'/cs_session.class.php'); +require_once(constant('LIBDIR') .'/cs-phpxml/cs_arrayToPath.class.php'); + +class cs_sessionDB extends cs_session { + + protected $db; + + //------------------------------------------------------------------------- + /** + * The constructor. + * + * @param $createSession (mixed,optional) determines if a session will be started or not; if + * this parameter is non-null and non-numeric, the value will be + * used as the session name. + */ + function __construct() { + + + require_once(dirname(__FILE__) .'/cs_fileSystem.class.php'); + $this->logger = new cs_fileSystem(constant('RWDIR')); + $this->logger->create_file('session.log',true); + $this->logger->openFile('session.log'); + + //now tell PHP to use this class's methods for saving the session. + session_set_save_handler( + array(&$this, 'sessdb_open'), + array(&$this, 'sessdb_close'), + array(&$this, 'sessdb_read'), + array(&$this, 'sessdb_write'), + array(&$this, 'sessdb_destroy'), + array(&$this, 'sessdb_gc') + ); + + //map some constants to connection parameters. + //NOTE::: all constants should be prefixed... + $constantPrefix = 'SESSION_DB_'; + $params = array('host', 'port', 'dbname', 'user', 'password'); + foreach($params as $name) { + $value = null; + $constantName = $constantPrefix . strtoupper($name); + if(defined($constantName)) { + $value = constant($constantName); + } + $dbParams[$name] = $value; + } + $this->db = new cs_phpDB(constant('DBTYPE')); + $this->db->connect($dbParams); + + $this->tableName = 'cs_session_store_table'; + $this->tablePKey = 'session_store_id'; + $this->sequenceName = 'cs_session_store_table_session_store_id_seq'; + + if(!$this->sessdb_table_exists()) { + $this->load_table(); + } + + parent::__construct(true); + + //Stop things from going into an audit log... see + //http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711/page3.html + // NOTE::: not sure if this is valid or not... + $this->audit_logging = false; + + }//end __construct() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Determines if the appropriate table exists in the database. + */ + public function sessdb_table_exists() { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + try { + $test = $this->db->run_query("SELECT * FROM ". $this->tableName . + " ORDER BY ". $this->tablePKey ." LIMIT 1"); + $exists = true; + } + catch(exception $e) { + $exists = false; + } + $this->logger->append_to_file(__METHOD__ .": result=(". $exists .")". microtime(true)); + + return($exists); + }//end sessdb_table_exists() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + private function load_table() { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $filename = dirname(__FILE__) .'/schema/db_session_schema.'. $this->db->get_dbtype() .'.sql'; + if(file_exists($filename)) { + try { + $this->db->run_update(file_get_contents($filename),true); + } + catch(exception $e) { + throw new exception(__METHOD__ .": failed to load required table " . + "into your database automatically::: ". $e->getMessage()); + } + } + else { + throw new exception(__METHOD__ .": while attempting to load required " . + "table into your database, discovered you have a missing schema " . + "file (". $filename .")"); + } + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + }//end load_table() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + protected function is_valid_sid($sid) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $isValid = false; + if(strlen($sid) == 32) { + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + try { + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". + $sid ."'"; + $this->db->run_query($sql); + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + $numrows = $this->db->numRows(); + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + if($numrows == 1) { + $isValid = true; + } + elseif($numrows > 0 || $numrows < 0) { + throw new exception(__METHOD__ .": invalid numrows returned (". $numrows .")"); + } + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), numrows=(". $numrows ."), SQL::: ". $sql ." ". microtime(true)); + } + catch(exception $e) { + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + //well... do nothing I guess. + } + } + $this->logger->append_to_file(__METHOD__ .": result=(". $isValid .")". microtime(true)); + + return($isValid); + }//end is_valid_sid() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Open the session (doesn't really do anything) + */ + public function sessdb_open($savePath, $sessionName) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + return(true); + }//end sessdb_open() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Close the session (call the "gc" method) + */ + public function sessdb_close() { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + return($this->sessdb_gc(0)); + }//end sessdb_close() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Read information about the session. If there is no data, it MUST return + * an empty string instead of NULL. + */ + public function sessdb_read($sid) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $retval = ''; + try { + $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". + $sid ."'"; + $data = $this->db->run_query($sql); + + if($this->db->numRows() == 1) { + $retval = $data['session_data']; + } + } + catch(exception $e) { + //no throwing exceptions... + } + $this->logger->append_to_file(__METHOD__ .": result=(". $retval .")". microtime(true)); + return($retval); + }//end sessdb_read() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + public function sessdb_write($sid, $data) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + $data = array( + 'session_data' => $data, + 'user_id' => null + ); + + + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + + //pull the uid out of the session... + if(defined('SESSION_DBSAVE_UIDPATH')) { + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + $a2p = new cs_arrayToPath($_SESSION); + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + $uidVal = $a2p->get_data(constant('SESSION_DBSAVE_UIDPATH')); + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + + if(is_string($uidVal) || is_numeric($uidVal)) { + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + $data['user_id'] = $uidVal; + } + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + } + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + + $afterSql = ""; + if($this->is_valid_sid($sid)) { + $type = 'update'; + $sql = "UPDATE ". $this->tableName ." SET "; + $afterSql = "WHERE session_id='". $sid ."'"; + $secondArg = false; + } + else { + $type = 'insert'; + $sql = "INSERT INTO ". $this->tableName ." "; + $data['session_id'] = $sid; + $secondArg = $this->sequenceName; + } + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); + + $sql .= $this->gfObj->string_from_array($data, $type, null, 'sql') . $afterSql; + try { + $funcName = 'run_'. $type; + $res = $this->db->$funcName($sql, $secondArg); + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), SQL::: ". $sql ." ". microtime(true)); + } + catch(exception $e) { + //umm... yeah. + $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), EXCEPTION::: ". $e->getMessage() ."\n ". microtime(true)); + } + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + + return(true); + }//end sessdb_write() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + public function sessdb_destroy($sid) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + try { + $sql = "DELETE FROM ". $this->tableName ." WHERE session_id='". $sid ."'"; + $this->db->run_update($sql, true); + } + catch(exception $e) { + //do... nothing? + } + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + return(true); + }//end sessdb_destroy() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Define maximum lifetime (in seconds) to store sessions in the database. + * Anything that is older than that time will be purged (gc='garbage collector'). + */ + public function sessdb_gc($maxLifetime=null) { + $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); + + $nowTime = date('Y-m-d H:i:s'); + if(is_null($maxLifetime) || !is_numeric($maxLifetime) || $maxLifetime < 0) { + //pull it from PHP's ini settings. + $maxLifetime = ini_get("session.gc_maxlifetime"); + } + $interval = $maxLifetime .' seconds'; + + $dt1 = strtotime($nowTime .' - '. $interval); + $dt2 = date('Y-m-d H:i:s', $dt1); + + + $this->logger->append_to_file(__METHOD__ .": still going, dt2=(". $dt2 .").. ". microtime(true)); + + + try { + //destroy old sessions, but don't complain if nothing is deleted. + $sql = "DELETE FROM ". $this->tableName ." WHERE last_updated < ". $dt2; + #$this->db->run_update($sql, true); + } + catch(exception $e) { + //probably should do something here. + } + $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); + + return(true); + + }//end sessdb_gc() + //------------------------------------------------------------------------- + + +}//end cs_session{} +?> \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-06 05:09:19
|
Revision: 418 http://cs-content.svn.sourceforge.net/cs-content/?rev=418&view=rev Author: crazedsanity Date: 2009-08-06 05:09:06 +0000 (Thu, 06 Aug 2009) Log Message: ----------- Working support for sessions stored in the database. /contentSystem.class.php: * initialize_locals(): -- start database-based session storage if SESSION_DBSAVE is a properly set constant. /cs_session.class.php: * __construct(): -- ARG CHANGE: DEFAULT VALUE CHANGED: #1 (from 1 to true) -- when passing a boolean true as arg #1, a session was created which was literally named "1" (the bool was interpretted to a string val). /cs_sessionDB.class.php: * REMOVE LOGGER STUFF::: -- sessdb_table_exists() -- load_table() -- is_valid_sid() -- sessdb_open() -- sessdb_close() -- sessdb_read() -- sessdb_destroy() -- sessdb_gc() * __construct(): -- remove logger stuff -- move session_set_save_handler() call to just before the call to the parent's __construct(). * sessdb_write(): -- removed logger stuff -- set array signifying how to clean the fields. -- pass the cleanString var to string_from_array() Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_session.class.php trunk/1.0/cs_sessionDB.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-05 20:28:56 UTC (rev 417) +++ trunk/1.0/contentSystem.class.php 2009-08-06 05:09:06 UTC (rev 418) @@ -134,6 +134,14 @@ * Creates internal objects & prepares for later usage. */ private function initialize_locals() { + + //create a session that gets stored in a database if they so desire... + if(defined('SESSION_DBSAVE')) { + require_once(dirname(__FILE__) .'/cs_sessionDB.class.php'); + $obj = new cs_sessionDB(); + $this->handle_session($obj); + } + //build the templating engine: this may cause an immediate redirect, if they need to be logged-in. //TODO: find a way to define this on a per-page basis. Possibly have templateObj->check_login() // run during the "finish" stage... probably using GenericPage{}->check_login(). Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2009-08-05 20:28:56 UTC (rev 417) +++ trunk/1.0/cs_session.class.php 2009-08-06 05:09:06 UTC (rev 418) @@ -25,10 +25,10 @@ * this parameter is non-null and non-numeric, the value will be * used as the session name. */ - function __construct($createSession=1) { + function __construct($createSession=true) { parent::__construct(true); if($createSession) { - if(!is_null($createSession) && strlen($createSession) && !is_numeric($createSession)) { + if(is_string($createSession) && strlen($createSession) >2) { session_name($createSession); } Modified: trunk/1.0/cs_sessionDB.class.php =================================================================== --- trunk/1.0/cs_sessionDB.class.php 2009-08-05 20:28:56 UTC (rev 417) +++ trunk/1.0/cs_sessionDB.class.php 2009-08-06 05:09:06 UTC (rev 418) @@ -26,21 +26,6 @@ function __construct() { - require_once(dirname(__FILE__) .'/cs_fileSystem.class.php'); - $this->logger = new cs_fileSystem(constant('RWDIR')); - $this->logger->create_file('session.log',true); - $this->logger->openFile('session.log'); - - //now tell PHP to use this class's methods for saving the session. - session_set_save_handler( - array(&$this, 'sessdb_open'), - array(&$this, 'sessdb_close'), - array(&$this, 'sessdb_read'), - array(&$this, 'sessdb_write'), - array(&$this, 'sessdb_destroy'), - array(&$this, 'sessdb_gc') - ); - //map some constants to connection parameters. //NOTE::: all constants should be prefixed... $constantPrefix = 'SESSION_DB_'; @@ -64,6 +49,16 @@ $this->load_table(); } + //now tell PHP to use this class's methods for saving the session. + session_set_save_handler( + array(&$this, 'sessdb_open'), + array(&$this, 'sessdb_close'), + array(&$this, 'sessdb_read'), + array(&$this, 'sessdb_write'), + array(&$this, 'sessdb_destroy'), + array(&$this, 'sessdb_gc') + ); + parent::__construct(true); //Stop things from going into an audit log... see @@ -81,7 +76,6 @@ * Determines if the appropriate table exists in the database. */ public function sessdb_table_exists() { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); try { $test = $this->db->run_query("SELECT * FROM ". $this->tableName . " ORDER BY ". $this->tablePKey ." LIMIT 1"); @@ -90,7 +84,6 @@ catch(exception $e) { $exists = false; } - $this->logger->append_to_file(__METHOD__ .": result=(". $exists .")". microtime(true)); return($exists); }//end sessdb_table_exists() @@ -101,7 +94,6 @@ //------------------------------------------------------------------------- private function load_table() { $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); - $filename = dirname(__FILE__) .'/schema/db_session_schema.'. $this->db->get_dbtype() .'.sql'; if(file_exists($filename)) { try { $this->db->run_update(file_get_contents($filename),true); @@ -124,32 +116,24 @@ //------------------------------------------------------------------------- protected function is_valid_sid($sid) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); $isValid = false; if(strlen($sid) == 32) { - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); try { - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". $sid ."'"; $this->db->run_query($sql); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $numrows = $this->db->numRows(); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); if($numrows == 1) { $isValid = true; } elseif($numrows > 0 || $numrows < 0) { throw new exception(__METHOD__ .": invalid numrows returned (". $numrows .")"); } - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), numrows=(". $numrows ."), SQL::: ". $sql ." ". microtime(true)); } catch(exception $e) { - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); //well... do nothing I guess. } } - $this->logger->append_to_file(__METHOD__ .": result=(". $isValid .")". microtime(true)); return($isValid); }//end is_valid_sid() @@ -162,8 +146,6 @@ * Open the session (doesn't really do anything) */ public function sessdb_open($savePath, $sessionName) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); - $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); return(true); }//end sessdb_open() //------------------------------------------------------------------------- @@ -175,8 +157,6 @@ * Close the session (call the "gc" method) */ public function sessdb_close() { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); - $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); return($this->sessdb_gc(0)); }//end sessdb_close() //------------------------------------------------------------------------- @@ -189,7 +169,6 @@ * an empty string instead of NULL. */ public function sessdb_read($sid) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); $retval = ''; try { $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". @@ -203,7 +182,6 @@ catch(exception $e) { //no throwing exceptions... } - $this->logger->append_to_file(__METHOD__ .": result=(". $retval .")". microtime(true)); return($retval); }//end sessdb_read() //------------------------------------------------------------------------- @@ -212,36 +190,33 @@ //------------------------------------------------------------------------- public function sessdb_write($sid, $data) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); $data = array( 'session_data' => $data, 'user_id' => null ); + $cleanString = array( + 'session_data' => 'sql', + 'user_id' => 'numeric' + ); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); //pull the uid out of the session... if(defined('SESSION_DBSAVE_UIDPATH')) { - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $a2p = new cs_arrayToPath($_SESSION); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $uidVal = $a2p->get_data(constant('SESSION_DBSAVE_UIDPATH')); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); if(is_string($uidVal) || is_numeric($uidVal)) { - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $data['user_id'] = $uidVal; } - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); } - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); $afterSql = ""; if($this->is_valid_sid($sid)) { $type = 'update'; $sql = "UPDATE ". $this->tableName ." SET "; $afterSql = "WHERE session_id='". $sid ."'"; + $data['last_updated'] = 'NOW()'; $secondArg = false; } else { @@ -250,19 +225,15 @@ $data['session_id'] = $sid; $secondArg = $this->sequenceName; } - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ .") ". microtime(true)); - $sql .= $this->gfObj->string_from_array($data, $type, null, 'sql') . $afterSql; + $sql .= $this->gfObj->string_from_array($data, $type, null, $cleanString) .' '. $afterSql; try { $funcName = 'run_'. $type; $res = $this->db->$funcName($sql, $secondArg); - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), SQL::: ". $sql ." ". microtime(true)); } catch(exception $e) { //umm... yeah. - $this->logger->append_to_file(__METHOD__ .": still going, line=(". __LINE__ ."), EXCEPTION::: ". $e->getMessage() ."\n ". microtime(true)); } - $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); return(true); }//end sessdb_write() @@ -272,7 +243,6 @@ //------------------------------------------------------------------------- public function sessdb_destroy($sid) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); try { $sql = "DELETE FROM ". $this->tableName ." WHERE session_id='". $sid ."'"; $this->db->run_update($sql, true); @@ -280,7 +250,6 @@ catch(exception $e) { //do... nothing? } - $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); return(true); }//end sessdb_destroy() //------------------------------------------------------------------------- @@ -293,7 +262,6 @@ * Anything that is older than that time will be purged (gc='garbage collector'). */ public function sessdb_gc($maxLifetime=null) { - $this->logger->append_to_file(__METHOD__ .": starting... ". microtime(true)); $nowTime = date('Y-m-d H:i:s'); if(is_null($maxLifetime) || !is_numeric($maxLifetime) || $maxLifetime < 0) { @@ -306,9 +274,7 @@ $dt2 = date('Y-m-d H:i:s', $dt1); - $this->logger->append_to_file(__METHOD__ .": still going, dt2=(". $dt2 .").. ". microtime(true)); - try { //destroy old sessions, but don't complain if nothing is deleted. $sql = "DELETE FROM ". $this->tableName ." WHERE last_updated < ". $dt2; @@ -317,7 +283,6 @@ catch(exception $e) { //probably should do something here. } - $this->logger->append_to_file(__METHOD__ .": done". microtime(true)); return(true); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-06 14:46:25
|
Revision: 419 http://cs-content.svn.sourceforge.net/cs-content/?rev=419&view=rev Author: crazedsanity Date: 2009-08-06 14:46:17 +0000 (Thu, 06 Aug 2009) Log Message: ----------- MySQL & PostgreSQL schema for database storage of sessions (cs_sessionDB{}). Added Paths: ----------- trunk/1.0/schema/ trunk/1.0/schema/db_session_schema.mysql.sql trunk/1.0/schema/db_session_schema.pgsql.sql Added: trunk/1.0/schema/db_session_schema.mysql.sql =================================================================== --- trunk/1.0/schema/db_session_schema.mysql.sql (rev 0) +++ trunk/1.0/schema/db_session_schema.mysql.sql 2009-08-06 14:46:17 UTC (rev 419) @@ -0,0 +1,17 @@ + + +-- +-- Store session data in here. +-- Idea originally from: http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711 +-- + +CREATE TABLE `test`.`sess_tmp` ( + `session_store_id` int NOT NULL AUTO_INCREMENT, + `session_id` varchar(32) NOT NULL, + `user_id` varchar(16) NOT NULL, + `date_created` datetime NOT NULL, + `last_updated` datetime NOT NULL, + `session_data` LONGTEXT NOT NULL, + PRIMARY KEY (`session_store_id`) +) +ENGINE = MyISAM; \ No newline at end of file Added: trunk/1.0/schema/db_session_schema.pgsql.sql =================================================================== --- trunk/1.0/schema/db_session_schema.pgsql.sql (rev 0) +++ trunk/1.0/schema/db_session_schema.pgsql.sql 2009-08-06 14:46:17 UTC (rev 419) @@ -0,0 +1,16 @@ + + +-- +-- Store session data in here. +-- Idea originally from: http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711 +-- + +CREATE TABLE cs_session_store_table ( + session_store_id serial NOT NULL PRIMARY KEY, + session_id varchar(32) NOT NULL DEFAULT '' UNIQUE, + user_id varchar(16), + date_created timestamp NOT NULL DEFAULT NOW(), + last_updated timestamp NOT NULL DEFAULT NOW(), + session_data text +); + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-13 18:57:39
|
Revision: 435 http://cs-content.svn.sourceforge.net/cs-content/?rev=435&view=rev Author: crazedsanity Date: 2009-08-13 18:57:31 +0000 (Thu, 13 Aug 2009) Log Message: ----------- Fix cs_tabs{} so it doesn't require the page object. /contentSystem.class.php: * initialize_locals(): -- TODO about making the tabs object useable. -- don't pass any arguments to cs_tabs::__construct() /cs_tabs.class.php: * MAIN::: -- remove csPageObj -- add gfObj * __construct(): -- ARG CHANGE: ARG DELETED: #1 (cs_genericPage $csPageObj) -- ARG CHANGE: ARG SHIFTED: #2 ($templateVar="tabs" now #1) -- special check so calling code knows not to try to pass cs_genericPage as the first argument (the old code caused an error about an inability to convert the object to a string). -- create cs_globalFunctions object. * load_tabs_template() [DELETED]: -- no longer needed * display_tabs(): -- ARG CHANGE: NEW ARG: #1 (array $blockRows) -- Need to pass an array of block rows (i.e. using $page->templateRows) so the tabs can be built. -- remove call to non-existent function load_tabs_template() -- fix exception -- returns parsed tabs instead of trying to use cs_genericPage::add_template_var()... Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_tabs.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-13 18:40:21 UTC (rev 434) +++ trunk/1.0/contentSystem.class.php 2009-08-13 18:57:31 UTC (rev 435) @@ -180,7 +180,8 @@ //create a tabs object, in case they want to load tabs on the page. - $this->tabs = new cs_tabs($this->templateObj); + //TODO: make the tabs object usable to included code! + $this->tabs = new cs_tabs(); //check versions, make sure they're all the same. $myVersion = $this->get_version(); Modified: trunk/1.0/cs_tabs.class.php =================================================================== --- trunk/1.0/cs_tabs.class.php 2009-08-13 18:40:21 UTC (rev 434) +++ trunk/1.0/cs_tabs.class.php 2009-08-13 18:57:31 UTC (rev 435) @@ -11,8 +11,8 @@ private $tabsArr=array(); private $selectedTab; - private $csPageObj; private $templateVar; + private $gfObj; /** This is the default suffix to use when none is given during the add_tab() call. */ private $defaultSuffix='tab'; @@ -24,19 +24,14 @@ * @param $csPageObj (object) Instance of the class "cs_genericPage". * @param $templateVar (str,optional) What template var to find the tab blockrows in. */ - public function __construct(cs_genericPage $csPageObj, $templateVar="tabs") { + public function __construct($templateVar="tabs") { parent::__construct(false); - if(is_null($csPageObj) || !is_object($csPageObj) || get_class($csPageObj) !== 'cs_genericPage') { - //can't continue without that! - throw new exception("cs_tabs::__construct(): cannot load without cs_genericPage{} object (". get_class($csPageObj) .")"); - } - else { - //set it as a member. - $this->csPageObj = $csPageObj; - } - - if(is_null($templateVar) || strlen($templateVar) < 3) { + if(is_object($templateVar)) { + //trying to pass cs_genericPage{}... tell 'em we don't like that anymore. + throw new exception(__METHOD__ .": got an object (". get_class($templateVar) .") instead of template var name"); + } + elseif(is_string($templateVar) && is_null($templateVar) || strlen($templateVar) < 3) { //no template name? AHH!!! throw new exception("cs_tabs::__construct(): failed to specify proper template file"); } @@ -44,33 +39,14 @@ //set the internal var. $this->templateVar = $templateVar; } + + $this->gfObj = new cs_globalFunctions; }//end __construct() //--------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- - /** - * Loads & parses the given tabs template. Requires that the given template has "selected_tab" - * and "unselected_tab" block row definitions. - * - * @param (void) - * @return (void) - */ - private function load_tabs_template() { - //now let's parse it for the proper block rows. - $blockRows = $this->csPageObj->rip_all_block_rows($this->templateVar); - - #if(count($blockRows) < 2) { - # //not enough blocks, or they're not properly named. - # throw new exception("cs_tabs::load_tabs_template(): failed to retrieve the required block rows"); - #} - }//end load_tabs_template() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- public function add_tab_array(array $tabs, $useSuffix=null) { $retval = 0; foreach($tabs as $name=>$url) { @@ -120,7 +96,7 @@ /** * Call this to add the parsed tabs into the page. */ - public function display_tabs() { + public function display_tabs(array $blockRows) { if(!strlen($this->selectedTab)) { $keys = array_keys($this->tabsArr); @@ -128,7 +104,6 @@ } if(is_array($this->tabsArr) && count($this->tabsArr)) { - $this->load_tabs_template(); $finalString = ""; //loop through the array. foreach($this->tabsArr as $tabName=>$tabData) { @@ -141,11 +116,13 @@ $blockRowName = 'selected_'. $suffix; } - if(isset($this->csPageObj->templateRows[$blockRowName])) { - $useTabContent = $this->csPageObj->templateRows[$blockRowName]; + if(isset($blockRows[$blockRowName])) { + $useTabContent = $blockRows[$blockRowName]; } else { - throw new exception(__METHOD__ ."(): failed to load block row (". $blockRowName .") for tab (". $tabName .")". $this->csPageObj->gfObj->debug_print($this->csPageObj->templateRows,0)); + throw new exception(__METHOD__ ."(): failed to load block row " . + "(". $blockRowName .") for tab (". $tabName .")". + $this->gfObj->debug_print($blockRows,0)); } $parseThis = array( @@ -153,17 +130,15 @@ 'url' => $url, 'cleanTitle' => preg_replace('/[^a-zA-Z0-9]/', '_', $tabName) ); - $finalString .= $this->csPageObj->mini_parser($useTabContent, $parseThis, '%%', '%%'); + $finalString .= $this->gfObj->mini_parser($useTabContent, $parseThis, '%%', '%%'); } - - //now parse it onto the page. - $this->csPageObj->add_template_var($this->templateVar, $finalString); } else { //something bombed. throw new exception(__METHOD__ ."(): no tabs to add"); } + return($finalString); }//end display_tabs() //--------------------------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-14 18:58:09
|
Revision: 438 http://cs-content.svn.sourceforge.net/cs-content/?rev=438&view=rev Author: crazedsanity Date: 2009-08-14 18:57:53 +0000 (Fri, 14 Aug 2009) Log Message: ----------- Tests for cs_fileSystem (and a superficial change to the code). /cs_fileSystem.class.php: * openFile(): -- formatting (removed an extra space). /tests/testOfCSFileSystem.php: * a couple of tests for basic I/O. Modified Paths: -------------- trunk/1.0/cs_fileSystem.class.php trunk/1.0/tests/testOfCSFileSystem.php Modified: trunk/1.0/cs_fileSystem.class.php =================================================================== --- trunk/1.0/cs_fileSystem.class.php 2009-08-14 16:36:52 UTC (rev 437) +++ trunk/1.0/cs_fileSystem.class.php 2009-08-14 18:57:53 UTC (rev 438) @@ -363,7 +363,7 @@ //something bad happened. $retval = 0; } - } + } else { throw new exception(__METHOD__ .": file is unreadable (". $filename .")"); } Modified: trunk/1.0/tests/testOfCSFileSystem.php =================================================================== --- trunk/1.0/tests/testOfCSFileSystem.php 2009-08-14 16:36:52 UTC (rev 437) +++ trunk/1.0/tests/testOfCSFileSystem.php 2009-08-14 18:57:53 UTC (rev 438) @@ -25,18 +25,145 @@ $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; - $filesDir = dirname(__FILE__) ."/files"; - define('TEST_FILESDIR', $filesDir); }//end __construct() //------------------------------------------------------------------------- //------------------------------------------------------------------------- + function setUp() { + $filesDir = dirname(__FILE__) ."/files"; + + $this->reader = new cs_fileSystem($filesDir); + $this->writer = new cs_fileSystem(constant('RWDIR')); + + //make a directory to write into. + $this->writer->mkdir(__CLASS__); + $this->writer->cd(__CLASS__); + }//end setUp() //------------------------------------------------------------------------- + //------------------------------------------------------------------------- + function tearDown() { + //TODO: this should be able to RECURSIVELY delete files & folders. + $this->writer->cd('/'); + $this->writer->rmdir(__CLASS__); + }//end tearDown() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + function test_basic_rw() { + + $this->assertEqual($this->reader->root, dirname(__FILE__) .'/files'); + + $outsideLs = $this->reader->ls("templates"); + + $this->reader->cd("templates"); + $insideLs = $this->reader->ls(); + + $this->assertEqual($outsideLs, $insideLs); + + //okay, read all the files & make the writer create them. + $matchSize = array(); + foreach($insideLs as $file=>$data) { + $this->assertEqual(1, $this->writer->create_file($file)); + + $this->assertNotEqual($this->writer->realcwd, $this->reader->realcwd); + + //now read data out of one & write into the other, make sure they're the same size. + $fileSize = $this->writer->write($this->reader->read($file), $file); + $this->assertEqual($fileSize, $data['size']); + + //now get rid of the new file. + $this->writer->rm($file); + } + + //lets take the contents of ALL of those files, push it into one big file, and make sure it is identical. + $testFilename_a = 'concat_file.txt'; + $testFilename_aplus = 'concat_file2.txt'; + $this->writer->create_file($testFilename_a); + $this->writer->create_file($testFilename_aplus); + + $totalSize = 0; + $totalContent = ""; + $loop=0; + $fileList = ""; + foreach($insideLs as $file=>$data) { + $totalSize += $data['size']; + + $content = $this->reader->read($file); + $totalContent .= $content; + + $this->writer->openFile($testFilename_a, 'a'); + $this->writer->append_to_file($content, null); + $this->writer->closeFile(); + + $this->writer->openFile($testFilename_aplus, 'a+'); + $this->writer->append_to_file($content, null); + $this->writer->closeFile(); + + $loop++; + } + + //now lets read each file & see if they have the proper content... + $this->assertEqual($totalContent, $this->writer->read($testFilename_a)); + $this->assertEqual($totalContent, $this->writer->read($testFilename_aplus)); + + + //Test if it can create and then move around within a file properly + { + //Generated from http://www.lipsum.com/feed/html + $fileLines = array( + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', + 'Nam nec risus eu mauris euismod convallis eget eget mi.', + 'Morbi eget mi eu sapien mollis porttitor vitae ut augue.', + 'Pellentesque porta volutpat sem, quis facilisis nulla dictum vitae.', + 'Praesent tempus lorem sit amet tortor tempor blandit.' + ); + + $appendTestFile = 'lipsum.txt'; + $this->writer->create_file($appendTestFile); + $this->writer->openFile($appendTestFile, 'a+'); + + //now let's make the array MASSIVE by replicating the file lines over & over again. + $finalFileLines = array(); + $replicate = 1000; + $myContent = null; + $actualNum = 0; + for($x=0; $x<$replicate;$x++) { + foreach($fileLines as $x2=>$line) { + $myLine = "line #". $actualNum ." ". $line; + $myContent .= $myLine ."\n"; + + $this->writer->append_to_file($myLine); + $actualNum++; + } + } + $this->writer->closeFile(); + + //now make sure the contents of the file are as expected... + $this->assertEqual($myContent, $this->writer->read($appendTestFile)); + + $this->writer->create_file('x.txt'); + $this->writer->write($myContent, 'x.txt'); + + unset($myContent,$finalFileLines); + } + + + //now delete the files. + foreach($this->writer->ls() as $file=>$garbage) { + $this->writer->rm($file); + } + }//end test_basic_rw() + //------------------------------------------------------------------------- + + + }//end TestOfCSFileSystem //============================================================================= ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-14 19:40:23
|
Revision: 439 http://cs-content.svn.sourceforge.net/cs-content/?rev=439&view=rev Author: crazedsanity Date: 2009-08-14 19:40:09 +0000 (Fri, 14 Aug 2009) Log Message: ----------- More tests of basic I/O, with fixes too. /cs_fileSystem.class.php: * move_file(): -- set the filename & destination to their absolute values so the call to rename() works. /tests/testOfCSFileSystem.php: * test_basic_rw(): -- writes a big file (5000 lines) and then jumps around in the file, picking random lines to see if the line content appears correct. -- move a file (rename it) and make sure the resulting ls data matches the previous ls (with slight modifications). Modified Paths: -------------- trunk/1.0/cs_fileSystem.class.php trunk/1.0/tests/testOfCSFileSystem.php Modified: trunk/1.0/cs_fileSystem.class.php =================================================================== --- trunk/1.0/cs_fileSystem.class.php 2009-08-14 18:57:53 UTC (rev 438) +++ trunk/1.0/cs_fileSystem.class.php 2009-08-14 19:40:09 UTC (rev 439) @@ -885,6 +885,8 @@ if($this->is_readable($filename)) { if($this->check_chroot($destination)) { //do the move. + $filename = $this->filename2absolute($filename); + $destination = $this->filename2absolute($destination); $retval = rename($filename, $destination); } else { Modified: trunk/1.0/tests/testOfCSFileSystem.php =================================================================== --- trunk/1.0/tests/testOfCSFileSystem.php 2009-08-14 18:57:53 UTC (rev 438) +++ trunk/1.0/tests/testOfCSFileSystem.php 2009-08-14 19:40:09 UTC (rev 439) @@ -148,13 +148,43 @@ //now make sure the contents of the file are as expected... $this->assertEqual($myContent, $this->writer->read($appendTestFile)); - $this->writer->create_file('x.txt'); - $this->writer->write($myContent, 'x.txt'); + unset($myContent,$finalFileLines); - unset($myContent,$finalFileLines); + //randomly pull a line and make sure it starts with the right phrase. + $this->writer->openFile($appendTestFile, 'r'); + $linesToTest = 100; + + for($i=0;$i<$linesToTest;$i++) { + $randomLine = rand(0, $actualNum); + + $this->writer->go_to_line($randomLine); + $lineContents = $this->writer->get_next_line(); + + $this->assertTrue(preg_match('/^line #'. $randomLine .' /', $lineContents)); + } + + $this->writer->go_to_last_line(); + $this->writer->go_to_line(($this->writer->lineNum -2));//go back two lines because we're actually past the last line, gotta go 2 up so when we fetch "the next line", it is actually the last. + $lineContents = $this->writer->get_next_line(); + $this->assertTrue(preg_match('/^line #'. ($this->writer->lineNum -1) .' /', $lineContents), " getting last line (#". $this->writer->lineNum ."), Line Contents::: ". $lineContents); + + $this->writer->closeFile(); } + //now let's try moving a file. + $newName = "movedFile.txt"; + $lsData = $this->writer->ls(); + $this->assertTrue(isset($lsData[$appendTestFile])); + $this->writer->move_file($appendTestFile, $newName); + //change the array and make sure it is approximately the same. + $newLsData = $this->writer->ls(); + $tmp = $lsData[$appendTestFile]; + unset($lsData[$appendTestFile]); + $lsData[$newName] = $tmp; + $this->assertEqual($newLsData, $lsData); + + //now delete the files. foreach($this->writer->ls() as $file=>$garbage) { $this->writer->rm($file); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-18 18:40:30
|
Revision: 440 http://cs-content.svn.sourceforge.net/cs-content/?rev=440&view=rev Author: crazedsanity Date: 2009-08-18 18:40:18 +0000 (Tue, 18 Aug 2009) Log Message: ----------- Cleanup, modifications for unit testing. /contentSystem.class.php: * intitialize_locals(): -- set the SITE_ROOT a bit more dynamically, so it should work even if the constant SITE_ROOT is not defined. /cs_genericPage.class.php: * MAIN::: -- a bit of formatting -- added templateFiles var as an array. -- dropped "showEditableLink" var. * __construct(): -- ARG CHANGE: ARG REMOVED: #3 ($allowRedirects=TRUE) -- removed unnecessary (and apparently unused) var for optionally disallowing redirects. -- NOTE: this was easily bypassed by using a method in cs_globalFunctions of the same name. -- remove code for showing editable link (this is NOT something that should be handled at this level; a CMS should handle that part). * initialize_locals(): -- attempt to set siteRoot from the mainTemplateFile value before trying to use SITE_ROOT (arguments should ALWAYS be able to override constant definitions). -- if no SITE_ROOT constant, try to find a templates directory beneath the server's DOCUMENT_ROOT. -- throw an exception if tmplDir isn't a directory (otherwise the Template class will exit with an error). * add_template_file(): -- dropped code that dealt with showEditableLink -- updates the internal templateFiles array. * conditional_header(): -- ARG CHANGE: NEW ARG: #3 ($isPermRedir=FALSE) -- now it calls cs_globalFunctions::conditional_header() so there is really only one set of code for this operation. * __get() [NEW]: -- magic PHP method for retrieving the values of protected/private vars (includes non-existent ones). * __set() [NEW]: -- magic PHP method for setting the values of protected/private vars (including non-existent ones). Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_genericPage.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-14 19:40:09 UTC (rev 439) +++ trunk/1.0/contentSystem.class.php 2009-08-18 18:40:18 UTC (rev 440) @@ -145,7 +145,11 @@ //build the templating engine: this may cause an immediate redirect, if they need to be logged-in. //TODO: find a way to define this on a per-page basis. Possibly have templateObj->check_login() // run during the "finish" stage... probably using GenericPage{}->check_login(). - $this->templateObj = new cs_genericPage(FALSE, "main.shared.tmpl"); + $root = $_SERVER['DOCUMENT_ROOT']; + if(defined('SITE_ROOT')) { + $root = constant('SITE_ROOT'); + } + $this->templateObj = new cs_genericPage(FALSE, $root ."/main.shared.tmpl"); //setup some default template vars. $this->templateObj->add_template_var('date', date('m-d-Y')); Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2009-08-14 19:40:09 UTC (rev 439) +++ trunk/1.0/cs_genericPage.class.php 2009-08-18 18:40:18 UTC (rev 440) @@ -12,9 +12,10 @@ class cs_genericPage extends cs_contentAbstract { public $templateObj; //template object to parse the pages - public $templateVars = array(); //our copy of the global templateVars - public $templateRows = array(); //array of block rows & their contents. - public $mainTemplate; //the default layout of the site + public $templateVars = array(); //our copy of the global templateVars + public $templateFiles = array(); //our list of template files... + public $templateRows = array(); //array of block rows & their contents. + public $mainTemplate; //the default layout of the site public $unhandledVars=array(); public $printOnFinish=true; @@ -23,17 +24,13 @@ private $siteRoot; private $allowRedirect; - private $showEditableLink = FALSE; - private $allowInvalidUrls=NULL; //--------------------------------------------------------------------------------------------- /** * The constructor. */ - public function __construct($restrictedAccess=TRUE, $mainTemplateFile=NULL, $allowRedirect=TRUE) { - //handle some configuration. - $this->allowRedirect = $allowRedirect; + public function __construct($restrictedAccess=TRUE, $mainTemplateFile=NULL) { //initialize stuff from our parent... parent::__construct(); @@ -47,11 +44,6 @@ if(!defined('CS-CONTENT_SESSION_NAME')) { define("CS-CONTENT_SESSION_NAME", ini_get('session.name')); } - - //TODO: if the end page doesn't want to allow the "edit" links, will this still work? - if(defined("CS_CONTENT_MODIFIABLE") && constant("CS_CONTENT_MODIFIABLE") === TRUE) { - $this->showEditableLink = TRUE; - } }//end __construct() //--------------------------------------------------------------------------------------------- @@ -72,16 +64,29 @@ $mainTemplateFile = preg_replace('/^\//', '', $mainTemplateFile); } - - if(defined('SITE_ROOT')) { + if(isset($mainTemplateFile) && strlen($mainTemplateFile) && is_dir(dirname($mainTemplateFile))) { + $this->siteRoot = dirname($mainTemplateFile); + if(preg_match('/\//', $this->siteRoot) && preg_match('/templates/', $this->siteRoot)) { + $this->siteRoot .= "/.."; + } + } + elseif(defined('SITE_ROOT') && is_dir(constant('SITE_ROOT'))) { $this->siteRoot = constant('SITE_ROOT'); } + elseif(is_dir($_SERVER['DOCUMENT_ROOT'] .'/templates')) { + $this->siteRoot = $_SERVER['DOCUMENT_ROOT'] .'/templates'; + } else { - throw new exception(__METHOD__ .": required constant 'SITE_ROOT' not set"); + throw new exception(__METHOD__ .": cannot locate siteRoot from main template file (". $mainTemplateFile .")"); } $this->tmplDir = $this->siteRoot .'/templates'; $this->libDir = $this->siteRoot .'/lib'; + if(!is_dir($this->tmplDir)) { + $this->gfObj->debug_print(func_get_args(),1); + throw new exception(__METHOD__ .": invalid templates folder (". $this->tmplDir ."), pwd=(". getcwd() .")"); + } + //if there have been some global template vars (or files) set, read 'em in here. if(is_array($GLOBALS['templateVars']) && count($GLOBALS['templateVars'])) { foreach($GLOBALS['templateVars'] as $key=>$value) { @@ -176,13 +181,8 @@ * TODO: check if $fileName exists before blindly trying to parse it. */ public function add_template_file($handleName, $fileName){ - if($this->showEditableLink) { - $prefix = '[<a href="#NULL_page='. $fileName .'"><font color="red"><b>Edit "'. $handleName .'"</b></font></a>]<BR>'; - $this->add_template_var($handleName, $prefix .$this->file_to_string($fileName)); - } - else { - $this->add_template_var($handleName, $this->file_to_string($fileName)); - } + $this->templateFiles[$handleName] = $fileName; + $this->add_template_var($handleName, $this->file_to_string($fileName)); }//end add_template_file() //--------------------------------------------------------------------------------------------- @@ -489,35 +489,8 @@ /** * Performs redirection, provided it is allowed. */ - function conditional_header($url, $exitAfter=TRUE) { - if($this->allowRedirect) { - //checks to see if headers were sent; if yes: use a meta redirect. - // if no: send header("location") info... - if(headers_sent()) { - //headers sent. Use the meta redirect. - print " - <HTML> - <HEAD> - <TITLE>Redirect Page</TITLE> - <META HTTP-EQUIV='refresh' content='0; URL=$url'> - </HEAD> - <a href=\"$url\"></a> - </HTML> - "; - } - else { - header("location:$url"); - } - - if($exitAfter) { - //redirecting without exitting is bad, m'kay? - exit; - } - } - else { - //TODO: should an exception be thrown, or maybe exit here anyway? - throw new exception(__METHOD__ .": auto redirects not allowed...?"); - } + function conditional_header($url, $exitAfter=TRUE,$isPermRedir=FALSE) { + $this->gfObj->conditional_header($url, $exitAfter, $isPermRedir); }//end conditional_header() //--------------------------------------------------------------------------------------------- @@ -691,6 +664,31 @@ return($this->templateVars[$section]); }//strip_undef_template_vars_from_section() //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Magic PHP method for retrieving the values of private/protected vars. + */ + public function __get($var) { + return($this->$var); + }//end __get() + //------------------------------------------------------------------------- + + + + //------------------------------------------------------------------------- + /** + * Magic PHP method for changing the values of private/protected vars (or + * creating new ones). + */ + public function __set($var, $val) { + + //TODO: set some restrictions on internal vars... + $this->$var = $val; + }//end __set() + //------------------------------------------------------------------------- }//end cs_genericPage{} ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-19 01:40:42
|
Revision: 447 http://cs-content.svn.sourceforge.net/cs-content/?rev=447&view=rev Author: crazedsanity Date: 2009-08-19 01:40:29 +0000 (Wed, 19 Aug 2009) Log Message: ----------- Pass siteRoot to contentSystem{}, fix pass-by-reference problems. /contentSystem.class.php: * __construct(): -- ARG CHANGE: ARG RENAMED: #1 ($testOnly=FALSE to $siteRoot=null) -- removed unused $testOnly arg for $siteRoot, so the root can be set dynamically & doesn't necessarily require SITE_ROOT as a defined constant. -- updated exception to hopefully denote options... -- remove "if" statement for $testOnly -- pass $siteRoot on to initialize_locals() * initialize_locals(): -- ARG CHANGE: NEW ARG: #1 ($siteRoot=null) -- test $siteRoot as the root directory before dealing with SITE_ROOT -- when passing the default main template var to cs_genericPage{}, add "templates/" so it find the directory properly (this broken code was fixed in cs_genericPage by requiring the constant SITE_ROOT). -- use $root when setting the base directory for templates and includes, so the use the same folder as cs_genericPage. * finish(): -- create the copy of templateObj later, since it seems the object isn't actually passed by reference. -- after the local $page var is created, only use that reference instead of working on the internal templateObj, since it is (at least potentially) different. /cs_genericPage.class.php: * initialize_locals(): -- better exception message details. Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_genericPage.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-18 20:43:12 UTC (rev 446) +++ trunk/1.0/contentSystem.class.php 2009-08-19 01:40:29 UTC (rev 447) @@ -103,27 +103,21 @@ /** * The CONSTRUCTOR. Duh. */ - public function __construct($testOnly=FALSE) { + public function __construct($siteRoot=null) { parent::__construct(); - if($testOnly === 'unit_test') { - //It's just a test, don't do anything we might regret later. - $this->isTest = TRUE; + + if(is_null($siteRoot) && !defined('SITE_ROOT')) { + throw new exception(__METHOD__ .": must set siteRoot or constant 'SITE_ROOT'"); } - else { - - if(!defined('SITE_ROOT')) { - throw new exception(__METHOD__ .": must set required constant 'SITE_ROOT'"); - } - - //setup the section stuff... - $repArr = array($_SERVER['SCRIPT_NAME'], "/"); - $_SERVER['REQUEST_URI'] = ereg_replace('^/', "", $_SERVER['REQUEST_URI']); - - //figure out the section & subsection stuff. - $this->section = $this->clean_url($_SERVER['REQUEST_URI']); - - $this->initialize_locals(); - } + + //setup the section stuff... + $repArr = array($_SERVER['SCRIPT_NAME'], "/"); + $_SERVER['REQUEST_URI'] = ereg_replace('^/', "", $_SERVER['REQUEST_URI']); + + //figure out the section & subsection stuff. + $this->section = $this->clean_url($_SERVER['REQUEST_URI']); + + $this->initialize_locals($siteRoot); }//end __construct() //------------------------------------------------------------------------ @@ -133,7 +127,7 @@ /** * Creates internal objects & prepares for later usage. */ - private function initialize_locals() { + private function initialize_locals($siteRoot=null) { //create a session that gets stored in a database if they so desire... if(defined('SESSION_DBSAVE')) { @@ -146,10 +140,13 @@ //TODO: find a way to define this on a per-page basis. Possibly have templateObj->check_login() // run during the "finish" stage... probably using GenericPage{}->check_login(). $root = $_SERVER['DOCUMENT_ROOT']; - if(defined('SITE_ROOT')) { + if(!is_null($siteRoot) && is_dir($siteRoot)) { + $root = $siteRoot; + } + elseif(defined('SITE_ROOT') && is_dir(constant('SITE_ROOT'))) { $root = constant('SITE_ROOT'); } - $this->templateObj = new cs_genericPage(FALSE, $root ."/main.shared.tmpl"); + $this->templateObj = new cs_genericPage(FALSE, $root ."/templates/main.shared.tmpl"); //setup some default template vars. $this->templateObj->add_template_var('date', date('m-d-Y')); @@ -168,18 +165,12 @@ } //create a fileSystem object for templates. - $tmplBaseDir = constant('SITE_ROOT') .'/templates'; - if(defined('TMPLDIR')) { - $tmplBaseDir = constant('TMPLDIR'); - } + $tmplBaseDir = $root .'/templates'; $this->tmplFs = new cs_fileSystem($tmplBaseDir); //create a fileSystem object for includes - $incBaseDir = constant('SITE_ROOT') .'/includes'; - if(defined('INCLUDES_DIR')) { - $incBaseDir = constant('INCLUDES_DIR'); - } + $incBaseDir = $root .'/includes'; $this->incFs = new cs_fileSystem($incBaseDir); @@ -782,8 +773,6 @@ unset($_GET[$badVarName], $_POST[$badVarName]); } - $page =& $this->templateObj; - if(is_array($this->injectVars) && count($this->injectVars)) { $definedVars = get_defined_vars(); foreach($this->injectVars as $myVarName=>$myVarVal) { @@ -797,14 +786,13 @@ } if(isset($this->session) && is_object($this->session)) { - $page->session = $this->session; + $this->templateObj->session = $this->session; } //if we loaded an index, but there is no "content", then move 'em around so we have content. - if(isset($this->templateList['index']) && !isset($this->templateList['content'])) { - $this->add_template('content', $this->templateList['index']); - unset($this->templateList['index']); + if(isset($this->templateObj->templateFiles['index']) && !isset($this->templateObj->templateFiles['content'])) { + $this->add_template('content', $this->templateObj->templateFiles['index']); } //make the "final section" available to scripts. @@ -813,6 +801,9 @@ array_unshift($sectionArr, $this->baseDir); $finalURL = $this->gfObj->string_from_array($sectionArr, NULL, '/'); + + $page = $this->templateObj; + //now include the includes scripts, if there are any. if(is_array($this->includesList) && count($this->includesList)) { try { @@ -832,7 +823,7 @@ catch(exception $e) { $myRoot = preg_replace('/\//', '\\\/', $this->incFs->root); $displayableInclude = preg_replace('/^'. $myRoot .'/', '', $this->myLastInclude); - $this->templateObj->set_message_wrapper(array( + $page->set_message_wrapper(array( 'title' => "Fatal Error", 'message' => __METHOD__ .": A fatal error occurred while processing <b>". $displayableInclude ."</b>:<BR>\n<b>ERROR</b>: ". $e->getMessage(), @@ -848,12 +839,12 @@ unset($myInternalScriptName); } - if(is_bool($this->templateObj->allow_invalid_urls() === TRUE) && $this->isValid === FALSE) { - $this->isValid = $this->templateObj->allow_invalid_urls(); + if(is_bool($page->allow_invalid_urls() === TRUE) && $this->isValid === FALSE) { + $this->isValid = $page->allow_invalid_urls(); } if($this->isValid === TRUE) { - if($this->templateObj->printOnFinish === true) { + if($page->printOnFinish === true) { $page->print_page(); } } Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2009-08-18 20:43:12 UTC (rev 446) +++ trunk/1.0/cs_genericPage.class.php 2009-08-19 01:40:29 UTC (rev 447) @@ -83,8 +83,7 @@ $this->libDir = $this->siteRoot .'/lib'; if(!is_dir($this->tmplDir)) { - $this->gfObj->debug_print(func_get_args(),1); - throw new exception(__METHOD__ .": invalid templates folder (". $this->tmplDir ."), pwd=(". getcwd() .")"); + throw new exception(__METHOD__ .": invalid templates folder (". $this->tmplDir ."), siteRoot=(". $this->siteRoot .")"); } //if there have been some global template vars (or files) set, read 'em in here. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-19 16:14:53
|
Revision: 448 http://cs-content.svn.sourceforge.net/cs-content/?rev=448&view=rev Author: crazedsanity Date: 2009-08-19 16:14:43 +0000 (Wed, 19 Aug 2009) Log Message: ----------- Fix some requirements for cs_versionParse & such. Modified Paths: -------------- trunk/1.0/abstract/cs_content.abstract.class.php trunk/1.0/cs_globalFunctions.class.php trunk/1.0/cs_session.class.php trunk/1.0/cs_sessionDB.class.php Modified: trunk/1.0/abstract/cs_content.abstract.class.php =================================================================== --- trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-19 01:40:29 UTC (rev 447) +++ trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-19 16:14:43 UTC (rev 448) @@ -11,7 +11,7 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/../../cs-versionparse/cs_version.abstract.class.php"); +require_once(dirname(__FILE__) ."/../../cs-webapplibs/cs_version.abstract.class.php"); abstract class cs_contentAbstract extends cs_versionAbstract { Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2009-08-19 01:40:29 UTC (rev 447) +++ trunk/1.0/cs_globalFunctions.class.php 2009-08-19 16:14:43 UTC (rev 448) @@ -1,6 +1,6 @@ <?php -require_once(dirname(__FILE__) ."/../cs-versionparse/cs_version.abstract.class.php"); +require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); class cs_globalFunctions extends cs_versionAbstract { Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2009-08-19 01:40:29 UTC (rev 447) +++ trunk/1.0/cs_session.class.php 2009-08-19 16:14:43 UTC (rev 448) @@ -9,7 +9,6 @@ */ require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); -require_once(dirname(__FILE__) ."/../cs-versionparse/cs_version.abstract.class.php"); class cs_session extends cs_contentAbstract { Modified: trunk/1.0/cs_sessionDB.class.php =================================================================== --- trunk/1.0/cs_sessionDB.class.php 2009-08-19 01:40:29 UTC (rev 447) +++ trunk/1.0/cs_sessionDB.class.php 2009-08-19 16:14:43 UTC (rev 448) @@ -11,7 +11,7 @@ require_once(dirname(__FILE__) .'/cs_session.class.php'); require_once(dirname(__FILE__) .'/cs_phpDB.class.php'); require_once(constant('LIBDIR') .'/cs-phpxml/cs_arrayToPath.class.php'); -require_once(constant('LIBDIR') .'/cs-webdblogger/cs_webdblogger.class.php'); +require_once(constant('LIBDIR') .'/cs-webapplibs/cs_webdblogger.class.php'); class cs_sessionDB extends cs_session { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-20 16:13:58
|
Revision: 451 http://cs-content.svn.sourceforge.net/cs-content/?rev=451&view=rev Author: crazedsanity Date: 2009-08-20 16:13:49 +0000 (Thu, 20 Aug 2009) Log Message: ----------- Moved cs_versionAbstract to cs-content. NOTE::: it occurred to me that having cs_versionAbstract in another project meant that the other library would be inextricably tied to cs-content instead of being an extension. It only made sense to move it here (though I wish I'd come to that realization much earlier). /abstract/cs_content.abstract.class.php: * MAIN::: -- fix requirement for cs_versionAbstract /abstract/cs_version.abstract.class.php [NEW]: * copied from cs-webapplibs (which in turn was copied from the now defunct cs-versionparse project). /tests/testOfCSVersionAbstract.php [NEW]: * copied from cs-webapplibs (bits from the main test file). /tests/files/version* [NEW]: * files required for testing cs_versionAbstract. Modified Paths: -------------- trunk/1.0/abstract/cs_content.abstract.class.php Added Paths: ----------- trunk/1.0/abstract/cs_version.abstract.class.php trunk/1.0/tests/files/version1 trunk/1.0/tests/files/version2 trunk/1.0/tests/files/version3 trunk/1.0/tests/testOfCSVersionAbstract.php Modified: trunk/1.0/abstract/cs_content.abstract.class.php =================================================================== --- trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-20 14:29:20 UTC (rev 450) +++ trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-20 16:13:49 UTC (rev 451) @@ -11,7 +11,7 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/../../cs-webapplibs/cs_version.abstract.class.php"); +require_once(dirname(__FILE__) ."/cs_version.abstract.class.php"); abstract class cs_contentAbstract extends cs_versionAbstract { Added: trunk/1.0/abstract/cs_version.abstract.class.php =================================================================== --- trunk/1.0/abstract/cs_version.abstract.class.php (rev 0) +++ trunk/1.0/abstract/cs_version.abstract.class.php 2009-08-20 16:13:49 UTC (rev 451) @@ -0,0 +1,398 @@ +<?php +/* + * Created on January 01, 2009 by Dan Falconer + * + * SVN INFORMATION::: + * ------------------- + * Last Author::::::::: $Author$ + * Current Revision:::: $Revision$ + * Repository Location: $HeadURL$ + * Last Updated:::::::: $Date$ + */ + +abstract class cs_versionAbstract { + + public $isTest = FALSE; + + + + private $versionFileLocation=null; + private $fullVersionString; + private $suffixList = array( + 'ALPHA', //very unstable + 'BETA', //kinda unstable, but probably useable + 'RC' //all known bugs fixed, searching for unknown ones + ); + + + + abstract public function __construct(); + + + + //========================================================================= + /** + * Retrieve our version string from the VERSION file. + */ + final public function get_version($asArray=false) { + $retval = NULL; + + $this->auto_set_version_file(); + + if(file_exists($this->versionFileLocation)) { + $myMatches = array(); + $findIt = preg_match('/VERSION: (.+)/', file_get_contents($this->versionFileLocation), $matches); + + if($findIt == 1 && count($matches) == 2) { + $fullVersionString = $matches[1]; + $versionInfo = $this->parse_version_string($fullVersionString); + $this->fullVersionString = $this->build_full_version_string($versionInfo); + + + if($asArray) { + $retval = $versionInfo; + $retval['version_string'] = $this->fullVersionString; + } + else { + $retval = $this->build_full_version_string($versionInfo); + } + } + else { + throw new exception(__METHOD__ .": failed to retrieve version string in file " . + "(". $this->versionFileLocation .")"); + } + } + else { + throw new exception(__METHOD__ .": failed to retrieve version information, file " . + "(". $this->versionFileLocation .") does not exist or was not set"); + } + + return($retval); + }//end get_version() + //========================================================================= + + + + //========================================================================= + public function __get($var) { + return($this->$var); + }//end __get() + //========================================================================= + + + + //========================================================================= + final public function get_project() { + $retval = NULL; + $this->auto_set_version_file(); + if(file_exists($this->versionFileLocation)) { + $myMatches = array(); + $findIt = preg_match('/PROJECT: (.+)/', file_get_contents($this->versionFileLocation), $matches); + + if($findIt == 1 && count($matches) == 2 && strlen($matches[1])) { + $retval = $matches[1]; + } + else { + throw new exception(__METHOD__ .": failed to retrieve project string"); + } + } + else { + throw new exception(__METHOD__ .": failed to retrieve project information"); + } + + return($retval); + }//end get_project() + //========================================================================= + + + + //========================================================================= + public function set_version_file_location($location) { + if(file_exists($location)) { + $this->versionFileLocation = $location; + } + else { + throw new exception(__METHOD__ .": invalid location of VERSION file (". $location .")"); + } + }//end set_version_file_location() + //========================================================================= + + + + //========================================================================= + protected function auto_set_version_file() { + if(!strlen($this->versionFileLocation)) { + $bt = debug_backtrace(); + foreach($bt as $callNum=>$data) { + if(strlen($data['class'])) { + if($data['class'] != __CLASS__) { + $dir = dirname($data['file']); + if(preg_match('/tests$/', $dir)) { + $dir = preg_replace('/\/tests$/', '', $dir); + } + elseif(preg_match('/test$/', $dir)) { + $dir = preg_replace('/\/test$/', '', $dir); + } + break; + } + } + else { + throw new exception(__METHOD__ .": failed to locate the calling class in backtrace"); + } + } + + if(file_exists($dir .'/VERSION')) { + $this->set_version_file_location($dir .'/VERSION'); + } + else { + throw new exception(__METHOD__ .": failed to automatically set version file (tried ". $dir ."/VERSION)"); + } + } + }//end auto_set_version_file() + //========================================================================= + + + + //========================================================================= + /** + * + * TODO: add logic to split apart the suffix (i.e. "-ALPHA5" broken into "ALPHA" and "5"). + */ + public function parse_version_string($version) { + if(is_string($version) && strlen($version) && preg_match('/\./', $version)) { + $version = preg_replace('/ /', '', $version); + + $pieces = explode('.', $version); + $retval = array( + 'version_major' => $pieces[0], + 'version_minor' => $pieces[1] + ); + if(isset($pieces[2]) && strlen($pieces[2])) { + $retval['version_maintenance'] = $pieces[2]; + } + else { + $retval['version_maintenance'] = 0; + } + + if(preg_match('/-/', $retval['version_maintenance'])) { + $bits = explode('-', $retval['version_maintenance']); + $retval['version_maintenance'] = $bits[0]; + $suffix = $bits[1]; + } + elseif(preg_match('/-/', $retval['version_minor'])) { + $bits = explode('-', $retval['version_minor']); + $retval['version_minor'] = $bits[0]; + $suffix = $bits[1]; + } + else { + $suffix = ""; + } + $retval['version_suffix'] = $suffix; + } + else { + throw new exception(__METHOD__ .": invalid version string passed (". $version .")"); + } + + return($retval); + }//end parse_version_string() + //========================================================================= + + + + //========================================================================= + public function build_full_version_string(array $versionInfo) { + $requiredIndexes = array( + 'version_major', 'version_minor', 'version_maintenance', 'version_suffix' + ); + + $missing=""; + $count=0; + foreach($requiredIndexes as $indexName) { + if(isset($versionInfo[$indexName])) { + $count++; + } + else { + if(strlen($missing)) { + $missing .= ", ". $indexName; + } + else { + $missing = $indexName; + } + } + } + + if($count == count($requiredIndexes) && !strlen($missing)) { + $suffix = $versionInfo['version_suffix']; + unset($versionInfo['version_suffix']); + + $retval = ""; + foreach($versionInfo as $name=>$value) { + if(strlen($retval)) { + $retval .= ".". $value; + } + else { + $retval = $value; + } + } + if(strlen($suffix)) { + $retval .= "-". $suffix; + } + } + else { + throw new exception(__METHOD__ .": missing indexes in given array (". $missing .")"); + } + + return($retval); + + }//end build_full_version_string() + //========================================================================= + + + + //========================================================================= + public function is_higher_version($version, $checkIfHigher) { + $retval = FALSE; + $this->gfObj = new cs_globalFunctions; + if(!is_string($version) || !is_string($checkIfHigher)) { + throw new exception(__METHOD__ .": no valid version strings, version=(". $version ."), checkIfHigher=(". $checkIfHigher .")"); + } + elseif($version == $checkIfHigher) { + $retval = FALSE; + } + else { + $curVersionArr = $this->parse_version_string($version); + $checkVersionArr = $this->parse_version_string($checkIfHigher); + + unset($curVersionArr['version_string'], $checkVersionArr['version_string']); + + + $curVersionSuffix = $curVersionArr['version_suffix']; + $checkVersionSuffix = $checkVersionArr['version_suffix']; + + + unset($curVersionArr['version_suffix']); + + foreach($curVersionArr as $index=>$versionNumber) { + $checkThis = $checkVersionArr[$index]; + + if(is_numeric($checkThis) && is_numeric($versionNumber)) { + //set them as integers. + settype($versionNumber, 'int'); + settype($checkThis, 'int'); + + if($checkThis > $versionNumber) { + $retval = TRUE; + break; + } + elseif($checkThis == $versionNumber) { + //they're equal... + } + else { + //TODO: should there maybe be an option to throw an exception (freak out) here? + } + } + else { + throw new exception(__METHOD__ .": ". $index ." is not numeric in one of the strings " . + "(versionNumber=". $versionNumber .", checkThis=". $checkThis .")"); + } + } + + //now deal with those damnable suffixes, but only if the versions are so far identical: if + // the "$checkIfHigher" is actually higher, don't bother (i.e. suffixes don't matter when + // we already know there's a major, minor, or maintenance version that's also higher. + if($retval === FALSE) { + //EXAMPLE: $version="1.0.0-BETA3", $checkIfHigher="1.1.0" + // Moving from a non-suffixed version to a suffixed version isn't supported, but the inverse is: + // i.e. (1.0.0-BETA3 to 1.0.0) is okay, but (1.0.0 to 1.0.0-BETA3) is NOT. + // Also: (1.0.0-BETA3 to 1.0.0-BETA4) is okay, but (1.0.0-BETA4 to 1.0.0-BETA3) is NOT. + if(strlen($curVersionSuffix) && strlen($checkVersionSuffix) && $curVersionSuffix == $checkVersionSuffix) { + //matching suffixes. + } + elseif(strlen($curVersionSuffix) || strlen($checkVersionSuffix)) { + //we know the suffixes are there and DO match. + if(strlen($curVersionSuffix) && strlen($checkVersionSuffix)) { + //okay, here's where we do some crazy things... + $curVersionData = $this->parse_suffix($curVersionSuffix); + $checkVersionData = $this->parse_suffix($checkVersionSuffix); + + if($curVersionData['type'] == $checkVersionData['type']) { + //got the same suffix type (like "BETA"), check the number. + if($checkVersionData['number'] > $curVersionData['number']) { + //new version's suffix number higher than current... + $retval = TRUE; + } + elseif($checkVersionData['number'] == $curVersionData['number']) { + //new version's suffix number is EQUAL TO current... + $retval = FALSE; + } + else { + //new version's suffix number is LESS THAN current... + $retval = FALSE; + } + } + else { + //not the same suffix... see if the new one is higher. + $suffixValues = array_flip($this->suffixList); + if($suffixValues[$checkVersionData['type']] > $suffixValues[$curVersionData['type']]) { + $retval = TRUE; + } + else { + //current suffix type is higher... + } + } + + } + elseif(strlen($curVersionSuffix) && !strlen($checkVersionSuffix)) { + //i.e. "1.0.0-BETA1" to "1.0.0" --->>> OKAY! + $retval = TRUE; + } + elseif(!strlen($curVersionSuffix) && strlen($checkVersionSuffix)) { + //i.e. "1.0.0" to "1.0.0-BETA1" --->>> NOT ACCEPTABLE! + } + } + else { + //no suffix to care about + } + } + } + + return($retval); + + }//end is_higher_version() + //========================================================================= + + + + //========================================================================= + protected function parse_suffix($suffix) { + $retval = NULL; + if(strlen($suffix)) { + //determine what kind it is. + foreach($this->suffixList as $type) { + if(preg_match('/^'. $type .'/', $suffix)) { + $checkThis = preg_replace('/^'. $type .'/', '', $suffix); + if(strlen($checkThis) && is_numeric($checkThis)) { + //oooh... it's something like "BETA3" + $retval = array( + 'type' => $type, + 'number' => $checkThis + ); + } + else { + throw new exception(__METHOD__ .": invalid suffix (". $suffix .")"); + } + break; + } + } + } + else { + throw new exception(__METHOD__ .": invalid suffix (". $suffix .")"); + } + + return($retval); + }//end parse_suffix() + //========================================================================= + + +} +?> \ No newline at end of file Property changes on: trunk/1.0/abstract/cs_version.abstract.class.php ___________________________________________________________________ Added: svn:keywords + Id Author Revision HeadURL Date Added: trunk/1.0/tests/files/version1 =================================================================== --- trunk/1.0/tests/files/version1 (rev 0) +++ trunk/1.0/tests/files/version1 2009-08-20 16:13:49 UTC (rev 451) @@ -0,0 +1,3 @@ + +PROJECT: test1 +VERSION: 0.1.2-ALPHA8754 \ No newline at end of file Added: trunk/1.0/tests/files/version2 =================================================================== --- trunk/1.0/tests/files/version2 (rev 0) +++ trunk/1.0/tests/files/version2 2009-08-20 16:13:49 UTC (rev 451) @@ -0,0 +1,3 @@ + +PROJECT: test2 +VERSION: 5.4 \ No newline at end of file Added: trunk/1.0/tests/files/version3 =================================================================== --- trunk/1.0/tests/files/version3 (rev 0) +++ trunk/1.0/tests/files/version3 2009-08-20 16:13:49 UTC (rev 451) @@ -0,0 +1,3 @@ + +PROJECT: test3 stuff +VERSION: 5.4.3-BETA5543 \ No newline at end of file Added: trunk/1.0/tests/testOfCSVersionAbstract.php =================================================================== --- trunk/1.0/tests/testOfCSVersionAbstract.php (rev 0) +++ trunk/1.0/tests/testOfCSVersionAbstract.php 2009-08-20 16:13:49 UTC (rev 451) @@ -0,0 +1,131 @@ +<?php +/* + * Created on Jan 25, 2009 + * + * FILE INFORMATION: + * + * $HeadURL$ + * $Id$ + * $LastChangedDate$ + * $LastChangedBy$ + * $LastChangedRevision$ + */ + +require_once(dirname(__FILE__) .'/../abstract/cs_version.abstract.class.php'); + +class testOfCSVersionAbstract extends UnitTestCase { + + //-------------------------------------------------------------------------- + function __construct() { + $this->gfObj = new cs_globalFunctions; + $this->gfObj->debugPrintOpt=1; + }//end __construct() + //-------------------------------------------------------------------------- + + + //-------------------------------------------------------------------------- + function test_version_basics() { + + $tests = array( + 'files/version1' => array( + '0.1.2-ALPHA8754', + 'test1', + array( + 'version_major' => 0, + 'version_minor' => 1, + 'version_maintenance' => 2, + 'version_suffix' => 'ALPHA8754' + ) + ), + 'files/version2' => array( + '5.4.0', + 'test2', + array( + 'version_major' => 5, + 'version_minor' => 4, + 'version_maintenance' => 0, + 'version_suffix' => null + ) + ), + 'files/version3' => array( + '5.4.3-BETA5543', + 'test3 stuff', + array( + 'version_major' => 5, + 'version_minor' => 4, + 'version_maintenance' => 3, + 'version_suffix' => 'BETA5543' + ) + ) + ); + + foreach($tests as $fileName=>$expectedArr) { + $ver = new middleTestClass(); + $ver->set_version_file_location(dirname(__FILE__) .'/'. $fileName); + + $this->assertEqual($expectedArr[0], $ver->get_version(), "Failed to match string from file (". $fileName .")"); + $this->assertEqual($expectedArr[1], $ver->get_project(), "Failed to match project from file (". $fileName .")"); + + //now check that pulling the version as an array is the same... + $checkItArr = $ver->get_version(true); + $expectThis = $expectedArr[2]; + $expectThis['version_string'] = $expectedArr[0]; + } + }//end test_version_basics() + //-------------------------------------------------------------------------- + + + + //-------------------------------------------------------------------------- + function test_check_higher() { + + //NOTE: the first item should ALWAYS be higher. + $tests = array( + 'basic, no suffix' => array('1.0.1', '1.0.0'), + 'basic + suffix' => array('1.0.0-ALPHA1', '1.0.0-ALPHA0'), + 'basic w/o maint' => array('1.0.1', '1.0'), + 'suffix check' => array('1.0.0-BETA1', '1.0.0-ALPHA1'), + 'suffix check2' => array('1.0.0-ALPHA10', '1.0.0-ALPHA1'), + 'suffix check3' => array('1.0.1', '1.0.0-RC1') + ); + + foreach($tests as $name=>$checkData) { + $ver = new middleTestClass; + $this->assertTrue($ver->is_higher_version($checkData[1], $checkData[0])); + $this->assertFalse($ver->is_higher_version($checkData[0], $checkData[1])); + } + + //now check to ensure there's no problem with parsing equivalent versions. + $tests = array( + 'no suffix' => array('1.0', '1.0.0'), + 'no maint + suffix' => array('1.0-ALPHA1', '1.0.0-ALPHA1'), + 'no maint + BETA' => array('1.0-BETA5555', '1.0.0-BETA5555'), + 'no maint + RC' => array('1.0-RC33', '1.0.0-RC33'), + 'maint with space' => array('1.0-RC 33', '1.0.0-RC33'), + 'extra spaces' => array(' 1.0 ', '1.0.0') + ); + foreach($tests as $name=>$checkData) { + $ver = new middleTestClass; + + //rip apart & recreate first version to test against the expected... + $derivedFullVersion = $ver->build_full_version_string($ver->parse_version_string($checkData[0])); + $this->assertEqual($derivedFullVersion, $checkData[1], "TEST=(". $name ."): derived version " . + "(". $derivedFullVersion .") doesn't match expected (". $checkData[1] .")"); + + //now rip apart & recreate the expected version (second) and make sure it matches itself. + $derivedFullVersion = $ver->build_full_version_string($ver->parse_version_string($checkData[1])); + $this->assertEqual($derivedFullVersion, $checkData[1], "TEST=(". $name ."): derived version " . + "(". $derivedFullVersion .") doesn't match expected (". $checkData[1] .")"); + } + + + }//end test_check_higher() + //-------------------------------------------------------------------------- +} + + +class middleTestClass extends cs_versionAbstract { + function __construct(){} +} + +?> Property changes on: trunk/1.0/tests/testOfCSVersionAbstract.php ___________________________________________________________________ Added: svn:keywords + Id Author Revision HeadURL Date This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-20 20:35:17
|
Revision: 453 http://cs-content.svn.sourceforge.net/cs-content/?rev=453&view=rev Author: crazedsanity Date: 2009-08-20 20:34:59 +0000 (Thu, 20 Aug 2009) Log Message: ----------- Moving all webapp-related libs to cs-webapplibs project. NOTE::: this is done to facilitate much faster changes to cs-content. While it may slow development of cs-webapplibs, there is also a lot of work being done to build unit tests there: this should hopefully avoid unexpected breakage in code during upgrades. This also makes upgrading of the database-reliant stuff (like cs_phpDB) to be more easily upgraded. CODE MOVED TO cs-webapplibs::: * /cs_bbCodeParser.class.php * /cs_phpDB.class.php (including db_types & abstract) * /cs_sessionDB.class.php (including schema files) * /cs_siteConfig.class.php * /cs_tabs.class.php * /tests/testOfCSPHPDB.php REMOVED::: * /sample_files/bin/convertSessionFilesToDB.php CHANGED REQUIRE_ONCE PATHS::: * /contentSystem.class.php (cs_sessionDB) MISC::: * /contentSystem.class.php: -- MAIN::: don't require cs_tabs -- initialize_locals(): drop cs_tabs stuff (unneeded) Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/tests/testOfCSContent.php trunk/1.0/tests/testOfCSGlobalFunctions.php Removed Paths: ------------- trunk/1.0/abstract/cs_phpDB.abstract.class.php trunk/1.0/cs_bbCodeParser.class.php trunk/1.0/cs_phpDB.class.php trunk/1.0/cs_sessionDB.class.php trunk/1.0/cs_siteConfig.class.php trunk/1.0/cs_tabs.class.php trunk/1.0/db_types/ trunk/1.0/sample_files/bin/ trunk/1.0/schema/ trunk/1.0/tests/testOfCSPHPDB.php Deleted: trunk/1.0/abstract/cs_phpDB.abstract.class.php =================================================================== --- trunk/1.0/abstract/cs_phpDB.abstract.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/abstract/cs_phpDB.abstract.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,166 +0,0 @@ -<?php -/* - * Created on Jan 29, 2009 - * - * FILE INFORMATION: - * - * $HeadURL$ - * $Id$ - * $LastChangedDate$ - * $LastChangedBy$ - * $LastChangedRevision$ - */ - -abstract class cs_phpDBAbstract { - - /** Internal result set pointer. */ - protected $result = NULL; - - /** Internal error code. */ - protected $errorCode = 0; - - /** Status of the current transaction. */ - protected $transStatus = NULL; - - /** Whether there is a transaction in progress or not. */ - protected $inTrans = FALSE; - - /** Holds the last query performed. */ - protected $lastQuery = NULL; - - /** List of queries that have been run */ - protected $queryList=array(); - - /** How many seconds to wait for a query before cancelling it. */ - protected $timeOutSeconds = NULL; - - /** Internal check to determine if a connection has been established. */ - protected $isConnected=FALSE; - - /** Internal check to determine if the parameters have been set. */ - protected $paramsAreSet=FALSE; - - /** Resource handle. */ - protected $connectionID = -1; - - /** Hostname or IP to connect to */ - protected $host; - - /** Port to connect to (default for Postgres is 5432) */ - protected $port; - - /** Name of the database */ - protected $dbname; - - /** Username to connect to the database */ - protected $user; - - /** password to connect to the database */ - protected $password; - - /** Row counter for looping through records */ - protected $row = -1; - - /** cs_globalFunctions object, for string stuff. */ - protected $gfObj; - - /** Internal check to ensure the object has been properly created. */ - protected $isInitialized=FALSE; - - /** List of prepared statements, indexed off the name, with the sub-array being fieldname=>dataType. */ - protected $preparedStatements = array(); - - /** Set to TRUE to save all queries into an array. */ - protected $useQueryList=FALSE; - - /** array that essentially remembers how many times beginTrans() was called. */ - protected $transactionTree = NULL; - - - - //Define some abstract methods so they MUST be provided in order for things to work. - abstract public function set_db_info(array $params); - abstract public function close(); - abstract public function connect(array $dbParams=NULL, $forceNewConnection=FALSE); - abstract public function exec($query); - abstract public function errorMsg($setMessage=null, $logError=null); - abstract public function fobject(); - abstract public function farray(); - abstract public function farray_fieldnames($index=null, $numbered=null,$unsetIndex=1); - abstract public function farray_nvp($name, $value); - abstract public function farray_numbered(); - abstract public function numAffected(); - abstract public function numRows(); - abstract public function is_connected(); - - - //========================================================================= - public function __construct() { - $this->gfObj = new cs_globalFunctions; - $this->isInitialized = true; - }//end __construct() - //========================================================================= - - - - //========================================================================= - /** - * Make sure the object is sane. - */ - final protected function sanity_check() { - if($this->isInitialized !== TRUE) { - throw new exception(__METHOD__ .": not properly initialized"); - } - }//end sanity_check() - //========================================================================= - - - - //========================================================================= - /** - * Disconnect from the database (calls internal "close()" method). - */ - public function disconnect() { - return($this->close()); - }//end disconnect() - //========================================================================= - - - - //========================================================================= - public function affectedRows() { - return($this->numAffected()); - }//end affectedRows() - //========================================================================= - - - - //========================================================================= - public function currRow() { - return($this->row); - }//end currRow() - //========================================================================= - - - - //========================================================================= - public function querySafe($string) { - return($this->gfObj->cleanString($string,"query")); - }//end querySafe() - //========================================================================= - - - - //========================================================================= - /** - * Make it SQL safe. - */ - public function sqlSafe($string) { - return($this->gfObj->cleanString($string,"sql")); - }//end sqlSafe() - //========================================================================= - - - -} -?> \ No newline at end of file Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/contentSystem.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -67,7 +67,6 @@ require_once(dirname(__FILE__) ."/cs_fileSystem.class.php"); require_once(dirname(__FILE__) ."/cs_session.class.php"); require_once(dirname(__FILE__) ."/cs_genericPage.class.php"); -require_once(dirname(__FILE__) ."/cs_tabs.class.php"); class contentSystem extends cs_contentAbstract { @@ -131,7 +130,7 @@ //create a session that gets stored in a database if they so desire... if(defined('SESSION_DBSAVE')) { - require_once(dirname(__FILE__) .'/cs_sessionDB.class.php'); + require_once(constant('LIBDIR') .'/cs-webapplibs/cs_sessionDB.class.php'); $obj = new cs_sessionDB(); $this->handle_session($obj); } @@ -188,10 +187,6 @@ $this->incFs = new cs_fileSystem($incBaseDir); - //create a tabs object, in case they want to load tabs on the page. - //TODO: make the tabs object usable to included code! - $this->tabs = new cs_tabs(); - //check versions, make sure they're all the same. $myVersion = $this->get_version(); if($this->templateObj->get_version() !== $myVersion) { @@ -203,9 +198,6 @@ if($this->gfObj->get_version() !== $myVersion) { throw new exception(__METHOD__ .": ". get_class($this->gfObj) ." has mismatched version (". $this->gfObj->get_version() ." does not equal ". $myVersion .")"); } - if($this->tabs->get_version() !== $myVersion) { - throw new exception(__METHOD__ .": ". get_class($this->tabs) ." has mismatched version (". $this->tabs->get_version() ." does not equal ". $myVersion .")"); - } //split apart the section so we can do stuff with it later. $this->parse_section(); Deleted: trunk/1.0/cs_bbCodeParser.class.php =================================================================== --- trunk/1.0/cs_bbCodeParser.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/cs_bbCodeParser.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,165 +0,0 @@ -<?php -/** - * Created on 2007-09-26 - * - * - * SVN INFORMATION::: - * ------------------ - * SVN Signature::::::: $Id$ - * Last Author::::::::: $Author$ - * Current Revision:::: $Revision$ - * Repository Location: $HeadURL$ - * Last Updated:::::::: $Date$ - * - * - * Originally from a snippet (just the function) on PHPFreaks.com: http://www.phpfreaks.com/quickcode/BBCode/712.php - * The original code had parse errors, so it had to be fixed... While it was posted as just a basic function, - * the code within (such as the reference to "$this->bbCodeData" indicated it was from a class... so it has - * been converted. - */ - -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); - -class cs_bbCodeParser extends cs_contentAbstract { - - /** Array containing all the codes & how to parse them. */ - private $bbCodeData = NULL; - - //========================================================================= - /** - * Setup internal structures. - */ - function __construct() { - parent::__construct(false); - # Which BBCode is accepted here - $this->bbCodeData = array( - 'bold' => array( - 'start' => array('[b]', '\[b\](.*)', '<b>\\1'), - 'end' => array('[/b]', '\[\/b\]', '</b>'), - ), - - 'underline' => array( - 'start' => array('[u]', '\[u\](.*)', '<u>\\1'), - 'end' => array('[/u]', '\[\/u\]', '</u>'), - ), - - 'italic' => array( - 'start' => array('[i]', '\[i\](.*)', '<i>\\1'), - 'end' => array('[/i]', '\[\/i\]', '</i>'), - ), - - 'image' => array( - 'start' => array('[img]', '\[img\](http:\/\/|https:\/\/|ftp:\/\/|\/)(.*)(.jpg|.jpeg|.bmp|.gif|.png)', '<img src=\'\\1\\2\\3\' />'), - 'end' => array('[/img]', '\[\/img\]', ''), - ), - - # [url]http://x.com[/url] - 'url1' => array( - 'start' => array('[url]', '\[url\](http:\/\/|https:\/\/|ftp:\/\/)(.*)', '<a target="_blank" href=\'\\1\\2\'>\\1\\2'), - 'end' => array('[/url]', '\[\/url\]', '</a>'), - ), - - # [url=http://x.com]stuff[/url] - 'url2' => array( - 'start' => array('[url]', '\[url=(http:\/\/|https:\/\/|ftp:\/\/)(.*)\](.*)', '<a target="_blank" href=\'\\1\\2\'>\\3'), - 'end' => array('[/url]', '\[\/url\]', '</a>'), - ), - - 'code' => array( - 'start' => array('[code]', '\[code\](.*)', '<br /><br /><b>CODE</b>:<div class="code">\\1'), - 'end' => array('[/code]', '\[\/code\]', '</div><br />'), - ), - ); - }//end __construct() - //========================================================================= - - - - //========================================================================= - /** - * Ensure the object is initialized properly, throw exception if not. - */ - private function isInitialized() { - if(!is_array($this->bbCodeData) || !count($this->bbCodeData)) { - throw new exception(__METHOD__ .": BBCode array not initialized"); - } - }//end isInitialized() - //========================================================================= - - - - //========================================================================= - /** - * Parse BBCode from the given string & return it with formatting. - */ - function parseString($data, $newlines2BR=FALSE) { - if(is_string($data) && strlen($data) > 10) { - $this->isInitialized(); - $data = str_replace("\n", '||newline||', $data); - - foreach( $this->bbCodeData as $k => $v ) { - if(isset($this->bbCodeData[$k]['special'])) { - $myMatches = array(); - $regex = '/'. $this->bbCodeData[$k]['start'][1] . $this->bbCodeData[$k]['end'][1] .'/'; - $x = preg_match_all($regex .'U', $data, $myMatches); - - if(count($myMatches[1])) { - $funcName = $v['special']; - $myArgs = $myMatches[1]; - $myArgs = array_unique($myArgs); - - foreach($myArgs as $index=>$value) { - $showThis = $this->$funcName($value); - $replaceThis = str_replace(array('[', ']'), array('\\[', '\\]'), $myMatches[0][$index]); - $data = preg_replace('/'. $replaceThis .'/U', $showThis, $data); - } - } - } - else { - $data = preg_replace("/".$this->bbCodeData[$k]['start'][1].$this->bbCodeData[$k]['end'][1]."/U", $this->bbCodeData[$k]['start'][2].$this->bbCodeData[$k]['end'][2], $data); - } - } - - $replaceNewlineStr = "\n"; - if($newlines2BR) { - $replaceNewlineStr = "<br />\n"; - } - $data = str_replace('||newline||', $replaceNewlineStr, $data); - - } - return $data; - }//end parseString() - //========================================================================= - - - - //========================================================================= - /** - * Enables extending classes to register a bbCode with special parsing. - * - * NOTE: right now, this will only handle syntax like "[{bbCodeString}={arg}]". - */ - protected function register_code_with_callback($bbCodeString, $method) { - - if(method_exists($this, $method)) { - $this->bbCodeData[$bbCodeString] = array( - 'special' => $method, - 'start' => array( - '['. $bbCodeString .']', - '\['. $bbCodeString .'=(.*)' - ), - 'end' => array( - '', - '\]' - ) - ); - } - else { - throw new exception(__METHOD__ .": method (". $method .") doesn't exist"); - } - - }//end register_code_with_callback() - //========================================================================= - -} -?> Deleted: trunk/1.0/cs_phpDB.class.php =================================================================== --- trunk/1.0/cs_phpDB.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/cs_phpDB.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,197 +0,0 @@ -<?php - -/* - * A class for generic PostgreSQL database access. - * - * SVN INFORMATION::: - * SVN Signature:::::::: $Id$ - * Last Committted Date: $Date$ - * Last Committed Path:: $HeadURL$ - * - */ - -/////////////////////// -// ORIGINATION INFO: -// Author: Trevin Chow (with contributions from Lee Pang, wle...@ho...) -// Email: t1...@ma... -// Date: February 21, 2000 -// Last Updated: August 14, 2001 -// -// Description: -// Abstracts both the php function calls and the server information to POSTGRES -// databases. Utilizes class variables to maintain connection information such -// as number of rows, result id of last operation, etc. -// -/////////////////////// - -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); -require_once(dirname(__FILE__) ."/abstract/cs_phpDB.abstract.class.php"); - -class cs_phpDB extends cs_contentAbstract { - - private $dbLayerObj; - private $dbType; - public $connectParams = array(); - - //========================================================================= - public function __construct($type='pgsql') { - - if(strlen($type)) { - - require_once(dirname(__FILE__) .'/db_types/'. __CLASS__ .'__'. $type .'.class.php'); - $className = __CLASS__ .'__'. $type; - $this->dbLayerObj = new $className; - $this->dbType = $type; - - parent::__construct(); - - $this->isInitialized = TRUE; - } - else { - throw new exception(__METHOD__ .": failed to give a type (". $type .")"); - } - }//end __construct() - //========================================================================= - - - - //========================================================================= - /** - * Magic method to call methods within the database abstraction layer ($this->dbLayerObj). - */ - public function __call($methodName, $args) { - if(method_exists($this->dbLayerObj, $methodName)) { - if($methodName == 'connect' && is_array($args[0])) { - //capture the connection parameters. - $this->connectParams = $args[0]; - } - $retval = call_user_func_array(array($this->dbLayerObj, $methodName), $args); - } - else { - throw new exception(__METHOD__ .': unsupported method ('. $methodName .') for database of type ('. $this->dbType .')'); - } - return($retval); - }//end __call() - //========================================================================= - - - - //========================================================================= - public function get_dbtype() { - return($this->dbType); - }//end get_dbtype() - //========================================================================= - - - - //========================================================================= - /** - * Performs queries which require results. Passing $indexField returns a - * complex array indexed from that field; passing $valueField will change - * it to a name=>value formatted array. - * - * NOTE:: when using an index field, be sure it is guaranteed to be unique, - * i.e. it is a primary key! If duplicates are found, the database class - * will throw an exception! - */ - public function run_query($sql, $indexField=null, $valueField=null) { - - $retval = array(); - - //length must be 19 as that's about the shortest valid SQL: "select * from table" - if(strlen($sql) >= 19) { - $this->exec($sql); - - $numRows = $this->numRows(); - $dbError = $this->errorMsg(); - if($numRows > 0 && !strlen($dbError)) { - if(strlen($indexField) && (is_null($valueField) || !strlen($valueField))) { - //return a complex array based on a given field. - $retval = $this->farray_fieldnames($indexField, null, 0); - } - elseif(strlen($indexField) && strlen($valueField)) { - //return an array as name=>value pairs. - $retval = $this->farray_nvp($indexField, $valueField); - } - else { - $retval = $this->farray_fieldnames(); - } - } - elseif($numRows == 0 && !strlen($dbError)) { - $retval = false; - } - else { - throw new exception(__METHOD__ .": no rows (". $numRows .") or dbError::: ". $dbError ."<BR>\nSQL::: ". $sql); - } - } - else { - throw new exception(__METHOD__ .": invalid length SQL (". $sql .")"); - } - - return($retval); - }//end run_query() - //========================================================================= - - - - //========================================================================= - /** - * Handles performing the insert statement & returning the last inserted ID. - */ - public function run_insert($sql, $sequence='null') { - - $this->exec($sql); - - if($this->numAffected() == 1 && !strlen($this->errorMsg())) { - //retrieve the ID just created. - $retval = $this->lastID($sequence); - } - else { - //something broke... - throw new exception(__METHOD__ .": failed to insert, rows=(". $this->numRows .")... " - ."ERROR::: ". $this->errorMsg() ."\n -- SQL:::: ". $sql); - } - - return($retval); - }//end run_insert() - //========================================================================= - - - - //========================================================================= - /** - * Performs the update & returns how many rows were affected. - */ - public function run_update($sql, $zeroIsOk=false) { - $this->exec($sql); - - $dberror = $this->errorMsg(); - $numAffected = $this->numAffected(); - - if(strlen($dberror)) { - throw new exception(__METHOD__ .": error while running update::: ". $dberror ." -- SQL::: ". $sql); - } - elseif($numAffected==0 && $zeroIsOk == false) { - throw new exception(__METHOD__ .": no rows updated (". $numAffected ."), SQL::: ". $sql); - } - - return($numAffected); - }//end run_update() - //========================================================================= - - - - //========================================================================= - public function reconnect() { - if(is_array($this->connectParams) && count($this->connectParams)) { - $this->dbLayerObj->connect($this->connectParams, true); - } - else { - throw new exception(__METHOD__ .": no connection parameters stored"); - } - }//end reconnect() - //========================================================================= - -} // end class phpDB - -?> Deleted: trunk/1.0/cs_sessionDB.class.php =================================================================== --- trunk/1.0/cs_sessionDB.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/cs_sessionDB.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,362 +0,0 @@ -<?php -/* - * FILE INFORMATION: - * $HeadURL$ - * $Id$ - * $LastChangedDate$ - * $LastChangedBy$ - * $LastChangedRevision$ - */ - -require_once(dirname(__FILE__) .'/cs_session.class.php'); -require_once(dirname(__FILE__) .'/cs_phpDB.class.php'); -require_once(constant('LIBDIR') .'/cs-phpxml/cs_arrayToPath.class.php'); -require_once(constant('LIBDIR') .'/cs-webapplibs/cs_webdblogger.class.php'); - -class cs_sessionDB extends cs_session { - - protected $db; - - protected $logger = null; - - protected $logCategory = "DB Sessions"; - - //------------------------------------------------------------------------- - /** - * The constructor. - * - * @param $createSession (mixed,optional) determines if a session will be started or not; if - * this parameter is non-null and non-numeric, the value will be - * used as the session name. - */ - function __construct() { - - - //map some constants to connection parameters. - //NOTE::: all constants should be prefixed... - $constantPrefix = 'SESSION_DB_'; - $params = array('host', 'port', 'dbname', 'user', 'password'); - foreach($params as $name) { - $value = null; - $constantName = $constantPrefix . strtoupper($name); - if(defined($constantName)) { - $value = constant($constantName); - } - $dbParams[$name] = $value; - } - $this->db = new cs_phpDB(constant('DBTYPE')); - $this->db->connect($dbParams); - - $this->tableName = 'cs_session_store_table'; - $this->tablePKey = 'session_store_id'; - $this->sequenceName = 'cs_session_store_table_session_store_id_seq'; - - if(!$this->sessdb_table_exists()) { - $this->load_table(); - } - - //now tell PHP to use this class's methods for saving the session. - session_set_save_handler( - array(&$this, 'sessdb_open'), - array(&$this, 'sessdb_close'), - array(&$this, 'sessdb_read'), - array(&$this, 'sessdb_write'), - array(&$this, 'sessdb_destroy'), - array(&$this, 'sessdb_gc') - ); - - parent::__construct(true); - - //Stop things from going into an audit log... see - //http://www.developertutorials.com/tutorials/php/saving-php-session-data-database-050711/page3.html - // NOTE::: not sure if this is valid or not... - $this->audit_logging = false; - - }//end __construct() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Determines if the appropriate table exists in the database. - */ - public function sessdb_table_exists() { - try { - $test = $this->db->run_query("SELECT * FROM ". $this->tableName . - " ORDER BY ". $this->tablePKey ." LIMIT 1"); - $exists = true; - } - catch(exception $e) { - $this->exception_handler(__METHOD__ .": exception while trying to detect table::: ". $e->getMessage()); - $exists = false; - } - - return($exists); - }//end sessdb_table_exists() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - private function load_table() { - $filename = dirname(__FILE__) .'/schema/db_session_schema.'. $this->db->get_dbtype() .'.sql'; - if(file_exists($filename)) { - try { - $this->db->run_update(file_get_contents($filename),true); - } - catch(exception $e) { - $this->exception_handler(__METHOD__ .": failed to load required table " . - "into your database automatically::: ". $e->getMessage(), true); - } - } - else { - $this->exception_handler(__METHOD__ .": while attempting to load required " . - "table into your database, discovered you have a missing schema " . - "file (". $filename .")", true); - } - }//end load_table() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - protected function is_valid_sid($sid) { - $isValid = false; - if(strlen($sid) == 32) { - try { - $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". - $sid ."'"; - $this->db->run_query($sql); - $numrows = $this->db->numRows(); - if($numrows == 1) { - $isValid = true; - } - elseif($numrows > 0 || $numrows < 0) { - $this->exception_handler(__METHOD__ .": invalid numrows returned (". $numrows .")",true); - } - } - catch(exception $e) { - //well... do nothing I guess. - } - } - - return($isValid); - }//end is_valid_sid() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Open the session (doesn't really do anything) - */ - public function sessdb_open($savePath, $sessionName) { - return(true); - }//end sessdb_open() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Close the session (call the "gc" method) - */ - public function sessdb_close() { - return($this->sessdb_gc(0)); - }//end sessdb_close() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Read information about the session. If there is no data, it MUST return - * an empty string instead of NULL. - */ - public function sessdb_read($sid) { - $retval = ''; - try { - $sql = "SELECT * FROM ". $this->tableName ." WHERE session_id='". - $sid ."'"; - $data = $this->db->run_query($sql); - - if($this->db->numRows() == 1) { - $retval = $data['session_data']; - } - } - catch(exception $e) { - //no throwing exceptions... - $this->exception_handler(__METHOD__ .": failed to read::: ". $e->getMessage()); - } - return($retval); - }//end sessdb_read() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function sessdb_write($sid, $data) { - $data = array( - 'session_data' => $data, - 'user_id' => null - ); - $cleanString = array( - 'session_data' => 'sql', - 'user_id' => 'numeric' - ); - - - - //pull the uid out of the session... - if(defined('SESSION_DBSAVE_UIDPATH')) { - $a2p = new cs_arrayToPath($_SESSION); - $uidVal = $a2p->get_data(constant('SESSION_DBSAVE_UIDPATH')); - - if(is_string($uidVal) || is_numeric($uidVal)) { - $data['user_id'] = $uidVal; - } - } - - $afterSql = ""; - if($this->is_valid_sid($sid)) { - $type = 'update'; - $sql = "UPDATE ". $this->tableName ." SET "; - $afterSql = "WHERE session_id='". $sid ."'"; - $data['last_updated'] = 'NOW()'; - $secondArg = false; - } - else { - $type = 'insert'; - $sql = "INSERT INTO ". $this->tableName ." "; - $data['session_id'] = $sid; - $secondArg = $this->sequenceName; - } - - $sql .= $this->gfObj->string_from_array($data, $type, null, $cleanString) .' '. $afterSql; - try { - $funcName = 'run_'. $type; - $res = $this->db->$funcName($sql, $secondArg); - } - catch(exception $e) { - //umm... yeah. - $this->exception_handler(__METHOD__ .": failed to perform action (". $type .")::: ". $e->getMessage()); - } - - return(true); - }//end sessdb_write() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function sessdb_destroy($sid) { - try { - $sql = "DELETE FROM ". $this->tableName ." WHERE session_id='". $sid ."'"; - $numDeleted = $this->db->run_update($sql, true); - - if($numDeleted > 0) { - $this->do_log("Destroyed session_id (". $sid .")", 'deleted'); - } - } - catch(exception $e) { - //do... nothing? - } - return(true); - }//end sessdb_destroy() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Define maximum lifetime (in seconds) to store sessions in the database. - * Anything that is older than that time will be purged (gc='garbage collector'). - */ - public function sessdb_gc($maxLifetime=null) { - - $dateFormat = 'Y-m-d H:i:s'; - $strftimeFormat = '%Y-%m-%d %H:%M:%S'; - $nowTime = date($dateFormat); - $excludeCurrent = true; - if(defined('SESSION_MAX_TIME') || defined('SESSION_MAX_IDLE')) { - $maxFreshness = null; - if(defined('SESSION_MAX_TIME')) { - $date = strtotime('- '. constant('SESSION_MAX_TIME')); - $maxFreshness = "date_created < '". strftime($strftimeFormat, $date) ."'"; - $excludeCurrent=false; - } - if(defined('SESSION_MAX_IDLE')) { - - $date = strtotime('- '. constant('SESSION_MAX_IDLE')); - $addThis = "last_updated < '". strftime($strftimeFormat, $date) ."'"; - $maxFreshness = $this->gfObj->create_list($maxFreshness, $addThis, ' OR '); - } - } - elseif(is_null($maxLifetime) || !is_numeric($maxLifetime) || $maxLifetime <= 0) { - //pull it from PHP's ini settings. - $maxLifetime = ini_get("session.gc_maxlifetime"); - $interval = $maxLifetime .' seconds'; - - $dt1 = strtotime($nowTime .' - '. $interval); - $maxFreshness = "last_updated < '". date($dateFormat, $dt1) ."'"; - } - - - - try { - //destroy old sessions, but don't complain if nothing is deleted. - $sql = "DELETE FROM ". $this->tableName ." WHERE ". $maxFreshness; - if(strlen($this->sid) && $excludeCurrent === false) { - $sql .= " AND session_id != '". $this->sid ."'"; - } - $numCleaned = $this->db->run_update($sql, true); - - if($numCleaned > 0) { - $this->do_log("cleaned (". $numCleaned .") old sessions, " . - "excludeCurrent=(". $this->gfObj->interpret_bool($excludeCurrent) .")" . - ", maxFreshness=(". $maxFreshness .")", "debug"); - } - } - catch(exception $e) { - $this->exception_handler(__METHOD__ .": exception while cleaning: ". $e->getMessage()); - } - - return(true); - - }//end sessdb_gc() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - protected function do_log($message, $type) { - - //check if the logger object has been created. - if(!is_object($this->logger)) { - $newDB = new cs_phpDB(constant('DBTYPE')); - $newDB->connect($this->db->connectParams, true); - $this->logger = new cs_webdblogger($newDB, $this->logCategory); - } - - return($this->logger->log_by_class("SID=(". $this->sid .") -- ". $message,$type)); - - }//end do_log() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - protected function exception_handler($message, $throwException=false) { - $logId = $this->do_log($message, 'exception in code'); - if($throwException === true) { - //in this class, it is mostly useless to throw exceptions, so by default they're not thrown. - throw new exception($message); - } - return($logId); - }//end exception_handler() - //------------------------------------------------------------------------- - - -}//end cs_session{} -?> \ No newline at end of file Deleted: trunk/1.0/cs_siteConfig.class.php =================================================================== --- trunk/1.0/cs_siteConfig.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/cs_siteConfig.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,404 +0,0 @@ -<?php - -/* - * A class for handling configuration of database-driven web applications. - * - * NOTICE::: this class requires that cs-phpxml and cs-arraytopath are both available - * at the same directory level as cs-content; all projects are SourceForge.net projects, - * using their unix names ("cs-phpxml" and "cs-arrayToPath"). The cs-phpxml project - * requires cs-arrayToPath for parsing XML paths. - * - * SVN INFORMATION::: - * SVN Signature:::::::: $Id$ - * Last Committted Date: $Date$ - * Last Committed Path:: $HeadURL$ - * - */ - -require_once(dirname(__FILE__) .'/abstract/cs_content.abstract.class.php'); -require_once(dirname(__FILE__) .'/cs_fileSystem.class.php'); -require_once(dirname(__FILE__). '/../cs-phpxml/cs_phpxmlParser.class.php'); -require_once(dirname(__FILE__) .'/../cs-phpxml/cs_phpxmlBuilder.class.php'); - -class cs_siteConfig extends cs_contentAbstract { - - /** XMLParser{} object, for reading XML config file. */ - private $xmlReader; - - /** cs_fileSystem{} object, for writing/updating XML config file - * (only available if file is writable) - */ - private $xmlWriter; - - /** XMLBuilder{} object, for updating XML. */ - private $xmlBuilder; - - /** cs_fileSystem{} object, for handling generic file operations (i.e. reading) */ - private $fs; - - /** boolean flag indicating if the given config file is readOnly (false=read/write) */ - private $readOnly; - - /** Directory for the config file. */ - private $configDirname; - - /** Location of the configuration file itself. */ - private $configFile; - - /** Active section of the full site configuration. */ - private $activeSection; - - /** The FULL configuration file, instead of just the active section. */ - private $fullConfig=array(); - - /** cs_arrayToPath{} object. */ - private $a2p; - - /** Prefix to add to every index in GLOBALS and CONSTANTS. */ - private $setVarPrefix; - - /** Sections available within the config */ - private $configSections=array(); - - /** Boolean flag to determine if the object has been properly initialized or not. */ - private $isInitialized=false; - - /** Store a list of items that need to be pushed into $GLOBALS on a given path. */ - private $setGlobalArrays=array(); - - //------------------------------------------------------------------------- - /** - * Constructor. - * - * @param $configFileLocation (str) URI for config file. - * @param $section (str,optional) set active section (default=MAIN) - * @param $setVarPrefix (str,optional) prefix to add to all global & constant names. - * - * @return NULL (PASS) object successfully created - * @return exception (FAIL) failed to create object (see exception message) - */ - public function __construct($configFileLocation, $section='MAIN', $setVarPrefix=null) { - - $section = strtoupper($section); - $this->setVarPrefix=$setVarPrefix; - - parent::__construct(); - - if(strlen($configFileLocation) && file_exists($configFileLocation)) { - - $this->configDirname = dirname($configFileLocation); - $this->configFile = $configFileLocation; - $this->fs = new cs_fileSystem($this->configDirname); - - $this->xmlReader = new cs_phpxmlParser($this->fs->read($configFileLocation)); - - if($this->fs->is_writable($configFileLocation)) { - $this->readOnly = false; - $this->xmlWriter = new cs_fileSystem($this->configDirname); - - } - else { - $this->readOnly = true; - } - } - else { - throw new exception(__METHOD__ .": invalid configuration file (". $configFileLocation .")"); - } - - if(strlen($section)) { - try { - $this->parse_config(); - $this->set_active_section($section); - $this->config = $this->get_section($section); - } - catch(exception $e) { - throw new exception(__METHOD__ .": invalid section (". $section ."), DETAILS::: ". $e->getMessage()); - } - } - else { - throw new exception(__METHOD__ .": no section given (". $section .")"); - } - - }//end __construct() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Sets the active section. - * - * @param $section (str) section to be set as active. - * - * @return VOID (PASS) section was set successfully. - * @return exception (FAIL) problem encountred setting section. - */ - public function set_active_section($section) { - if($this->isInitialized === true) { - $section = strtoupper($section); - if(in_array($section, $this->configSections)) { - $this->activeSection = $section; - } - else { - throw new exception(__METHOD__ .": invalid section (". $section .")"); - } - } - else { - throw new exception(__METHOD__ .": not initialized"); - } - }//end set_active_section($section) - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Parse the configuration file. Handles replacing {VARIABLES} in values, - * sets items as global or as constants, and creates array indicating the - * available sections from the config file. - * - * @param VOID (void) no arguments accepted. - * - * @return NULL (PASS) successfully parsed configuration - * @return exception (FAIL) exception indicates problem encountered. - */ - private function parse_config() { - if(is_object($this->xmlReader)) { - $data = $this->xmlReader->get_path($this->xmlReader->get_root_element()); - $specialVars = $this->build_special_vars(); - $parseThis = array(); - - - $this->configSections = array(); - - foreach($data as $section=>$secData) { - //only handle UPPERCASE index names; lowercase indexes are special entries (i.e. "type" or "attributes" - if($section == strtoupper($section)) { - $this->configSections[] = $section; - - unset($secData['type']); - - if(isset($secData['attributes']) && is_array($secData['attributes'])) { - $sectionAttribs = $secData['attributes']; - unset($secData['attributes']); - - //put stuff into the globals scope... - if(isset($sectionAttribs['SETGLOBAL'])) { - $path = $section; - - $setPath = $path; - if(strlen($sectionAttribs['GLOBALARRAYLOCATION'])) { - $setPath = $sectionAttribs['GLOBALARRAYLOCATION']; - } - $this->setGlobalArrays[$path] = $setPath; - } - } - - foreach($secData as $itemName=>$itemValue) { - $attribs = array(); - if(isset($itemValue['attributes']) && is_array($itemValue['attributes'])) { - $attribs = $itemValue['attributes']; - } - if(isset($itemValue['value'])) { - $itemValue = $itemValue['value']; - } - else { - $itemValue = null; - } - if(preg_match("/{/", $itemValue)) { - $origVal = $itemValue; - - //remove double-slashes (//) - $itemValue = preg_replace('/[\/]{2,}/', '\/', $itemValue); - - //remove leading slash for string replaces (i.e. "{/MAIN/SITE_ROOT}" becomes "{MAIN/SITE_ROOT}") - $itemValue = preg_replace('/{\//', '{', $itemValue); - - //replace special vars. - $itemValue = $this->gfObj->mini_parser($itemValue, $specialVars, '{', '}'); - - //replace internal vars. - $itemValue = $this->gfObj->mini_parser($itemValue, $parseThis, '{', '}'); - } - - if(isset($attribs['CLEANPATH'])) { - $itemValue = $this->fs->resolve_path_with_dots($itemValue); - } - - $parseThis[$itemName] = $itemValue; - $parseThis[$section ."/". $itemName] = $itemValue; - $data[$section][$itemName]['value'] = $itemValue; - - $setVarIndex = $this->setVarPrefix . $itemName; - if(isset($attribs['SETGLOBAL'])) { - $GLOBALS[$setVarIndex] = $itemValue; - } - if(isset($attribs['SETCONSTANT'])) { - if(isset($attribs['SETCONSTANTPREFIX'])) { - //did they give a specific prefix, or just a number/true? - if(strlen($attribs['SETCONSTANTPREFIX']) == 1) { - $setVarIndex = $section ."-". $setVarIndex; - } - else { - //use the prefix they gave. - $setVarIndex = $attribs['SETCONSTANTPREFIX'] ."-". $setVarIndex; - } - } - if(!defined($setVarIndex)) { - define($setVarIndex, $itemValue); - } - } - } - } - } - - $this->a2p = new cs_arrayToPath($data); - $this->isInitialized=true; - - if(count($this->setGlobalArrays)) { - $globA2p = new cs_arrayToPath(&$GLOBALS); - foreach($this->setGlobalArrays as $configPath=>$globalsPath) { - if($this->a2p->get_data($configPath)) { - $setMe = array(); - foreach($this->a2p->get_data($configPath) as $i=>$v) { - $setMe[$i] = $v['value']; - } - $globA2p->set_data($globalsPath, $setMe); - } - else { - throw new exception(__METHOD__ .": attempted to set global array from non-existent path (". $configPath .")"); - } - } - } - } - else { - throw new exception(__METHOD__ .": xmlReader not created, object probably not initialized"); - } - }//end parse_config() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Retrieve all data about the given section. - * - * @param $section (str) section to retrieve. - * - * @return array (PASS) array contains section data. - * @return exception (FAIL) exception indicates problem. - */ - public function get_section($section) { - if($this->isInitialized === true) { - $section = strtoupper($section); - $data = $this->a2p->get_data($section); - - if(is_array($data) && count($data) && $data['type'] == 'open') { - unset($data['type']); - $retval = $data; - } - else { - throw new exception(__METHOD__ .": invalid section (". $section .") or no data (". $data['type'] .")"); - } - } - else { - throw new exception(__METHOD__ .": not initialized"); - } - - return($retval); - }//end get_section() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Retrieves value from the active section, or from another (other sections - * specified like "SECTION/INDEX"). - * - * @param $index (str) index name of value to retrieve. - * - * @return mixed (PASS) returns value of given index. - * - * NOTE::: this will return NULL if the given index or section/index does - * not exist. - */ - public function get_value($index) { - if($this->isInitialized === true) { - if(preg_match("/\//", $index)) { - //section NOT given, assume they're looking for something in the active section. - $index = $this->activeSection ."/". $index; - } - $retval = $this->a2p->get_data($index .'/value'); - } - else { - throw new exception(__METHOD__ .": not initialized"); - } - return($retval); - }//end get_value() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - /** - * Retrieves list of valid configuration sections, as defined by - * parse_config(). - * - * @param VOID (void) no parameters accepted. - * - * @return array (PASS) array holds list of valid sections. - * @return exception (FAIL) exception gives error. - */ - public function get_valid_sections() { - if($this->isInitialized === true) { - if(is_array($this->configSections) && count($this->configSections)) { - $retval = $this->configSections; - } - else { - throw new exception(__METHOD__ .": no sections defined, probably invalid configuration"); - } - } - else { - throw new exception(__METHOD__ .": not initialized"); - } - - return($retval); - }//end get_valid_sections() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - private function build_special_vars() { - //determine the current "APPURL" (current URL minus hostname and current filename) - { - $appUrl = $_SERVER['SCRIPT_NAME']; - $bits = explode('/', $appUrl); - if(!strlen($bits[0])) { - array_shift($bits); - } - if(count($bits)) { - array_pop($bits); - } - if(!count($bits)) { - $appUrl = '/'; - } - else { - $appUrl = '/'. $this->gfObj->string_from_array($bits, null, '/'); - } - } - - $specialVars = array( - '_DIRNAMEOFFILE_' => $this->configDirname, - '_CONFIGFILE_' => $this->configFile, - '_THISFILE_' => $this->configFile, - '_APPURL_' => $appUrl - ); - return($specialVars); - }//end build_special_vars() - //------------------------------------------------------------------------- - -}//end cs_siteConfig - -?> Deleted: trunk/1.0/cs_tabs.class.php =================================================================== --- trunk/1.0/cs_tabs.class.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/cs_tabs.class.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,175 +0,0 @@ -<?php -/* - * Created on Jan 9, 2007 - * - */ - -require_once(dirname(__FILE__) .'/abstract/cs_content.abstract.class.php'); - - -class cs_tabs extends cs_contentAbstract { - private $tabsArr=array(); - private $selectedTab; - - private $templateVar; - private $gfObj; - - /** This is the default suffix to use when none is given during the add_tab() call. */ - private $defaultSuffix='tab'; - - //--------------------------------------------------------------------------------------------- - /** - * Build the object, and parses the given template. Tabs must be added & selected manually. - * - * @param $csPageObj (object) Instance of the class "cs_genericPage". - * @param $templateVar (str,optional) What template var to find the tab blockrows in. - */ - public function __construct($templateVar="tabs") { - parent::__construct(false); - - if(is_object($templateVar)) { - //trying to pass cs_genericPage{}... tell 'em we don't like that anymore. - throw new exception(__METHOD__ .": got an object (". get_class($templateVar) .") instead of template var name"); - } - elseif(is_string($templateVar) && is_null($templateVar) || strlen($templateVar) < 3) { - //no template name? AHH!!! - throw new exception("cs_tabs::__construct(): failed to specify proper template file"); - } - else { - //set the internal var. - $this->templateVar = $templateVar; - } - - $this->gfObj = new cs_globalFunctions; - }//end __construct() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- - public function add_tab_array(array $tabs, $useSuffix=null) { - $retval = 0; - foreach($tabs as $name=>$url) { - //call an internal method to do it. - $retval += $this->add_tab($name, $url, $useSuffix); - } - - return($retval); - }//end add_tab_array() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- - /** - * Sets the given tab as selected, provided it exists. - * - * @param $tabName (str) Sets this tab as selected. - * @return (void) - */ - public function select_tab($tabName) { - $this->selectedTab = $tabName; - }//end select_tab() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- - public function add_tab($tabName, $url, $useSuffix=null) { - - //set the default suffix. - if(is_null($useSuffix)) { - $useSuffix = $this->defaultSuffix; - } - - //add it to an array. - $this->tabsArr[$tabName] = array( - 'url' => $url, - 'suffix' => $useSuffix - ); - }//end add_tab() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- - /** - * Call this to add the parsed tabs into the page. - */ - public function display_tabs(array $blockRows) { - - if(!strlen($this->selectedTab)) { - $keys = array_keys($this->tabsArr); - $this->select_tab($keys[0]); - } - - if(is_array($this->tabsArr) && count($this->tabsArr)) { - $finalString = ""; - //loop through the array. - foreach($this->tabsArr as $tabName=>$tabData) { - - $url = $tabData['url']; - $suffix = $tabData['suffix']; - - $blockRowName = 'unselected_'. $suffix; - if(strtolower($tabName) == strtolower($this->selectedTab)) { - $blockRowName = 'selected_'. $suffix; - } - - if(isset($blockRows[$blockRowName])) { - $useTabContent = $blockRows[$blockRowName]; - } - else { - throw new exception(__METHOD__ ."(): failed to load block row " . - "(". $blockRowName .") for tab (". $tabName .")". - $this->gfObj->debug_print($blockRows,0)); - } - - $parseThis = array( - 'title' => $tabName, - 'url' => $url, - 'cleanTitle' => preg_replace('/[^a-zA-Z0-9]/', '_', $tabName) - ); - $finalString .= $this->gfObj->mini_parser($useTabContent, $parseThis, '%%', '%%'); - } - } - else { - //something bombed. - throw new exception(__METHOD__ ."(): no tabs to add"); - } - - return($finalString); - }//end display_tabs() - //--------------------------------------------------------------------------------------------- - - - //--------------------------------------------------------------------------------------------- - /** - * Determine if the given named tab exists (returns boolean true/false) - */ - public function tab_exists($tabName) { - $retval = false; - if(isset($this->tabsArr[$tabName])) { - $retval = true; - } - return($retval); - }//end tab_exists() - //--------------------------------------------------------------------------------------------- - - - - //--------------------------------------------------------------------------------------------- - public function rename_tab($tabName, $newTabName) { - if($this->tab_exists($tabName) && !$this->tab_exists($newTabName)) { - $tabContents = $this->tabsArr[$tabName]; - unset($this->tabsArr[$tabName]); - $this->tabsArr[$newTabName] = $tabContents; - } - else { - throw new exception(__METHOD__ .": tried to rename non-existent tab (". $tabName .") to (". $newTabName .")"); - } - }//end rename_tab(); - //--------------------------------------------------------------------------------------------- - -} -?> Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/tests/testOfCSContent.php 2009-08-20 20:34:59 UTC (rev 453) @@ -20,7 +20,7 @@ //------------------------------------------------------------------------- function __construct() { require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); - require_once(dirname(__FILE__) .'/../cs_siteConfig.class.php'); + require_once(constant('LIBDIR') .'/cs-webapplibs/cs_siteConfig.class.php'); $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; Modified: trunk/1.0/tests/testOfCSGlobalFunctions.php =================================================================== --- trunk/1.0/tests/testOfCSGlobalFunctions.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/tests/testOfCSGlobalFunctions.php 2009-08-20 20:34:59 UTC (rev 453) @@ -20,7 +20,6 @@ //------------------------------------------------------------------------- function __construct() { require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); - require_once(dirname(__FILE__) .'/../cs_siteConfig.class.php'); $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; Deleted: trunk/1.0/tests/testOfCSPHPDB.php =================================================================== --- trunk/1.0/tests/testOfCSPHPDB.php 2009-08-20 16:32:56 UTC (rev 452) +++ trunk/1.0/tests/testOfCSPHPDB.php 2009-08-20 20:34:59 UTC (rev 453) @@ -1,158 +0,0 @@ -<?php -/* - * Created on Jun 12, 2009 - */ - - -require_once(dirname(__FILE__) .'/../cs_phpDB.class.php'); - -class TestOfCSPHPDB extends UnitTestCase { - - private $dbParams=array(); - private $dbObjs = array(); - - - //------------------------------------------------------------------------- - public function __construct() { - $this->gfObj = new cs_globalFunctions; - - }//end __construct() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function setUp() { - $this->skipUnless($this->check_requirements(), "Skipping database tests, not configured"); - } - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - private function check_requirements() { - $retval=false; - - $globalPrefix = 'UNITTEST__'; - - $requirements = array( - 'host' => 'DB_HOST', - 'user' => 'DB_USER', - 'password' => 'DB_PASS', - 'dbname' => 'DB_NAME' - ); - - $dbTypes = array( - 'mysql' => "MY_", - 'pgsql' => "PG_"); - - foreach($dbTypes as $type=>$prefix) { - foreach($requirements as $index => $name) { - $myIndex = $globalPrefix . $prefix . $name; - $this->dbParams[$type][$index] = constant($myIndex); - } - } - - - - $validDbs = 0; - foreach($this->dbParams as $dbType=>$data) { - if(count($data) >= 4) { - $validDbs++; - } - else { - $this->gfObj->debug_print(__METHOD__ .": dropping ". $dbType .": not enough params (". count($data) .")"); - unset($this->dbParams[$dbType]); - } - } - - if($dbTypes >= 1) { - $retval = true; - } - - return($retval); - }//end check_requirements() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - private function internal_connect_db($connect=true) { - $this->dbObjs['pgsql'] = new cs_phpDB('pgsql'); - $this->dbObjs['mysql'] = new cs_phpDB('mysql'); - - if($connect) { - $this->dbObjs['pgsql']->connect($this->dbParams['pgsql']); - $this->dbObjs['mysql']->connect($this->dbParams['mysql']); - } - - }//end internal_connect_db() - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - private function handle_sql($dbType, $sql) { - if(strlen($dbType) && isset($this->dbObjs[$dbType])) { - $this->dbObjs[$dbType]->exec($sql); - - - $numrows = $this->dbObjs[$dbType]->numRows(); - if(!$numrows) { - $numrows = $this->dbObjs[$dbType]->numAffected(); - } - $dberror = $this->dbObjs[$dbType]->errorMsg(); - - if(strlen($dberror) || !is_numeric($numrows) || $numrows < 0) { - $retval = false; - } - else { - $retval = $numrows; - } - } - else { - $this->gfObj->debug_print($this); - throw new exception(__METHOD__ .": invalid dbType (". $dbType .")"); - } - - return($retval); - - }//end handle_sql(); - //------------------------------------------------------------------------- - - - - //------------------------------------------------------------------------- - public function test_transactions() { - $this->assertTrue(true); - $this->skipUnless($this->check_requirements(), "Skipping transaction tests (not configured: ". $this->check_requirements() .")"); - - $this->internal_connect_db(); - // - $beginTransRes = $this->dbObjs['pgsql']->beginTrans(); - $transactionStatus = $this->dbObjs['pgsql']->get_transaction_status(); - $beginTransRes = true; - if($this->assertTrue($beginTransRes, "Start of transaction failed (". $beginTransRes .")")) { - - $createRes = $this->handle_sql('pgsql', 'CREATE TABLE test (id serial not null, data text not null);'); - $this->assertTrue($createRes, "failed to create table (". $createRes .") -- affected: (". $this->dbObjs['pgsql']->numAffected() .")"); - - $data = array( - 'test1', 'test2' - ); - $i=1; - foreach($data as $val) { - #$this->assertTrue($this->handle_sql('pgsql', "INSERT INTO test (data) VALUES ('". $val ."')")); - #$this->assertEqual($i, $this->dbObjs['pgsql']->lastID()); - } - - $this->assertTrue($this->handle_sql('pgsql', 'ROLLBACK')); - } - else { - } - }//end test_transactions() - //------------------------------------------------------------------------- - - -} -?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-08-28 20:21:33
|
Revision: 455 http://cs-content.svn.sourceforge.net/cs-content/?rev=455&view=rev Author: crazedsanity Date: 2009-08-28 20:21:25 +0000 (Fri, 28 Aug 2009) Log Message: ----------- Script that has __autoload(), drop nearly all require_once() statements. NOTE::: this should fix issues with not having the correct libraries loaded all the time. /__autoload.php [NEW]: * contains the magic PHP "__autoload()" function, to automatically require the proper files for classes if they are not already available. /sample_files/public_html/content: * updated to require the __autoload.php file and nothing else. REMOVED require_once() STATEMENTS FROM::: * /contentSystem.class.php * /cs_fileSystem.class.php * /cs_genericPage.class.php * /cs_globalFunctions.class.php * /cs_session.class.php * /abstract/cs_content.abstract.class.php * /tests/testOfCSContent.php * /tests/testOfCSFileSystem.php * /tests/testOfCSGlobalFunctions.php * /tests/testOfCSVersionAbstract.php Modified Paths: -------------- trunk/1.0/abstract/cs_content.abstract.class.php trunk/1.0/contentSystem.class.php trunk/1.0/cs_fileSystem.class.php trunk/1.0/cs_genericPage.class.php trunk/1.0/cs_globalFunctions.class.php trunk/1.0/cs_session.class.php trunk/1.0/sample_files/public_html/content trunk/1.0/tests/testOfCSContent.php trunk/1.0/tests/testOfCSFileSystem.php trunk/1.0/tests/testOfCSGlobalFunctions.php trunk/1.0/tests/testOfCSVersionAbstract.php Added Paths: ----------- trunk/1.0/__autoload.php Added: trunk/1.0/__autoload.php =================================================================== --- trunk/1.0/__autoload.php (rev 0) +++ trunk/1.0/__autoload.php 2009-08-28 20:21:25 UTC (rev 455) @@ -0,0 +1,92 @@ +<?php +/* + * Created on Aug 28, 2009 + * + * SVN INFORMATION::: + * ------------------- + * Last Author::::::::: $Author$ + * Current Revision:::: $Revision$ + * Repository Location: $HeadURL$ + * Last Updated:::::::: $Date$ + */ + +//these libraries are **REQUIRED** to make __autoload() function without chicken-or-the-egg issues. +require_once(dirname(__FILE__) .'/abstract/cs_version.abstract.class.php'); +require_once(dirname(__FILE__) .'/abstract/cs_content.abstract.class.php'); +require_once(dirname(__FILE__) .'/cs_fileSystem.class.php'); +require_once(dirname(__FILE__) .'/cs_globalFunctions.class.php'); + + + + +function __autoload($class) { + + if(is_array($GLOBALS['__autoload__libDefs']) && isset($GLOBALS['__autoload__libDefs'][$class])) { + require_once($GLOBALS['__autoload__libDefs'][$class]); + } + else { + + $tried = array(); + + $fsRoot = dirname(__FILE__) .'/../../'; + if(defined('LIBDIR')) { + $fsRoot = constant('LIBDIR'); + } + $fs = new cs_fileSystem($fsRoot); + + //try going into a "lib" directory. + $fs->cd('lib'); + $lsData = $fs->ls(); + + //attempt to find it here... + $tryThis = array(); + if(preg_match('/[aA]bstract/', $class)) { + $myClass = preg_replace('/[aA]bstract/', '', $class); + $tryThis[] = $class .'.abstract.class.php'; + $tryThis[] = $myClass .'.abstract.class.php'; + $tryThis[] = 'abstract/'. $myClass .'.abstract.class.php'; + } + $tryThis[] = $class .'.class.php'; + $tryThis[] = $class .'.php'; + + $found=false; + foreach($tryThis as $filename) { + if(isset($lsData[$filename])) { + $tried[] = $fs->realcwd .'/'. $filename; + require_once($fs->realcwd .'/'. $filename); + $found=true; + break; + } + } + + if(!$found) { + //try going into sub-directories to pull the files. + foreach($lsData as $i=>$d) { + if($d['type'] == 'dir') { + $subLs = $fs->ls($i); + foreach($tryThis as $filename) { + $fileLocation = $fs->realcwd .'/'. $i .'/'. $filename; + if(file_exists($fileLocation)) { + $tried[] = $fileLocation; + require_once($fileLocation); + $found=true; + break; + } + } + } + if($found) { + break; + } + } + } + } + + if(!$found) { + $gf = new cs_globalFunctions; + $gf->debug_print(__FILE__ ." - line#". __LINE__ ."::: couldn't find (". $class .")",1); + $gf->debug_print($tried,1); + $gf->debug_print($tryThis,1); + exit; + } +}//end __autoload() +?> Property changes on: trunk/1.0/__autoload.php ___________________________________________________________________ Added: svn:keywords + Id Author Revision HeadURL Date Modified: trunk/1.0/abstract/cs_content.abstract.class.php =================================================================== --- trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/abstract/cs_content.abstract.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -11,7 +11,6 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/cs_version.abstract.class.php"); abstract class cs_contentAbstract extends cs_versionAbstract { @@ -24,7 +23,6 @@ if($makeGfObj === true) { //make a cs_globalFunctions{} object. - require_once(dirname(__FILE__) ."/../cs_globalFunctions.class.php"); $this->gfObj = new cs_globalFunctions(); } }//end __construct() Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/contentSystem.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -63,10 +63,6 @@ * |--> /includes/content/members/test.inc */ -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); -require_once(dirname(__FILE__) ."/cs_fileSystem.class.php"); -require_once(dirname(__FILE__) ."/cs_session.class.php"); -require_once(dirname(__FILE__) ."/cs_genericPage.class.php"); class contentSystem extends cs_contentAbstract { @@ -130,7 +126,6 @@ //create a session that gets stored in a database if they so desire... if(defined('SESSION_DBSAVE')) { - require_once(constant('LIBDIR') .'/cs-webapplibs/cs_sessionDB.class.php'); $obj = new cs_sessionDB(); $this->handle_session($obj); } Modified: trunk/1.0/cs_fileSystem.class.php =================================================================== --- trunk/1.0/cs_fileSystem.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/cs_fileSystem.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -9,8 +9,6 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); - class cs_fileSystem extends cs_contentAbstract { public $root; //actual root directory. Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/cs_genericPage.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -8,7 +8,6 @@ * $LastChangedRevision$ */ require_once(dirname(__FILE__) ."/required/template.inc"); -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); class cs_genericPage extends cs_contentAbstract { public $templateObj; //template object to parse the pages Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/cs_globalFunctions.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -1,6 +1,5 @@ <?php -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); class cs_globalFunctions extends cs_versionAbstract { Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/cs_session.class.php 2009-08-28 20:21:25 UTC (rev 455) @@ -8,8 +8,6 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/abstract/cs_content.abstract.class.php"); - class cs_session extends cs_contentAbstract { protected $uid; Modified: trunk/1.0/sample_files/public_html/content =================================================================== --- trunk/1.0/sample_files/public_html/content 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/sample_files/public_html/content 2009-08-28 20:21:25 UTC (rev 455) @@ -1,10 +1,15 @@ <?php -require_once("../lib/cs-content/contentSystem.class.php"); +//load script that has the magic "__autoload()" function, to automatically load libraries if not included/required. +require_once(dirname(__FILE__) .'/../lib/cs-content/__autoload.php'); -//conditionally include files pointing to it... +$siteConfig = new cs_siteConfig(dirname(__FILE__) .'/../rw/siteConfig.xml', 'website'); + +require_once(dirname(__FILE__) .'/../lib/cs-content/contentSystem.class.php'); +require_once(dirname(__FILE__) .'/../lib/website.class.php'); + $contentObj = new contentSystem(); +$contentObj->inject_var('websiteObj', new website()); $contentObj->finish(); - ?> Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/tests/testOfCSContent.php 2009-08-28 20:21:25 UTC (rev 455) @@ -19,8 +19,6 @@ //------------------------------------------------------------------------- function __construct() { - require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); - require_once(constant('LIBDIR') .'/cs-webapplibs/cs_siteConfig.class.php'); $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; Modified: trunk/1.0/tests/testOfCSFileSystem.php =================================================================== --- trunk/1.0/tests/testOfCSFileSystem.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/tests/testOfCSFileSystem.php 2009-08-28 20:21:25 UTC (rev 455) @@ -19,9 +19,6 @@ //------------------------------------------------------------------------- function __construct() { - require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); - require_once(dirname(__FILE__) .'/../cs_fileSystem.class.php'); - $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; Modified: trunk/1.0/tests/testOfCSGlobalFunctions.php =================================================================== --- trunk/1.0/tests/testOfCSGlobalFunctions.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/tests/testOfCSGlobalFunctions.php 2009-08-28 20:21:25 UTC (rev 455) @@ -19,8 +19,6 @@ //------------------------------------------------------------------------- function __construct() { - require_once(dirname(__FILE__) .'/../cs_globalFunctions.class.php'); - $this->gfObj = new cs_globalFunctions; $this->gfObj->debugPrintOpt=1; Modified: trunk/1.0/tests/testOfCSVersionAbstract.php =================================================================== --- trunk/1.0/tests/testOfCSVersionAbstract.php 2009-08-24 16:52:54 UTC (rev 454) +++ trunk/1.0/tests/testOfCSVersionAbstract.php 2009-08-28 20:21:25 UTC (rev 455) @@ -11,7 +11,6 @@ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) .'/../abstract/cs_version.abstract.class.php'); class testOfCSVersionAbstract extends UnitTestCase { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-09-15 20:28:26
|
Revision: 459 http://cs-content.svn.sourceforge.net/cs-content/?rev=459&view=rev Author: crazedsanity Date: 2009-09-15 20:28:18 +0000 (Tue, 15 Sep 2009) Log Message: ----------- Fix issue #301 + #237. /cs_genericPage.class.php: * MAIN::: -- remove dependency on template.inc (#237) -- remove templateObj var * initialize_locals(): -- don't allow dirname if it equals "." -- fix path using cs_fileSystem::resolve_path_with_dots() so there are no "../" things in the path (for unit testing) -- don't create instance of Template{}. * print_page(): -- do ALL parsing of template vars internally instead of using methods from Template (i.e. Template::parse() and Template::pparse()). -- if the template var "main" is set, use that instead of pulling the contents of the mainTemplate (maintains old functionality). -- prints output directly. * file_to_string(): -- explodes the filename on "templates" so there's no redundant adding of the templates directory... (There are probably situations where this logic is broken, i.e. if there is "templates/../templates" in the filename) -- use the path given by template_file_exists() as the path to the file. -- NOTE::: if the file can't be loaded, it should really throw an exception instead of calling set_message_wrapper(), since that would break if the file that couldn't be loaded was the main template or the message template. * template_file_exists(): -- returns boolean false instead of numeric 0 by default. /required/ [DELETED] * removed unneeded folder (and "template.inc" from PHPLib). /tests/testOfCSContent.php: * test_genericPage(): -- add tests on template_file_exists() and file_to_string(). -- drop bogus check on templateObj->varvals['out'], since Template{} is no longer being used. -- added notes about where things fail on r455 (or less) of cs_genericPage. -- use full path to the main template. -- lots of tests with block rows to ensure issue #237 is fixed. /tests/files/(et all) -- tests with blockrows embedded within other blockrows with unused template vars sprinkled around. -- added the required "system" folder with the 404 and message_box templates. Modified Paths: -------------- trunk/1.0/cs_genericPage.class.php trunk/1.0/tests/files/gptest_all-together.txt trunk/1.0/tests/files/templates/content.shared.tmpl trunk/1.0/tests/testOfCSContent.php Added Paths: ----------- trunk/1.0/tests/files/gptest_blockrows.txt trunk/1.0/tests/files/gptest_blockrows2.txt trunk/1.0/tests/files/templates/system/ trunk/1.0/tests/files/templates/system/404.shared.tmpl trunk/1.0/tests/files/templates/system/message_box.tmpl Removed Paths: ------------- trunk/1.0/required/ Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2009-09-14 15:21:16 UTC (rev 458) +++ trunk/1.0/cs_genericPage.class.php 2009-09-15 20:28:18 UTC (rev 459) @@ -7,10 +7,8 @@ * $LastChangedBy$ * $LastChangedRevision$ */ -require_once(dirname(__FILE__) ."/required/template.inc"); class cs_genericPage extends cs_contentAbstract { - public $templateObj; //template object to parse the pages public $templateVars = array(); //our copy of the global templateVars public $templateFiles = array(); //our list of template files... public $templateRows = array(); //array of block rows & their contents. @@ -63,7 +61,7 @@ $mainTemplateFile = preg_replace('/^\//', '', $mainTemplateFile); } - if(isset($mainTemplateFile) && strlen($mainTemplateFile) && is_dir(dirname($mainTemplateFile))) { + if(isset($mainTemplateFile) && strlen($mainTemplateFile) && is_dir(dirname($mainTemplateFile)) && dirname($mainTemplateFile) != '.') { $this->siteRoot = dirname($mainTemplateFile); if(preg_match('/\//', $this->siteRoot) && preg_match('/templates/', $this->siteRoot)) { $this->siteRoot .= "/.."; @@ -78,6 +76,8 @@ else { throw new exception(__METHOD__ .": cannot locate siteRoot from main template file (". $mainTemplateFile .")"); } + $fs = new cs_fileSystem(dirname(__FILE__)); + $this->siteRoot = $fs->resolve_path_with_dots($this->siteRoot); $this->tmplDir = $this->siteRoot .'/templates'; $this->libDir = $this->siteRoot .'/lib'; @@ -97,9 +97,6 @@ } } unset($GLOBALS['templateVars'], $GLOBALS['templateFiles']); - - //build a new instance of the template library (from PHPLib) - $this->templateObj=new Template($this->tmplDir,"keep"); //initialize a new template parser if(!preg_match('/^\//', $mainTemplateFile)) { $mainTemplateFile = $this->tmplDir ."/". $mainTemplateFile; @@ -270,21 +267,33 @@ //Show any available messages. $this->process_set_message(); - //Load the default page layout. - $this->templateObj->set_file("main", $this->mainTemplate); - - //load the placeholder names and thier values - $this->templateObj->set_var($this->templateVars); - $this->templateObj->parse("out","main"); //parse the sub-files into the main page + if(isset($this->templateVars['main'])) { + //this is done to simulate old behaviour (the "main" templateVar could overwrite the entire main template). + $out = $this->templateVars['main']; + } + else { + $out = $this->file_to_string($this->mainTemplate); + } + if(!strlen($out)) { + $this->gfObj->debug_print($out); + $this->gfObj->debug_print($this->mainTemplate); + $this->gfObj->debug_print("MANUAL FILE CONTENTS::: ". htmlentities(file_get_contents($this->tmplDir .'/'. $this->mainTemplate))); + exit(__METHOD__ .": mainTemplate (". $this->mainTemplate .") was empty...?"); + } + $numLoops = 0; + $tags = array(); + while(preg_match_all('/\{.\S+?\}/', $out, $tags) && $numLoops < 10) { + $out = $this->gfObj->mini_parser($out, $this->templateVars, '{', '}'); + $numLoops++; + } + if($stripUndefVars) { - $this->templateObj->varvals['out'] = $this->strip_undef_template_vars( - $this->templateObj->varvals['out'], - $this->unhandledVars - ); + $out = $this->strip_undef_template_vars($out, $this->unhandledVars); } - $this->templateObj->pparse("out","out"); //parse the main page + print($out); + }//end of print_page() //--------------------------------------------------------------------------------------------- @@ -330,9 +339,20 @@ * content & returns it. */ public function file_to_string($templateFileName) { + + if(preg_match('/templates/', $templateFileName)) { + $bits = explode('templates', $templateFileName); + if(count($bits) == 2) { + $templateFileName = $bits[1]; + } + else { + throw new exception(__METHOD__ .": full path to template file given but could not break the path into bits::: ". $templateFileName); + } + } $templateFileName = preg_replace('/\/\//', '\/', $templateFileName); - if($this->template_file_exists($templateFileName)) { - $retval = file_get_contents($this->tmplDir .'/'. $templateFileName); + $fullPathToFile = $this->template_file_exists($templateFileName); + if($fullPathToFile !== false && strlen($fullPathToFile)) { + $retval = file_get_contents($fullPathToFile); } else { $this->set_message_wrapper(array( "title" => 'Template File Error', @@ -351,7 +371,7 @@ * Checks to see if the given filename exists within the template directory. */ public function template_file_exists($file) { - $retval = 0; + $retval = false; //If the string doesn't start with a /, add one if (strncmp("/",$file,1)) { //strncmp returns 0 if they match, so we're putting a / on if they don't Modified: trunk/1.0/tests/files/gptest_all-together.txt =================================================================== --- trunk/1.0/tests/files/gptest_all-together.txt 2009-09-14 15:21:16 UTC (rev 458) +++ trunk/1.0/tests/files/gptest_all-together.txt 2009-09-15 20:28:18 UTC (rev 459) @@ -13,6 +13,10 @@ <!-- END blockRow3 --> <!-- BEGIN blockRow4 --><!-- END blockRow4 --> + + <!-- BEGIN blockRow5 --><!-- BEGIN embeddedBlockRow1 --><!-- END embeddedBlockRow1 --> + <!-- BEGIN embeddedBlockRow2 --><!-- END embeddedBlockRow2 --> + <!-- END blockRow5 --> ---+++ CONTENT ENDS HERE +++--- --- the footer. </body> Copied: trunk/1.0/tests/files/gptest_blockrows.txt (from rev 458, trunk/1.0/tests/files/gptest_all-together.txt) =================================================================== --- trunk/1.0/tests/files/gptest_blockrows.txt (rev 0) +++ trunk/1.0/tests/files/gptest_blockrows.txt 2009-09-15 20:28:18 UTC (rev 459) @@ -0,0 +1,20 @@ +<html> + <head> + <title>This is the title.</title> + </head> +<body> + <table>This is the infobar.</table> + --- the menubar (DATE: ) +---+++ CONTENT STARTS HERE +++--- + + +<!-- BEGIN blockRow3 --> Some data In here... + <!-- END blockRow3 --> + + + + +---+++ CONTENT ENDS HERE +++--- + --- the footer. +</body> +</html> \ No newline at end of file Copied: trunk/1.0/tests/files/gptest_blockrows2.txt (from rev 458, trunk/1.0/tests/files/gptest_all-together.txt) =================================================================== --- trunk/1.0/tests/files/gptest_blockrows2.txt (rev 0) +++ trunk/1.0/tests/files/gptest_blockrows2.txt 2009-09-15 20:28:18 UTC (rev 459) @@ -0,0 +1,19 @@ +<html> + <head> + <title>This is the title.</title> + </head> +<body> + <table>This is the infobar.</table> + --- the menubar (DATE: ) +---+++ CONTENT STARTS HERE +++--- + + + + + + + +---+++ CONTENT ENDS HERE +++--- + --- the footer. +</body> +</html> \ No newline at end of file Modified: trunk/1.0/tests/files/templates/content.shared.tmpl =================================================================== --- trunk/1.0/tests/files/templates/content.shared.tmpl 2009-09-14 15:21:16 UTC (rev 458) +++ trunk/1.0/tests/files/templates/content.shared.tmpl 2009-09-15 20:28:18 UTC (rev 459) @@ -6,3 +6,7 @@ <!-- END blockRow3 --> <!-- BEGIN blockRow4 -->{anotherInvisibleVar}<!-- END blockRow4 -->{invisibleTemplateVar} + + <!-- BEGIN blockRow5 -->{anotherInvisibleVar}<!-- BEGIN embeddedBlockRow1 -->{testEmbedded}<!-- END embeddedBlockRow1 --> + <!-- BEGIN embeddedBlockRow2 -->{testEmbedded2}<!-- END embeddedBlockRow2 --> + <!-- END blockRow5 --> Copied: trunk/1.0/tests/files/templates/system/404.shared.tmpl (from rev 458, trunk/1.0/sample_files/templates/system/404.shared.tmpl) =================================================================== --- trunk/1.0/tests/files/templates/system/404.shared.tmpl (rev 0) +++ trunk/1.0/tests/files/templates/system/404.shared.tmpl 2009-09-15 20:28:18 UTC (rev 459) @@ -0,0 +1,33 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" + "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<html xmlns="http://www.w3.org/1999/xhtml" lang="en_US" xml:lang="en_US"> +<!-- + * Created on Jun 3, 2007 + * +--> + <head> + <title>Page Not Found</title> + <link rel="stylesheet" href="{APPURL}/css/site.css" type="text/css"> + </head> + <body> + + <table border=0 cellpadding=0 cellspacing=0 width="90%" align="center"> +<TR> + <td align="center"><!-- This row should span across the page. --><hr>{datetime}<hr></td> +</TR> + + <tr> + + <td> + + + {content} + + + + </td> + </tr> +</table> + </body> +</html> Copied: trunk/1.0/tests/files/templates/system/message_box.tmpl (from rev 458, trunk/1.0/sample_files/templates/system/message_box.tmpl) =================================================================== --- trunk/1.0/tests/files/templates/system/message_box.tmpl (rev 0) +++ trunk/1.0/tests/files/templates/system/message_box.tmpl 2009-09-15 20:28:18 UTC (rev 459) @@ -0,0 +1,29 @@ +<!-- *** MESSAGE_BOX START (/system/message_box.tmpl) *** --> +<table border="0" cellspacing="0" cellpadding="0" align="center"> + <tr> + <td class="{messageType}" width="5" align="left" valign="top"><img src="{APPURL}/images/frame/crn-white-tl.gif" width="5" height="5" alt=""></td> + <td class="{messageType}"><img src="{APPURL}/images/clear.gif" width="20" height="2" alt=""></td> + <td class="{messageType}" width="5" align="right" valign="top"><img src="{APPURL}/images/frame/crn-white-tr.gif" width="5" height="5" alt=""></td> + </tr> + <tr> + <td class="{messageType}" width="5"><img src="{APPURL}/images/clear.gif" width="5" height="20" alt=""></td> + <td> + <table class="{messageType}" width="100%" border="0" cellspacing="0" cellpadding="5"> + <tr> + <td valign="top"> + <p style="border-style: solid; border-width: 0px 0px 2px 0px" class="title1">{title}</p> +<p style="margin: 5px 0px 5px 0px">{message}</p> + {redirect} </td> + </tr> + </table></td> + <td class="{messageType}" width="5"><img src="{APPURL}/images/clear.gif" width="5" height="20" alt=""></td> + </tr> + <tr> + <td class="{messageType}" width="5" align="left" valign="bottom"><img src="{APPURL}/images/frame/crn-white-bl.gif" width="5" height="5" alt=""></td> + <td class="{messageType}"><img src="{APPURL}/images/clear.gif" width="20" height="2" alt=""></td> + <td class="{messageType}" width="5" align="right" valign="bottom"><img src="{APPURL}/images/frame/crn-white-br.gif" width="5" height="5" alt=""></td> + </tr> + </table> +<br> +<!-- *** MESSAGE_BOX END (/system/message_box.tmpl) *** --> + Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-09-14 15:21:16 UTC (rev 458) +++ trunk/1.0/tests/testOfCSContent.php 2009-09-15 20:28:18 UTC (rev 459) @@ -102,8 +102,18 @@ function test_genericPage() { $filesDir = dirname(__FILE__) .'/files'; - $mainTemplate = $filesDir .'/templates/main.shared.tmpl'; - $page = new cs_genericPage(false, $mainTemplate); + $mainTemplateFullUrl = $filesDir .'/templates/main.shared.tmpl'; + $mainTemplate = 'main.shared.tmpl'; + + $page = new cs_genericPage(false, $mainTemplateFullUrl); + + //NOTE::: this test FAILS with cs_genericPage.class.php@455 (or any revision less than 455) + $this->assertEqual($mainTemplateFullUrl, $page->template_file_exists($mainTemplate)); + + $this->assertEqual($page->file_to_string($mainTemplate), file_get_contents($mainTemplateFullUrl)); + + + $fs = new cs_fileSystem($filesDir .'/templates'); $lsData = $fs->ls(); @@ -118,9 +128,7 @@ $checkThis = $page->return_printed_page(); - $this->assertEqual($checkThis, file_get_contents($filesDir .'/gptest_all-together.txt')); - $this->assertEqual($checkThis, $page->templateObj->varvals['out']); //now let's rip all the template rows out & add them back in. $rowDefs = $page->get_block_row_defs('content'); @@ -137,11 +145,10 @@ } $checkThis2 = $page->return_printed_page(); + //NOTE::: this test FAILS with cs_genericPage.class.php@455 (or any revision less than 455) $this->assertEqual($checkThis, $checkThis2); - $this->assertEqual($checkThis2, $page->templateObj->varvals['out']); $checkThis = $page->return_printed_page(0); - $this->assertTrue(preg_match('/\{.\S+?\}/', $page->templateObj->varvals['out'])); $this->assertTrue(preg_match('/\{.\S+?\}/', $checkThis)); //clone the page object so we can change stuff & not affect the original. @@ -169,9 +176,9 @@ } - //make sure stripping undefined vars works properly. + //make sure stripping undefined vars works properly (see issue #237) { - $page = new cs_genericPage(false, $mainTemplate); + $page = new cs_genericPage(false, $mainTemplateFullUrl); $this->assertEqual($fs->read($mainTemplate), $page->return_printed_page(0)); $this->assertNotEqual($fs->read($mainTemplate), $page->return_printed_page(1)); @@ -192,6 +199,49 @@ $this->gfObj->debug_print($page->unhandledVars); } } + + //Test if ripping out all the block rows works as intended (also related to issue #237) + { + $page = new cs_genericPage(false, $mainTemplateFullUrl); + $page->add_template_var('blockRowTestVal', 3); + + $fs = new cs_fileSystem($filesDir .'/templates'); + $lsData = $fs->ls(); + foreach($lsData as $index=>$value) { + $filenameBits = explode('.', $index); + $page->add_template_file($filenameBits[0], $index); + } + + $blockRows = $page->rip_all_block_rows('content'); + + //make sure printing the page multiple times doesn't change its output. + $this->assertEqual($page->return_printed_page(), $page->return_printed_page()); + $this->assertEqual($page->return_printed_page(), $page->return_printed_page()); + $this->assertEqual($page->return_printed_page(), $page->return_printed_page()); + + /* + * NOTE::: if this seems confusing, well... it is. Basically, the template var "{blockRowTestVal}" doesn't get + * parsed into the value of 3 until the call to print_page(), so therefore the block row "blockRow3" doesn't have + * a valid BEGIN statement until AFTER the page is built... ripping out that blockrow would have to be done after + * everything is all complete (i.e. by assigning the value of return_printed_page() to a template var) + */ + if(!$this->assertEqual(6, count($blockRows))) { + $this->gfObj->debug_print($blockRows); + } + + $this->assertEqual(file_get_contents($filesDir .'/gptest_blockrows.txt'), $page->return_printed_page()); + + $rasterizedData = $page->return_printed_page(); + $page->add_template_var('main', $page->return_printed_page()); + $this->assertEqual($rasterizedData, $page->return_printed_page()); + + $blockRows = $page->rip_all_block_rows('main'); + $this->assertEqual(1, count($blockRows)); + $this->assertTrue(isset($blockRows['blockRow3'])); + + $this->assertEqual(file_get_contents($filesDir .'/gptest_blockrows2.txt'), $page->return_printed_page()); + $this->assertNotEqual(file_get_contents($filesDir .'/gptest_blockrows2.txt'), file_get_contents($filesDir .'/gptest_blockrows.txt')); + } }//end test_genericPage //------------------------------------------------------------------------- This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-09-21 03:26:13
|
Revision: 461 http://cs-content.svn.sourceforge.net/cs-content/?rev=461&view=rev Author: crazedsanity Date: 2009-09-21 03:26:01 +0000 (Mon, 21 Sep 2009) Log Message: ----------- Minor updates to __autoload(), fixes for setting root path. /__autoload.php: * __autoload(): -- drop unused code where all libraries were linked to their respective file names through GLOBALS (never implemented). -- check if class exists after including a file before breaking. -- minor update to debug prints if it couldn't find the file. /contentSystem.class.php: * __construct(): -- drop section requiring the constant SITE_ROOT * initialize_locals(): -- when setting $root, remove "public_html" and "html" from the path. Modified Paths: -------------- trunk/1.0/__autoload.php trunk/1.0/contentSystem.class.php Modified: trunk/1.0/__autoload.php =================================================================== --- trunk/1.0/__autoload.php 2009-09-15 20:53:51 UTC (rev 460) +++ trunk/1.0/__autoload.php 2009-09-21 03:26:01 UTC (rev 461) @@ -21,11 +21,6 @@ function __autoload($class) { - if(is_array($GLOBALS['__autoload__libDefs']) && isset($GLOBALS['__autoload__libDefs'][$class])) { - require_once($GLOBALS['__autoload__libDefs'][$class]); - } - else { - $tried = array(); $fsRoot = dirname(__FILE__) .'/../../'; @@ -55,8 +50,10 @@ if(isset($lsData[$filename])) { $tried[] = $fs->realcwd .'/'. $filename; require_once($fs->realcwd .'/'. $filename); - $found=true; - break; + if(class_exists($class)) { + $found=true; + break; + } } } @@ -70,8 +67,10 @@ if(file_exists($fileLocation)) { $tried[] = $fileLocation; require_once($fileLocation); - $found=true; - break; + if(class_exists($class)) { + $found=true; + break; + } } } } @@ -80,11 +79,10 @@ } } } - } if(!$found) { $gf = new cs_globalFunctions; - $gf->debug_print(__FILE__ ." - line#". __LINE__ ."::: couldn't find (". $class .")",1); + $gf->debug_print(__FILE__ ." - line #". __LINE__ ."::: couldn't find (". $class .")",1); $gf->debug_print($tried,1); $gf->debug_print($tryThis,1); exit; Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-09-15 20:53:51 UTC (rev 460) +++ trunk/1.0/contentSystem.class.php 2009-09-21 03:26:01 UTC (rev 461) @@ -101,10 +101,6 @@ public function __construct($siteRoot=null) { parent::__construct(); - if(is_null($siteRoot) && !defined('SITE_ROOT')) { - throw new exception(__METHOD__ .": must set siteRoot or constant 'SITE_ROOT'"); - } - //setup the section stuff... $repArr = array($_SERVER['SCRIPT_NAME'], "/"); $_SERVER['REQUEST_URI'] = ereg_replace('^/', "", $_SERVER['REQUEST_URI']); @@ -133,7 +129,9 @@ //build the templating engine: this may cause an immediate redirect, if they need to be logged-in. //TODO: find a way to define this on a per-page basis. Possibly have templateObj->check_login() // run during the "finish" stage... probably using GenericPage{}->check_login(). - $root = $_SERVER['DOCUMENT_ROOT']; + $root = preg_replace('/\/public_html$/', '', $_SERVER['DOCUMENT_ROOT']); + $root = preg_replace('/\/html/', '', $root); + if(!is_null($siteRoot) && is_dir($siteRoot)) { $root = $siteRoot; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-10-21 16:31:01
|
Revision: 467 http://cs-content.svn.sourceforge.net/cs-content/?rev=467&view=rev Author: crazedsanity Date: 2009-10-21 16:30:53 +0000 (Wed, 21 Oct 2009) Log Message: ----------- Minor updates for unit testing. Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/tests/testOfCSContent.php Added Paths: ----------- trunk/1.0/tests/files/includes/ trunk/1.0/tests/files/includes/shared.inc Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2009-10-21 16:30:18 UTC (rev 466) +++ trunk/1.0/contentSystem.class.php 2009-10-21 16:30:53 UTC (rev 467) @@ -107,7 +107,8 @@ $_SERVER['REQUEST_URI'] = ereg_replace('^/', "", $_SERVER['REQUEST_URI']); //figure out the section & subsection stuff. - $this->fullSectionArr = split('/', $_SERVER['REQUEST_URI']); //TODO: will this cope with an APPURL being set? + $requestUri = preg_replace('/\/$/', '', $_SERVER['REQUEST_URI']); + $this->fullSectionArr = split('/', $requestUri); //TODO: will this cope with an APPURL being set? $this->section = $this->clean_url($_SERVER['REQUEST_URI']); $this->initialize_locals($siteRoot); @@ -772,6 +773,7 @@ foreach($badUrlVars as $badVarName) { unset($_GET[$badVarName], $_POST[$badVarName]); } + unset($badUrlVars, $badVarName); if(is_array($this->injectVars) && count($this->injectVars)) { $definedVars = get_defined_vars(); @@ -784,6 +786,7 @@ } } } + unset($definedVars, $myVarName, $myVarVal); if(isset($this->session) && is_object($this->session)) { $this->templateObj->session = $this->session; @@ -810,6 +813,7 @@ try { foreach($this->includesList as $myInternalIndex=>$myInternalScriptName) { $this->myLastInclude = $myInternalScriptName; + unset($myInternalScriptName, $myInternalIndex); include_once($this->myLastInclude); } @@ -817,6 +821,7 @@ if(is_array($this->afterIncludesList)) { foreach($this->afterIncludesList as $myInternalIndex=>$myInternalScriptName) { $this->myLastInclude = $myInternalScriptName; + unset($myInternalScriptName, $myInternalIndex); include_once($this->myLastInclude); } } Added: trunk/1.0/tests/files/includes/shared.inc =================================================================== --- trunk/1.0/tests/files/includes/shared.inc (rev 0) +++ trunk/1.0/tests/files/includes/shared.inc 2009-10-21 16:30:53 UTC (rev 467) @@ -0,0 +1,40 @@ +<?php +/* + * Created on Oct 21, 2009 + * + * SVN INFORMATION::: + * ------------------- + * Last Author::::::::: $Author$ + * Current Revision:::: $Revision$ + * Repository Location: $HeadURL$ + * Last Updated:::::::: $Date$ + */ + + +$page->gfObj->debugPrintOpt=1; +$page->allow_invalid_urls(true); +$page->printOnFinish=false; + +if(isset($testObj) && is_object($testObj) && get_class($testObj) == 'TestOfCSContent') { + + //start unit tests!!! + + $testObj->assertTrue(is_array($sectionArr)); + $testObj->assertTrue(is_array($fullSectionArr)); + if(!$testObj->assertEqual(count($sectionArr), count($fullSectionArr))) { + $testObj->assertEqual(false, true, $page->gfObj->debug_print($fullSectionArr)); + } + + foreach(get_defined_vars() as $n=>$v) { + $acceptableVars = array('testObj', 'page', 'sectionArr', 'fullSectionArr', 'finalURL', 'finalSection', 'this'); + $testObj->assertTrue(in_array($n, $acceptableVars), "local var '". $n ."' not allowed as a local var"); + unset($acceptableVars); + } + +} +else { + throw new exception(__FILE__ .": failed to locate unit test object (testObj) while running include script unit tests"); +} + + +?> Property changes on: trunk/1.0/tests/files/includes/shared.inc ___________________________________________________________________ Added: svn:keywords + Author Revision HeadURL Date Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-10-21 16:30:18 UTC (rev 466) +++ trunk/1.0/tests/testOfCSContent.php 2009-10-21 16:30:53 UTC (rev 467) @@ -247,6 +247,17 @@ + //------------------------------------------------------------------------- + public function test_contentSystem () { + + $content = new contentSystem(dirname(__FILE__) .'/files'); + $content->inject_var('testObj', $this); + $content->finish(); + }//end test_contentSystem() + //------------------------------------------------------------------------- + + + }//end TestOfCSContent //============================================================================= ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2009-11-11 01:06:26
|
Revision: 470 http://cs-content.svn.sourceforge.net/cs-content/?rev=470&view=rev Author: crazedsanity Date: 2009-11-11 01:06:10 +0000 (Wed, 11 Nov 2009) Log Message: ----------- Minor fixes for PHP warnings/notices. /cs_genericPage.class.php: * __get(): -- suppress notices/warnings about retrieving properties that don't exist. /cs_session.class.php: * __construct(): -- suppress notices/warnings if the session is already active. /tests/testOfCSContent.php: * __construct(): -- only define TEST_FILESDIR if it isn't already defined to avoid warnings/notices. Modified Paths: -------------- trunk/1.0/cs_genericPage.class.php trunk/1.0/cs_session.class.php trunk/1.0/tests/testOfCSContent.php Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2009-10-30 02:40:26 UTC (rev 469) +++ trunk/1.0/cs_genericPage.class.php 2009-11-11 01:06:10 UTC (rev 470) @@ -680,7 +680,7 @@ * Magic PHP method for retrieving the values of private/protected vars. */ public function __get($var) { - return($this->$var); + return(@$this->$var); }//end __get() //------------------------------------------------------------------------- Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2009-10-30 02:40:26 UTC (rev 469) +++ trunk/1.0/cs_session.class.php 2009-11-11 01:06:10 UTC (rev 470) @@ -30,7 +30,7 @@ } //now actually create the session. - session_start(); + @session_start(); } //check if there's a uid in the session already. Modified: trunk/1.0/tests/testOfCSContent.php =================================================================== --- trunk/1.0/tests/testOfCSContent.php 2009-10-30 02:40:26 UTC (rev 469) +++ trunk/1.0/tests/testOfCSContent.php 2009-11-11 01:06:10 UTC (rev 470) @@ -24,7 +24,9 @@ $this->gfObj->debugPrintOpt=1; $filesDir = dirname(__FILE__) ."/files"; - define('TEST_FILESDIR', $filesDir); + if(!defined('TEST_FILESDIR')) { + define('TEST_FILESDIR', $filesDir); + } }//end __construct() //------------------------------------------------------------------------- @@ -68,7 +70,7 @@ foreach($sc->get_valid_sections() as $section) { $sectionData = $sc->get_section($section); foreach($sectionData as $name=>$value) { - if(is_array($value['attributes'])) { + if(isset($value['attributes']) && is_array($value['attributes'])) { if(isset($value['attributes']['SETGLOBAL'])) { $setAsGlobals[$name] = $value['value']; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-07 15:06:03
|
Revision: 477 http://cs-content.svn.sourceforge.net/cs-content/?rev=477&view=rev Author: crazedsanity Date: 2010-07-07 15:05:57 +0000 (Wed, 07 Jul 2010) Log Message: ----------- Fix warnings & deprecated function usages. /contentSystem.class.php: * __construct(): -- replace ereg_replace() with preg_replace() -- use explode() instead of split(). * parse_section(): -- use explode() instead of split() * clean_url(): -- use preg_match() instead of ereg() -- use explode() instead of split() /cs_session.class.php: * get_cookie(): -- use isset() on $_COOKIE **and* $_COOKIE[$name] (avoids PHP notices/warnings. Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_session.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2010-05-26 17:47:04 UTC (rev 476) +++ trunk/1.0/contentSystem.class.php 2010-07-07 15:05:57 UTC (rev 477) @@ -104,11 +104,11 @@ //setup the section stuff... $repArr = array($_SERVER['SCRIPT_NAME'], "/"); - $_SERVER['REQUEST_URI'] = ereg_replace('^/', "", $_SERVER['REQUEST_URI']); + $_SERVER['REQUEST_URI'] = preg_replace('/^\//', "", $_SERVER['REQUEST_URI']); //figure out the section & subsection stuff. $requestUri = preg_replace('/\/$/', '', $_SERVER['REQUEST_URI']); - $this->fullSectionArr = split('/', $requestUri); //TODO: will this cope with an APPURL being set? + $this->fullSectionArr = explode('/', $requestUri); //TODO: will this cope with an APPURL being set? $this->section = $this->clean_url($_SERVER['REQUEST_URI']); $this->initialize_locals($siteRoot); @@ -298,7 +298,7 @@ if(($this->section === 0 || is_null($this->section) || !strlen($this->section)) && defined('DEFAULT_SECTION')) { $this->section = preg_replace('/^\//', '', constant('DEFAULT_SECTION')); } - $myArr = split('/', $this->section); + $myArr = explode('/', $this->section); //if we've got something in the array, keep going. if(is_array($myArr) && count($myArr) > 0) { @@ -357,13 +357,13 @@ $section = $section[0]; } - if(ereg("\.", $section)) { + if(preg_match("/\./", $section)) { //disregard file extensions, but keep everything else... // i.e. "index.php/yermom.html" becomes "index/yermom" - $tArr = split('/', $section); + $tArr = explode('/', $section); $tSection = null; foreach($tArr as $tSecName) { - $temp = split("\.", $tSecName); + $temp = explode(".", $tSecName); if(strlen($temp[0]) > 1) { $tSecName = $temp[0]; } Modified: trunk/1.0/cs_session.class.php =================================================================== --- trunk/1.0/cs_session.class.php 2010-05-26 17:47:04 UTC (rev 476) +++ trunk/1.0/cs_session.class.php 2010-07-07 15:05:57 UTC (rev 477) @@ -76,7 +76,7 @@ */ public function get_cookie($name) { $retval = NULL; - if(isset($_COOKIE) && $_COOKIE[$name]) { + if(isset($_COOKIE) && isset($_COOKIE[$name])) { $retval = $_COOKIE[$name]; } return($retval); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-08 17:44:31
|
Revision: 478 http://cs-content.svn.sourceforge.net/cs-content/?rev=478&view=rev Author: crazedsanity Date: 2010-07-08 17:44:25 +0000 (Thu, 08 Jul 2010) Log Message: ----------- Fix __autoload() to be more thorough. NOTE::: in some cases, this class could be very slow, depending on disk speed, caching, etc. The "clearstatcache()" call in cs_fileSystem::ls() may add to this slowing effect... consider removal or only optionally running it. /__autoload.php: * __autoload(): -- call _autoload_directory_checker()--a new recursive fuction--to look at all files & sub-folders until the class is found or there's no more stuff to look at. * _autoload_directory_checker() [NEW]: -- function that recursively calls itself, digging into sub-folders until it finds the class or runs out of files. /cs_fileSystem.class.php: * ls(): -- set return value var ($retval) as null initially to avoid PHP warnings/notices. -- removed some unnecessary commented-out debugging stuff. Modified Paths: -------------- trunk/1.0/__autoload.php trunk/1.0/cs_fileSystem.class.php Modified: trunk/1.0/__autoload.php =================================================================== --- trunk/1.0/__autoload.php 2010-07-07 15:05:57 UTC (rev 477) +++ trunk/1.0/__autoload.php 2010-07-08 17:44:25 UTC (rev 478) @@ -39,53 +39,60 @@ $myClass = preg_replace('/[aA]bstract/', '', $class); $tryThis[] = $class .'.abstract.class.php'; $tryThis[] = $myClass .'.abstract.class.php'; - $tryThis[] = 'abstract/'. $myClass .'.abstract.class.php'; } $tryThis[] = $class .'.class.php'; $tryThis[] = $class .'Class.php'; $tryThis[] = $class .'.php'; - $found=false; - foreach($tryThis as $filename) { - if(isset($lsData[$filename])) { - $tried[] = $fs->realcwd .'/'. $filename; - require_once($fs->realcwd .'/'. $filename); - if(class_exists($class)) { - $found=true; - break; - } + _autoload_directory_checker($fs, $class, $tryThis); + if(!class_exists($class)) { + $gf = new cs_globalFunctions; + $gf->debug_print(__FILE__ ." - line #". __LINE__ ."::: couldn't find (". $class ."), realcwd=(". $fs->realcwd .")",1); + $gf->debug_print($tried,1); + $gf->debug_print($tryThis,1); + $gf->debug_print($lsData,1); + exit; + } +}//end __autoload() + + +function _autoload_directory_checker($fs, $class, $lookForFiles) { + $lsData = $fs->ls(); + $dirNames = array(); + $curDirectory = $fs->realcwd; + + $found = false; + + if(is_array($lsData)) { + foreach($lsData as $objectName => $objectData) { + if($objectData['type'] == 'dir') { + $dirNames[] = $objectName; } - } - - if(!$found) { - //try going into sub-directories to pull the files. - foreach($lsData as $i=>$d) { - if($d['type'] == 'dir') { - $subLs = $fs->ls($i); - foreach($tryThis as $filename) { - $fileLocation = $fs->realcwd .'/'. $i .'/'. $filename; - if(file_exists($fileLocation)) { - $tried[] = $fileLocation; - require_once($fileLocation); - if(class_exists($class)) { - $found=true; - break; - } - } + elseif($objectData['type'] == 'file') { + if(in_array($objectName, $lookForFiles)) { + require_once($fs->realcwd .'/'. $objectName); + if(class_exists($class)) { + $found = true; + break; } } - if($found) { - break; - } } } + } - if(!$found) { - $gf = new cs_globalFunctions; - $gf->debug_print(__FILE__ ." - line #". __LINE__ ."::: couldn't find (". $class .")",1); - $gf->debug_print($tried,1); - $gf->debug_print($tryThis,1); - exit; + if(!$found && is_array($dirNames) && count($dirNames)) { + foreach($dirNames as $dir) { + $fs->cd($dir); + $found = _autoload_directory_checker($fs, $class, $lookForFiles); + $fs->cdup(); + + if($found === true) { + break; + } + } } -}//end __autoload() + + return($found); +} + ?> Modified: trunk/1.0/cs_fileSystem.class.php =================================================================== --- trunk/1.0/cs_fileSystem.class.php 2010-07-07 15:05:57 UTC (rev 477) +++ trunk/1.0/cs_fileSystem.class.php 2010-07-08 17:44:25 UTC (rev 478) @@ -137,6 +137,7 @@ public function ls($filename=NULL, $args=NULL) { clearstatcache(); + $retval = null; //open the directory for reading. $this->dh = opendir($this->realcwd); clearstatcache(); @@ -175,13 +176,10 @@ debug_print("FILE: $tFile || TYPE: $tType || is_file(): ". is_file($tFile) ."is_dir(): ". is_dir($tFile)); exit; } - #debug_print("FILE: $file || $dir". $file); unset($tType); } } } - #debug_print($retval); - #debug_print(readdir($this->dh)); return($retval); }//end ls() //======================================================================================== This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-07-28 00:49:23
|
Revision: 481 http://cs-content.svn.sourceforge.net/cs-content/?rev=481&view=rev Author: crazedsanity Date: 2010-07-28 00:49:16 +0000 (Wed, 28 Jul 2010) Log Message: ----------- Fix cleaning for numeric values. /cs_globalFunctions.class.php: * string_from_array(): -- fix SQL quoting for int/integer/numeric/number/decimal/float values when an array of values is passed. -- add "-" to the list of excluded characters -- add "number" and "int" as synonyms for integer/numeric /tests/testOfCSGlobalFunctions.php: * test_cleanString(): -- integer/numeric both return negative numbers (the "-" isn't cleaned) Modified Paths: -------------- trunk/1.0/cs_globalFunctions.class.php trunk/1.0/tests/testOfCSGlobalFunctions.php Added Paths: ----------- trunk/1.0/useForCLI.patch Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2010-07-12 23:37:31 UTC (rev 480) +++ trunk/1.0/cs_globalFunctions.class.php 2010-07-28 00:49:16 UTC (rev 481) @@ -176,7 +176,12 @@ } else { //now format it properly. - $array[$myIndex] = $this->cleanString($array[$myIndex], $myCleanStringArg); + $myUseSqlQuotes = null; + if(in_array($myCleanStringArg, array('int', 'integer', 'numeric', 'number', 'decimal', 'float'))) { + $myUseSqlQuotes = false; + } + $array[$myIndex] = $this->cleanString($array[$myIndex], $myCleanStringArg, $myUseSqlQuotes); + unset($myUseSqlQuotes); } } } @@ -507,15 +512,17 @@ $cleanThis = preg_replace("/[^0-9-+() ]/","",$cleanThis); break; + case "int": case "integer": case "numeric": + case "number": //Remove everything that's not numeric. if(is_null($cleanThis)) { $cleanThis = "NULL"; $sqlQuotes = 0; } else { - $cleanThis = preg_replace("/[^0-9]/","",$cleanThis); + $cleanThis = preg_replace("/[^0-9\-]/","",$cleanThis); } break; Modified: trunk/1.0/tests/testOfCSGlobalFunctions.php =================================================================== --- trunk/1.0/tests/testOfCSGlobalFunctions.php 2010-07-12 23:37:31 UTC (rev 480) +++ trunk/1.0/tests/testOfCSGlobalFunctions.php 2010-07-28 00:49:16 UTC (rev 481) @@ -54,8 +54,8 @@ 'email' => '@_-34..JuSTTHIS', 'email_plus_spaces' => '@_-34..JuST THIS', 'phone_fax' => '()+-34 ', - 'integer' => '34', - 'numeric' => '34', + 'integer' => '-34', + 'numeric' => '-34', 'decimal' => '34..', 'float' => '34..', 'name' => '\'JuSTTHIS', @@ -72,7 +72,7 @@ $cleanedData = $gf->cleanString($cleanThis, $name); //NOTE::: passing "%" in the message data causes an exception with the simpletest framework. - $this->assertEqual($expected, $cleanedData); + $this->assertEqual($expected, $cleanedData, "Cleaning test '". $name ."' FAILED... expected=(". $expected ."), got (". $cleanedData ."), "); } Added: trunk/1.0/useForCLI.patch =================================================================== --- trunk/1.0/useForCLI.patch (rev 0) +++ trunk/1.0/useForCLI.patch 2010-07-28 00:49:16 UTC (rev 481) @@ -0,0 +1,53 @@ +Index: code/lib/cs-content/cs_genericPage.class.php +=================================================================== +--- code/lib/cs-content/cs_genericPage.class.php (revision 480) ++++ code/lib/cs-content/cs_genericPage.class.php (working copy) +@@ -277,7 +277,7 @@ + if(!strlen($out)) { + $this->gfObj->debug_print($out); + $this->gfObj->debug_print($this->mainTemplate); +- $this->gfObj->debug_print("MANUAL FILE CONTENTS::: ". htmlentities(file_get_contents($this->tmplDir .'/'. $this->mainTemplate))); ++ $this->gfObj->debug_print("MANUAL FILE CONTENTS::: ". htmlentities(file_get_contents($this->mainTemplate))); + exit(__METHOD__ .": mainTemplate (". $this->mainTemplate .") was empty...?"); + } + +Index: code/lib/cs-content/contentSystem.class.php +=================================================================== +--- code/lib/cs-content/contentSystem.class.php (revision 480) ++++ code/lib/cs-content/contentSystem.class.php (working copy) +@@ -99,7 +99,7 @@ + /** + * The CONSTRUCTOR. Duh. + */ +- public function __construct($siteRoot=null) { ++ public function __construct($siteRoot=null, $section=null) { + parent::__construct(); + + //setup the section stuff... +@@ -109,8 +109,12 @@ + //figure out the section & subsection stuff. + $requestUri = preg_replace('/\/$/', '', $_SERVER['REQUEST_URI']); + $this->fullSectionArr = explode('/', $requestUri); //TODO: will this cope with an APPURL being set? +- $this->section = $this->clean_url($_SERVER['REQUEST_URI']); + ++ if(is_null($section)) { ++ $section = @$_SERVER['REQUEST_URI']; ++ } ++ $this->section = $this->clean_url($section); ++ + $this->initialize_locals($siteRoot); + }//end __construct() + //------------------------------------------------------------------------ +@@ -736,8 +740,10 @@ + * Called when something is broken. + */ + private function die_gracefully($details=NULL) { +- if(isset($_SERVER['SERVER_PROTOCOL']) && $this->templateObj->template_file_exists('system/404.shared.tmpl')) { +- header('HTTP/1.0 404 Not Found'); ++ if($this->templateObj->template_file_exists('system/404.shared.tmpl')) { ++ if(isset($_SERVER['SERVER_PROTOCOL'])) { ++ header('HTTP/1.0 404 Not Found'); ++ } + //Simple "Page Not Found" error... show 'em. + $this->templateObj->add_template_var('main', $this->templateObj->file_to_string('system/404.shared.tmpl')); + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2010-08-12 15:06:13
|
Revision: 482 http://cs-content.svn.sourceforge.net/cs-content/?rev=482&view=rev Author: crazedsanity Date: 2010-08-12 15:06:07 +0000 (Thu, 12 Aug 2010) Log Message: ----------- Fixes to allow cs-content be used for command-line things. NOTE::: if an error occurs, it still parses an HTML template. It would probably be better to have a class that extends cs_genericPage, overriding some of the methods to be more CLI-friendly. /contentSystem.class.php: * __construct(): -- ARG CHANGE: NEW ARG: #2 ($section=null) -- only set section to REQUEST_URI if the passed $section is null /cs_genericPage.class.php: * print_page(): -- added a bit of debug info if something goes wrong. Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_genericPage.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2010-07-28 00:49:16 UTC (rev 481) +++ trunk/1.0/contentSystem.class.php 2010-08-12 15:06:07 UTC (rev 482) @@ -99,7 +99,7 @@ /** * The CONSTRUCTOR. Duh. */ - public function __construct($siteRoot=null) { + public function __construct($siteRoot=null, $section=null) { parent::__construct(); //setup the section stuff... @@ -109,8 +109,12 @@ //figure out the section & subsection stuff. $requestUri = preg_replace('/\/$/', '', $_SERVER['REQUEST_URI']); $this->fullSectionArr = explode('/', $requestUri); //TODO: will this cope with an APPURL being set? - $this->section = $this->clean_url($_SERVER['REQUEST_URI']); + if(is_null($section)) { + $section = @$_SERVER['REQUEST_URI']; + } + $this->section = $this->clean_url($section); + $this->initialize_locals($siteRoot); }//end __construct() //------------------------------------------------------------------------ Modified: trunk/1.0/cs_genericPage.class.php =================================================================== --- trunk/1.0/cs_genericPage.class.php 2010-07-28 00:49:16 UTC (rev 481) +++ trunk/1.0/cs_genericPage.class.php 2010-08-12 15:06:07 UTC (rev 482) @@ -277,7 +277,7 @@ if(!strlen($out)) { $this->gfObj->debug_print($out); $this->gfObj->debug_print($this->mainTemplate); - $this->gfObj->debug_print("MANUAL FILE CONTENTS::: ". htmlentities(file_get_contents($this->tmplDir .'/'. $this->mainTemplate))); + $this->gfObj->debug_print("MANUAL FILE CONTENTS::: ". htmlentities(file_get_contents($this->mainTemplate))); exit(__METHOD__ .": mainTemplate (". $this->mainTemplate .") was empty...?"); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-19 03:40:03
|
Revision: 487 http://cs-content.svn.sourceforge.net/cs-content/?rev=487&view=rev Author: crazedsanity Date: 2011-01-19 03:39:57 +0000 (Wed, 19 Jan 2011) Log Message: ----------- Performance enhancements for __autoload(). NOTE::: both changes (__autoload() and cs_fileSystem::ls()) are optional; sites/apps that don't want to use them will continue to function as normal. /__autoload.php: * __autoload(): -- fixed indentation. -- test for class hints before trying to find files manually. -- stop searching if _autoload_hints_parser() returns true. * _autoload_hints_parser() [NEW]: -- function for finding and parsing a class hints file. * _autoload_directory_checker(): -- call to cs_fileSystem::ls() send args to avoid unncessary parsing. /contentSystem.class.php: * ARGUMENTS CHANGE TO cs_fileSystem::ls()::: -- arrange_directory_contents() -- load_includes() -- load_dir_includes() /cs_fileSystem.class.php: * ls(): -- ARG CHANGE: ARG RENAMED: #2 ($extendedInfo=true, WAS $args=NULL) -- extra call to self passes $extendedInfo argument -- call to get_fileinfo() passes $extendedInfo argument * get_fileinfo(): -- optionally adds file information to the returned array (still gets type, is_readable, and is_writable). /bin/generateHints.bash [NEW]: * create hints file with some standard Linux command-line utilities. Modified Paths: -------------- trunk/1.0/__autoload.php trunk/1.0/contentSystem.class.php trunk/1.0/cs_fileSystem.class.php Added Paths: ----------- trunk/1.0/bin/ trunk/1.0/bin/generateHints.bash Modified: trunk/1.0/__autoload.php =================================================================== --- trunk/1.0/__autoload.php 2011-01-16 00:18:29 UTC (rev 486) +++ trunk/1.0/__autoload.php 2011-01-19 03:39:57 UTC (rev 487) @@ -21,18 +21,17 @@ function __autoload($class) { - $tried = array(); + $tried = array(); + + $fsRoot = dirname(__FILE__) .'/../../'; + if(defined('LIBDIR')) { + $fsRoot = constant('LIBDIR'); + } + $fs = new cs_fileSystem($fsRoot); + $fs->cd('lib'); + if(!_autoload_hints_parser($class, $fs)) { + $lsData = $fs->ls(null,false); - $fsRoot = dirname(__FILE__) .'/../../'; - if(defined('LIBDIR')) { - $fsRoot = constant('LIBDIR'); - } - $fs = new cs_fileSystem($fsRoot); - - //try going into a "lib" directory. - $fs->cd('lib'); - $lsData = $fs->ls(); - //attempt to find it here... $tryThis = array(); if(preg_match('/[aA]bstract/', $class)) { @@ -44,22 +43,47 @@ $tryThis[] = $class .'Class.php'; $tryThis[] = $class .'.php'; - _autoload_directory_checker($fs, $class, $tryThis); - if(!class_exists($class)) { - $gf = new cs_globalFunctions; - $gf->debug_print(__FILE__ ." - line #". __LINE__ ."::: couldn't find (". $class ."), realcwd=(". $fs->realcwd .")",1); - $gf->debug_print($tried,1); - $gf->debug_print($tryThis,1); - if(function_exists('cs_debug_backtrace')) { - cs_debug_backtrace(1); + _autoload_directory_checker($fs, $class, $tryThis); + if(!class_exists($class)) { + $gf = new cs_globalFunctions; + $gf->debug_print(__FILE__ ." - line #". __LINE__ ."::: couldn't find (". $class ."), realcwd=(". $fs->realcwd .")",1); + $gf->debug_print($tried,1); + $gf->debug_print($tryThis,1); + if(function_exists('cs_debug_backtrace')) { + cs_debug_backtrace(1); + } + exit; } - exit; } }//end __autoload() +function _autoload_hints_parser($class, $fs) { + $foundClass=false; + if(defined('AUTOLOAD_HINTS') && file_exists(constant('AUTOLOAD_HINTS'))) { + $data = $fs->read(constant('AUTOLOAD_HINTS'),true); + $myHints = array(); + foreach($data as $s) { + $bits = explode('|', rtrim($s)); + if(count($bits) == 2) { + $myHints[$bits[1]] = $bits[0]; + } + } + #print "<pre>"; + #print_r($myHints); + $tryFile = constant('LIBDIR') .'/'. $myHints[$class]; + if(isset($myHints[$class]) && file_exists($tryFile)) { + require_once($tryFile); + if(class_exists($class)) { + $foundClass=true; + } + } + } + return($foundClass); +}//end _autoload_hints_parser() + function _autoload_directory_checker($fs, $class, $lookForFiles) { - $lsData = $fs->ls(); + $lsData = $fs->ls(null,false); $dirNames = array(); $curDirectory = $fs->realcwd; Added: trunk/1.0/bin/generateHints.bash =================================================================== --- trunk/1.0/bin/generateHints.bash (rev 0) +++ trunk/1.0/bin/generateHints.bash 2011-01-19 03:39:57 UTC (rev 487) @@ -0,0 +1,2 @@ +#!/bin/bash +grep "^class " * -R --exclude=*.svn* --exclude=*.tmp| grep ".php" | cut --delimiter=" " --fields 1,2 | sed "s/class //" | sed "s/:/\|/"> class.hints Property changes on: trunk/1.0/bin/generateHints.bash ___________________________________________________________________ Added: svn:executable + * Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2011-01-16 00:18:29 UTC (rev 486) +++ trunk/1.0/contentSystem.class.php 2011-01-19 03:39:57 UTC (rev 487) @@ -572,7 +572,7 @@ * name, or vice-versa. */ private function arrange_directory_contents($primaryIndex='section', $secondaryIndex='name') { - $directoryInfo = $this->tmplFs->ls(); + $directoryInfo = $this->tmplFs->ls(null,false); $arrangedArr = array(); if(is_array($directoryInfo)) { foreach($directoryInfo as $index=>$data) { @@ -678,7 +678,7 @@ $mySection = preg_replace('/\/index$/','', $mySection); } if($this->incFs->cd('/'. $mySection)) { - $lsData = $this->incFs->ls(); + $lsData = $this->incFs->ls(null,false); if(isset($lsData['shared.inc']) && is_array($lsData['shared.inc'])) { $this->add_include('shared.inc'); } @@ -700,7 +700,7 @@ * solely by load_includes(). */ private function load_dir_includes($section) { - $lsData = $this->incFs->ls(); + $lsData = $this->incFs->ls(null,false); $addThese = array(); Modified: trunk/1.0/cs_fileSystem.class.php =================================================================== --- trunk/1.0/cs_fileSystem.class.php 2011-01-16 00:18:29 UTC (rev 486) +++ trunk/1.0/cs_fileSystem.class.php 2011-01-19 03:39:57 UTC (rev 487) @@ -134,7 +134,7 @@ /** * Just like the linux version of the 'ls' command. */ - public function ls($filename=NULL, $args=NULL) { + public function ls($filename=NULL, $extendedInfo=true) { clearstatcache(); $retval = null; @@ -146,13 +146,13 @@ $tFile=$this->filename2absolute($filename); if(file_exists($tFile)) { //it's there... get info about it. - $info = $this->get_fileinfo($tFile); + $info = $this->get_fileinfo($tFile, $extendedInfo); if($info['type'] == 'dir') { $oldCwd = $this->cwd; $oldRealCwd = $this->realcwd; $this->cd($filename); - $retval = $this->ls(); + $retval = $this->ls(null, $extendedInfo); $this->cwd = $oldCwd; $this->realcwd = $oldRealCwd; @@ -189,23 +189,25 @@ /** * Grabs an array of information for a given file. */ - public function get_fileinfo($tFile) { + public function get_fileinfo($tFile,$extendedInfo=true) { //TODO: shouldn't require putting the "@" in front of these calls! $retval = array( - "size" => @filesize($tFile), "type" => @filetype($tFile), - "accessed" => @fileatime($tFile), - "modified" => @filemtime($tFile), - "owner" => @$this->my_getuser_group(fileowner($tFile), 'uid'), - "uid" => @fileowner($tFile), - "group" => @$this->my_getuser_group(filegroup($tFile), 'gid'), - "gid" => @filegroup($tFile), - "perms" => @$this->translate_perms(fileperms($tFile)), - "perms_num" => @substr(sprintf('%o', fileperms($tFile)), -4), "is_readable" => is_readable($tFile), "is_writable" => is_writable($tFile) ); + if($extendedInfo) { + $retval["size"] = @filesize($tFile); + $retval["accessed"] = @fileatime($tFile); + $retval["modified"] = @filemtime($tFile); + $retval["owner"] = @$this->my_getuser_group(fileowner($tFile), 'uid'); + $retval["uid"] = @fileowner($tFile); + $retval["group"] = @$this->my_getuser_group(filegroup($tFile), 'gid'); + $retval["gid"] = @filegroup($tFile); + $retval["perms"] = @$this->translate_perms(fileperms($tFile)); + $retval["perms_num"]= @substr(sprintf('%o', fileperms($tFile)), -4); + } return($retval); }//end get_fileinfo() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-25 00:01:13
|
Revision: 489 http://cs-content.svn.sourceforge.net/cs-content/?rev=489&view=rev Author: crazedsanity Date: 2011-01-25 00:01:07 +0000 (Tue, 25 Jan 2011) Log Message: ----------- Move URL-cleaning to global functions so other classes can use it. /cs_globalFunctions.class.php: * clean_url() [NEW]: -- derived from contentSystem::clean_url() /contentSystem.class.php: * clean_url(): -- mostly moved to cs_globalFunctions::clean_url(), except some internally-specific things. Modified Paths: -------------- trunk/1.0/contentSystem.class.php trunk/1.0/cs_globalFunctions.class.php Modified: trunk/1.0/contentSystem.class.php =================================================================== --- trunk/1.0/contentSystem.class.php 2011-01-19 15:36:24 UTC (rev 488) +++ trunk/1.0/contentSystem.class.php 2011-01-25 00:01:07 UTC (rev 489) @@ -331,52 +331,17 @@ } //make sure we've still got something valid to work with. - if(!strlen($section)) { - //TODO: remove the extra return statement (should only be one at the bottom of the method). - return(NULL); - } - else { - - //if there's an "APPURL" constant, drop that from the section. - if(defined('APPURL') && strlen(constant('APPURL'))) { - $dropThis = preg_replace('/^\//', '', constant('APPURL')); - $dropThis = preg_replace('/\//', '\\/', $dropThis); - $section = preg_replace('/^'. $dropThis .'/', '', $section); + if(strlen($section)) { + try { + $section = $this->gfObj->clean_url($section); } - - //check the string to make sure it doesn't begin with a "/" - if($section[0] == '/') { - $section = substr($section, 1, strlen($section)); + catch(Exception $e) { + //hide the exception and allow it to return NULL. } - - //check the last char for a "/"... - if($section[strlen($section) -1] == '/') { - //last char is a '/'... kill it. - $section = substr($section, 0, strlen($section) -1); - } - - //if we've been sent a query, kill it off the string... - if(preg_match('/\?/', $section)) { - $section = split('\?', $section); - $section = $section[0]; - } - - if(preg_match("/\./", $section)) { - //disregard file extensions, but keep everything else... - // i.e. "index.php/yermom.html" becomes "index/yermom" - $tArr = explode('/', $section); - $tSection = null; - foreach($tArr as $tSecName) { - $temp = explode(".", $tSecName); - if(strlen($temp[0]) > 1) { - $tSecName = $temp[0]; - } - $tSection = $this->gfObj->create_list($tSection, $tSecName, '/'); - } - $section = $tSection; - } } - + else { + $section = null; + } return($section); }//end clean_url() //------------------------------------------------------------------------ Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2011-01-19 15:36:24 UTC (rev 488) +++ trunk/1.0/cs_globalFunctions.class.php 2011-01-25 00:01:07 UTC (rev 489) @@ -878,7 +878,64 @@ return($this->debug_print($printThis, $printItForMe, $removeHr)); }//end debug_var_dump() //########################################################################## + + + + //------------------------------------------------------------------------ + /** + * Removes all the crap from the url, so we can figure out what section we + * need to load templates & includes for. + */ + public function clean_url($url=NULL) { + //make sure we've still got something valid to work with. + if(strlen($url)) { + //if there's an "APPURL" constant, drop that from the url. + if(defined('APPURL') && strlen(constant('APPURL'))) { + $dropThis = preg_replace('/^\//', '', constant('APPURL')); + $dropThis = preg_replace('/\//', '\\/', $dropThis); + $url = preg_replace('/^'. $dropThis .'/', '', $url); + } + + //check the string to make sure it doesn't begin with a "/" + if($url[0] == '/') { + $url = substr($url, 1, strlen($url)); + } + + //check the last char for a "/"... + if($url[strlen($url) -1] == '/') { + //last char is a '/'... kill it. + $url = substr($url, 0, strlen($url) -1); + } + + //if we've been sent a query, kill it off the string... + if(preg_match('/\?/', $url)) { + $url = split('\?', $url); + $url = $url[0]; + } + + if(preg_match("/\./", $url)) { + //disregard file extensions, but keep everything else... + // i.e. "index.php/yermom.html" becomes "index/yermom" + $tArr = explode('/', $url); + $tUrl = null; + foreach($tArr as $tUrlPart) { + $temp = explode(".", $tUrlPart); + if(strlen($temp[0]) > 1) { + $tUrlPart = $temp[0]; + } + $tUrl = $this->create_list($tUrl, $tUrlPart, '/'); + } + $url = $tUrl; + } + } + else { + throw new exception(__METHOD__ .": invalid url (". $url .")"); + } + return($url); + }//end clean_url() + //------------------------------------------------------------------------ + }//end cs_globalFunctions{} ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <cra...@us...> - 2011-01-25 02:01:16
|
Revision: 490 http://cs-content.svn.sourceforge.net/cs-content/?rev=490&view=rev Author: crazedsanity Date: 2011-01-25 02:01:09 +0000 (Tue, 25 Jan 2011) Log Message: ----------- Parts of URL can be one character long; tests to make sure it always works. /tests/testOfCSGlobalFunctions.php: * test_clean_url() [NEW]: -- test the new clean_url() method /cs_globalFunctions.class.php: * clean_url(): -- modified so the bits of the URL can be one character long or more (not two or more) Modified Paths: -------------- trunk/1.0/cs_globalFunctions.class.php trunk/1.0/tests/testOfCSGlobalFunctions.php Modified: trunk/1.0/cs_globalFunctions.class.php =================================================================== --- trunk/1.0/cs_globalFunctions.class.php 2011-01-25 00:01:07 UTC (rev 489) +++ trunk/1.0/cs_globalFunctions.class.php 2011-01-25 02:01:09 UTC (rev 490) @@ -920,7 +920,7 @@ $tUrl = null; foreach($tArr as $tUrlPart) { $temp = explode(".", $tUrlPart); - if(strlen($temp[0]) > 1) { + if(strlen($temp[0])) { $tUrlPart = $temp[0]; } $tUrl = $this->create_list($tUrl, $tUrlPart, '/'); @@ -929,7 +929,7 @@ } } else { - throw new exception(__METHOD__ .": invalid url (". $url .")"); + $url = null; } return($url); Modified: trunk/1.0/tests/testOfCSGlobalFunctions.php =================================================================== --- trunk/1.0/tests/testOfCSGlobalFunctions.php 2011-01-25 00:01:07 UTC (rev 489) +++ trunk/1.0/tests/testOfCSGlobalFunctions.php 2011-01-25 02:01:09 UTC (rev 490) @@ -399,6 +399,34 @@ + //------------------------------------------------------------------------- + function test_clean_url() { + $testUrls = array( + "testNulls" => NULL, + "testEmpty" => array("", NULL), + "root" => "", + "simple" => array("/index.php/test.html","index/test"), + "complex" => array("/x.xyz/y.123/_x/-y/*z", "x/y/_x/-y/*z"), + "noLeadingSlash"=> array("page/stuff.html", "page/stuff"), + ); + $gf = new cs_globalFunctions; + foreach($testUrls as $testName=>$cleanThis) { + if(is_array($cleanThis)) { + $expectThis = $cleanThis[1]; + $cleanThis = $cleanThis[0]; + } + else { + $expectThis = $cleanThis; + } + $actualOutput = $gf->clean_url($cleanThis); + $this->assertEqual($expectThis, $actualOutput, "failed test '". $testName ."', expected=(". $expectThis ."), actualOutput=(". $actualOutput .")"); + } + }//end test_clean_url() + //------------------------------------------------------------------------- + + + + }//end TestOfCSGlobalFunctions //============================================================================= ?> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |